Fixed some bugs in ARP and TCP Code
[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_Log("TCP", "SourcePort = %i, DestPort = %i",
125                 ntohs(hdr->SourcePort), ntohs(hdr->DestPort));
126         Log_Log("TCP", "SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
127         Log_Log("TCP", "AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
128         Log_Log("TCP", "DataOffset = %i", hdr->DataOffset >> 4);
129         Log_Log("TCP", "Flags = {");
130         Log_Log("TCP", "  CWR = %B, ECE = %B",
131                 !!(hdr->Flags & TCP_FLAG_CWR), !!(hdr->Flags & TCP_FLAG_ECE));
132         Log_Log("TCP", "  URG = %B, ACK = %B",
133                 !!(hdr->Flags & TCP_FLAG_URG), !!(hdr->Flags & TCP_FLAG_ACK));
134         Log_Log("TCP", "  PSH = %B, RST = %B",
135                 !!(hdr->Flags & TCP_FLAG_PSH), !!(hdr->Flags & TCP_FLAG_RST));
136         Log_Log("TCP", "  SYN = %B, FIN = %B",
137                 !!(hdr->Flags & TCP_FLAG_SYN), !!(hdr->Flags & TCP_FLAG_FIN));
138         Log_Log("TCP", "}");
139         Log_Log("TCP", "WindowSize = %i", htons(hdr->WindowSize));
140         Log_Log("TCP", "Checksum = 0x%x", htons(hdr->Checksum));
141         Log_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_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_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_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_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_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_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_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_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
295         
296         if(Header->Flags & TCP_FLAG_ACK) {
297                 // TODO: Process an ACKed Packet
298                 Log_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_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                 if(dataLen)
343                         Connection->NextSequenceRcv += dataLen;
344                 else
345                         Connection->NextSequenceRcv += 1;
346                 
347                 // TODO: This should be moved out of the watcher thread,
348                 // so that a single lost packet on one connection doesn't cause
349                 // all connections on the interface to lag.
350                 TCP_INT_UpdateRecievedFromFuture(Connection);
351         
352                 // TODO: Check ACK code validity
353                 Header->AcknowlegementNumber = ntohl(pkt->Sequence) + dataLen;
354                 Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
355                 Header->Flags &= TCP_FLAG_SYN;
356                 Header->Flags = TCP_FLAG_ACK;
357                 TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
358         }
359 }
360
361 /**
362  * \brief Appends a packet to the recieved list
363  * \param Connection    Connection structure
364  * \param Pkt   Packet structure on heap
365  */
366 void TCP_INT_AppendRecieved(tTCPConnection *Connection, tTCPStoredPacket *Pkt)
367 {
368         LOCK( &Connection->lRecievedPackets );
369         if(Connection->RecievedPackets)
370         {
371                 Connection->RecievedPacketsTail->Next = Pkt;
372                 Connection->RecievedPacketsTail = Pkt;
373         }
374         else
375         {
376                 Connection->RecievedPackets = Pkt;
377                 Connection->RecievedPacketsTail = Pkt;
378         }
379         RELEASE( &Connection->lRecievedPackets );
380 }
381
382 /**
383  * \brief Updates the connections recieved list from the future list
384  * \param Connection    Connection structure
385  * 
386  * Updates the recieved packets list with packets from the future (out 
387  * of order) packets list that are now able to be added in direct
388  * sequence.
389  */
390 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
391 {
392         tTCPStoredPacket        *pkt, *prev;
393         for(;;)
394         {
395                 prev = NULL;
396                 // Look for the next expected packet in the cache.
397                 LOCK( &Connection->lFuturePackets );
398                 for(pkt = Connection->FuturePackets;
399                         pkt && pkt->Sequence < Connection->NextSequenceRcv;
400                         prev = pkt, pkt = pkt->Next);
401                 
402                 // If we can't find the expected next packet, stop looking
403                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
404                         RELEASE( &Connection->lFuturePackets );
405                         return;
406                 }
407                 
408                 // Delete packet from future list
409                 if(prev)
410                         prev->Next = pkt->Next;
411                 else
412                         Connection->FuturePackets = pkt->Next;
413                 
414                 // Release list
415                 RELEASE( &Connection->lFuturePackets );
416                 
417                 // Looks like we found one
418                 TCP_INT_AppendRecieved(Connection, pkt);
419                 Connection->NextSequenceRcv ++;
420         }
421 }
422
423 /**
424  * \fn Uint16 TCP_GetUnusedPort()
425  * \brief Gets an unused port and allocates it
426  */
427 Uint16 TCP_GetUnusedPort()
428 {
429         Uint16  ret;
430
431         // Get Next outbound port
432         ret = giTCP_NextOutPort++;
433         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
434         {
435                 ret ++;
436                 giTCP_NextOutPort++;
437                 if(giTCP_NextOutPort == 0x10000) {
438                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
439                 }
440         }
441
442         // Mark the new port as used
443         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
444
445         return ret;
446 }
447
448 /**
449  * \fn int TCP_AllocatePort(Uint16 Port)
450  * \brief Marks a port as used
451  */
452 int TCP_AllocatePort(Uint16 Port)
453 {
454         // Check if the port has already been allocated
455         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
456                 return 0;
457
458         // Allocate
459         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
460
461         return 1;
462 }
463
464 /**
465  * \fn int TCP_DeallocatePort(Uint16 Port)
466  * \brief Marks a port as unused
467  */
468 int TCP_DeallocatePort(Uint16 Port)
469 {
470         // Check if the port has already been allocated
471         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
472                 return 0;
473
474         // Allocate
475         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
476
477         return 1;
478 }
479
480 // --- Server
481 tVFS_Node *TCP_Server_Init(tInterface *Interface)
482 {
483         tTCPListener    *srv;
484         
485         srv = malloc( sizeof(tTCPListener) );
486
487         Log_Debug("TCP", "srv = %p", srv);
488
489         if( srv == NULL ) {
490                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
491                 return NULL;
492         }
493
494         srv->Interface = Interface;
495         srv->Port = 0;
496         srv->NextID = 0;
497         srv->Connections = NULL;
498         srv->Next = NULL;
499         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
500         srv->Node.Size = -1;
501         srv->Node.ImplPtr = srv;
502         srv->Node.NumACLs = 1;
503         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
504         srv->Node.ReadDir = TCP_Server_ReadDir;
505         srv->Node.FindDir = TCP_Server_FindDir;
506         srv->Node.IOCtl = TCP_Server_IOCtl;
507         srv->Node.Close = TCP_Server_Close;
508
509         LOCK(&glTCP_Listeners);
510         srv->Next = gTCP_Listeners;
511         gTCP_Listeners = srv;
512         RELEASE(&glTCP_Listeners);
513
514         return &srv->Node;
515 }
516
517 /**
518  * \brief Wait for a new connection and return the connection ID
519  * \note Blocks until a new connection is made
520  * \param Node  Server node
521  * \param Pos   Position (ignored)
522  */
523 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
524 {
525         tTCPListener    *srv = Node->ImplPtr;
526         tTCPConnection  *conn;
527         char    *ret;
528
529         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
530         for(;;)
531         {
532                 LOCK( &srv->lConnections );
533                 if( srv->NewConnections != NULL )       break;
534                 RELEASE( &srv->lConnections );
535                 Threads_Yield();
536                 continue;
537         }
538         
539
540         // Increment the new list (the current connection is still on the 
541         // normal list
542         conn = srv->NewConnections;
543         srv->NewConnections = conn->Next;
544         
545         RELEASE( &srv->lConnections );
546
547         ret = malloc(9);
548         itoa(ret, Node->ImplInt, 16, 8, '0');
549         Log("TCP_Server_ReadDir: RETURN '%s'", ret);
550         return ret;
551 }
552
553 /**
554  * \brief Gets a client connection node
555  * \param Node  Server node
556  * \param Name  Hexadecimal ID of the node
557  */
558 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
559 {
560         tTCPConnection  *conn;
561         tTCPListener    *srv = Node->ImplPtr;
562         char    tmp[9];
563          int    id = atoi(Name);
564         
565         // Sanity Check
566         itoa(tmp, id, 16, 8, '0');
567         if(strcmp(tmp, Name) != 0)      return NULL;
568         
569         // Search
570         LOCK( &srv->lConnections );
571         for(conn = srv->Connections;
572                 conn && conn->Node.ImplInt != id;
573                 conn = conn->Next);
574         RELEASE( &srv->lConnections );
575         
576         // If not found, ret NULL
577         if(!conn)       return NULL;
578         
579         // Return node
580         return &conn->Node;
581 }
582
583 /**
584  * \brief Handle IOCtl calls
585  */
586 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
587 {
588         tTCPListener    *srv = Node->ImplPtr;
589
590         switch(ID)
591         {
592         case 4: // Get/Set Port
593                 if(!Data)       // Get Port
594                         return srv->Port;
595
596                 if(srv->Port)   // Wait, you can't CHANGE the port
597                         return -1;
598
599                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
600                         return -1;
601
602                 // Permissions check
603                 if(Threads_GetUID() != 0
604                 && *(Uint16*)Data != 0
605                 && *(Uint16*)Data < 1024)
606                         return -1;
607
608                 // TODO: Check if a port is in use
609
610                 // Set Port
611                 srv->Port = *(Uint16*)Data;
612                 if(srv->Port == 0)      // Allocate a random port
613                         srv->Port = TCP_GetUnusedPort();
614                 else    // Else, mark this as used
615                         TCP_AllocatePort(srv->Port);
616                 
617                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
618                 
619                 return srv->Port;
620         }
621         return 0;
622 }
623
624 void TCP_Server_Close(tVFS_Node *Node)
625 {
626         free(Node->ImplPtr);
627 }
628
629 // --- Client
630 /**
631  * \brief Create a client node
632  */
633 tVFS_Node *TCP_Client_Init(tInterface *Interface)
634 {
635         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
636
637         conn->State = TCP_ST_CLOSED;
638         conn->Interface = Interface;
639         conn->LocalPort = 0;
640         conn->RemotePort = 0;
641         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
642
643         conn->Node.ImplPtr = conn;
644         conn->Node.NumACLs = 1;
645         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
646         conn->Node.Read = TCP_Client_Read;
647         conn->Node.Write = TCP_Client_Write;
648         conn->Node.IOCtl = TCP_Client_IOCtl;
649         conn->Node.Close = TCP_Client_Close;
650
651         LOCK(&glTCP_OutbountCons);
652         conn->Next = gTCP_OutbountCons;
653         gTCP_OutbountCons = conn;
654         RELEASE(&glTCP_OutbountCons);
655
656         return &conn->Node;
657 }
658
659 /**
660  * \brief Wait for a packet and return it
661  * \note If \a Length is smaller than the size of the packet, the rest
662  *       of the packet's data will be discarded.
663  */
664 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
665 {
666         tTCPConnection  *conn = Node->ImplPtr;
667         tTCPStoredPacket        *pkt;
668         
669         Log("TCP_Client_Read: (Length=%i)", Length);
670         
671         // Check if connection is open
672         if( conn->State != TCP_ST_OPEN )        return 0;
673         
674         // Poll packets
675         for(;;)
676         {               
677                 // Lock list and check if there is a packet
678                 LOCK( &conn->lRecievedPackets );
679                 if( conn->RecievedPackets == NULL ) {
680                         // If not, release the lock, yield and try again
681                         RELEASE( &conn->lRecievedPackets );
682                         Threads_Yield();
683                         continue;
684                 }
685                 
686                 // Get packet pointer
687                 pkt = conn->RecievedPackets;
688                 conn->RecievedPackets = pkt->Next;
689                 // Release the lock (we don't need it any more)
690                 RELEASE( &conn->lRecievedPackets );
691                 
692                 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
693                 
694                 // Copy Data
695                 if(Length > pkt->Length)        Length = pkt->Length;
696                 memcpy(Buffer, pkt->Data, Length);
697                 
698                 // Free packet and return
699                 free(pkt);
700                 return Length;
701         }
702 }
703
704 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
705 {
706         return 0;
707 }
708
709 /**
710  * \brief Control a client socket
711  */
712 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
713 {
714         tTCPConnection  *conn = Node->ImplPtr;
715
716         switch(ID)
717         {
718         case 4: // Get/Set local port
719                 if(!Data)
720                         return conn->LocalPort;
721                 if(conn->State != TCP_ST_CLOSED)
722                         return -1;
723                 if(!CheckMem(Data, sizeof(Uint16)))
724                         return -1;
725
726                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
727                         return -1;
728
729                 conn->LocalPort = *(Uint16*)Data;
730                 return 0;
731
732         case 5: // Get/Set remote port
733                 if(!Data)       return conn->RemotePort;
734                 if(conn->State != TCP_ST_CLOSED)        return -1;
735                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
736                 conn->RemotePort = *(Uint16*)Data;
737                 return 0;
738
739         case 6: // Set Remote IP
740                 if( conn->State != TCP_ST_CLOSED )
741                         return -1;
742                 if( conn->Interface->Type == 4 )
743                 {
744                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
745                         conn->RemoteIP.v4 = *(tIPv4*)Data;
746                 }
747                 else if( conn->Interface->Type == 6 )
748                 {
749                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
750                         conn->RemoteIP.v6 = *(tIPv6*)Data;
751                 }
752                 return 0;
753
754         case 7: // Connect
755                 if(conn->LocalPort == -1)
756                         conn->LocalPort = TCP_GetUnusedPort();
757                 if(conn->RemotePort == -1)
758                         return 0;
759
760                 TCP_StartConnection(conn);
761                 return 1;
762         }
763
764         return 0;
765 }
766
767 void TCP_Client_Close(tVFS_Node *Node)
768 {
769         free(Node->ImplPtr);
770 }

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