IPStack - Bugfixing (and testing IRC client)
[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         Mutex_Release( &Connection->lRecievedPackets );
431 }
432
433 /**
434  * \brief Updates the connections recieved list from the future list
435  * \param Connection    Connection structure
436  * 
437  * Updates the recieved packets list with packets from the future (out 
438  * of order) packets list that are now able to be added in direct
439  * sequence.
440  */
441 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
442 {
443         tTCPStoredPacket        *pkt, *prev;
444         for(;;)
445         {
446                 prev = NULL;
447                 // Look for the next expected packet in the cache.
448                 SHORTLOCK( &Connection->lFuturePackets );
449                 for(pkt = Connection->FuturePackets;
450                         pkt && pkt->Sequence < Connection->NextSequenceRcv;
451                         prev = pkt, pkt = pkt->Next);
452                 
453                 // If we can't find the expected next packet, stop looking
454                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
455                         SHORTREL( &Connection->lFuturePackets );
456                         return;
457                 }
458                 
459                 // Delete packet from future list
460                 if(prev)
461                         prev->Next = pkt->Next;
462                 else
463                         Connection->FuturePackets = pkt->Next;
464                 
465                 // Release list
466                 SHORTREL( &Connection->lFuturePackets );
467                 
468                 // Looks like we found one
469                 TCP_INT_AppendRecieved(Connection, pkt);
470                 Connection->NextSequenceRcv += pkt->Length;
471                 free(pkt);
472         }
473 }
474
475 /**
476  * \fn Uint16 TCP_GetUnusedPort()
477  * \brief Gets an unused port and allocates it
478  */
479 Uint16 TCP_GetUnusedPort()
480 {
481         Uint16  ret;
482
483         // Get Next outbound port
484         ret = giTCP_NextOutPort++;
485         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
486         {
487                 ret ++;
488                 giTCP_NextOutPort++;
489                 if(giTCP_NextOutPort == 0x10000) {
490                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
491                 }
492         }
493
494         // Mark the new port as used
495         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
496
497         return ret;
498 }
499
500 /**
501  * \fn int TCP_AllocatePort(Uint16 Port)
502  * \brief Marks a port as used
503  */
504 int TCP_AllocatePort(Uint16 Port)
505 {
506         // Check if the port has already been allocated
507         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
508                 return 0;
509
510         // Allocate
511         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
512
513         return 1;
514 }
515
516 /**
517  * \fn int TCP_DeallocatePort(Uint16 Port)
518  * \brief Marks a port as unused
519  */
520 int TCP_DeallocatePort(Uint16 Port)
521 {
522         // Check if the port has already been allocated
523         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
524                 return 0;
525
526         // Allocate
527         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
528
529         return 1;
530 }
531
532 // --- Server
533 tVFS_Node *TCP_Server_Init(tInterface *Interface)
534 {
535         tTCPListener    *srv;
536         
537         srv = malloc( sizeof(tTCPListener) );
538
539         if( srv == NULL ) {
540                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
541                 return NULL;
542         }
543
544         srv->Interface = Interface;
545         srv->Port = 0;
546         srv->NextID = 0;
547         srv->Connections = NULL;
548         srv->ConnectionsTail = NULL;
549         srv->NewConnections = NULL;
550         srv->Next = NULL;
551         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
552         srv->Node.Size = -1;
553         srv->Node.ImplPtr = srv;
554         srv->Node.NumACLs = 1;
555         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
556         srv->Node.ReadDir = TCP_Server_ReadDir;
557         srv->Node.FindDir = TCP_Server_FindDir;
558         srv->Node.IOCtl = TCP_Server_IOCtl;
559         srv->Node.Close = TCP_Server_Close;
560
561         SHORTLOCK(&glTCP_Listeners);
562         srv->Next = gTCP_Listeners;
563         gTCP_Listeners = srv;
564         SHORTREL(&glTCP_Listeners);
565
566         return &srv->Node;
567 }
568
569 /**
570  * \brief Wait for a new connection and return the connection ID
571  * \note Blocks until a new connection is made
572  * \param Node  Server node
573  * \param Pos   Position (ignored)
574  */
575 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
576 {
577         tTCPListener    *srv = Node->ImplPtr;
578         tTCPConnection  *conn;
579         char    *ret;
580         
581         ENTER("pNode iPos", Node, Pos);
582
583         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
584         for(;;)
585         {
586                 SHORTLOCK( &srv->lConnections );
587                 if( srv->NewConnections != NULL )       break;
588                 SHORTREL( &srv->lConnections );
589                 Threads_Yield();        // TODO: Sleep until poked
590                 continue;
591         }
592         
593
594         // Increment the new list (the current connection is still on the 
595         // normal list)
596         conn = srv->NewConnections;
597         srv->NewConnections = conn->Next;
598         
599         SHORTREL( &srv->lConnections );
600         
601         LOG("conn = %p", conn);
602         LOG("srv->Connections = %p", srv->Connections);
603         LOG("srv->NewConnections = %p", srv->NewConnections);
604         LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
605
606         ret = malloc(9);
607         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
608         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
609         LEAVE('s', ret);
610         return ret;
611 }
612
613 /**
614  * \brief Gets a client connection node
615  * \param Node  Server node
616  * \param Name  Hexadecimal ID of the node
617  */
618 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
619 {
620         tTCPConnection  *conn;
621         tTCPListener    *srv = Node->ImplPtr;
622         char    tmp[9];
623          int    id = atoi(Name);
624         
625         ENTER("pNode sName", Node, Name);
626         
627         // Sanity Check
628         itoa(tmp, id, 16, 8, '0');
629         if(strcmp(tmp, Name) != 0) {
630                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
631                 LEAVE('n');
632                 return NULL;
633         }
634         
635         Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
636         Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
637         Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
638         
639         // Search
640         SHORTLOCK( &srv->lConnections );
641         for(conn = srv->Connections;
642                 conn;
643                 conn = conn->Next)
644         {
645                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
646                 if(conn->Node.ImplInt == id)    break;
647         }
648         SHORTREL( &srv->lConnections );
649         
650         // If not found, ret NULL
651         if(!conn) {
652                 LOG("Connection %i not found", id);
653                 LEAVE('n');
654                 return NULL;
655         }
656         
657         // Return node
658         LEAVE('p', &conn->Node);
659         return &conn->Node;
660 }
661
662 /**
663  * \brief Handle IOCtl calls
664  */
665 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
666 {
667         tTCPListener    *srv = Node->ImplPtr;
668
669         switch(ID)
670         {
671         case 4: // Get/Set Port
672                 if(!Data)       // Get Port
673                         return srv->Port;
674
675                 if(srv->Port)   // Wait, you can't CHANGE the port
676                         return -1;
677
678                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
679                         return -1;
680
681                 // Permissions check
682                 if(Threads_GetUID() != 0
683                 && *(Uint16*)Data != 0
684                 && *(Uint16*)Data < 1024)
685                         return -1;
686
687                 // TODO: Check if a port is in use
688
689                 // Set Port
690                 srv->Port = *(Uint16*)Data;
691                 if(srv->Port == 0)      // Allocate a random port
692                         srv->Port = TCP_GetUnusedPort();
693                 else    // Else, mark this as used
694                         TCP_AllocatePort(srv->Port);
695                 
696                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
697                 
698                 return srv->Port;
699         }
700         return 0;
701 }
702
703 void TCP_Server_Close(tVFS_Node *Node)
704 {
705         free(Node->ImplPtr);
706 }
707
708 // --- Client
709 /**
710  * \brief Create a client node
711  */
712 tVFS_Node *TCP_Client_Init(tInterface *Interface)
713 {
714         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
715
716         conn->State = TCP_ST_CLOSED;
717         conn->Interface = Interface;
718         conn->LocalPort = -1;
719         conn->RemotePort = -1;
720         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
721
722         conn->Node.ImplPtr = conn;
723         conn->Node.NumACLs = 1;
724         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
725         conn->Node.Read = TCP_Client_Read;
726         conn->Node.Write = TCP_Client_Write;
727         conn->Node.IOCtl = TCP_Client_IOCtl;
728         conn->Node.Close = TCP_Client_Close;
729
730         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
731
732         SHORTLOCK(&glTCP_OutbountCons);
733         conn->Next = gTCP_OutbountCons;
734         gTCP_OutbountCons = conn;
735         SHORTREL(&glTCP_OutbountCons);
736
737         return &conn->Node;
738 }
739
740 /**
741  * \brief Wait for a packet and return it
742  * \note If \a Length is smaller than the size of the packet, the rest
743  *       of the packet's data will be discarded.
744  */
745 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
746 {
747         tTCPConnection  *conn = Node->ImplPtr;
748         char    *destbuf = Buffer;
749         size_t  len;
750         
751         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
752         LOG("conn = %p", conn);
753         LOG("conn->State = %i", conn->State);
754         
755         // Check if connection is open
756         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
757                 Threads_Yield();
758         if( conn->State != TCP_ST_OPEN ) {
759                 LEAVE('i', 0);
760                 return 0;
761         }
762         
763         // Poll packets
764         for(;;)
765         {
766                 // Lock list and check if there is a packet
767                 Mutex_Acquire( &conn->lRecievedPackets );
768                 if( conn->RecievedBuffer->Length == 0 ) {
769                         // If not, release the lock, yield and try again
770                         Mutex_Release( &conn->lRecievedPackets );
771                         Threads_Yield();        // TODO: Less expensive wait
772                         continue;
773                 }
774                 
775                 // Attempt to read all `Length` bytes
776                 len = RingBuffer_Read( destbuf, conn->RecievedBuffer, Length );
777                 
778                 // Release the lock (we don't need it any more)
779                 Mutex_Release( &conn->lRecievedPackets );
780         
781                 LEAVE('i', len);
782                 return len;
783         }
784 }
785
786 /**
787  * \brief Send a data packet on a connection
788  */
789 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
790 {
791         char    buf[sizeof(tTCPHeader)+Length];
792         tTCPHeader      *packet = (void*)buf;
793         
794         packet->SourcePort = htons(Connection->LocalPort);
795         packet->DestPort = htons(Connection->RemotePort);
796         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
797         packet->WindowSize = TCP_WINDOW_SIZE;
798         
799         packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
800         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
801         packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK;      // Hey, ACK if you can!
802         
803         memcpy(packet->Options, Data, Length);
804         
805         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
806         
807         Connection->NextSequenceSend += Length;
808 }
809
810 /**
811  * \brief Send some bytes on a connection
812  */
813 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
814 {
815         tTCPConnection  *conn = Node->ImplPtr;
816         size_t  rem = Length;
817         
818         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
819         
820         // Check if connection is open
821         while( conn->State == TCP_ST_HALFOPEN || conn->State == TCP_ST_SYN_SENT )
822                 Threads_Yield();
823         if( conn->State != TCP_ST_OPEN ) {
824                 LEAVE('i', 0);
825                 return 0;
826         }
827         
828         while( rem > TCP_MAX_PACKET_SIZE )
829         {
830                 TCP_INT_SendDataPacket(conn, TCP_MAX_PACKET_SIZE, Buffer);
831                 Buffer += TCP_MAX_PACKET_SIZE;
832         }
833         
834         TCP_INT_SendDataPacket(conn, rem, Buffer);
835         
836         LEAVE('i', Length);
837         return Length;
838 }
839
840 /**
841  * \brief Open a connection to another host using TCP
842  * \param Conn  Connection structure
843  */
844 void TCP_StartConnection(tTCPConnection *Conn)
845 {
846         tTCPHeader      hdr = {0};
847
848         Conn->State = TCP_ST_SYN_SENT;
849
850         hdr.SourcePort = htons(Conn->LocalPort);
851         hdr.DestPort = htons(Conn->RemotePort);
852         Conn->NextSequenceSend = rand();
853         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
854         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
855         hdr.Flags = TCP_FLAG_SYN;
856         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
857         hdr.Checksum = 0;       // TODO
858         
859         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
860         
861         Conn->NextSequenceSend ++;
862         Conn->State = TCP_ST_SYN_SENT;
863         return ;
864 }
865
866 /**
867  * \brief Control a client socket
868  */
869 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
870 {
871         tTCPConnection  *conn = Node->ImplPtr;
872         
873         ENTER("pNode iID pData", Node, ID, Data);
874
875         switch(ID)
876         {
877         case 4: // Get/Set local port
878                 if(!Data)
879                         LEAVE_RET('i', conn->LocalPort);
880                 if(conn->State != TCP_ST_CLOSED)
881                         LEAVE_RET('i', -1);
882                 if(!CheckMem(Data, sizeof(Uint16)))
883                         LEAVE_RET('i', -1);
884
885                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
886                         LEAVE_RET('i', -1);
887
888                 conn->LocalPort = *(Uint16*)Data;
889                 LEAVE_RET('i', conn->LocalPort);
890
891         case 5: // Get/Set remote port
892                 if(!Data)       LEAVE_RET('i', conn->RemotePort);
893                 if(conn->State != TCP_ST_CLOSED)        LEAVE_RET('i', -1);
894                 if(!CheckMem(Data, sizeof(Uint16)))     LEAVE_RET('i', -1);
895                 conn->RemotePort = *(Uint16*)Data;
896                 LEAVE_RET('i', conn->RemotePort);
897
898         case 6: // Set Remote IP
899                 if( conn->State != TCP_ST_CLOSED )
900                         LEAVE_RET('i', -1);
901                 if( conn->Interface->Type == 4 )
902                 {
903                         if(!CheckMem(Data, sizeof(tIPv4)))      LEAVE_RET('i', -1);
904                         conn->RemoteIP.v4 = *(tIPv4*)Data;
905                 }
906                 else if( conn->Interface->Type == 6 )
907                 {
908                         if(!CheckMem(Data, sizeof(tIPv6)))      LEAVE_RET('i', -1);
909                         conn->RemoteIP.v6 = *(tIPv6*)Data;
910                 }
911                 LEAVE_RET('i', 0);
912
913         case 7: // Connect
914                 if(conn->LocalPort == 0xFFFF)
915                         conn->LocalPort = TCP_GetUnusedPort();
916                 if(conn->RemotePort == -1)
917                         LEAVE_RET('i', 0);
918
919                 TCP_StartConnection(conn);
920                 LEAVE_RET('i', 1);
921         
922         // Get recieve buffer length
923         case 8:
924                 LEAVE_RET('i', conn->RecievedBuffer->Length);
925         }
926
927         return 0;
928 }
929
930 void TCP_Client_Close(tVFS_Node *Node)
931 {
932         tTCPConnection  *conn = Node->ImplPtr;
933         tTCPHeader      packet;
934         
935         ENTER("pNode", Node);
936         
937         packet.SourcePort = htons(conn->LocalPort);
938         packet.DestPort = htons(conn->RemotePort);
939         packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
940         packet.WindowSize = TCP_WINDOW_SIZE;
941         
942         packet.AcknowlegementNumber = 0;
943         packet.SequenceNumber = htonl(conn->NextSequenceSend);
944         packet.Flags = TCP_FLAG_FIN;
945         
946         conn->State = TCP_ST_FIN_SENT;
947         
948         TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
949         
950         while( conn->State == TCP_ST_FIN_SENT ) Threads_Yield();
951         
952         free(conn);
953         
954         LEAVE('-');
955 }

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