a6fb60e44d7d7cdf9b80752702af9146874c005e
[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, 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 tSpinlock       glTCP_Listeners;
48 tTCPListener    *gTCP_Listeners;
49 tSpinlock       glTCP_OutbountCons;
50 tTCPConnection  *gTCP_OutbountCons;
51 Uint32  gaTCP_PortBitmap[0x800];
52  int    giTCP_NextOutPort = TCP_MIN_DYNPORT;
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 Open a connection to another host using TCP
69  * \param Conn  Connection structure
70  */
71 void TCP_StartConnection(tTCPConnection *Conn)
72 {
73         tTCPHeader      hdr;
74
75         Conn->State = TCP_ST_SYN_SENT;
76
77         hdr.SourcePort = htons(Conn->LocalPort);
78         hdr.DestPort = htons(Conn->RemotePort);
79         Conn->NextSequenceSend = rand();
80         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
81         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
82         hdr.Flags = TCP_FLAG_SYN;
83         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
84         hdr.Checksum = 0;       // TODO
85         hdr.UrgentPointer = 0;
86         
87         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
88         return ;
89 }
90
91 /**
92  * \brief Sends a packet from the specified connection, calculating the checksums
93  * \param Conn  Connection
94  * \param Length        Length of data
95  * \param Data  Packet data (cast as a TCP Header)
96  */
97 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
98 {
99         size_t  buflen;
100         Uint32  *buf;
101         switch( Conn->Interface->Type )
102         {
103         case 4: // Append IPv4 Pseudo Header
104                 buflen = 4 + 4 + 4 + ((Length+1)&~1);
105                 buf = malloc( buflen );
106                 buf[0] = Conn->Interface->IP4.Address.L;
107                 buf[1] = Conn->RemoteIP.v4.L;
108                 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
109                 Data->Checksum = 0;
110                 memcpy( &buf[3], Data, Length );
111                 Data->Checksum = IPv4_Checksum( buf, buflen );
112                 free(buf);
113                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
114                 break;
115         }
116 }
117
118 /**
119  * \brief Handles a packet from the IP Layer
120  * \param Interface     Interface the packet arrived from
121  * \param Address       Pointer to the addres structure
122  * \param Length        Size of packet in bytes
123  * \param Buffer        Packet data
124  */
125 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
126 {
127         tTCPHeader      *hdr = Buffer;
128         tTCPListener    *srv;
129         tTCPConnection  *conn;
130
131         Log_Log("TCP", "SourcePort = %i, DestPort = %i",
132                 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
133 /*
134         Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
135         Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
136         Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
137         Log_Log("TCP", "Flags = {");
138         Log_Log("TCP", "  CWR = %B, ECE = %B",
139                 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
140         Log_Log("TCP", "  URG = %B, ACK = %B",
141                 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
142         Log_Log("TCP", "  PSH = %B, RST = %B",
143                 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
144         Log_Log("TCP", "  SYN = %B, FIN = %B",
145                 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
146         Log_Log("TCP", "}");
147         Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
148         Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
149         Log_Log("TCP", "UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
150 */
151
152         if( Length > (hdr->DataOffset >> 4)*4 )
153         {
154                 Debug_HexDump(
155                         "[TCP  ] Packet Data = ",
156                         (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
157                         Length - (hdr->DataOffset >> 4)*4
158                         );
159         }
160
161         // Check Servers
162         {
163                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
164                 {
165                         // Check if the server is active
166                         if(srv->Port == 0)      continue;
167                         // Check the interface
168                         if(srv->Interface && srv->Interface != Interface)       continue;
169                         // Check the destination port
170                         if(srv->Port != htons(hdr->DestPort))   continue;
171                         
172                         Log_Log("TCP", "Matches server %p", srv);
173                         // Is this in an established connection?
174                         for( conn = srv->Connections; conn; conn = conn->Next )
175                         {
176                                 Log_Log("TCP", "conn->Interface(%p) == Interface(%p)",
177                                         conn->Interface, Interface);
178                                 // Check that it is coming in on the same interface
179                                 if(conn->Interface != Interface)        continue;
180
181                                 // Check Source Port
182                                 Log_Log("TCP", "conn->RemotePort(%i) == hdr->SourcePort(%i)",
183                                         conn->RemotePort, ntohs(hdr->SourcePort));
184                                 if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
185
186                                 // Check Source IP
187                                 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
188                                         continue;
189                                 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
190                                         continue;
191
192                                 Log_Log("TCP", "Matches connection %p", conn);
193                                 // We have a response!
194                                 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
195
196                                 return;
197                         }
198
199                         Log_Log("TCP", "Opening Connection");
200                         // Open a new connection (well, check that it's a SYN)
201                         if(hdr->Flags != TCP_FLAG_SYN) {
202                                 Log_Log("TCP", "Packet is not a SYN");
203                                 return ;
204                         }
205                         
206                         // TODO: Check for halfopen max
207                         
208                         conn = calloc(1, sizeof(tTCPConnection));
209                         conn->State = TCP_ST_HALFOPEN;
210                         conn->LocalPort = srv->Port;
211                         conn->RemotePort = ntohs(hdr->SourcePort);
212                         conn->Interface = Interface;
213                         
214                         switch(Interface->Type)
215                         {
216                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
217                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
218                         }
219                         
220                         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
221                         
222                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
223                         conn->NextSequenceSend = rand();
224                         
225                         // Create node
226                         conn->Node.NumACLs = 1;
227                         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
228                         conn->Node.ImplPtr = conn;
229                         conn->Node.ImplInt = srv->NextID ++;
230                         conn->Node.Read = TCP_Client_Read;
231                         conn->Node.Write = TCP_Client_Write;
232                         //conn->Node.Close = TCP_SrvConn_Close;
233                         
234                         // Hmm... Theoretically, this lock will never have to wait,
235                         // as the interface is locked to the watching thread, and this
236                         // runs in the watching thread. But, it's a good idea to have
237                         // it, just in case
238                         // Oh, wait, there is a case where a wildcard can be used
239                         // (srv->Interface == NULL) so having the lock is a good idea
240                         LOCK(&srv->lConnections);
241                         if( !srv->Connections )
242                                 srv->Connections = conn;
243                         else
244                                 srv->ConnectionsTail->Next = conn;
245                         srv->ConnectionsTail = conn;
246                         if(!srv->NewConnections)
247                                 srv->NewConnections = conn;
248                         RELEASE(&srv->lConnections);
249
250                         // Send the SYN ACK
251                         hdr->Flags |= TCP_FLAG_ACK;
252                         hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
253                         hdr->SequenceNumber = htonl(conn->NextSequenceSend);
254                         hdr->DestPort = hdr->SourcePort;
255                         hdr->SourcePort = htons(srv->Port);
256                         hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
257                         TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
258                         conn->NextSequenceSend ++;
259                         return ;
260                 }
261         }
262
263
264         // Check Open Connections
265         {
266                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
267                 {
268                         // Check that it is coming in on the same interface
269                         if(conn->Interface != Interface)        continue;
270
271                         // Check Source Port
272                         if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
273
274                         // Check Source IP
275                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
276                                 continue;
277                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
278                                 continue;
279
280                         TCP_INT_HandleConnectionPacket(conn, hdr, Length);
281                         return ;
282                 }
283         }
284         
285         Log_Log("TCP", "No Match");
286 }
287
288 /**
289  * \brief Handles a packet sent to a specific connection
290  * \param Connection    TCP Connection pointer
291  * \param Header        TCP Packet pointer
292  * \param Length        Length of the packet
293  */
294 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
295 {       
296         tTCPStoredPacket        *pkt;
297          int    dataLen;
298         
299         if(Header->Flags & TCP_FLAG_SYN) {
300                 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
301         }
302         
303         if( Connection->State == TCP_ST_SYN_SENT )
304         {
305                 if( Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK) ) {
306                         
307                         Header->DestPort = Header->SourcePort;
308                         Header->SourcePort = htons(Connection->LocalPort);
309                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
310                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
311                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
312                         Header->Flags = TCP_FLAG_ACK;
313                         Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
314                         Log_Log("TCP", "ACKing SYN-ACK");
315                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
316                 }
317                 Connection->State = TCP_ST_OPEN;
318         }
319         
320         // Get length of data
321         dataLen = Length - (Header->DataOffset>>4)*4;
322         Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
323         
324         if(Header->Flags & TCP_FLAG_ACK) {
325                 // TODO: Process an ACKed Packet
326                 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
327         }
328         
329         // TODO: Check what to do here
330         if(Header->Flags & TCP_FLAG_FIN) {
331                 if( Connection->State == TCP_ST_FIN_SENT ) {
332                         
333                 }
334                 else {
335                         Connection->State = TCP_ST_FINISHED;
336                         Header->DestPort = Header->SourcePort;
337                         Header->SourcePort = htons(Connection->LocalPort);
338                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
339                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
340                         Header->Flags = TCP_FLAG_ACK;
341                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
342                         return ;
343                 }
344         }
345         
346         if(dataLen == 0) {
347                 Log_Log("TCP", "Empty Packet");
348                 return ;
349         }
350         
351         // NOTES:
352         // Flags
353         //    PSH - Has Data?
354         // /NOTES
355         
356         // Allocate and fill cached packet
357         pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
358         pkt->Next = NULL;
359         pkt->Sequence = ntohl(Header->SequenceNumber);
360         pkt->Length = dataLen;
361         memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
362         
363         // Is this packet the next expected packet?
364         // TODO: Fix this to check if the packet is in the window.
365         if( pkt->Sequence != Connection->NextSequenceRcv )
366         {
367                 tTCPStoredPacket        *tmp, *prev = NULL;
368                 
369                 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
370                         pkt->Sequence, Connection->NextSequenceRcv);
371                 
372                 // No? Well, let's cache it and look at it later
373                 LOCK( &Connection->lFuturePackets );
374                 for(tmp = Connection->FuturePackets;
375                         tmp;
376                         prev = tmp, tmp = tmp->Next)
377                 {
378                         if(tmp->Sequence > pkt->Sequence)       break;
379                 }
380                 if(prev)
381                         prev->Next = pkt;
382                 else
383                         Connection->FuturePackets = pkt;
384                 pkt->Next = tmp;
385                 RELEASE( &Connection->lFuturePackets );
386         }
387         else
388         {
389                 // Ooh, Goodie! Add it to the recieved list
390                 TCP_INT_AppendRecieved(Connection, pkt);
391                 free(pkt);
392                 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
393                 Connection->NextSequenceRcv += dataLen;
394                 
395                 // TODO: This should be moved out of the watcher thread,
396                 // so that a single lost packet on one connection doesn't cause
397                 // all connections on the interface to lag.
398                 TCP_INT_UpdateRecievedFromFuture(Connection);
399         
400                 // ACK Packet
401                 Header->DestPort = Header->SourcePort;
402                 Header->SourcePort = htons(Connection->LocalPort);
403                 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
404                 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
405                 Header->WindowSize = htons(TCP_WINDOW_SIZE);
406                 Header->Flags &= TCP_FLAG_SYN;  // Eliminate all flags save for SYN
407                 Header->Flags |= TCP_FLAG_ACK;  // Add ACK
408                 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
409                 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
410                 //Connection->NextSequenceSend ++;
411         }
412 }
413
414 /**
415  * \brief Appends a packet to the recieved list
416  * \param Connection    Connection structure
417  * \param Pkt   Packet structure on heap
418  */
419 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
420 {
421         LOCK( &Connection->lRecievedPackets );
422         if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
423         {
424                 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
425                 //      TCP_INT_DumpConnection(Connection)
426                         ""
427                         );
428                 return ;
429         }
430         
431         RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
432         
433         RELEASE( &Connection->lRecievedPackets );
434 }
435
436 /**
437  * \brief Updates the connections recieved list from the future list
438  * \param Connection    Connection structure
439  * 
440  * Updates the recieved packets list with packets from the future (out 
441  * of order) packets list that are now able to be added in direct
442  * sequence.
443  */
444 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
445 {
446         tTCPStoredPacket        *pkt, *prev;
447         for(;;)
448         {
449                 prev = NULL;
450                 // Look for the next expected packet in the cache.
451                 LOCK( &Connection->lFuturePackets );
452                 for(pkt = Connection->FuturePackets;
453                         pkt && pkt->Sequence < Connection->NextSequenceRcv;
454                         prev = pkt, pkt = pkt->Next);
455                 
456                 // If we can't find the expected next packet, stop looking
457                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
458                         RELEASE( &Connection->lFuturePackets );
459                         return;
460                 }
461                 
462                 // Delete packet from future list
463                 if(prev)
464                         prev->Next = pkt->Next;
465                 else
466                         Connection->FuturePackets = pkt->Next;
467                 
468                 // Release list
469                 RELEASE( &Connection->lFuturePackets );
470                 
471                 // Looks like we found one
472                 TCP_INT_AppendRecieved(Connection, pkt);
473                 Connection->NextSequenceRcv += pkt->Length;
474                 free(pkt);
475         }
476 }
477
478 /**
479  * \fn Uint16 TCP_GetUnusedPort()
480  * \brief Gets an unused port and allocates it
481  */
482 Uint16 TCP_GetUnusedPort()
483 {
484         Uint16  ret;
485
486         // Get Next outbound port
487         ret = giTCP_NextOutPort++;
488         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
489         {
490                 ret ++;
491                 giTCP_NextOutPort++;
492                 if(giTCP_NextOutPort == 0x10000) {
493                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
494                 }
495         }
496
497         // Mark the new port as used
498         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
499
500         return ret;
501 }
502
503 /**
504  * \fn int TCP_AllocatePort(Uint16 Port)
505  * \brief Marks a port as used
506  */
507 int TCP_AllocatePort(Uint16 Port)
508 {
509         // Check if the port has already been allocated
510         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
511                 return 0;
512
513         // Allocate
514         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
515
516         return 1;
517 }
518
519 /**
520  * \fn int TCP_DeallocatePort(Uint16 Port)
521  * \brief Marks a port as unused
522  */
523 int TCP_DeallocatePort(Uint16 Port)
524 {
525         // Check if the port has already been allocated
526         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
527                 return 0;
528
529         // Allocate
530         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
531
532         return 1;
533 }
534
535 // --- Server
536 tVFS_Node *TCP_Server_Init(tInterface *Interface)
537 {
538         tTCPListener    *srv;
539         
540         srv = malloc( sizeof(tTCPListener) );
541
542         if( srv == NULL ) {
543                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
544                 return NULL;
545         }
546
547         srv->Interface = Interface;
548         srv->Port = 0;
549         srv->NextID = 0;
550         srv->Connections = NULL;
551         srv->ConnectionsTail = NULL;
552         srv->NewConnections = NULL;
553         srv->Next = NULL;
554         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
555         srv->Node.Size = -1;
556         srv->Node.ImplPtr = srv;
557         srv->Node.NumACLs = 1;
558         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
559         srv->Node.ReadDir = TCP_Server_ReadDir;
560         srv->Node.FindDir = TCP_Server_FindDir;
561         srv->Node.IOCtl = TCP_Server_IOCtl;
562         srv->Node.Close = TCP_Server_Close;
563
564         LOCK(&glTCP_Listeners);
565         srv->Next = gTCP_Listeners;
566         gTCP_Listeners = srv;
567         RELEASE(&glTCP_Listeners);
568
569         return &srv->Node;
570 }
571
572 /**
573  * \brief Wait for a new connection and return the connection ID
574  * \note Blocks until a new connection is made
575  * \param Node  Server node
576  * \param Pos   Position (ignored)
577  */
578 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
579 {
580         tTCPListener    *srv = Node->ImplPtr;
581         tTCPConnection  *conn;
582         char    *ret;
583         
584         ENTER("pNode iPos", Node, Pos);
585
586         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
587         for(;;)
588         {
589                 LOCK( &srv->lConnections );
590                 if( srv->NewConnections != NULL )       break;
591                 RELEASE( &srv->lConnections );
592                 Threads_Yield();
593                 continue;
594         }
595         
596
597         // Increment the new list (the current connection is still on the 
598         // normal list)
599         conn = srv->NewConnections;
600         srv->NewConnections = conn->Next;
601         
602         LOG("conn = %p", conn);
603         LOG("srv->Connections = %p", srv->Connections);
604         LOG("srv->NewConnections = %p", srv->NewConnections);
605         LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
606         
607         RELEASE( &srv->lConnections );
608
609         ret = malloc(9);
610         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
611         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
612         LEAVE('s', ret);
613         return ret;
614 }
615
616 /**
617  * \brief Gets a client connection node
618  * \param Node  Server node
619  * \param Name  Hexadecimal ID of the node
620  */
621 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
622 {
623         tTCPConnection  *conn;
624         tTCPListener    *srv = Node->ImplPtr;
625         char    tmp[9];
626          int    id = atoi(Name);
627         
628         ENTER("pNode sName", Node, Name);
629         
630         // Sanity Check
631         itoa(tmp, id, 16, 8, '0');
632         if(strcmp(tmp, Name) != 0) {
633                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
634                 LEAVE('n');
635                 return NULL;
636         }
637         
638         Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
639         Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
640         Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
641         
642         // Search
643         LOCK( &srv->lConnections );
644         for(conn = srv->Connections;
645                 conn;
646                 conn = conn->Next)
647         {
648                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
649                 if(conn->Node.ImplInt == id)    break;
650         }
651         RELEASE( &srv->lConnections );
652         
653         // If not found, ret NULL
654         if(!conn) {
655                 LOG("Connection %i not found", id);
656                 LEAVE('n');
657                 return NULL;
658         }
659         
660         // Return node
661         LEAVE('p', &conn->Node);
662         return &conn->Node;
663 }
664
665 /**
666  * \brief Handle IOCtl calls
667  */
668 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
669 {
670         tTCPListener    *srv = Node->ImplPtr;
671
672         switch(ID)
673         {
674         case 4: // Get/Set Port
675                 if(!Data)       // Get Port
676                         return srv->Port;
677
678                 if(srv->Port)   // Wait, you can't CHANGE the port
679                         return -1;
680
681                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
682                         return -1;
683
684                 // Permissions check
685                 if(Threads_GetUID() != 0
686                 && *(Uint16*)Data != 0
687                 && *(Uint16*)Data < 1024)
688                         return -1;
689
690                 // TODO: Check if a port is in use
691
692                 // Set Port
693                 srv->Port = *(Uint16*)Data;
694                 if(srv->Port == 0)      // Allocate a random port
695                         srv->Port = TCP_GetUnusedPort();
696                 else    // Else, mark this as used
697                         TCP_AllocatePort(srv->Port);
698                 
699                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
700                 
701                 return srv->Port;
702         }
703         return 0;
704 }
705
706 void TCP_Server_Close(tVFS_Node *Node)
707 {
708         free(Node->ImplPtr);
709 }
710
711 // --- Client
712 /**
713  * \brief Create a client node
714  */
715 tVFS_Node *TCP_Client_Init(tInterface *Interface)
716 {
717         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
718
719         conn->State = TCP_ST_CLOSED;
720         conn->Interface = Interface;
721         conn->LocalPort = -1;
722         conn->RemotePort = -1;
723         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
724
725         conn->Node.ImplPtr = conn;
726         conn->Node.NumACLs = 1;
727         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
728         conn->Node.Read = TCP_Client_Read;
729         conn->Node.Write = TCP_Client_Write;
730         conn->Node.IOCtl = TCP_Client_IOCtl;
731         conn->Node.Close = TCP_Client_Close;
732
733         LOCK(&glTCP_OutbountCons);
734         conn->Next = gTCP_OutbountCons;
735         gTCP_OutbountCons = conn;
736         RELEASE(&glTCP_OutbountCons);
737
738         return &conn->Node;
739 }
740
741 /**
742  * \brief Wait for a packet and return it
743  * \note If \a Length is smaller than the size of the packet, the rest
744  *       of the packet's data will be discarded.
745  */
746 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
747 {
748         tTCPConnection  *conn = Node->ImplPtr;
749         char    *destbuf = Buffer;
750         size_t  len;
751         
752         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
753         
754         // Check if connection is open
755         while( conn->State == TCP_ST_HALFOPEN ) Threads_Yield();
756         if( conn->State != TCP_ST_OPEN ) {
757                 LEAVE('i', 0);
758                 return 0;
759         }
760         
761         // Poll packets
762         for(;;)
763         {
764                 // Lock list and check if there is a packet
765                 LOCK( &conn->lRecievedPackets );
766                 if( conn->RecievedBuffer->Length == 0 ) {
767                         // If not, release the lock, yield and try again
768                         RELEASE( &conn->lRecievedPackets );
769                         Threads_Yield();
770                         continue;
771                 }
772                 
773                 // Attempt to read all `Length` bytes
774                 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
775                 
776                 // Release the lock (we don't need it any more)
777                 RELEASE( &conn->lRecievedPackets );
778         
779                 LEAVE('i', len);
780                 return len;
781         }
782 }
783
784 /**
785  * \brief Send a data packet on a connection
786  */
787 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
788 {
789         char    buf[sizeof(tTCPHeader)+Length];
790         tTCPHeader      *packet = (void*)buf;
791         
792         packet->SourcePort = htons(Connection->LocalPort);
793         packet->DestPort = htons(Connection->RemotePort);
794         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
795         packet->WindowSize = TCP_WINDOW_SIZE;
796         
797         //packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
798         packet->AcknowlegementNumber = 0;
799         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
800         packet->Flags = TCP_FLAG_PSH;   // Hey, ACK if you can!
801         
802         memcpy(packet->Options, Data, Length);
803         
804         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
805         
806         Connection->NextSequenceSend += Length;
807 }
808
809 /**
810  * \brief Send some bytes on a connection
811  */
812 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
813 {
814         tTCPConnection  *conn = Node->ImplPtr;
815         size_t  rem = Length;
816         
817         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
818         
819         // Check if connection is open
820         while( conn->State == TCP_ST_HALFOPEN ) Threads_Yield();
821         if( conn->State != TCP_ST_OPEN ) {
822                 LEAVE('i', 0);
823                 return 0;
824         }
825         
826         while( rem > TCP_MAX_PACKET_SIZE )
827         {
828                 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
829                 Buffer += TCP_MAX_PACKET_SIZE;
830         }
831         
832         TCP_INT_SendDataPacket(conn, rem, Buffer);
833         
834         LEAVE('i', Length);
835         return Length;
836 }
837
838 /**
839  * \brief Control a client socket
840  */
841 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
842 {
843         tTCPConnection  *conn = Node->ImplPtr;
844
845         switch(ID)
846         {
847         case 4: // Get/Set local port
848                 if(!Data)
849                         return conn->LocalPort;
850                 if(conn->State != TCP_ST_CLOSED)
851                         return -1;
852                 if(!CheckMem(Data, sizeof(Uint16)))
853                         return -1;
854
855                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
856                         return -1;
857
858                 conn->LocalPort = *(Uint16*)Data;
859                 return 0;
860
861         case 5: // Get/Set remote port
862                 if(!Data)       return conn->RemotePort;
863                 if(conn->State != TCP_ST_CLOSED)        return -1;
864                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
865                 conn->RemotePort = *(Uint16*)Data;
866                 return 0;
867
868         case 6: // Set Remote IP
869                 if( conn->State != TCP_ST_CLOSED )
870                         return -1;
871                 if( conn->Interface->Type == 4 )
872                 {
873                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
874                         conn->RemoteIP.v4 = *(tIPv4*)Data;
875                 }
876                 else if( conn->Interface->Type == 6 )
877                 {
878                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
879                         conn->RemoteIP.v6 = *(tIPv6*)Data;
880                 }
881                 return 0;
882
883         case 7: // Connect
884                 if(conn->LocalPort == -1)
885                         conn->LocalPort = TCP_GetUnusedPort();
886                 if(conn->RemotePort == -1)
887                         return 0;
888
889                 TCP_StartConnection(conn);
890                 return 1;
891         }
892
893         return 0;
894 }
895
896 void TCP_Client_Close(tVFS_Node *Node)
897 {
898         free(Node->ImplPtr);
899 }

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