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

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