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

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