Various changes, most of them involving the FAT and Ext2 Drivers, adding write support
[tpg/acess2.git] / Modules / IPStack / tcp.c
1 /*
2  * Acess2 IP Stack
3  * - TCP Handling
4  */
5 #include "ipstack.h"
6 #include "ipv4.h"
7 #include "tcp.h"
8
9 #define TCP_MIN_DYNPORT 0xC000
10 #define TCP_MAX_HALFOPEN        1024    // Should be enough
11
12 // === PROTOTYPES ===
13 void    TCP_Initialise();
14 void    TCP_StartConnection(tTCPConnection *Conn);
15 void    TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
16 void    TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
17 void    TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
18 void    TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Ptk);
19 void    TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
20 Uint16  TCP_GetUnusedPort();
21  int    TCP_AllocatePort(Uint16 Port);
22  int    TCP_DeallocatePort(Uint16 Port);
23 // --- Server
24 tVFS_Node       *TCP_Server_Init(tInterface *Interface);
25 char    *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
26 tVFS_Node       *TCP_Server_FindDir(tVFS_Node *Node, char *Name);
27  int    TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
28 void    TCP_Server_Close(tVFS_Node *Node);
29 // --- Client
30 tVFS_Node       *TCP_Client_Init(tInterface *Interface);
31 Uint64  TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
32 Uint64  TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
33  int    TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
34 void    TCP_Client_Close(tVFS_Node *Node);
35
36 // === TEMPLATES ===
37 tSocketFile     gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
38 tSocketFile     gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
39
40 // === GLOBALS ===
41  int    giTCP_NumHalfopen = 0;
42 tSpinlock       glTCP_Listeners;
43 tTCPListener    *gTCP_Listeners;
44 tSpinlock       glTCP_OutbountCons;
45 tTCPConnection  *gTCP_OutbountCons;
46 Uint32  gaTCP_PortBitmap[0x800];
47  int    giTCP_NextOutPort = TCP_MIN_DYNPORT;
48
49 // === CODE ===
50 /**
51  * \brief Initialise the TCP Layer
52  * 
53  * Registers the client and server files and the GetPacket callback
54  */
55 void TCP_Initialise()
56 {
57         IPStack_AddFile(&gTCP_ServerFile);
58         IPStack_AddFile(&gTCP_ClientFile);
59         IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
60 }
61
62 /**
63  * \brief Open a connection to another host using TCP
64  * \param Conn  Connection structure
65  */
66 void TCP_StartConnection(tTCPConnection *Conn)
67 {
68         tTCPHeader      hdr;
69
70         hdr.SourcePort = Conn->LocalPort;
71         hdr.DestPort = Conn->RemotePort;
72         Conn->NextSequenceSend = rand();
73         hdr.SequenceNumber = Conn->NextSequenceSend;
74         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
75         hdr.Flags = TCP_FLAG_SYN;
76         hdr.WindowSize = 0;     // TODO
77         hdr.Checksum = 0;       // TODO
78         hdr.UrgentPointer = 0;
79         
80         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
81         return ;
82 }
83
84 /**
85  * \brief Sends a packet from the specified connection, calculating the checksums
86  * \param Conn  Connection
87  * \param Length        Length of data
88  * \param Data  Packet data (cast as a TCP Header)
89  */
90 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
91 {
92         size_t  buflen;
93         Uint32  *buf;
94         switch( Conn->Interface->Type )
95         {
96         case 4: // Append IPv4 Pseudo Header
97                 buflen = 4 + 4 + 4 + ((Length+1)&~1);
98                 buf = malloc( buflen );
99                 buf[0] = Conn->Interface->IP4.Address.L;
100                 buf[1] = Conn->RemoteIP.v4.L;
101                 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
102                 Data->Checksum = 0;
103                 memcpy( &buf[3], Data, Length );
104                 Data->Checksum = IPv4_Checksum( buf, buflen );
105                 free(buf);
106                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
107                 break;
108         }
109 }
110
111 /**
112  * \brief Handles a packet from the IP Layer
113  * \param Interface     Interface the packet arrived from
114  * \param Address       Pointer to the addres structure
115  * \param Length        Size of packet in bytes
116  * \param Buffer        Packet data
117  */
118 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
119 {
120         tTCPHeader      *hdr = Buffer;
121         tTCPListener    *srv;
122         tTCPConnection  *conn;
123
124         Log("[TCP  ] SourcePort = %i, DestPort = %i",
125                 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
126         Log("[TCP  ] SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
127         Log("[TCP  ] AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
128         Log("[TCP  ] DataOffset = %i", hdr->DataOffset >> 4);
129         Log("[TCP  ] Flags = {");
130         Log("[TCP  ]   CWR = %B, ECE = %B",
131                 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
132         Log("[TCP  ]   URG = %B, ACK = %B",
133                 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
134         Log("[TCP  ]   PSH = %B, RST = %B",
135                 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
136         Log("[TCP  ]   SYN = %B, FIN = %B",
137                 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
138         Log("[TCP  ] }");
139         Log("[TCP  ] WindowSize = %i", htons(hdr->WindowSize));
140         Log("[TCP  ] Checksum = 0x%x", htons(hdr->Checksum));
141         Log("[TCP  ] UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
142
143         if( Length > (hdr->DataOffset >> 4)*4 )
144         {
145                 Debug_HexDump(
146                         "[TCP  ] Packet Data = ",
147                         (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
148                         Length - (hdr->DataOffset >> 4)*4
149                         );
150         }
151
152         // Check Servers
153         {
154                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
155                 {
156                         // Check if the server is active
157                         if(srv->Port == 0)      continue;
158                         // Check the interface
159                         if(srv->Interface && srv->Interface != Interface)       continue;
160                         // Check the destination port
161                         if(srv->Port != htons(hdr->DestPort))   continue;
162                         
163                         Log("[TCP  ] Matches server %p", srv);
164                         // Is this in an established connection?
165                         for( conn = srv->Connections; conn; conn = conn->Next )
166                         {
167                                 Log("[TCP  ] conn->Interface(%p) == Interface(%p)",
168                                         conn->Interface, Interface);
169                                 // Check that it is coming in on the same interface
170                                 if(conn->Interface != Interface)        continue;
171
172                                 // Check Source Port
173                                 Log("[TCP  ] conn->RemotePort(%i) == hdr->SourcePort(%i)",
174                                         conn->RemotePort, ntohs(hdr->SourcePort));
175                                 if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
176
177                                 // Check Source IP
178                                 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
179                                         continue;
180                                 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
181                                         continue;
182
183                                 Log("[TCP  ] Matches connection %p", conn);
184                                 // We have a response!
185                                 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
186
187                                 return;
188                         }
189
190                         Log("[TCP  ] Opening Connection");
191                         // Open a new connection (well, check that it's a SYN)
192                         if(hdr->Flags != TCP_FLAG_SYN) {
193                                 Log("[TCP  ] Packet is not a SYN");
194                                 return ;
195                         }
196                         
197                         // TODO: Check for halfopen max
198                         
199                         conn = calloc(1, sizeof(tTCPConnection));
200                         conn->State = TCP_ST_HALFOPEN;
201                         conn->LocalPort = srv->Port;
202                         conn->RemotePort = ntohs(hdr->SourcePort);
203                         conn->Interface = Interface;
204                         
205                         switch(Interface->Type)
206                         {
207                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
208                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
209                         }
210                         
211                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
212                         conn->NextSequenceSend = rand();
213                         
214                         // Create node
215                         conn->Node.NumACLs = 1;
216                         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
217                         conn->Node.ImplInt = srv->NextID ++;
218                         conn->Node.Read = TCP_Client_Read;
219                         conn->Node.Write = TCP_Client_Write;
220                         //conn->Node.Close = TCP_SrvConn_Close;
221                         
222                         // Hmm... Theoretically, this lock will never have to wait,
223                         // as the interface is locked to the watching thread, and this
224                         // runs in the watching thread. But, it's a good idea to have
225                         // it, just in case
226                         // Oh, wait, there is a case where a wildcard can be used
227                         // (srv->Interface == NULL) so having the lock is a good idea
228                         LOCK(&srv->lConnections);
229                         if( !srv->Connections )
230                                 srv->Connections = conn;
231                         else
232                                 srv->ConnectionsTail->Next = conn;
233                         srv->ConnectionsTail = conn;
234                         if(!srv->NewConnections)
235                                 srv->NewConnections = conn;
236                         RELEASE(&srv->lConnections);
237
238                         // Send the SYN ACK
239                         hdr->Flags |= TCP_FLAG_ACK;
240                         hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
241                         hdr->SequenceNumber = htonl(conn->NextSequenceSend);
242                         hdr->DestPort = hdr->SourcePort;
243                         hdr->SourcePort = htons(srv->Port);
244                         hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
245                         TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
246
247                         return ;
248                 }
249         }
250
251
252         // Check Open Connections
253         {
254                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
255                 {
256                         // Check that it is coming in on the same interface
257                         if(conn->Interface != Interface)        continue;
258
259                         // Check Source Port
260                         if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
261
262                         // Check Source IP
263                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
264                                 continue;
265                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
266                                 continue;
267
268                         TCP_INT_HandleConnectionPacket(conn, hdr, Length);
269                         return ;
270                 }
271         }
272         
273         Log("[TCP  ] No Match");
274 }
275
276 /**
277  * \brief Handles a packet sent to a specific connection
278  * \param Connection    TCP Connection pointer
279  * \param Header        TCP Packet pointer
280  * \param Length        Length of the packet
281  */
282 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
283 {       
284         tTCPStoredPacket        *pkt;
285          int    dataLen;
286         
287         Connection->State = TCP_ST_OPEN;
288         if(Header->Flags & TCP_FLAG_SYN) {
289                 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
290         }
291         
292         // Get length of data
293         dataLen = Length - (Header->DataOffset>>4)*4;
294         Log("[TCP  ] HandleConnectionPacket - dataLen = %i", dataLen);
295         
296         if(Header->Flags & TCP_FLAG_ACK) {
297                 // TODO: Process an ACKed Packet
298                 Log("[TCP  ] Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
299         }
300         
301         if(dataLen == 0)        return ;
302         
303         // NOTES:
304         // Flags
305         //    PSH - Has Data?
306         // /NOTES
307         
308         // Allocate and fill cached packet
309         pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
310         pkt->Next = NULL;
311         pkt->Sequence = ntohl(Header->SequenceNumber);
312         pkt->Length = dataLen;
313         memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset>>4)*4, dataLen);
314         
315         // Is this packet the next expected packet?
316         if( pkt->Sequence != Connection->NextSequenceRcv )
317         {
318                 tTCPStoredPacket        *tmp, *prev = NULL;
319                 
320                 Log("[TCP  ] Out of sequence packet (0x%08x != 0x%08x)",
321                         pkt->Sequence, Connection->NextSequenceRcv);
322                 
323                 // No? Well, let's cache it and look at it later
324                 LOCK( &Connection->lFuturePackets );
325                 for(tmp = Connection->FuturePackets;
326                         tmp;
327                         prev = tmp, tmp = tmp->Next)
328                 {
329                         if(tmp->Sequence > pkt->Sequence)       break;
330                 }
331                 if(prev)
332                         prev->Next = pkt;
333                 else
334                         Connection->FuturePackets = pkt;
335                 pkt->Next = tmp;
336                 RELEASE( &Connection->lFuturePackets );
337         }
338         else
339         {
340                 // Ooh, Goodie! Add it to the recieved list
341                 TCP_INT_AppendRecieved(Connection, pkt);
342                 Connection->NextSequenceRcv ++;
343                 
344                 // TODO: This should be moved out of the watcher thread,
345                 // so that a single lost packet on one connection doesn't cause
346                 // all connections on the interface to lag.
347                 TCP_INT_UpdateRecievedFromFuture(Connection);
348         }
349         
350         // TODO: Check ACK code validity
351         Header->AcknowlegementNumber = ntohl(pkt->Sequence);
352         Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
353         Header->Flags &= TCP_FLAG_SYN;
354         Header->Flags = TCP_FLAG_ACK;
355         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
356 }
357
358 /**
359  * \brief Appends a packet to the recieved list
360  * \param Connection    Connection structure
361  * \param Pkt   Packet structure on heap
362  */
363 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
364 {
365         LOCK( &Connection->lRecievedPackets );
366         if(Connection->RecievedPackets)
367         {
368                 Connection->RecievedPacketsTail->Next = Pkt;
369                 Connection->RecievedPacketsTail = Pkt;
370         }
371         else
372         {
373                 Connection->RecievedPackets = Pkt;
374                 Connection->RecievedPacketsTail = Pkt;
375         }
376         RELEASE( &Connection->lRecievedPackets );
377 }
378
379 /**
380  * \brief Updates the connections recieved list from the future list
381  * \param Connection    Connection structure
382  * 
383  * Updates the recieved packets list with packets from the future (out 
384  * of order) packets list that are now able to be added in direct
385  * sequence.
386  */
387 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
388 {
389         tTCPStoredPacket        *pkt, *prev;
390         for(;;)
391         {
392                 prev = NULL;
393                 // Look for the next expected packet in the cache.
394                 LOCK( &Connection->lFuturePackets );
395                 for(pkt = Connection->FuturePackets;
396                         pkt && pkt->Sequence < Connection->NextSequenceRcv;
397                         prev = pkt, pkt = pkt->Next);
398                 
399                 // If we can't find the expected next packet, stop looking
400                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
401                         RELEASE( &Connection->lFuturePackets );
402                         return;
403                 }
404                 
405                 // Delete packet from future list
406                 if(prev)
407                         prev->Next = pkt->Next;
408                 else
409                         Connection->FuturePackets = pkt->Next;
410                 
411                 // Release list
412                 RELEASE( &Connection->lFuturePackets );
413                 
414                 // Looks like we found one
415                 TCP_INT_AppendRecieved(Connection, pkt);
416                 Connection->NextSequenceRcv ++;
417         }
418 }
419
420 /**
421  * \fn Uint16 TCP_GetUnusedPort()
422  * \brief Gets an unused port and allocates it
423  */
424 Uint16 TCP_GetUnusedPort()
425 {
426         Uint16  ret;
427
428         // Get Next outbound port
429         ret = giTCP_NextOutPort++;
430         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
431         {
432                 ret ++;
433                 giTCP_NextOutPort++;
434                 if(giTCP_NextOutPort == 0x10000) {
435                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
436                 }
437         }
438
439         // Mark the new port as used
440         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
441
442         return ret;
443 }
444
445 /**
446  * \fn int TCP_AllocatePort(Uint16 Port)
447  * \brief Marks a port as used
448  */
449 int TCP_AllocatePort(Uint16 Port)
450 {
451         // Check if the port has already been allocated
452         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
453                 return 0;
454
455         // Allocate
456         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
457
458         return 1;
459 }
460
461 /**
462  * \fn int TCP_DeallocatePort(Uint16 Port)
463  * \brief Marks a port as unused
464  */
465 int TCP_DeallocatePort(Uint16 Port)
466 {
467         // Check if the port has already been allocated
468         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
469                 return 0;
470
471         // Allocate
472         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
473
474         return 1;
475 }
476
477 // --- Server
478 tVFS_Node *TCP_Server_Init(tInterface *Interface)
479 {
480         tTCPListener    *srv = malloc( sizeof(tTCPListener) );
481
482         srv->Interface = Interface;
483         srv->Port = 0;
484         srv->NextID = 0;
485         srv->Connections = NULL;
486         srv->Next = NULL;
487         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
488         srv->Node.Size = -1;
489         srv->Node.ImplPtr = srv;
490         srv->Node.NumACLs = 1;
491         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
492         srv->Node.ReadDir = TCP_Server_ReadDir;
493         srv->Node.FindDir = TCP_Server_FindDir;
494         srv->Node.IOCtl = TCP_Server_IOCtl;
495         srv->Node.Close = TCP_Server_Close;
496
497         LOCK(&glTCP_Listeners);
498         srv->Next = gTCP_Listeners;
499         gTCP_Listeners = srv;
500         RELEASE(&glTCP_Listeners);
501
502         return &srv->Node;
503 }
504
505 /**
506  * \brief Wait for a new connection and return the connection ID
507  * \note Blocks until a new connection is made
508  * \param Node  Server node
509  * \param Pos   Position (ignored)
510  */
511 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
512 {
513         tTCPListener    *srv = Node->ImplPtr;
514         tTCPConnection  *conn;
515         char    *ret;
516
517         Log("[TCP  ] Thread %i waiting for a connection", Threads_GetTID());
518         for(;;)
519         {
520                 LOCK( &srv->lConnections );
521                 if( srv->NewConnections != NULL )       break;
522                 RELEASE( &srv->lConnections );
523                 Threads_Yield();
524                 continue;
525         }
526         
527
528         // Increment the new list (the current connection is still on the 
529         // normal list
530         conn = srv->NewConnections;
531         srv->NewConnections = conn->Next;
532         
533         RELEASE( &srv->lConnections );
534
535         ret = malloc(9);
536         itoa(ret, Node->ImplInt, 16, 8, '0');
537         Log("TCP_Server_ReadDir: RETURN '%s'", ret);
538         return ret;
539 }
540
541 /**
542  * \brief Gets a client connection node
543  * \param Node  Server node
544  * \param Name  Hexadecimal ID of the node
545  */
546 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
547 {
548         tTCPConnection  *conn;
549         tTCPListener    *srv = Node->ImplPtr;
550         char    tmp[9];
551          int    id = atoi(Name);
552         
553         // Sanity Check
554         itoa(tmp, id, 16, 8, '0');
555         if(strcmp(tmp, Name) != 0)      return NULL;
556         
557         // Search
558         LOCK( &srv->lConnections );
559         for(conn = srv->Connections;
560                 conn && conn->Node.ImplInt != id;
561                 conn = conn->Next);
562         RELEASE( &srv->lConnections );
563         
564         // If not found, ret NULL
565         if(!conn)       return NULL;
566         
567         // Return node
568         return &conn->Node;
569 }
570
571 /**
572  * \brief Handle IOCtl calls
573  */
574 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
575 {
576         tTCPListener    *srv = Node->ImplPtr;
577
578         switch(ID)
579         {
580         case 4: // Get/Set Port
581                 if(!Data)       // Get Port
582                         return srv->Port;
583
584                 if(srv->Port)   // Wait, you can't CHANGE the port
585                         return -1;
586
587                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
588                         return -1;
589
590                 // Permissions check
591                 if(Threads_GetUID() != 0
592                 && *(Uint16*)Data != 0
593                 && *(Uint16*)Data < 1024)
594                         return -1;
595
596                 // TODO: Check if a port is in use
597
598                 // Set Port
599                 srv->Port = *(Uint16*)Data;
600                 if(srv->Port == 0)      // Allocate a random port
601                         srv->Port = TCP_GetUnusedPort();
602                 else    // Else, mark this as used
603                         TCP_AllocatePort(srv->Port);
604                 
605                 Log("[TCP  ] Server %p listening on port %i", srv, srv->Port);
606                 
607                 return srv->Port;
608         }
609         return 0;
610 }
611
612 void TCP_Server_Close(tVFS_Node *Node)
613 {
614         free(Node->ImplPtr);
615 }
616
617 // --- Client
618 /**
619  * \brief Create a client node
620  */
621 tVFS_Node *TCP_Client_Init(tInterface *Interface)
622 {
623         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
624
625         conn->State = TCP_ST_CLOSED;
626         conn->Interface = Interface;
627         conn->LocalPort = 0;
628         conn->RemotePort = 0;
629         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
630
631         conn->Node.ImplPtr = conn;
632         conn->Node.NumACLs = 1;
633         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
634         conn->Node.Read = TCP_Client_Read;
635         conn->Node.Write = TCP_Client_Write;
636         conn->Node.IOCtl = TCP_Client_IOCtl;
637         conn->Node.Close = TCP_Client_Close;
638
639         LOCK(&glTCP_OutbountCons);
640         conn->Next = gTCP_OutbountCons;
641         gTCP_OutbountCons = conn;
642         RELEASE(&glTCP_OutbountCons);
643
644         return &conn->Node;
645 }
646
647 /**
648  * \brief Wait for a packet and return it
649  * \note If \a Length is smaller than the size of the packet, the rest
650  *       of the packet's data will be discarded.
651  */
652 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
653 {
654         tTCPConnection  *conn = Node->ImplPtr;
655         tTCPStoredPacket        *pkt;
656         
657         Log("TCP_Client_Read: (Length=%i)", Length);
658         
659         // Check if connection is open
660         if( conn->State != TCP_ST_OPEN )        return 0;
661         
662         // Poll packets
663         for(;;)
664         {               
665                 // Lock list and check if there is a packet
666                 LOCK( &conn->lRecievedPackets );
667                 if( conn->RecievedPackets == NULL ) {
668                         // If not, release the lock, yield and try again
669                         RELEASE( &conn->lRecievedPackets );
670                         Threads_Yield();
671                         continue;
672                 }
673                 
674                 // Get packet pointer
675                 pkt = conn->RecievedPackets;
676                 conn->RecievedPackets = pkt->Next;
677                 // Release the lock (we don't need it any more)
678                 RELEASE( &conn->lRecievedPackets );
679                 
680                 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
681                 
682                 // Copy Data
683                 if(Length > pkt->Length)        Length = pkt->Length;
684                 memcpy(Buffer, pkt->Data, Length);
685                 
686                 // Free packet and return
687                 free(pkt);
688                 return Length;
689         }
690 }
691
692 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
693 {
694         return 0;
695 }
696
697 /**
698  * \brief Control a client socket
699  */
700 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
701 {
702         tTCPConnection  *conn = Node->ImplPtr;
703
704         switch(ID)
705         {
706         case 4: // Get/Set local port
707                 if(!Data)
708                         return conn->LocalPort;
709                 if(conn->State != TCP_ST_CLOSED)
710                         return -1;
711                 if(!CheckMem(Data, sizeof(Uint16)))
712                         return -1;
713
714                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
715                         return -1;
716
717                 conn->LocalPort = *(Uint16*)Data;
718                 return 0;
719
720         case 5: // Get/Set remote port
721                 if(!Data)       return conn->RemotePort;
722                 if(conn->State != TCP_ST_CLOSED)        return -1;
723                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
724                 conn->RemotePort = *(Uint16*)Data;
725                 return 0;
726
727         case 6: // Set Remote IP
728                 if( conn->State != TCP_ST_CLOSED )
729                         return -1;
730                 if( conn->Interface->Type == 4 )
731                 {
732                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
733                         conn->RemoteIP.v4 = *(tIPv4*)Data;
734                 }
735                 else if( conn->Interface->Type == 6 )
736                 {
737                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
738                         conn->RemoteIP.v6 = *(tIPv6*)Data;
739                 }
740                 return 0;
741
742         case 7: // Connect
743                 if(conn->LocalPort == -1)
744                         conn->LocalPort = TCP_GetUnusedPort();
745                 if(conn->RemotePort == -1)
746                         return 0;
747
748                 TCP_StartConnection(conn);
749                 return 1;
750         }
751
752         return 0;
753 }
754
755 void TCP_Client_Close(tVFS_Node *Node)
756 {
757         free(Node->ImplPtr);
758 }

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