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

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