Fixing select() implementation (and usage)
[tpg/acess2.git] / Modules / IPStack / tcp.c
1 /*
2  * Acess2 IP Stack
3  * - TCP Handling
4  */
5 #define DEBUG   1
6 #include "ipstack.h"
7 #include "ipv4.h"
8 #include "tcp.h"
9
10 #define USE_SELECT      1
11
12 #define TCP_MIN_DYNPORT 0xC000
13 #define TCP_MAX_HALFOPEN        1024    // Should be enough
14
15 #define TCP_MAX_PACKET_SIZE     1024
16 #define TCP_WINDOW_SIZE 0x2000
17 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
18
19 // === PROTOTYPES ===
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);
30 // --- Server
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);
36 // --- Client
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);
42
43 // === TEMPLATES ===
44 tSocketFile     gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
45 tSocketFile     gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
46
47 // === GLOBALS ===
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;
55
56 // === CODE ===
57 /**
58  * \brief Initialise the TCP Layer
59  * 
60  * Registers the client and server files and the GetPacket callback
61  */
62 void TCP_Initialise()
63 {
64         IPStack_AddFile(&gTCP_ServerFile);
65         IPStack_AddFile(&gTCP_ClientFile);
66         IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
67 }
68
69 /**
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)
74  */
75 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
76 {
77         size_t  buflen;
78         Uint32  *buf;
79         switch( Conn->Interface->Type )
80         {
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;
87                 Data->Checksum = 0;
88                 memcpy( &buf[3], Data, Length );
89                 Data->Checksum = htons( IPv4_Checksum( buf, buflen ) );
90                 free(buf);
91                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
92                 break;
93         }
94 }
95
96 /**
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
102  */
103 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
104 {
105         tTCPHeader      *hdr = Buffer;
106         tTCPListener    *srv;
107         tTCPConnection  *conn;
108
109         Log_Log("TCP", "TCP_GetPacket: SourcePort = %i, DestPort = %i",
110                 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
111 /*
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));
128 */
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 " : ""
138                 );
139
140         if( Length > (hdr->DataOffset >> 4)*4 )
141         {
142                 Debug_HexDump(
143                         "[TCP  ] Packet Data = ",
144                         (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
145                         Length - (hdr->DataOffset >> 4)*4
146                         );
147         }
148
149         // Check Servers
150         {
151                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
152                 {
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;
159                         
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 )
163                         {
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;
168
169                                 // Check Source Port
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;
173
174                                 // Check Source IP
175                                 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
176                                         continue;
177                                 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
178                                         continue;
179
180                                 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
181                                 // We have a response!
182                                 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
183
184                                 return;
185                         }
186
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");
191                                 return ;
192                         }
193                         
194                         // TODO: Check for halfopen max
195                         
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;
201                         
202                         switch(Interface->Type)
203                         {
204                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
205                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
206                         }
207                         
208                         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
209                         
210                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
211                         conn->NextSequenceSend = rand();
212                         
213                         // Create node
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;
221                         
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
225                         // it, just in case
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;
231                         else
232                                 srv->ConnectionsTail->Next = conn;
233                         srv->ConnectionsTail = conn;
234                         if(!srv->NewConnections)
235                                 srv->NewConnections = conn;
236                         SHORTREL(&srv->lConnections);
237
238                         // Send the SYN ACK
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 ++;
247                         return ;
248                 }
249         }
250
251
252         // Check Open Connections
253         {
254                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
255                 {
256                         // Check that it is coming in on the same interface
257                         if(conn->Interface != Interface)        continue;
258
259                         // Check Source Port
260                         if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
261
262                         // Check Source IP
263                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
264                                 continue;
265                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
266                                 continue;
267
268                         TCP_INT_HandleConnectionPacket(conn, hdr, Length);
269                         return ;
270                 }
271         }
272         
273         Log_Log("TCP", "TCP_GetPacket: No Match");
274 }
275
276 /**
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
281  */
282 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
283 {       
284         tTCPStoredPacket        *pkt;
285          int    dataLen;
286         
287         // Syncronise sequence values
288         if(Header->Flags & TCP_FLAG_SYN) {
289                 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
290         }
291         
292         // Handle a server replying to our initial SYN
293         if( Connection->State == TCP_ST_SYN_SENT )
294         {
295                 if( (Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == (TCP_FLAG_SYN|TCP_FLAG_ACK) )
296                 {       
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;
307                 }
308         }
309         
310         // Handle a client confirming the connection
311         if( Connection->State == TCP_ST_HALFOPEN && (Header->Flags & TCP_FLAG_ACK) )
312         {
313                 Connection->State = TCP_ST_OPEN;
314                 Log_Log("TCP", "Connection fully opened");
315         }
316         
317         // Get length of data
318         dataLen = Length - (Header->DataOffset>>4)*4;
319         Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
320         
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);
324                 
325                 // HACK
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;
329                         return ;
330                 }
331         }
332         
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;
337                         return ;
338                 }
339                 else {
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 );
347                         return ;
348                 }
349         }
350         
351         // Check for an empty packet
352         if(dataLen == 0) {
353                 Log_Log("TCP", "Empty Packet");
354                 return ;
355         }
356         
357         // NOTES:
358         // Flags
359         //    PSH - Has Data?
360         // /NOTES
361         
362         // Allocate and fill cached packet
363         pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
364         pkt->Next = NULL;
365         pkt->Sequence = ntohl(Header->SequenceNumber);
366         pkt->Length = dataLen;
367         memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
368         
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 )
372         {
373                 tTCPStoredPacket        *tmp, *prev = NULL;
374                 
375                 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
376                         pkt->Sequence, Connection->NextSequenceRcv);
377                 
378                 // No? Well, let's cache it and look at it later
379                 SHORTLOCK( &Connection->lFuturePackets );
380                 for(tmp = Connection->FuturePackets;
381                         tmp;
382                         prev = tmp, tmp = tmp->Next)
383                 {
384                         if(tmp->Sequence > pkt->Sequence)       break;
385                 }
386                 if(prev)
387                         prev->Next = pkt;
388                 else
389                         Connection->FuturePackets = pkt;
390                 pkt->Next = tmp;
391                 SHORTREL( &Connection->lFuturePackets );
392         }
393         else
394         {
395                 // Ooh, Goodie! Add it to the recieved list
396                 TCP_INT_AppendRecieved(Connection, pkt);
397                 free(pkt);
398                 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
399                 Connection->NextSequenceRcv += dataLen;
400                 
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);
405         
406                 // ACK Packet
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 ++;
417         }
418 }
419
420 /**
421  * \brief Appends a packet to the recieved list
422  * \param Connection    Connection structure
423  * \param Pkt   Packet structure on heap
424  */
425 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
426 {
427         Mutex_Acquire( &Connection->lRecievedPackets );
428         if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
429         {
430                 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
431                 //      TCP_INT_DumpConnection(Connection)
432                         ""
433                         );
434                 return ;
435         }
436         
437         RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
438
439         #if USE_SELECT
440         VFS_MarkAvaliable(&Connection->Node, 1);
441         #endif
442         
443         Mutex_Release( &Connection->lRecievedPackets );
444 }
445
446 /**
447  * \brief Updates the connections recieved list from the future list
448  * \param Connection    Connection structure
449  * 
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
452  * sequence.
453  */
454 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
455 {
456         tTCPStoredPacket        *pkt, *prev;
457         for(;;)
458         {
459                 prev = NULL;
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);
465                 
466                 // If we can't find the expected next packet, stop looking
467                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
468                         SHORTREL( &Connection->lFuturePackets );
469                         return;
470                 }
471                 
472                 // Delete packet from future list
473                 if(prev)
474                         prev->Next = pkt->Next;
475                 else
476                         Connection->FuturePackets = pkt->Next;
477                 
478                 // Release list
479                 SHORTREL( &Connection->lFuturePackets );
480                 
481                 // Looks like we found one
482                 TCP_INT_AppendRecieved(Connection, pkt);
483                 Connection->NextSequenceRcv += pkt->Length;
484                 free(pkt);
485         }
486 }
487
488 /**
489  * \fn Uint16 TCP_GetUnusedPort()
490  * \brief Gets an unused port and allocates it
491  */
492 Uint16 TCP_GetUnusedPort()
493 {
494         Uint16  ret;
495
496         // Get Next outbound port
497         ret = giTCP_NextOutPort++;
498         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
499         {
500                 ret ++;
501                 giTCP_NextOutPort++;
502                 if(giTCP_NextOutPort == 0x10000) {
503                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
504                 }
505         }
506
507         // Mark the new port as used
508         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
509
510         return ret;
511 }
512
513 /**
514  * \fn int TCP_AllocatePort(Uint16 Port)
515  * \brief Marks a port as used
516  */
517 int TCP_AllocatePort(Uint16 Port)
518 {
519         // Check if the port has already been allocated
520         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
521                 return 0;
522
523         // Allocate
524         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
525
526         return 1;
527 }
528
529 /**
530  * \fn int TCP_DeallocatePort(Uint16 Port)
531  * \brief Marks a port as unused
532  */
533 int TCP_DeallocatePort(Uint16 Port)
534 {
535         // Check if the port has already been allocated
536         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
537                 return 0;
538
539         // Allocate
540         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
541
542         return 1;
543 }
544
545 // --- Server
546 tVFS_Node *TCP_Server_Init(tInterface *Interface)
547 {
548         tTCPListener    *srv;
549         
550         srv = malloc( sizeof(tTCPListener) );
551
552         if( srv == NULL ) {
553                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
554                 return NULL;
555         }
556
557         srv->Interface = Interface;
558         srv->Port = 0;
559         srv->NextID = 0;
560         srv->Connections = NULL;
561         srv->ConnectionsTail = NULL;
562         srv->NewConnections = NULL;
563         srv->Next = NULL;
564         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
565         srv->Node.Size = -1;
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;
573
574         SHORTLOCK(&glTCP_Listeners);
575         srv->Next = gTCP_Listeners;
576         gTCP_Listeners = srv;
577         SHORTREL(&glTCP_Listeners);
578
579         return &srv->Node;
580 }
581
582 /**
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)
587  */
588 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
589 {
590         tTCPListener    *srv = Node->ImplPtr;
591         tTCPConnection  *conn;
592         char    *ret;
593         
594         ENTER("pNode iPos", Node, Pos);
595
596         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
597         for(;;)
598         {
599                 SHORTLOCK( &srv->lConnections );
600                 if( srv->NewConnections != NULL )       break;
601                 SHORTREL( &srv->lConnections );
602                 Threads_Yield();        // TODO: Sleep until poked
603                 continue;
604         }
605         
606
607         // Increment the new list (the current connection is still on the 
608         // normal list)
609         conn = srv->NewConnections;
610         srv->NewConnections = conn->Next;
611         
612         SHORTREL( &srv->lConnections );
613         
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);
618
619         ret = malloc(9);
620         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
621         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
622         LEAVE('s', ret);
623         return ret;
624 }
625
626 /**
627  * \brief Gets a client connection node
628  * \param Node  Server node
629  * \param Name  Hexadecimal ID of the node
630  */
631 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
632 {
633         tTCPConnection  *conn;
634         tTCPListener    *srv = Node->ImplPtr;
635         char    tmp[9];
636          int    id = atoi(Name);
637         
638         ENTER("pNode sName", Node, Name);
639         
640         // Sanity Check
641         itoa(tmp, id, 16, 8, '0');
642         if(strcmp(tmp, Name) != 0) {
643                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
644                 LEAVE('n');
645                 return NULL;
646         }
647         
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);
651         
652         // Search
653         SHORTLOCK( &srv->lConnections );
654         for(conn = srv->Connections;
655                 conn;
656                 conn = conn->Next)
657         {
658                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
659                 if(conn->Node.ImplInt == id)    break;
660         }
661         SHORTREL( &srv->lConnections );
662         
663         // If not found, ret NULL
664         if(!conn) {
665                 LOG("Connection %i not found", id);
666                 LEAVE('n');
667                 return NULL;
668         }
669         
670         // Return node
671         LEAVE('p', &conn->Node);
672         return &conn->Node;
673 }
674
675 /**
676  * \brief Handle IOCtl calls
677  */
678 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
679 {
680         tTCPListener    *srv = Node->ImplPtr;
681
682         switch(ID)
683         {
684         case 4: // Get/Set Port
685                 if(!Data)       // Get Port
686                         return srv->Port;
687
688                 if(srv->Port)   // Wait, you can't CHANGE the port
689                         return -1;
690
691                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
692                         return -1;
693
694                 // Permissions check
695                 if(Threads_GetUID() != 0
696                 && *(Uint16*)Data != 0
697                 && *(Uint16*)Data < 1024)
698                         return -1;
699
700                 // TODO: Check if a port is in use
701
702                 // Set Port
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);
708                 
709                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
710                 
711                 return srv->Port;
712         }
713         return 0;
714 }
715
716 void TCP_Server_Close(tVFS_Node *Node)
717 {
718         free(Node->ImplPtr);
719 }
720
721 // --- Client
722 /**
723  * \brief Create a client node
724  */
725 tVFS_Node *TCP_Client_Init(tInterface *Interface)
726 {
727         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
728
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) );
734
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;
742
743         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
744
745         SHORTLOCK(&glTCP_OutbountCons);
746         conn->Next = gTCP_OutbountCons;
747         gTCP_OutbountCons = conn;
748         SHORTREL(&glTCP_OutbountCons);
749
750         return &conn->Node;
751 }
752
753 /**
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.
757  */
758 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
759 {
760         tTCPConnection  *conn = Node->ImplPtr;
761         char    *destbuf = Buffer;
762         size_t  len;
763         
764         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
765         LOG("conn = %p", conn);
766         LOG("conn->State = %i", conn->State);
767         
768         // Check if connection is open
769         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
770                 Threads_Yield();
771         if( conn->State != TCP_ST_OPEN ) {
772                 LEAVE('i', 0);
773                 return 0;
774         }
775         
776         // Poll packets
777         for(;;)
778         {
779                 // Wait
780                 VFS_SelectNode(Node, VFS_SELECT_READ, NULL);
781                 // Lock list and read
782                 Mutex_Acquire( &conn->lRecievedPackets );
783                 
784                 // Attempt to read all `Length` bytes
785                 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
786                 
787                 if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
788                         LOG("Marking as none avaliable (len = %i)\n", len);
789                         VFS_MarkAvaliable(Node, 0);
790                 }
791                         
792                 // Release the lock (we don't need it any more)
793                 Mutex_Release( &conn->lRecievedPackets );
794         
795                 LEAVE('i', len);
796                 return len;
797         }
798 }
799
800 /**
801  * \brief Send a data packet on a connection
802  */
803 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
804 {
805         char    buf[sizeof(tTCPHeader)+Length];
806         tTCPHeader      *packet = (void*)buf;
807         
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;
812         
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!
816         
817         memcpy(packet->Options, Data, Length);
818         
819         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
820         
821         Connection->NextSequenceSend += Length;
822 }
823
824 /**
825  * \brief Send some bytes on a connection
826  */
827 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
828 {
829         tTCPConnection  *conn = Node->ImplPtr;
830         size_t  rem = Length;
831         
832         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
833         
834         // Check if connection is open
835         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
836                 Threads_Yield();
837         if( conn->State != TCP_ST_OPEN ) {
838                 LEAVE('i', 0);
839                 return 0;
840         }
841         
842         while( rem > TCP_MAX_PACKET_SIZE )
843         {
844                 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
845                 Buffer += TCP_MAX_PACKET_SIZE;
846         }
847         
848         TCP_INT_SendDataPacket(conn, rem, Buffer);
849         
850         LEAVE('i', Length);
851         return Length;
852 }
853
854 /**
855  * \brief Open a connection to another host using TCP
856  * \param Conn  Connection structure
857  */
858 void TCP_StartConnection(tTCPConnection *Conn)
859 {
860         tTCPHeader      hdr = {0};
861
862         Conn->State = TCP_ST_SYN_SENT;
863
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
872         
873         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
874         
875         Conn->NextSequenceSend ++;
876         Conn->State = TCP_ST_SYN_SENT;
877         return ;
878 }
879
880 /**
881  * \brief Control a client socket
882  */
883 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
884 {
885         tTCPConnection  *conn = Node->ImplPtr;
886         
887         ENTER("pNode iID pData", Node, ID, Data);
888
889         switch(ID)
890         {
891         case 4: // Get/Set local port
892                 if(!Data)
893                         LEAVE_RET('i', conn->LocalPort);
894                 if(conn->State != TCP_ST_CLOSED)
895                         LEAVE_RET('i', -1);
896                 if(!CheckMem(Data, sizeof(Uint16)))
897                         LEAVE_RET('i', -1);
898
899                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
900                         LEAVE_RET('i', -1);
901
902                 conn->LocalPort = *(Uint16*)Data;
903                 LEAVE_RET('i', conn->LocalPort);
904
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);
911
912         case 6: // Set Remote IP
913                 if( conn->State != TCP_ST_CLOSED )
914                         LEAVE_RET('i', -1);
915                 if( conn->Interface->Type == 4 )
916                 {
917                         if(!CheckMem(Data, sizeof(tIPv4)))      LEAVE_RET('i', -1);
918                         conn->RemoteIP.v4 = *(tIPv4*)Data;
919                 }
920                 else if( conn->Interface->Type == 6 )
921                 {
922                         if(!CheckMem(Data, sizeof(tIPv6)))      LEAVE_RET('i', -1);
923                         conn->RemoteIP.v6 = *(tIPv6*)Data;
924                 }
925                 LEAVE_RET('i', 0);
926
927         case 7: // Connect
928                 if(conn->LocalPort == 0xFFFF)
929                         conn->LocalPort = TCP_GetUnusedPort();
930                 if(conn->RemotePort == -1)
931                         LEAVE_RET('i', 0);
932
933                 TCP_StartConnection(conn);
934                 LEAVE_RET('i', 1);
935         
936         // Get recieve buffer length
937         case 8:
938                 LEAVE_RET('i', conn->RecievedBuffer->Length);
939         }
940
941         return 0;
942 }
943
944 void TCP_Client_Close(tVFS_Node *Node)
945 {
946         tTCPConnection  *conn = Node->ImplPtr;
947         tTCPHeader      packet;
948         
949         ENTER("pNode", Node);
950         
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;
955         
956         packet.AcknowlegementNumber = 0;
957         packet.SequenceNumber = htonl(conn->NextSequenceSend);
958         packet.Flags = TCP_FLAG_FIN;
959         
960         conn->State = TCP_ST_FIN_SENT;
961         
962         TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
963         
964         while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();
965         
966         free(conn);
967         
968         LEAVE('-');
969 }

UCC git Repository :: git.ucc.asn.au