1415deaacb933e94420441736a66bb7f041eabba
[tpg/acess2.git] / Modules / IPStack / tcp.c
1 /*
2  * Acess2 IP Stack
3  * - TCP Handling
4  */
5 #define DEBUG   1
6 #include "ipstack.h"
7 #include "ipv4.h"
8 #include "ipv6.h"
9 #include "tcp.h"
10
11 #define USE_SELECT      1
12 #define HEXDUMP_INCOMING        0
13 #define HEXDUMP_OUTGOING        0
14 #define CACHE_FUTURE_PACKETS_IN_BYTES   1       // Use a ring buffer to cache out of order packets
15
16 #define TCP_MIN_DYNPORT 0xC000
17 #define TCP_MAX_HALFOPEN        1024    // Should be enough
18
19 #define TCP_MAX_PACKET_SIZE     1024
20 #define TCP_WINDOW_SIZE 0x2000
21 #define TCP_RECIEVE_BUFFER_SIZE 0x4000
22
23 // === PROTOTYPES ===
24 void    TCP_Initialise(void);
25 void    TCP_StartConnection(tTCPConnection *Conn);
26 void    TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
27 void    TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
28 void    TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
29 int     TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length);
30 void    TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection);
31 Uint16  TCP_GetUnusedPort();
32  int    TCP_AllocatePort(Uint16 Port);
33  int    TCP_DeallocatePort(Uint16 Port);
34 // --- Server
35 tVFS_Node       *TCP_Server_Init(tInterface *Interface);
36 char    *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
37 tVFS_Node       *TCP_Server_FindDir(tVFS_Node *Node, const char *Name);
38  int    TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
39 void    TCP_Server_Close(tVFS_Node *Node);
40 // --- Client
41 tVFS_Node       *TCP_Client_Init(tInterface *Interface);
42 Uint64  TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
43 Uint64  TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer);
44  int    TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
45 void    TCP_Client_Close(tVFS_Node *Node);
46 // --- Helpers
47  int    WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue);
48
49 // === TEMPLATES ===
50 tSocketFile     gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
51 tSocketFile     gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
52 tVFS_NodeType   gTCP_ServerNodeType = {
53         .TypeName = "TCP Server",
54         .ReadDir = TCP_Server_ReadDir,
55         .FindDir = TCP_Server_FindDir,
56         .IOCtl   = TCP_Server_IOCtl,
57         .Close   = TCP_Server_Close
58         };
59 tVFS_NodeType   gTCP_ClientNodeType = {
60         .TypeName = "TCP Client/Connection",
61         .Read  = TCP_Client_Read,
62         .Write = TCP_Client_Write,
63         .IOCtl = TCP_Client_IOCtl,
64         .Close = TCP_Client_Close
65         };
66
67 // === GLOBALS ===
68  int    giTCP_NumHalfopen = 0;
69 tShortSpinlock  glTCP_Listeners;
70 tTCPListener    *gTCP_Listeners;
71 tShortSpinlock  glTCP_OutbountCons;
72 tTCPConnection  *gTCP_OutbountCons;
73 Uint32  gaTCP_PortBitmap[0x800];
74  int    giTCP_NextOutPort = TCP_MIN_DYNPORT;
75
76 // === CODE ===
77 /**
78  * \brief Initialise the TCP Layer
79  * 
80  * Registers the client and server files and the GetPacket callback
81  */
82 void TCP_Initialise(void)
83 {
84         giTCP_NextOutPort += rand()%32;
85         IPStack_AddFile(&gTCP_ServerFile);
86         IPStack_AddFile(&gTCP_ClientFile);
87         IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
88         IPv6_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
89 }
90
91 /**
92  * \brief Sends a packet from the specified connection, calculating the checksums
93  * \param Conn  Connection
94  * \param Length        Length of data
95  * \param Data  Packet data (cast as a TCP Header)
96  */
97 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
98 {
99         Uint16  checksum[2];
100         
101         Data->Checksum = 0;
102         checksum[1] = htons( ~IPv4_Checksum( (void*)Data, Length ) );   // Partial checksum
103         if(Length & 1)
104                 ((Uint8*)Data)[Length] = 0;
105         
106         // TODO: Fragment packet
107         
108         switch( Conn->Interface->Type )
109         {
110         case 4:
111                 // Append IPv4 Pseudo Header
112                 {
113                         Uint32  buf[3];
114                         buf[0] = ((tIPv4*)Conn->Interface->Address)->L;
115                         buf[1] = Conn->RemoteIP.v4.L;
116                         buf[2] = (htons(Length)<<16) | (6<<8) | 0;
117                         checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) );        // Partial checksum
118                 }
119                 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
120                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, Length, Data);
121                 break;
122                 
123         case 6:
124                 // Append IPv6 Pseudo Header
125                 {
126                         Uint32  buf[4+4+1+1];
127                         memcpy(buf, Conn->Interface->Address, 16);
128                         memcpy(&buf[4], &Conn->RemoteIP, 16);
129                         buf[8] = htonl(Length);
130                         buf[9] = htonl(6);
131                         checksum[0] = htons( ~IPv4_Checksum(buf, sizeof(buf)) );        // Partial checksum
132                 }
133                 Data->Checksum = htons( IPv4_Checksum(checksum, 2*2) ); // Combine the two
134                 IPv6_SendPacket(Conn->Interface, Conn->RemoteIP.v6, IP4PROT_TCP, Length, Data);
135                 break;
136         }
137 }
138
139 /**
140  * \brief Handles a packet from the IP Layer
141  * \param Interface     Interface the packet arrived from
142  * \param Address       Pointer to the addres structure
143  * \param Length        Size of packet in bytes
144  * \param Buffer        Packet data
145  */
146 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
147 {
148         tTCPHeader      *hdr = Buffer;
149         tTCPListener    *srv;
150         tTCPConnection  *conn;
151
152         Log_Log("TCP", "TCP_GetPacket: <Local>:%i from [%s]:%i, Flags= %s%s%s%s%s%s%s%s",
153                 ntohs(hdr->SourcePort),
154                 IPStack_PrintAddress(Interface->Type, Address),
155                 ntohs(hdr->DestPort),
156                 (hdr->Flags & TCP_FLAG_CWR) ? "CWR " : "",
157                 (hdr->Flags & TCP_FLAG_ECE) ? "ECE " : "",
158                 (hdr->Flags & TCP_FLAG_URG) ? "URG " : "",
159                 (hdr->Flags & TCP_FLAG_ACK) ? "ACK " : "",
160                 (hdr->Flags & TCP_FLAG_PSH) ? "PSH " : "",
161                 (hdr->Flags & TCP_FLAG_RST) ? "RST " : "",
162                 (hdr->Flags & TCP_FLAG_SYN) ? "SYN " : "",
163                 (hdr->Flags & TCP_FLAG_FIN) ? "FIN " : ""
164                 );
165
166         if( Length > (hdr->DataOffset >> 4)*4 )
167         {
168                 Log_Log("TCP", "TCP_GetPacket: SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
169 #if HEXDUMP_INCOMING
170                 Debug_HexDump(
171                         "TCP_GetPacket: Packet Data = ",
172                         (Uint8*)hdr + (hdr->DataOffset >> 4)*4,
173                         Length - (hdr->DataOffset >> 4)*4
174                         );
175 #endif
176         }
177
178         // Check Servers
179         {
180                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
181                 {
182                         // Check if the server is active
183                         if(srv->Port == 0)      continue;
184                         // Check the interface
185                         if(srv->Interface && srv->Interface != Interface)       continue;
186                         // Check the destination port
187                         if(srv->Port != htons(hdr->DestPort))   continue;
188                         
189                         Log_Log("TCP", "TCP_GetPacket: Matches server %p", srv);
190                         // Is this in an established connection?
191                         for( conn = srv->Connections; conn; conn = conn->Next )
192                         {
193                                 // Check that it is coming in on the same interface
194                                 if(conn->Interface != Interface)        continue;
195
196                                 // Check Source Port
197                                 Log_Log("TCP", "TCP_GetPacket: conn->RemotePort(%i) == hdr->SourcePort(%i)",
198                                         conn->RemotePort, ntohs(hdr->SourcePort));
199                                 if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
200
201                                 // Check Source IP
202                                 if( IPStack_CompareAddress(conn->Interface->Type, &conn->RemoteIP, Address, -1) != 0 )
203                                         continue ;
204
205                                 Log_Log("TCP", "TCP_GetPacket: Matches connection %p", conn);
206                                 // We have a response!
207                                 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
208
209                                 return;
210                         }
211
212                         Log_Log("TCP", "TCP_GetPacket: Opening Connection");
213                         // Open a new connection (well, check that it's a SYN)
214                         if(hdr->Flags != TCP_FLAG_SYN) {
215                                 Log_Log("TCP", "TCP_GetPacket: Packet is not a SYN");
216                                 return ;
217                         }
218                         
219                         // TODO: Check for halfopen max
220                         
221                         conn = calloc(1, sizeof(tTCPConnection));
222                         conn->State = TCP_ST_SYN_RCVD;
223                         conn->LocalPort = srv->Port;
224                         conn->RemotePort = ntohs(hdr->SourcePort);
225                         conn->Interface = Interface;
226                         
227                         switch(Interface->Type)
228                         {
229                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
230                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
231                         }
232                         
233                         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
234                         
235                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber ) + 1;
236                         conn->NextSequenceSend = rand();
237                         
238                         // Create node
239                         conn->Node.NumACLs = 1;
240                         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
241                         conn->Node.ImplPtr = conn;
242                         conn->Node.ImplInt = srv->NextID ++;
243                         conn->Node.Type = &gTCP_ClientNodeType; // TODO: Special type for the server end?
244                         
245                         // Hmm... Theoretically, this lock will never have to wait,
246                         // as the interface is locked to the watching thread, and this
247                         // runs in the watching thread. But, it's a good idea to have
248                         // it, just in case
249                         // Oh, wait, there is a case where a wildcard can be used
250                         // (srv->Interface == NULL) so having the lock is a good idea
251                         SHORTLOCK(&srv->lConnections);
252                         if( !srv->Connections )
253                                 srv->Connections = conn;
254                         else
255                                 srv->ConnectionsTail->Next = conn;
256                         srv->ConnectionsTail = conn;
257                         if(!srv->NewConnections)
258                                 srv->NewConnections = conn;
259                         SHORTREL(&srv->lConnections);
260
261                         // Send the SYN ACK
262                         hdr->Flags |= TCP_FLAG_ACK;
263                         hdr->AcknowlegementNumber = htonl(conn->NextSequenceRcv);
264                         hdr->SequenceNumber = htonl(conn->NextSequenceSend);
265                         hdr->DestPort = hdr->SourcePort;
266                         hdr->SourcePort = htons(srv->Port);
267                         hdr->DataOffset = (sizeof(tTCPHeader)/4) << 4;
268                         TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
269                         conn->NextSequenceSend ++;
270                         return ;
271                 }
272         }
273
274
275         // Check Open Connections
276         {
277                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
278                 {
279                         // Check that it is coming in on the same interface
280                         if(conn->Interface != Interface)        continue;
281
282                         // Check Source Port
283                         if(conn->RemotePort != ntohs(hdr->SourcePort))  continue;
284
285                         // Check Source IP
286                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
287                                 continue;
288                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
289                                 continue;
290
291                         TCP_INT_HandleConnectionPacket(conn, hdr, Length);
292                         return ;
293                 }
294         }
295         
296         Log_Log("TCP", "TCP_GetPacket: No Match");
297 }
298
299 /**
300  * \brief Handles a packet sent to a specific connection
301  * \param Connection    TCP Connection pointer
302  * \param Header        TCP Packet pointer
303  * \param Length        Length of the packet
304  */
305 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
306 {
307          int    dataLen;
308         Uint32  sequence_num;
309         
310         // Silently drop once finished
311         // TODO: Check if this needs to be here
312         if( Connection->State == TCP_ST_FINISHED ) {
313                 Log_Log("TCP", "Packet ignored - connection finnished");
314                 return ;
315         }
316         
317         // Syncronise sequence values
318         if(Header->Flags & TCP_FLAG_SYN) {
319                 // TODO: What if the packet also has data?
320                 Connection->NextSequenceRcv = ntohl(Header->SequenceNumber);
321         }
322         
323         // Ackowledge a sent packet
324         if(Header->Flags & TCP_FLAG_ACK) {
325                 // TODO: Process an ACKed Packet
326                 Log_Log("TCP", "Conn %p, Sent packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
327         }
328         
329         // Get length of data
330         dataLen = Length - (Header->DataOffset>>4)*4;
331         Log_Log("TCP", "HandleConnectionPacket - dataLen = %i", dataLen);
332         
333         // 
334         // State Machine
335         //
336         switch( Connection->State )
337         {
338         // Pre-init connection?
339         case TCP_ST_CLOSED:
340                 Log_Log("TCP", "Packets to a closed connection?!");
341                 break;
342         
343         // --- Init States ---
344         // SYN sent, expecting SYN-ACK Connection Opening
345         case TCP_ST_SYN_SENT:
346                 if( Header->Flags & TCP_FLAG_SYN )
347                 {
348                         Connection->NextSequenceRcv ++;
349                         Header->DestPort = Header->SourcePort;
350                         Header->SourcePort = htons(Connection->LocalPort);
351                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
352                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
353                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
354                         Header->Flags = TCP_FLAG_ACK;
355                         Header->DataOffset = (sizeof(tTCPHeader)/4) << 4;
356                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
357                         
358                         if( Header->Flags & TCP_FLAG_ACK )
359                         {       
360                                 Log_Log("TCP", "ACKing SYN-ACK");
361                                 Connection->State = TCP_ST_OPEN;
362                         }
363                         else
364                         {
365                                 Log_Log("TCP", "ACKing SYN");
366                                 Connection->State = TCP_ST_SYN_RCVD;
367                         }
368                 }
369                 break;
370         
371         // SYN-ACK sent, expecting ACK
372         case TCP_ST_SYN_RCVD:
373                 if( Header->Flags & TCP_FLAG_ACK )
374                 {
375                         // TODO: Handle max half-open limit
376                         Connection->State = TCP_ST_OPEN;
377                         Log_Log("TCP", "Connection fully opened");
378                 }
379                 break;
380                 
381         // --- Established State ---
382         case TCP_ST_OPEN:
383                 // - Handle State changes
384                 //
385                 if( Header->Flags & TCP_FLAG_FIN ) {
386                         Log_Log("TCP", "Conn %p closed, recieved FIN", Connection);
387                         VFS_MarkError(&Connection->Node, 1);
388                         Connection->State = TCP_ST_CLOSE_WAIT;
389 //                      Header->Flags &= ~TCP_FLAG_FIN;
390                         // CLOSE WAIT requires the client to close (or does it?)
391                         #if 0
392                         
393                         #endif
394                 }
395         
396                 // Check for an empty packet
397                 if(dataLen == 0) {
398                         if( Header->Flags == TCP_FLAG_ACK )
399                         {
400                                 Log_Log("TCP", "ACK only packet");
401                                 return ;
402                         }
403                         Connection->NextSequenceRcv ++; // TODO: Is this right? (empty packet counts as one byte)
404                         Log_Log("TCP", "Empty Packet, inc and ACK the current sequence number");
405                         Header->DestPort = Header->SourcePort;
406                         Header->SourcePort = htons(Connection->LocalPort);
407                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
408                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
409                         Header->Flags |= TCP_FLAG_ACK;
410                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
411                         return ;
412                 }
413                 
414                 // NOTES:
415                 // Flags
416                 //    PSH - Has Data?
417                 // /NOTES
418                 
419                 sequence_num = ntohl(Header->SequenceNumber);
420                 
421                 Log_Log("TCP", "0x%08x <= 0x%08x < 0x%08x",
422                         Connection->NextSequenceRcv,
423                         ntohl(Header->SequenceNumber),
424                         Connection->NextSequenceRcv + TCP_WINDOW_SIZE
425                         );
426                 
427                 // Is this packet the next expected packet?
428                 if( sequence_num == Connection->NextSequenceRcv )
429                 {
430                          int    rv;
431                         // Ooh, Goodie! Add it to the recieved list
432                         rv = TCP_INT_AppendRecieved(Connection,
433                                 (Uint8*)Header + (Header->DataOffset>>4)*4,
434                                 dataLen
435                                 );
436                         if(rv != 0) {
437                                 break;
438                         }
439                         Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
440                         Connection->NextSequenceRcv += dataLen;
441                         
442                         // TODO: This should be moved out of the watcher thread,
443                         // so that a single lost packet on one connection doesn't cause
444                         // all connections on the interface to lag.
445                         // - Meh, no real issue, as the cache shouldn't be that large
446                         TCP_INT_UpdateRecievedFromFuture(Connection);
447                 
448                         // ACK Packet
449                         Header->DestPort = Header->SourcePort;
450                         Header->SourcePort = htons(Connection->LocalPort);
451                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
452                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
453                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
454                         Header->Flags &= TCP_FLAG_SYN;  // Eliminate all flags save for SYN
455                         Header->Flags |= TCP_FLAG_ACK;  // Add ACK
456                         Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
457                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
458                         //Connection->NextSequenceSend ++;
459                 }
460                 // Check if the packet is in window
461                 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
462                                 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
463                 {
464                         Uint8   *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
465                         #if CACHE_FUTURE_PACKETS_IN_BYTES
466                         Uint32  index;
467                          int    i;
468                         
469                         index = sequence_num % TCP_WINDOW_SIZE;
470                         for( i = 0; i < dataLen; i ++ )
471                         {
472                                 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
473                                 Connection->FuturePacketData[index] = dataptr[i];
474                                 // Do a wrap increment
475                                 index ++;
476                                 if(index == TCP_WINDOW_SIZE)    index = 0;
477                         }
478                         #else
479                         tTCPStoredPacket        *pkt, *tmp, *prev = NULL;
480                         
481                         // Allocate and fill cached packet
482                         pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
483                         pkt->Next = NULL;
484                         pkt->Sequence = ntohl(Header->SequenceNumber);
485                         pkt->Length = dataLen;
486                         memcpy(pkt->Data, dataptr, dataLen);
487                         
488                         Log_Log("TCP", "We missed a packet, caching",
489                                 pkt->Sequence, Connection->NextSequenceRcv);
490                         
491                         // No? Well, let's cache it and look at it later
492                         SHORTLOCK( &Connection->lFuturePackets );
493                         for(tmp = Connection->FuturePackets;
494                                 tmp;
495                                 prev = tmp, tmp = tmp->Next)
496                         {
497                                 if(tmp->Sequence >= pkt->Sequence)      break;
498                         }
499                         
500                         // Add if before first, or sequences don't match 
501                         if( !tmp || tmp->Sequence != pkt->Sequence )
502                         {
503                                 if(prev)
504                                         prev->Next = pkt;
505                                 else
506                                         Connection->FuturePackets = pkt;
507                                 pkt->Next = tmp;
508                         }
509                         // Replace if larger
510                         else if(pkt->Length > tmp->Length)
511                         {
512                                 if(prev)
513                                         prev->Next = pkt;
514                                 pkt->Next = tmp->Next;
515                                 free(tmp);
516                         }
517                         else
518                         {
519                                 free(pkt);      // TODO: Find some way to remove this
520                         }
521                         SHORTREL( &Connection->lFuturePackets );
522                         #endif
523                 }
524                 // Badly out of sequence packet
525                 else
526                 {
527                         Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
528                                 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
529                         // TODO: Spec says we should send an empty ACK with the current state
530                 }
531                 break;
532         
533         // --- Remote close states
534         case TCP_ST_CLOSE_WAIT:
535                 
536                 // Ignore everything, CLOSE_WAIT is terminated by the client
537                 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
538                 
539                 break;
540         
541         // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
542         case TCP_ST_LAST_ACK:
543                 if( Header->Flags & TCP_FLAG_ACK )
544                 {
545                         Connection->State = TCP_ST_FINISHED;    // Connection completed
546                         Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
547                         // TODO: Destrory the TCB
548                 }
549                 break;
550         
551         // --- Local close States
552         case TCP_ST_FIN_WAIT1:
553                 if( Header->Flags & TCP_FLAG_FIN )
554                 {
555                         Connection->State = TCP_ST_CLOSING;
556                         Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
557                         VFS_MarkError(&Connection->Node, 1);
558                         
559                         // ACK Packet
560                         Header->DestPort = Header->SourcePort;
561                         Header->SourcePort = htons(Connection->LocalPort);
562                         Header->AcknowlegementNumber = Header->SequenceNumber;
563                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
564                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
565                         Header->Flags = TCP_FLAG_ACK;
566                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
567                         break ;
568                 }
569                 
570                 // TODO: Make sure that the packet is actually ACKing the FIN
571                 if( Header->Flags & TCP_FLAG_ACK )
572                 {
573                         Connection->State = TCP_ST_FIN_WAIT2;
574                         Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
575                         VFS_MarkError(&Connection->Node, 1);
576                         return ;
577                 }
578                 break;
579         
580         case TCP_ST_FIN_WAIT2:
581                 if( Header->Flags & TCP_FLAG_FIN )
582                 {
583                         Connection->State = TCP_ST_TIME_WAIT;
584                         Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
585                         // Send ACK
586                         Header->DestPort = Header->SourcePort;
587                         Header->SourcePort = htons(Connection->LocalPort);
588                         Header->AcknowlegementNumber = Header->SequenceNumber;
589                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
590                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
591                         Header->Flags = TCP_FLAG_ACK;
592                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
593                 }
594                 break;
595         
596         case TCP_ST_CLOSING:
597                 // TODO: Make sure that the packet is actually ACKing the FIN
598                 if( Header->Flags & TCP_FLAG_ACK )
599                 {
600                         Connection->State = TCP_ST_TIME_WAIT;
601                         Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
602                         VFS_MarkError(&Connection->Node, 1);
603                         return ;
604                 }
605                 break;
606         
607         // --- Closed (or near closed) states) ---
608         case TCP_ST_TIME_WAIT:
609                 Log_Log("TCP", "Packets on Time-Wait, ignored");
610                 break;
611         
612         case TCP_ST_FINISHED:
613                 Log_Log("TCP", "Packets when CLOSED, ignoring");
614                 break;
615         
616         //default:
617         //      Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
618         //      break;
619         }
620         
621 }
622
623 /**
624  * \brief Appends a packet to the recieved list
625  * \param Connection    Connection structure
626  * \param Data  Packet contents
627  * \param Length        Length of \a Data
628  */
629 int TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
630 {
631         Mutex_Acquire( &Connection->lRecievedPackets );
632
633         if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
634         {
635                 VFS_MarkAvaliable(&Connection->Node, 1);
636                 Log_Error("TCP", "Buffer filled, packet dropped (:%i) - %i + %i > %i",
637                         Connection->LocalPort, Connection->RecievedBuffer->Length, Length,
638                         Connection->RecievedBuffer->Space
639                         );
640                 Mutex_Release( &Connection->lRecievedPackets );
641                 return 1;
642         }
643         
644         RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
645
646         VFS_MarkAvaliable(&Connection->Node, 1);
647         
648         Mutex_Release( &Connection->lRecievedPackets );
649         return 0;
650 }
651
652 /**
653  * \brief Updates the connections recieved list from the future list
654  * \param Connection    Connection structure
655  * 
656  * Updates the recieved packets list with packets from the future (out 
657  * of order) packets list that are now able to be added in direct
658  * sequence.
659  */
660 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
661 {
662         #if CACHE_FUTURE_PACKETS_IN_BYTES
663          int    i, length = 0;
664         Uint32  index;
665         
666         // Calculate length of contiguous bytes
667         length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
668         index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
669         for( i = 0; i < length; i ++ )
670         {
671                 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
672                         i += 7; index += 7;
673                         continue;
674                 }
675                 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
676                         break;
677                 
678                 index ++;
679                 if(index > TCP_WINDOW_SIZE)
680                         index -= TCP_WINDOW_SIZE;
681         }
682         length = i;
683         
684         index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
685         
686         // Write data to to the ring buffer
687         if( TCP_WINDOW_SIZE - index > length )
688         {
689                 // Simple case
690                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
691         }
692         else
693         {
694                  int    endLen = TCP_WINDOW_SIZE - index;
695                 // 2-part case
696                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
697                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
698         }
699         
700         // Mark (now saved) bytes as invalid
701         // - Align index
702         while(index % 8 && length)
703         {
704                 Connection->FuturePacketData[index] = 0;
705                 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
706                 index ++;
707                 if(index > TCP_WINDOW_SIZE)
708                         index -= TCP_WINDOW_SIZE;
709                 length --;
710         }
711         while( length > 7 )
712         {
713                 Connection->FuturePacketData[index] = 0;
714                 Connection->FuturePacketValidBytes[index/8] = 0;
715                 length -= 8;
716                 index += 8;
717                 if(index > TCP_WINDOW_SIZE)
718                         index -= TCP_WINDOW_SIZE;
719         }
720         while(length)
721         {
722                 Connection->FuturePacketData[index] = 0;
723                 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
724                 index ++;
725                 if(index > TCP_WINDOW_SIZE)
726                         index -= TCP_WINDOW_SIZE;
727                 length --;
728         }
729         
730         #else
731         tTCPStoredPacket        *pkt;
732         for(;;)
733         {
734                 SHORTLOCK( &Connection->lFuturePackets );
735                 
736                 // Clear out duplicates from cache
737                 // - If a packet has just been recieved, and it is expected, then
738                 //   (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
739                 //   packets in cache that are smaller than the next expected
740                 //   are now defunct.
741                 pkt = Connection->FuturePackets;
742                 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
743                 {
744                         tTCPStoredPacket        *next = pkt->Next;
745                         free(pkt);
746                         pkt = next;
747                 }
748                 
749                 // If there's no packets left in cache, stop looking
750                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
751                         SHORTREL( &Connection->lFuturePackets );
752                         return;
753                 }
754                 
755                 // Delete packet from future list
756                 Connection->FuturePackets = pkt->Next;
757                 
758                 // Release list
759                 SHORTREL( &Connection->lFuturePackets );
760                 
761                 // Looks like we found one
762                 TCP_INT_AppendRecieved(Connection, pkt);
763                 Connection->NextSequenceRcv += pkt->Length;
764                 free(pkt);
765         }
766         #endif
767 }
768
769 /**
770  * \fn Uint16 TCP_GetUnusedPort()
771  * \brief Gets an unused port and allocates it
772  */
773 Uint16 TCP_GetUnusedPort()
774 {
775         Uint16  ret;
776
777         // Get Next outbound port
778         ret = giTCP_NextOutPort++;
779         while( gaTCP_PortBitmap[ret/32] & (1UL << (ret%32)) )
780         {
781                 ret ++;
782                 giTCP_NextOutPort++;
783                 if(giTCP_NextOutPort == 0x10000) {
784                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
785                 }
786         }
787
788         // Mark the new port as used
789         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
790
791         return ret;
792 }
793
794 /**
795  * \fn int TCP_AllocatePort(Uint16 Port)
796  * \brief Marks a port as used
797  */
798 int TCP_AllocatePort(Uint16 Port)
799 {
800         // Check if the port has already been allocated
801         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
802                 return 0;
803
804         // Allocate
805         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
806
807         return 1;
808 }
809
810 /**
811  * \fn int TCP_DeallocatePort(Uint16 Port)
812  * \brief Marks a port as unused
813  */
814 int TCP_DeallocatePort(Uint16 Port)
815 {
816         // Check if the port has already been allocated
817         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
818                 return 0;
819
820         // Allocate
821         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
822
823         return 1;
824 }
825
826 // --- Server
827 tVFS_Node *TCP_Server_Init(tInterface *Interface)
828 {
829         tTCPListener    *srv;
830         
831         srv = malloc( sizeof(tTCPListener) );
832
833         if( srv == NULL ) {
834                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
835                 return NULL;
836         }
837
838         srv->Interface = Interface;
839         srv->Port = 0;
840         srv->NextID = 0;
841         srv->Connections = NULL;
842         srv->ConnectionsTail = NULL;
843         srv->NewConnections = NULL;
844         srv->Next = NULL;
845         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
846         srv->Node.Size = -1;
847         srv->Node.ImplPtr = srv;
848         srv->Node.NumACLs = 1;
849         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
850         srv->Node.Type = &gTCP_ServerNodeType;
851
852         SHORTLOCK(&glTCP_Listeners);
853         srv->Next = gTCP_Listeners;
854         gTCP_Listeners = srv;
855         SHORTREL(&glTCP_Listeners);
856
857         return &srv->Node;
858 }
859
860 /**
861  * \brief Wait for a new connection and return the connection ID
862  * \note Blocks until a new connection is made
863  * \param Node  Server node
864  * \param Pos   Position (ignored)
865  */
866 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
867 {
868         tTCPListener    *srv = Node->ImplPtr;
869         tTCPConnection  *conn;
870         char    *ret;
871         
872         ENTER("pNode iPos", Node, Pos);
873
874         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
875         for(;;)
876         {
877                 SHORTLOCK( &srv->lConnections );
878                 if( srv->NewConnections != NULL )       break;
879                 SHORTREL( &srv->lConnections );
880                 Threads_Yield();        // TODO: Sleep until poked
881                 continue;
882         }
883         
884
885         // Increment the new list (the current connection is still on the 
886         // normal list)
887         conn = srv->NewConnections;
888         srv->NewConnections = conn->Next;
889         
890         SHORTREL( &srv->lConnections );
891         
892         LOG("conn = %p", conn);
893         LOG("srv->Connections = %p", srv->Connections);
894         LOG("srv->NewConnections = %p", srv->NewConnections);
895         LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
896
897         ret = malloc(9);
898         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
899         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
900         LEAVE('s', ret);
901         return ret;
902 }
903
904 /**
905  * \brief Gets a client connection node
906  * \param Node  Server node
907  * \param Name  Hexadecimal ID of the node
908  */
909 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
910 {
911         tTCPConnection  *conn;
912         tTCPListener    *srv = Node->ImplPtr;
913         char    tmp[9];
914          int    id = atoi(Name);
915         
916         ENTER("pNode sName", Node, Name);
917
918         // Check for a non-empty name
919         if( Name[0] ) 
920         {       
921                 // Sanity Check
922                 itoa(tmp, id, 16, 8, '0');
923                 if(strcmp(tmp, Name) != 0) {
924                         LOG("'%s' != '%s' (%08x)", Name, tmp, id);
925                         LEAVE('n');
926                         return NULL;
927                 }
928                 
929                 Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
930                 Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
931                 Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
932                 
933                 // Search
934                 SHORTLOCK( &srv->lConnections );
935                 for(conn = srv->Connections;
936                         conn;
937                         conn = conn->Next)
938                 {
939                         LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
940                         if(conn->Node.ImplInt == id)    break;
941                 }
942                 SHORTREL( &srv->lConnections );
943         }
944         // Empty Name - Check for a new connection and if it's there, open it
945         else
946         {
947                 SHORTLOCK( &srv->lConnections );
948                 conn = srv->NewConnections;
949                 if( conn != NULL )
950                         srv->NewConnections = conn->Next;
951                 SHORTREL( &srv->lConnections );
952         }
953                 
954         // If not found, ret NULL
955         if(!conn) {
956                 LOG("Connection %i not found", id);
957                 LEAVE('n');
958                 return NULL;
959         }
960         
961         // Return node
962         LEAVE('p', &conn->Node);
963         return &conn->Node;
964 }
965
966 /**
967  * \brief Handle IOCtl calls
968  */
969 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
970 {
971         tTCPListener    *srv = Node->ImplPtr;
972
973         switch(ID)
974         {
975         case 4: // Get/Set Port
976                 if(!Data)       // Get Port
977                         return srv->Port;
978
979                 if(srv->Port)   // Wait, you can't CHANGE the port
980                         return -1;
981
982                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
983                         return -1;
984
985                 // Permissions check
986                 if(Threads_GetUID() != 0
987                 && *(Uint16*)Data != 0
988                 && *(Uint16*)Data < 1024)
989                         return -1;
990
991                 // TODO: Check if a port is in use
992
993                 // Set Port
994                 srv->Port = *(Uint16*)Data;
995                 if(srv->Port == 0)      // Allocate a random port
996                         srv->Port = TCP_GetUnusedPort();
997                 else    // Else, mark this as used
998                         TCP_AllocatePort(srv->Port);
999                 
1000                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
1001                 
1002                 return srv->Port;
1003         }
1004         return 0;
1005 }
1006
1007 void TCP_Server_Close(tVFS_Node *Node)
1008 {
1009         free(Node->ImplPtr);
1010 }
1011
1012 // --- Client
1013 /**
1014  * \brief Create a client node
1015  */
1016 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1017 {
1018         tTCPConnection  *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1019
1020         conn->State = TCP_ST_CLOSED;
1021         conn->Interface = Interface;
1022         conn->LocalPort = -1;
1023         conn->RemotePort = -1;
1024
1025         conn->Node.ImplPtr = conn;
1026         conn->Node.NumACLs = 1;
1027         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1028         conn->Node.Type = &gTCP_ClientNodeType;
1029
1030         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1031         #if 0
1032         conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1033         Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1034         #endif
1035         
1036         #if CACHE_FUTURE_PACKETS_IN_BYTES
1037         // Future recieved data (ahead of the expected sequence number)
1038         conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1039         conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1040         #endif
1041
1042         SHORTLOCK(&glTCP_OutbountCons);
1043         conn->Next = gTCP_OutbountCons;
1044         gTCP_OutbountCons = conn;
1045         SHORTREL(&glTCP_OutbountCons);
1046
1047         return &conn->Node;
1048 }
1049
1050 /**
1051  * \brief Wait for a packet and return it
1052  * \note If \a Length is smaller than the size of the packet, the rest
1053  *       of the packet's data will be discarded.
1054  */
1055 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1056 {
1057         tTCPConnection  *conn = Node->ImplPtr;
1058         size_t  len;
1059         
1060         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1061         LOG("conn = %p {State:%i}", conn, conn->State);
1062         
1063         // Check if connection is estabilishing
1064         // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1065         //   data to be availiable
1066         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1067                 Threads_Yield();
1068         
1069         // If the conneciton is not open, then clean out the recieved buffer
1070         if( conn->State != TCP_ST_OPEN )
1071         {
1072                 Mutex_Acquire( &conn->lRecievedPackets );
1073                 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1074                 Mutex_Release( &conn->lRecievedPackets );
1075                 
1076                 if( len == 0 ) {
1077                         VFS_MarkAvaliable(Node, 0);
1078                         LEAVE('i', -1);
1079                         return -1;
1080                 }
1081                 
1082                 LEAVE('i', len);
1083                 return len;
1084         }
1085         
1086         // Wait
1087         VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1088         
1089         // Lock list and read as much as possible (up to `Length`)
1090         Mutex_Acquire( &conn->lRecievedPackets );
1091         len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1092         
1093         if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1094                 LOG("Marking as none avaliable (len = %i)", len);
1095                 VFS_MarkAvaliable(Node, 0);
1096         }
1097                 
1098         // Release the lock (we don't need it any more)
1099         Mutex_Release( &conn->lRecievedPackets );
1100
1101         LEAVE('i', len);
1102         return len;
1103 }
1104
1105 /**
1106  * \brief Send a data packet on a connection
1107  */
1108 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1109 {
1110         char    buf[sizeof(tTCPHeader)+Length];
1111         tTCPHeader      *packet = (void*)buf;
1112         
1113         packet->SourcePort = htons(Connection->LocalPort);
1114         packet->DestPort = htons(Connection->RemotePort);
1115         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1116         packet->WindowSize = htons(TCP_WINDOW_SIZE);
1117         
1118         packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1119         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1120         packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK;      // Hey, ACK if you can!
1121         
1122         memcpy(packet->Options, Data, Length);
1123         
1124         Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1125 #if HEXDUMP_OUTGOING
1126         Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1127 #endif
1128         
1129         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1130         
1131         Connection->NextSequenceSend += Length;
1132 }
1133
1134 /**
1135  * \brief Send some bytes on a connection
1136  */
1137 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer)
1138 {
1139         tTCPConnection  *conn = Node->ImplPtr;
1140         size_t  rem = Length;
1141         
1142         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1143         
1144 //      #if DEBUG
1145 //      Debug_HexDump("TCP_Client_Write: Buffer = ",
1146 //              Buffer, Length);
1147 //      #endif
1148         
1149         // Check if connection is open
1150         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1151                 Threads_Yield();
1152         
1153         if( conn->State != TCP_ST_OPEN ) {
1154                 VFS_MarkError(Node, 1);
1155                 LEAVE('i', -1);
1156                 return -1;
1157         }
1158         
1159         do
1160         {
1161                  int    len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1162                 
1163                 #if 0
1164                 // Wait for space in the buffer
1165                 Semaphore_Signal( &Connection->SentBufferSpace, len );
1166                 
1167                 // Save data to buffer (and update the length read by the ammount written)
1168                 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1169                 #endif
1170                 
1171                 // Send packet
1172                 TCP_INT_SendDataPacket(conn, len, Buffer);
1173                 
1174                 Buffer += len;
1175                 rem -= len;
1176         } while( rem > 0 );
1177         
1178         LEAVE('i', Length);
1179         return Length;
1180 }
1181
1182 /**
1183  * \brief Open a connection to another host using TCP
1184  * \param Conn  Connection structure
1185  */
1186 void TCP_StartConnection(tTCPConnection *Conn)
1187 {
1188         tTCPHeader      hdr = {0};
1189
1190         Conn->State = TCP_ST_SYN_SENT;
1191
1192         hdr.SourcePort = htons(Conn->LocalPort);
1193         hdr.DestPort = htons(Conn->RemotePort);
1194         Conn->NextSequenceSend = rand();
1195         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1196         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1197         hdr.Flags = TCP_FLAG_SYN;
1198         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
1199         hdr.Checksum = 0;       // TODO
1200         
1201         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1202         
1203         Conn->NextSequenceSend ++;
1204         Conn->State = TCP_ST_SYN_SENT;
1205
1206         return ;
1207 }
1208
1209 /**
1210  * \brief Control a client socket
1211  */
1212 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1213 {
1214         tTCPConnection  *conn = Node->ImplPtr;
1215         
1216         ENTER("pNode iID pData", Node, ID, Data);
1217
1218         switch(ID)
1219         {
1220         case 4: // Get/Set local port
1221                 if(!Data)
1222                         LEAVE_RET('i', conn->LocalPort);
1223                 if(conn->State != TCP_ST_CLOSED)
1224                         LEAVE_RET('i', -1);
1225                 if(!CheckMem(Data, sizeof(Uint16)))
1226                         LEAVE_RET('i', -1);
1227
1228                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1229                         LEAVE_RET('i', -1);
1230
1231                 conn->LocalPort = *(Uint16*)Data;
1232                 LEAVE_RET('i', conn->LocalPort);
1233
1234         case 5: // Get/Set remote port
1235                 if(!Data)       LEAVE_RET('i', conn->RemotePort);
1236                 if(conn->State != TCP_ST_CLOSED)        LEAVE_RET('i', -1);
1237                 if(!CheckMem(Data, sizeof(Uint16)))     LEAVE_RET('i', -1);
1238                 conn->RemotePort = *(Uint16*)Data;
1239                 LEAVE_RET('i', conn->RemotePort);
1240
1241         case 6: // Set Remote IP
1242                 if( conn->State != TCP_ST_CLOSED )
1243                         LEAVE_RET('i', -1);
1244                 if( conn->Interface->Type == 4 )
1245                 {
1246                         if(!CheckMem(Data, sizeof(tIPv4)))      LEAVE_RET('i', -1);
1247                         conn->RemoteIP.v4 = *(tIPv4*)Data;
1248                 }
1249                 else if( conn->Interface->Type == 6 )
1250                 {
1251                         if(!CheckMem(Data, sizeof(tIPv6)))      LEAVE_RET('i', -1);
1252                         conn->RemoteIP.v6 = *(tIPv6*)Data;
1253                 }
1254                 LEAVE_RET('i', 0);
1255
1256         case 7: // Connect
1257                 if(conn->LocalPort == 0xFFFF)
1258                         conn->LocalPort = TCP_GetUnusedPort();
1259                 if(conn->RemotePort == -1)
1260                         LEAVE_RET('i', 0);
1261
1262                 {
1263                         tTime   timeout_end = now() + conn->Interface->TimeoutDelay;
1264         
1265                         TCP_StartConnection(conn);
1266                         // TODO: Wait for connection to open
1267                         while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1268                                 Threads_Yield();
1269                         }
1270                         if( conn->State == TCP_ST_SYN_SENT )
1271                                 LEAVE_RET('i', 0);
1272                 }
1273
1274                 LEAVE_RET('i', 1);
1275         
1276         // Get recieve buffer length
1277         case 8:
1278                 LEAVE_RET('i', conn->RecievedBuffer->Length);
1279         }
1280
1281         return 0;
1282 }
1283
1284 void TCP_Client_Close(tVFS_Node *Node)
1285 {
1286         tTCPConnection  *conn = Node->ImplPtr;
1287         tTCPHeader      packet;
1288         
1289         ENTER("pNode", Node);
1290         
1291         if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1292         {
1293                 packet.SourcePort = htons(conn->LocalPort);
1294                 packet.DestPort = htons(conn->RemotePort);
1295                 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1296                 packet.WindowSize = TCP_WINDOW_SIZE;
1297                 
1298                 packet.AcknowlegementNumber = 0;
1299                 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1300                 packet.Flags = TCP_FLAG_FIN;
1301                 
1302                 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1303         }
1304         
1305         switch( conn->State )
1306         {
1307         case TCP_ST_CLOSE_WAIT:
1308                 conn->State = TCP_ST_LAST_ACK;
1309                 break;
1310         case TCP_ST_OPEN:
1311                 conn->State = TCP_ST_FIN_WAIT1;
1312                 while( conn->State == TCP_ST_FIN_WAIT1 )        Threads_Yield();
1313                 break;
1314         default:
1315                 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1316                 break;
1317         }
1318         
1319         free(conn);
1320         
1321         LEAVE('-');
1322 }
1323
1324 /**
1325  * \brief Checks if a value is between two others (after taking into account wrapping)
1326  */
1327 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1328 {
1329         if( MaxValue < 0xFFFFFFFF )
1330         {
1331                 Lower %= MaxValue + 1;
1332                 Value %= MaxValue + 1;
1333                 Higher %= MaxValue + 1;
1334         }
1335         
1336         // Simple Case, no wrap ?
1337         //       Lower Value Higher
1338         // | ... + ... + ... + ... |
1339
1340         if( Lower < Higher ) {
1341                 return Lower < Value && Value < Higher;
1342         }
1343         // Higher has wrapped below lower
1344         
1345         // Value > Lower ?
1346         //       Higher Lower Value
1347         // | ... +  ... + ... + ... |
1348         if( Value > Lower ) {
1349                 return 1;
1350         }
1351         
1352         // Value < Higher ?
1353         //       Value Higher Lower
1354         // | ... + ... +  ... + ... |
1355         if( Value < Higher ) {
1356                 return 1;
1357         }
1358         
1359         return 0;
1360 }

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