Fixes to x86 error and interrupt handling
[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                 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         
353         // TODO: Check ACK code validity
354         Header->AcknowlegementNumber = ntohl(pkt->Sequence) + dataLen;
355         Header->SequenceNumber = ntohl(Connection->NextSequenceSend);
356         Header->Flags &= TCP_FLAG_SYN;
357         Header->Flags = TCP_FLAG_ACK;
358         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
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 = malloc( sizeof(tTCPListener) );
484
485         srv->Interface = Interface;
486         srv->Port = 0;
487         srv->NextID = 0;
488         srv->Connections = NULL;
489         srv->Next = NULL;
490         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
491         srv->Node.Size = -1;
492         srv->Node.ImplPtr = srv;
493         srv->Node.NumACLs = 1;
494         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
495         srv->Node.ReadDir = TCP_Server_ReadDir;
496         srv->Node.FindDir = TCP_Server_FindDir;
497         srv->Node.IOCtl = TCP_Server_IOCtl;
498         srv->Node.Close = TCP_Server_Close;
499
500         LOCK(&glTCP_Listeners);
501         srv->Next = gTCP_Listeners;
502         gTCP_Listeners = srv;
503         RELEASE(&glTCP_Listeners);
504
505         return &srv->Node;
506 }
507
508 /**
509  * \brief Wait for a new connection and return the connection ID
510  * \note Blocks until a new connection is made
511  * \param Node  Server node
512  * \param Pos   Position (ignored)
513  */
514 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
515 {
516         tTCPListener    *srv = Node->ImplPtr;
517         tTCPConnection  *conn;
518         char    *ret;
519
520         Log("[TCP  ] Thread %i waiting for a connection", Threads_GetTID());
521         for(;;)
522         {
523                 LOCK( &srv->lConnections );
524                 if( srv->NewConnections != NULL )       break;
525                 RELEASE( &srv->lConnections );
526                 Threads_Yield();
527                 continue;
528         }
529         
530
531         // Increment the new list (the current connection is still on the 
532         // normal list
533         conn = srv->NewConnections;
534         srv->NewConnections = conn->Next;
535         
536         RELEASE( &srv->lConnections );
537
538         ret = malloc(9);
539         itoa(ret, Node->ImplInt, 16, 8, '0');
540         Log("TCP_Server_ReadDir: RETURN '%s'", ret);
541         return ret;
542 }
543
544 /**
545  * \brief Gets a client connection node
546  * \param Node  Server node
547  * \param Name  Hexadecimal ID of the node
548  */
549 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
550 {
551         tTCPConnection  *conn;
552         tTCPListener    *srv = Node->ImplPtr;
553         char    tmp[9];
554          int    id = atoi(Name);
555         
556         // Sanity Check
557         itoa(tmp, id, 16, 8, '0');
558         if(strcmp(tmp, Name) != 0)      return NULL;
559         
560         // Search
561         LOCK( &srv->lConnections );
562         for(conn = srv->Connections;
563                 conn && conn->Node.ImplInt != id;
564                 conn = conn->Next);
565         RELEASE( &srv->lConnections );
566         
567         // If not found, ret NULL
568         if(!conn)       return NULL;
569         
570         // Return node
571         return &conn->Node;
572 }
573
574 /**
575  * \brief Handle IOCtl calls
576  */
577 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
578 {
579         tTCPListener    *srv = Node->ImplPtr;
580
581         switch(ID)
582         {
583         case 4: // Get/Set Port
584                 if(!Data)       // Get Port
585                         return srv->Port;
586
587                 if(srv->Port)   // Wait, you can't CHANGE the port
588                         return -1;
589
590                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
591                         return -1;
592
593                 // Permissions check
594                 if(Threads_GetUID() != 0
595                 && *(Uint16*)Data != 0
596                 && *(Uint16*)Data < 1024)
597                         return -1;
598
599                 // TODO: Check if a port is in use
600
601                 // Set Port
602                 srv->Port = *(Uint16*)Data;
603                 if(srv->Port == 0)      // Allocate a random port
604                         srv->Port = TCP_GetUnusedPort();
605                 else    // Else, mark this as used
606                         TCP_AllocatePort(srv->Port);
607                 
608                 Log("[TCP  ] Server %p listening on port %i", srv, srv->Port);
609                 
610                 return srv->Port;
611         }
612         return 0;
613 }
614
615 void TCP_Server_Close(tVFS_Node *Node)
616 {
617         free(Node->ImplPtr);
618 }
619
620 // --- Client
621 /**
622  * \brief Create a client node
623  */
624 tVFS_Node *TCP_Client_Init(tInterface *Interface)
625 {
626         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
627
628         conn->State = TCP_ST_CLOSED;
629         conn->Interface = Interface;
630         conn->LocalPort = 0;
631         conn->RemotePort = 0;
632         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
633
634         conn->Node.ImplPtr = conn;
635         conn->Node.NumACLs = 1;
636         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
637         conn->Node.Read = TCP_Client_Read;
638         conn->Node.Write = TCP_Client_Write;
639         conn->Node.IOCtl = TCP_Client_IOCtl;
640         conn->Node.Close = TCP_Client_Close;
641
642         LOCK(&glTCP_OutbountCons);
643         conn->Next = gTCP_OutbountCons;
644         gTCP_OutbountCons = conn;
645         RELEASE(&glTCP_OutbountCons);
646
647         return &conn->Node;
648 }
649
650 /**
651  * \brief Wait for a packet and return it
652  * \note If \a Length is smaller than the size of the packet, the rest
653  *       of the packet's data will be discarded.
654  */
655 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
656 {
657         tTCPConnection  *conn = Node->ImplPtr;
658         tTCPStoredPacket        *pkt;
659         
660         Log("TCP_Client_Read: (Length=%i)", Length);
661         
662         // Check if connection is open
663         if( conn->State != TCP_ST_OPEN )        return 0;
664         
665         // Poll packets
666         for(;;)
667         {               
668                 // Lock list and check if there is a packet
669                 LOCK( &conn->lRecievedPackets );
670                 if( conn->RecievedPackets == NULL ) {
671                         // If not, release the lock, yield and try again
672                         RELEASE( &conn->lRecievedPackets );
673                         Threads_Yield();
674                         continue;
675                 }
676                 
677                 // Get packet pointer
678                 pkt = conn->RecievedPackets;
679                 conn->RecievedPackets = pkt->Next;
680                 // Release the lock (we don't need it any more)
681                 RELEASE( &conn->lRecievedPackets );
682                 
683                 Log("TCP_Client_Read: pkt->Length = %i", pkt->Length);
684                 
685                 // Copy Data
686                 if(Length > pkt->Length)        Length = pkt->Length;
687                 memcpy(Buffer, pkt->Data, Length);
688                 
689                 // Free packet and return
690                 free(pkt);
691                 return Length;
692         }
693 }
694
695 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
696 {
697         return 0;
698 }
699
700 /**
701  * \brief Control a client socket
702  */
703 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
704 {
705         tTCPConnection  *conn = Node->ImplPtr;
706
707         switch(ID)
708         {
709         case 4: // Get/Set local port
710                 if(!Data)
711                         return conn->LocalPort;
712                 if(conn->State != TCP_ST_CLOSED)
713                         return -1;
714                 if(!CheckMem(Data, sizeof(Uint16)))
715                         return -1;
716
717                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
718                         return -1;
719
720                 conn->LocalPort = *(Uint16*)Data;
721                 return 0;
722
723         case 5: // Get/Set remote port
724                 if(!Data)       return conn->RemotePort;
725                 if(conn->State != TCP_ST_CLOSED)        return -1;
726                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
727                 conn->RemotePort = *(Uint16*)Data;
728                 return 0;
729
730         case 6: // Set Remote IP
731                 if( conn->State != TCP_ST_CLOSED )
732                         return -1;
733                 if( conn->Interface->Type == 4 )
734                 {
735                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
736                         conn->RemoteIP.v4 = *(tIPv4*)Data;
737                 }
738                 else if( conn->Interface->Type == 6 )
739                 {
740                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
741                         conn->RemoteIP.v6 = *(tIPv6*)Data;
742                 }
743                 return 0;
744
745         case 7: // Connect
746                 if(conn->LocalPort == -1)
747                         conn->LocalPort = TCP_GetUnusedPort();
748                 if(conn->RemotePort == -1)
749                         return 0;
750
751                 TCP_StartConnection(conn);
752                 return 1;
753         }
754
755         return 0;
756 }
757
758 void TCP_Client_Close(tVFS_Node *Node)
759 {
760         free(Node->ImplPtr);
761 }

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