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

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