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

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