Lots of work on the AcessNative kernel
[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 = 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", "SourcePort = %i, DestPort = %i",
108                 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
109 /*
110         Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
111         Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
112         Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
113         Log_Log("TCP", "Flags = {");
114         Log_Log("TCP", "  CWR = %B, ECE = %B",
115                 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
116         Log_Log("TCP", "  URG = %B, ACK = %B",
117                 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
118         Log_Log("TCP", "  PSH = %B, RST = %B",
119                 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
120         Log_Log("TCP", "  SYN = %B, FIN = %B",
121                 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
122         Log_Log("TCP", "}");
123         Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
124         Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
125         Log_Log("TCP", "UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
126 */
127         Log_Log("TCP", "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", "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", "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", "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", "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", "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", "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", "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         if(Header->Flags & TCP_FLAG_SYN) {
286                 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber) + 1;
287         }
288         
289         if( Connection->State == TCP_ST_SYN_SENT )
290         {
291                 if( (Header->Flags & (TCP_FLAG_SYN|TCP_FLAG_ACK)) == (TCP_FLAG_SYN|TCP_FLAG_ACK) ) {
292                         
293                         Header->DestPort = Header->SourcePort;
294                         Header->SourcePort = htons(Connection->LocalPort);
295                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
296                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
297                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
298                         Header->Flags = TCP_FLAG_ACK;
299                         Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
300                         Log_Log("TCP", "ACKing SYN-ACK");
301                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
302                         Connection->State = TCP_ST_OPEN;
303                 }
304         }
305         
306         // Get length of data
307         dataLen = Length - (Header->DataOffset>>4)*4;
308         Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
309         
310         if(Header->Flags & TCP_FLAG_ACK) {
311                 // TODO: Process an ACKed Packet
312                 Log_Log("TCP", "Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
313         }
314         
315         // TODO: Check what to do here
316         if(Header->Flags & TCP_FLAG_FIN) {
317                 if( Connection->State == TCP_ST_FIN_SENT ) {
318                         Connection->State = TCP_ST_FINISHED;
319                         return ;
320                 }
321                 else {
322                         Connection->State = TCP_ST_FINISHED;
323                         Header->DestPort = Header->SourcePort;
324                         Header->SourcePort = htons(Connection->LocalPort);
325                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
326                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
327                         Header->Flags = TCP_FLAG_ACK;
328                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
329                         return ;
330                 }
331         }
332         
333         if(dataLen == 0) {
334                 Log_Log("TCP", "Empty Packet");
335                 return ;
336         }
337         
338         // NOTES:
339         // Flags
340         //    PSH - Has Data?
341         // /NOTES
342         
343         // Allocate and fill cached packet
344         pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
345         pkt->Next = NULL;
346         pkt->Sequence = ntohl(Header->SequenceNumber);
347         pkt->Length = dataLen;
348         memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
349         
350         // Is this packet the next expected packet?
351         // TODO: Fix this to check if the packet is in the window.
352         if( pkt->Sequence != Connection->NextSequenceRcv )
353         {
354                 tTCPStoredPacket        *tmp, *prev = NULL;
355                 
356                 Log_Log("TCP", "Out of sequence packet (0x%08x != 0x%08x)",
357                         pkt->Sequence, Connection->NextSequenceRcv);
358                 
359                 // No? Well, let's cache it and look at it later
360                 SHORTLOCK( &Connection->lFuturePackets );
361                 for(tmp = Connection->FuturePackets;
362                         tmp;
363                         prev = tmp, tmp = tmp->Next)
364                 {
365                         if(tmp->Sequence > pkt->Sequence)       break;
366                 }
367                 if(prev)
368                         prev->Next = pkt;
369                 else
370                         Connection->FuturePackets = pkt;
371                 pkt->Next = tmp;
372                 SHORTREL( &Connection->lFuturePackets );
373         }
374         else
375         {
376                 // Ooh, Goodie! Add it to the recieved list
377                 TCP_INT_AppendRecieved(Connection, pkt);
378                 free(pkt);
379                 Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
380                 Connection->NextSequenceRcv += dataLen;
381                 
382                 // TODO: This should be moved out of the watcher thread,
383                 // so that a single lost packet on one connection doesn't cause
384                 // all connections on the interface to lag.
385                 TCP_INT_UpdateRecievedFromFuture(Connection);
386         
387                 // ACK Packet
388                 Header->DestPort = Header->SourcePort;
389                 Header->SourcePort = htons(Connection->LocalPort);
390                 Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
391                 Header->SequenceNumber = htonl(Connection->NextSequenceSend);
392                 Header->WindowSize = htons(TCP_WINDOW_SIZE);
393                 Header->Flags &= TCP_FLAG_SYN;  // Eliminate all flags save for SYN
394                 Header->Flags |= TCP_FLAG_ACK;  // Add ACK
395                 Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
396                 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
397                 //Connection->NextSequenceSend ++;
398         }
399 }
400
401 /**
402  * \brief Appends a packet to the recieved list
403  * \param Connection    Connection structure
404  * \param Pkt   Packet structure on heap
405  */
406 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
407 {
408         Mutex_Acquire( &Connection->lRecievedPackets );
409         if(Connection->RecievedBuffer->Length + Pkt->Length > Connection->RecievedBuffer->Space )
410         {
411                 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
412                 //      TCP_INT_DumpConnection(Connection)
413                         ""
414                         );
415                 return ;
416         }
417         
418         RingBuffer_Write( Connection->RecievedBuffer, Pkt->Data, Pkt->Length );
419         
420         Mutex_Release( &Connection->lRecievedPackets );
421 }
422
423 /**
424  * \brief Updates the connections recieved list from the future list
425  * \param Connection    Connection structure
426  * 
427  * Updates the recieved packets list with packets from the future (out 
428  * of order) packets list that are now able to be added in direct
429  * sequence.
430  */
431 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
432 {
433         tTCPStoredPacket        *pkt, *prev;
434         for(;;)
435         {
436                 prev = NULL;
437                 // Look for the next expected packet in the cache.
438                 SHORTLOCK( &Connection->lFuturePackets );
439                 for(pkt = Connection->FuturePackets;
440                         pkt && pkt->Sequence < Connection->NextSequenceRcv;
441                         prev = pkt, pkt = pkt->Next);
442                 
443                 // If we can't find the expected next packet, stop looking
444                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
445                         SHORTREL( &Connection->lFuturePackets );
446                         return;
447                 }
448                 
449                 // Delete packet from future list
450                 if(prev)
451                         prev->Next = pkt->Next;
452                 else
453                         Connection->FuturePackets = pkt->Next;
454                 
455                 // Release list
456                 SHORTREL( &Connection->lFuturePackets );
457                 
458                 // Looks like we found one
459                 TCP_INT_AppendRecieved(Connection, pkt);
460                 Connection->NextSequenceRcv += pkt->Length;
461                 free(pkt);
462         }
463 }
464
465 /**
466  * \fn Uint16 TCP_GetUnusedPort()
467  * \brief Gets an unused port and allocates it
468  */
469 Uint16 TCP_GetUnusedPort()
470 {
471         Uint16  ret;
472
473         // Get Next outbound port
474         ret = giTCP_NextOutPort++;
475         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
476         {
477                 ret ++;
478                 giTCP_NextOutPort++;
479                 if(giTCP_NextOutPort == 0x10000) {
480                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
481                 }
482         }
483
484         // Mark the new port as used
485         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
486
487         return ret;
488 }
489
490 /**
491  * \fn int TCP_AllocatePort(Uint16 Port)
492  * \brief Marks a port as used
493  */
494 int TCP_AllocatePort(Uint16 Port)
495 {
496         // Check if the port has already been allocated
497         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
498                 return 0;
499
500         // Allocate
501         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
502
503         return 1;
504 }
505
506 /**
507  * \fn int TCP_DeallocatePort(Uint16 Port)
508  * \brief Marks a port as unused
509  */
510 int TCP_DeallocatePort(Uint16 Port)
511 {
512         // Check if the port has already been allocated
513         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
514                 return 0;
515
516         // Allocate
517         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
518
519         return 1;
520 }
521
522 // --- Server
523 tVFS_Node *TCP_Server_Init(tInterface *Interface)
524 {
525         tTCPListener    *srv;
526         
527         srv = malloc( sizeof(tTCPListener) );
528
529         if( srv == NULL ) {
530                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
531                 return NULL;
532         }
533
534         srv->Interface = Interface;
535         srv->Port = 0;
536         srv->NextID = 0;
537         srv->Connections = NULL;
538         srv->ConnectionsTail = NULL;
539         srv->NewConnections = NULL;
540         srv->Next = NULL;
541         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
542         srv->Node.Size = -1;
543         srv->Node.ImplPtr = srv;
544         srv->Node.NumACLs = 1;
545         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
546         srv->Node.ReadDir = TCP_Server_ReadDir;
547         srv->Node.FindDir = TCP_Server_FindDir;
548         srv->Node.IOCtl = TCP_Server_IOCtl;
549         srv->Node.Close = TCP_Server_Close;
550
551         SHORTLOCK(&glTCP_Listeners);
552         srv->Next = gTCP_Listeners;
553         gTCP_Listeners = srv;
554         SHORTREL(&glTCP_Listeners);
555
556         return &srv->Node;
557 }
558
559 /**
560  * \brief Wait for a new connection and return the connection ID
561  * \note Blocks until a new connection is made
562  * \param Node  Server node
563  * \param Pos   Position (ignored)
564  */
565 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
566 {
567         tTCPListener    *srv = Node->ImplPtr;
568         tTCPConnection  *conn;
569         char    *ret;
570         
571         ENTER("pNode iPos", Node, Pos);
572
573         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
574         for(;;)
575         {
576                 SHORTLOCK( &srv->lConnections );
577                 if( srv->NewConnections != NULL )       break;
578                 SHORTREL( &srv->lConnections );
579                 Threads_Yield();        // TODO: Sleep until poked
580                 continue;
581         }
582         
583
584         // Increment the new list (the current connection is still on the 
585         // normal list)
586         conn = srv->NewConnections;
587         srv->NewConnections = conn->Next;
588         
589         SHORTREL( &srv->lConnections );
590         
591         LOG("conn = %p", conn);
592         LOG("srv->Connections = %p", srv->Connections);
593         LOG("srv->NewConnections = %p", srv->NewConnections);
594         LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
595
596         ret = malloc(9);
597         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
598         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
599         LEAVE('s', ret);
600         return ret;
601 }
602
603 /**
604  * \brief Gets a client connection node
605  * \param Node  Server node
606  * \param Name  Hexadecimal ID of the node
607  */
608 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
609 {
610         tTCPConnection  *conn;
611         tTCPListener    *srv = Node->ImplPtr;
612         char    tmp[9];
613          int    id = atoi(Name);
614         
615         ENTER("pNode sName", Node, Name);
616         
617         // Sanity Check
618         itoa(tmp, id, 16, 8, '0');
619         if(strcmp(tmp, Name) != 0) {
620                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
621                 LEAVE('n');
622                 return NULL;
623         }
624         
625         Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
626         Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
627         Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
628         
629         // Search
630         SHORTLOCK( &srv->lConnections );
631         for(conn = srv->Connections;
632                 conn;
633                 conn = conn->Next)
634         {
635                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
636                 if(conn->Node.ImplInt == id)    break;
637         }
638         SHORTREL( &srv->lConnections );
639         
640         // If not found, ret NULL
641         if(!conn) {
642                 LOG("Connection %i not found", id);
643                 LEAVE('n');
644                 return NULL;
645         }
646         
647         // Return node
648         LEAVE('p', &conn->Node);
649         return &conn->Node;
650 }
651
652 /**
653  * \brief Handle IOCtl calls
654  */
655 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
656 {
657         tTCPListener    *srv = Node->ImplPtr;
658
659         switch(ID)
660         {
661         case 4: // Get/Set Port
662                 if(!Data)       // Get Port
663                         return srv->Port;
664
665                 if(srv->Port)   // Wait, you can't CHANGE the port
666                         return -1;
667
668                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
669                         return -1;
670
671                 // Permissions check
672                 if(Threads_GetUID() != 0
673                 && *(Uint16*)Data != 0
674                 && *(Uint16*)Data < 1024)
675                         return -1;
676
677                 // TODO: Check if a port is in use
678
679                 // Set Port
680                 srv->Port = *(Uint16*)Data;
681                 if(srv->Port == 0)      // Allocate a random port
682                         srv->Port = TCP_GetUnusedPort();
683                 else    // Else, mark this as used
684                         TCP_AllocatePort(srv->Port);
685                 
686                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
687                 
688                 return srv->Port;
689         }
690         return 0;
691 }
692
693 void TCP_Server_Close(tVFS_Node *Node)
694 {
695         free(Node->ImplPtr);
696 }
697
698 // --- Client
699 /**
700  * \brief Create a client node
701  */
702 tVFS_Node *TCP_Client_Init(tInterface *Interface)
703 {
704         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
705
706         conn->State = TCP_ST_CLOSED;
707         conn->Interface = Interface;
708         conn->LocalPort = -1;
709         conn->RemotePort = -1;
710         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
711
712         conn->Node.ImplPtr = conn;
713         conn->Node.NumACLs = 1;
714         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
715         conn->Node.Read = TCP_Client_Read;
716         conn->Node.Write = TCP_Client_Write;
717         conn->Node.IOCtl = TCP_Client_IOCtl;
718         conn->Node.Close = TCP_Client_Close;
719
720         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
721
722         SHORTLOCK(&glTCP_OutbountCons);
723         conn->Next = gTCP_OutbountCons;
724         gTCP_OutbountCons = conn;
725         SHORTREL(&glTCP_OutbountCons);
726
727         return &conn->Node;
728 }
729
730 /**
731  * \brief Wait for a packet and return it
732  * \note If \a Length is smaller than the size of the packet, the rest
733  *       of the packet's data will be discarded.
734  */
735 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
736 {
737         tTCPConnection  *conn = Node->ImplPtr;
738         char    *destbuf = Buffer;
739         size_t  len;
740         
741         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
742         LOG("conn = %p", conn);
743         LOG("conn->State = %i", conn->State);
744         
745         // Check if connection is open
746         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
747                 Threads_Yield();
748         if( conn->State != TCP_ST_OPEN ) {
749                 LEAVE('i', 0);
750                 return 0;
751         }
752         
753         // Poll packets
754         for(;;)
755         {
756                 // Lock list and check if there is a packet
757                 Mutex_Acquire( &conn->lRecievedPackets );
758                 if( conn->RecievedBuffer->Length == 0 ) {
759                         // If not, release the lock, yield and try again
760                         Mutex_Release( &conn->lRecievedPackets );
761                         Threads_Yield();        // TODO: Less expensive wait
762                         continue;
763                 }
764                 
765                 // Attempt to read all `Length` bytes
766                 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
767                 
768                 // Release the lock (we don't need it any more)
769                 Mutex_Release( &conn->lRecievedPackets );
770         
771                 LEAVE('i', len);
772                 return len;
773         }
774 }
775
776 /**
777  * \brief Send a data packet on a connection
778  */
779 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
780 {
781         char    buf[sizeof(tTCPHeader)+Length];
782         tTCPHeader      *packet = (void*)buf;
783         
784         packet->SourcePort = htons(Connection->LocalPort);
785         packet->DestPort = htons(Connection->RemotePort);
786         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
787         packet->WindowSize = TCP_WINDOW_SIZE;
788         
789         packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
790         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
791         packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK;      // Hey, ACK if you can!
792         
793         memcpy(packet->Options, Data, Length);
794         
795         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
796         
797         Connection->NextSequenceSend += Length;
798 }
799
800 /**
801  * \brief Send some bytes on a connection
802  */
803 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
804 {
805         tTCPConnection  *conn = Node->ImplPtr;
806         size_t  rem = Length;
807         
808         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
809         
810         // Check if connection is open
811         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
812                 Threads_Yield();
813         if( conn->State != TCP_ST_OPEN ) {
814                 LEAVE('i', 0);
815                 return 0;
816         }
817         
818         while( rem > TCP_MAX_PACKET_SIZE )
819         {
820                 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
821                 Buffer += TCP_MAX_PACKET_SIZE;
822         }
823         
824         TCP_INT_SendDataPacket(conn, rem, Buffer);
825         
826         LEAVE('i', Length);
827         return Length;
828 }
829
830 /**
831  * \brief Open a connection to another host using TCP
832  * \param Conn  Connection structure
833  */
834 void TCP_StartConnection(tTCPConnection *Conn)
835 {
836         tTCPHeader      hdr = {0};
837
838         Conn->State = TCP_ST_SYN_SENT;
839
840         hdr.SourcePort = htons(Conn->LocalPort);
841         hdr.DestPort = htons(Conn->RemotePort);
842         Conn->NextSequenceSend = rand();
843         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
844         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
845         hdr.Flags = TCP_FLAG_SYN;
846         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
847         hdr.Checksum = 0;       // TODO
848         
849         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
850         
851         Conn->NextSequenceSend ++;
852         Conn->State = TCP_ST_SYN_SENT;
853         return ;
854 }
855
856 /**
857  * \brief Control a client socket
858  */
859 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
860 {
861         tTCPConnection  *conn = Node->ImplPtr;
862
863         switch(ID)
864         {
865         case 4: // Get/Set local port
866                 if(!Data)
867                         return conn->LocalPort;
868                 if(conn->State != TCP_ST_CLOSED)
869                         return -1;
870                 if(!CheckMem(Data, sizeof(Uint16)))
871                         return -1;
872
873                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
874                         return -1;
875
876                 conn->LocalPort = *(Uint16*)Data;
877                 return 0;
878
879         case 5: // Get/Set remote port
880                 if(!Data)       return conn->RemotePort;
881                 if(conn->State != TCP_ST_CLOSED)        return -1;
882                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
883                 conn->RemotePort = *(Uint16*)Data;
884                 return conn->RemotePort;
885
886         case 6: // Set Remote IP
887                 if( conn->State != TCP_ST_CLOSED )
888                         return -1;
889                 if( conn->Interface->Type == 4 )
890                 {
891                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
892                         conn->RemoteIP.v4 = *(tIPv4*)Data;
893                 }
894                 else if( conn->Interface->Type == 6 )
895                 {
896                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
897                         conn->RemoteIP.v6 = *(tIPv6*)Data;
898                 }
899                 return 0;
900
901         case 7: // Connect
902                 if(conn->LocalPort == 0xFFFF)
903                         conn->LocalPort = TCP_GetUnusedPort();
904                 if(conn->RemotePort == -1)
905                         return 0;
906
907                 TCP_StartConnection(conn);
908                 return 1;
909         
910         // Get recieve buffer length
911         case 8:
912                 return conn->RecievedBuffer->Length;
913         }
914
915         return 0;
916 }
917
918 void TCP_Client_Close(tVFS_Node *Node)
919 {
920         tTCPConnection  *conn = Node->ImplPtr;
921         tTCPHeader      packet;
922         
923         packet.SourcePort = htons(conn->LocalPort);
924         packet.DestPort = htons(conn->RemotePort);
925         packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
926         packet.WindowSize = TCP_WINDOW_SIZE;
927         
928         packet.AcknowlegementNumber = 0;
929         packet.SequenceNumber = htonl(conn->NextSequenceSend);
930         packet.Flags = TCP_FLAG_FIN;
931         
932         conn->State = TCP_ST_FIN_SENT;
933         
934         TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
935         
936         while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();
937         
938         free(conn);
939 }

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