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

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