7ba25565a4059cb6c192813b91d8d3579d65abd6
[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         // Sanity Check
919         itoa(tmp, id, 16, 8, '0');
920         if(strcmp(tmp, Name) != 0) {
921                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
922                 LEAVE('n');
923                 return NULL;
924         }
925         
926         Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
927         Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
928         Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
929         
930         // Search
931         SHORTLOCK( &srv->lConnections );
932         for(conn = srv->Connections;
933                 conn;
934                 conn = conn->Next)
935         {
936                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
937                 if(conn->Node.ImplInt == id)    break;
938         }
939         SHORTREL( &srv->lConnections );
940         
941         // If not found, ret NULL
942         if(!conn) {
943                 LOG("Connection %i not found", id);
944                 LEAVE('n');
945                 return NULL;
946         }
947         
948         // Return node
949         LEAVE('p', &conn->Node);
950         return &conn->Node;
951 }
952
953 /**
954  * \brief Handle IOCtl calls
955  */
956 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
957 {
958         tTCPListener    *srv = Node->ImplPtr;
959
960         switch(ID)
961         {
962         case 4: // Get/Set Port
963                 if(!Data)       // Get Port
964                         return srv->Port;
965
966                 if(srv->Port)   // Wait, you can't CHANGE the port
967                         return -1;
968
969                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
970                         return -1;
971
972                 // Permissions check
973                 if(Threads_GetUID() != 0
974                 && *(Uint16*)Data != 0
975                 && *(Uint16*)Data < 1024)
976                         return -1;
977
978                 // TODO: Check if a port is in use
979
980                 // Set Port
981                 srv->Port = *(Uint16*)Data;
982                 if(srv->Port == 0)      // Allocate a random port
983                         srv->Port = TCP_GetUnusedPort();
984                 else    // Else, mark this as used
985                         TCP_AllocatePort(srv->Port);
986                 
987                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
988                 
989                 return srv->Port;
990         }
991         return 0;
992 }
993
994 void TCP_Server_Close(tVFS_Node *Node)
995 {
996         free(Node->ImplPtr);
997 }
998
999 // --- Client
1000 /**
1001  * \brief Create a client node
1002  */
1003 tVFS_Node *TCP_Client_Init(tInterface *Interface)
1004 {
1005         tTCPConnection  *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
1006
1007         conn->State = TCP_ST_CLOSED;
1008         conn->Interface = Interface;
1009         conn->LocalPort = -1;
1010         conn->RemotePort = -1;
1011
1012         conn->Node.ImplPtr = conn;
1013         conn->Node.NumACLs = 1;
1014         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1015         conn->Node.Type = &gTCP_ClientNodeType;
1016
1017         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1018         #if 0
1019         conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1020         Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1021         #endif
1022         
1023         #if CACHE_FUTURE_PACKETS_IN_BYTES
1024         // Future recieved data (ahead of the expected sequence number)
1025         conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1026         conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1027         #endif
1028
1029         SHORTLOCK(&glTCP_OutbountCons);
1030         conn->Next = gTCP_OutbountCons;
1031         gTCP_OutbountCons = conn;
1032         SHORTREL(&glTCP_OutbountCons);
1033
1034         return &conn->Node;
1035 }
1036
1037 /**
1038  * \brief Wait for a packet and return it
1039  * \note If \a Length is smaller than the size of the packet, the rest
1040  *       of the packet's data will be discarded.
1041  */
1042 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1043 {
1044         tTCPConnection  *conn = Node->ImplPtr;
1045         size_t  len;
1046         
1047         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1048         LOG("conn = %p {State:%i}", conn, conn->State);
1049         
1050         // Check if connection is estabilishing
1051         // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1052         //   data to be availiable
1053         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1054                 Threads_Yield();
1055         
1056         // If the conneciton is not open, then clean out the recieved buffer
1057         if( conn->State != TCP_ST_OPEN )
1058         {
1059                 Mutex_Acquire( &conn->lRecievedPackets );
1060                 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1061                 Mutex_Release( &conn->lRecievedPackets );
1062                 
1063                 if( len == 0 ) {
1064                         VFS_MarkAvaliable(Node, 0);
1065                         LEAVE('i', -1);
1066                         return -1;
1067                 }
1068                 
1069                 LEAVE('i', len);
1070                 return len;
1071         }
1072         
1073         // Wait
1074         VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1075         
1076         // Lock list and read as much as possible (up to `Length`)
1077         Mutex_Acquire( &conn->lRecievedPackets );
1078         len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1079         
1080         if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1081                 LOG("Marking as none avaliable (len = %i)", len);
1082                 VFS_MarkAvaliable(Node, 0);
1083         }
1084                 
1085         // Release the lock (we don't need it any more)
1086         Mutex_Release( &conn->lRecievedPackets );
1087
1088         LEAVE('i', len);
1089         return len;
1090 }
1091
1092 /**
1093  * \brief Send a data packet on a connection
1094  */
1095 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, const void *Data)
1096 {
1097         char    buf[sizeof(tTCPHeader)+Length];
1098         tTCPHeader      *packet = (void*)buf;
1099         
1100         packet->SourcePort = htons(Connection->LocalPort);
1101         packet->DestPort = htons(Connection->RemotePort);
1102         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1103         packet->WindowSize = htons(TCP_WINDOW_SIZE);
1104         
1105         packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1106         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1107         packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK;      // Hey, ACK if you can!
1108         
1109         memcpy(packet->Options, Data, Length);
1110         
1111         Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1112 #if HEXDUMP_OUTGOING
1113         Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1114 #endif
1115         
1116         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1117         
1118         Connection->NextSequenceSend += Length;
1119 }
1120
1121 /**
1122  * \brief Send some bytes on a connection
1123  */
1124 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, const void *Buffer)
1125 {
1126         tTCPConnection  *conn = Node->ImplPtr;
1127         size_t  rem = Length;
1128         
1129         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1130         
1131 //      #if DEBUG
1132 //      Debug_HexDump("TCP_Client_Write: Buffer = ",
1133 //              Buffer, Length);
1134 //      #endif
1135         
1136         // Check if connection is open
1137         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1138                 Threads_Yield();
1139         
1140         if( conn->State != TCP_ST_OPEN ) {
1141                 VFS_MarkError(Node, 1);
1142                 LEAVE('i', -1);
1143                 return -1;
1144         }
1145         
1146         do
1147         {
1148                  int    len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1149                 
1150                 #if 0
1151                 // Wait for space in the buffer
1152                 Semaphore_Signal( &Connection->SentBufferSpace, len );
1153                 
1154                 // Save data to buffer (and update the length read by the ammount written)
1155                 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1156                 #endif
1157                 
1158                 // Send packet
1159                 TCP_INT_SendDataPacket(conn, len, Buffer);
1160                 
1161                 Buffer += len;
1162                 rem -= len;
1163         } while( rem > 0 );
1164         
1165         LEAVE('i', Length);
1166         return Length;
1167 }
1168
1169 /**
1170  * \brief Open a connection to another host using TCP
1171  * \param Conn  Connection structure
1172  */
1173 void TCP_StartConnection(tTCPConnection *Conn)
1174 {
1175         tTCPHeader      hdr = {0};
1176
1177         Conn->State = TCP_ST_SYN_SENT;
1178
1179         hdr.SourcePort = htons(Conn->LocalPort);
1180         hdr.DestPort = htons(Conn->RemotePort);
1181         Conn->NextSequenceSend = rand();
1182         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1183         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1184         hdr.Flags = TCP_FLAG_SYN;
1185         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
1186         hdr.Checksum = 0;       // TODO
1187         
1188         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1189         
1190         Conn->NextSequenceSend ++;
1191         Conn->State = TCP_ST_SYN_SENT;
1192
1193         return ;
1194 }
1195
1196 /**
1197  * \brief Control a client socket
1198  */
1199 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1200 {
1201         tTCPConnection  *conn = Node->ImplPtr;
1202         
1203         ENTER("pNode iID pData", Node, ID, Data);
1204
1205         switch(ID)
1206         {
1207         case 4: // Get/Set local port
1208                 if(!Data)
1209                         LEAVE_RET('i', conn->LocalPort);
1210                 if(conn->State != TCP_ST_CLOSED)
1211                         LEAVE_RET('i', -1);
1212                 if(!CheckMem(Data, sizeof(Uint16)))
1213                         LEAVE_RET('i', -1);
1214
1215                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1216                         LEAVE_RET('i', -1);
1217
1218                 conn->LocalPort = *(Uint16*)Data;
1219                 LEAVE_RET('i', conn->LocalPort);
1220
1221         case 5: // Get/Set remote port
1222                 if(!Data)       LEAVE_RET('i', conn->RemotePort);
1223                 if(conn->State != TCP_ST_CLOSED)        LEAVE_RET('i', -1);
1224                 if(!CheckMem(Data, sizeof(Uint16)))     LEAVE_RET('i', -1);
1225                 conn->RemotePort = *(Uint16*)Data;
1226                 LEAVE_RET('i', conn->RemotePort);
1227
1228         case 6: // Set Remote IP
1229                 if( conn->State != TCP_ST_CLOSED )
1230                         LEAVE_RET('i', -1);
1231                 if( conn->Interface->Type == 4 )
1232                 {
1233                         if(!CheckMem(Data, sizeof(tIPv4)))      LEAVE_RET('i', -1);
1234                         conn->RemoteIP.v4 = *(tIPv4*)Data;
1235                 }
1236                 else if( conn->Interface->Type == 6 )
1237                 {
1238                         if(!CheckMem(Data, sizeof(tIPv6)))      LEAVE_RET('i', -1);
1239                         conn->RemoteIP.v6 = *(tIPv6*)Data;
1240                 }
1241                 LEAVE_RET('i', 0);
1242
1243         case 7: // Connect
1244                 if(conn->LocalPort == 0xFFFF)
1245                         conn->LocalPort = TCP_GetUnusedPort();
1246                 if(conn->RemotePort == -1)
1247                         LEAVE_RET('i', 0);
1248
1249                 {
1250                         tTime   timeout_end = now() + conn->Interface->TimeoutDelay;
1251         
1252                         TCP_StartConnection(conn);
1253                         // TODO: Wait for connection to open
1254                         while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1255                                 Threads_Yield();
1256                         }
1257                         if( conn->State == TCP_ST_SYN_SENT )
1258                                 LEAVE_RET('i', 0);
1259                 }
1260
1261                 LEAVE_RET('i', 1);
1262         
1263         // Get recieve buffer length
1264         case 8:
1265                 LEAVE_RET('i', conn->RecievedBuffer->Length);
1266         }
1267
1268         return 0;
1269 }
1270
1271 void TCP_Client_Close(tVFS_Node *Node)
1272 {
1273         tTCPConnection  *conn = Node->ImplPtr;
1274         tTCPHeader      packet;
1275         
1276         ENTER("pNode", Node);
1277         
1278         if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1279         {
1280                 packet.SourcePort = htons(conn->LocalPort);
1281                 packet.DestPort = htons(conn->RemotePort);
1282                 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1283                 packet.WindowSize = TCP_WINDOW_SIZE;
1284                 
1285                 packet.AcknowlegementNumber = 0;
1286                 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1287                 packet.Flags = TCP_FLAG_FIN;
1288                 
1289                 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1290         }
1291         
1292         switch( conn->State )
1293         {
1294         case TCP_ST_CLOSE_WAIT:
1295                 conn->State = TCP_ST_LAST_ACK;
1296                 break;
1297         case TCP_ST_OPEN:
1298                 conn->State = TCP_ST_FIN_WAIT1;
1299                 while( conn->State == TCP_ST_FIN_WAIT1 )        Threads_Yield();
1300                 break;
1301         default:
1302                 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1303                 break;
1304         }
1305         
1306         free(conn);
1307         
1308         LEAVE('-');
1309 }
1310
1311 /**
1312  * \brief Checks if a value is between two others (after taking into account wrapping)
1313  */
1314 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1315 {
1316         if( MaxValue < 0xFFFFFFFF )
1317         {
1318                 Lower %= MaxValue + 1;
1319                 Value %= MaxValue + 1;
1320                 Higher %= MaxValue + 1;
1321         }
1322         
1323         // Simple Case, no wrap ?
1324         //       Lower Value Higher
1325         // | ... + ... + ... + ... |
1326
1327         if( Lower < Higher ) {
1328                 return Lower < Value && Value < Higher;
1329         }
1330         // Higher has wrapped below lower
1331         
1332         // Value > Lower ?
1333         //       Higher Lower Value
1334         // | ... +  ... + ... + ... |
1335         if( Value > Lower ) {
1336                 return 1;
1337         }
1338         
1339         // Value < Higher ?
1340         //       Value Higher Lower
1341         // | ... + ... +  ... + ... |
1342         if( Value < Higher ) {
1343                 return 1;
1344         }
1345         
1346         return 0;
1347 }

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