IPStack - Cleaned up unneeded malloc() calls
[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 void    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                         // Ooh, Goodie! Add it to the recieved list
428                         TCP_INT_AppendRecieved(Connection,
429                                 (Uint8*)Header + (Header->DataOffset>>4)*4,
430                                 dataLen
431                                 );
432                         Log_Log("TCP", "0x%08x += %i", Connection->NextSequenceRcv, dataLen);
433                         Connection->NextSequenceRcv += dataLen;
434                         
435                         // TODO: This should be moved out of the watcher thread,
436                         // so that a single lost packet on one connection doesn't cause
437                         // all connections on the interface to lag.
438                         // - Meh, no real issue, as the cache shouldn't be that large
439                         TCP_INT_UpdateRecievedFromFuture(Connection);
440                 
441                         // ACK Packet
442                         Header->DestPort = Header->SourcePort;
443                         Header->SourcePort = htons(Connection->LocalPort);
444                         Header->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
445                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
446                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
447                         Header->Flags &= TCP_FLAG_SYN;  // Eliminate all flags save for SYN
448                         Header->Flags |= TCP_FLAG_ACK;  // Add ACK
449                         Log_Log("TCP", "Sending ACK for 0x%08x", Connection->NextSequenceRcv);
450                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
451                         //Connection->NextSequenceSend ++;
452                 }
453                 // Check if the packet is in window
454                 else if( WrapBetween(Connection->NextSequenceRcv, sequence_num,
455                                 Connection->NextSequenceRcv+TCP_WINDOW_SIZE, 0xFFFFFFFF) )
456                 {
457                         Uint8   *dataptr = (Uint8*)Header + (Header->DataOffset>>4)*4;
458                         #if CACHE_FUTURE_PACKETS_IN_BYTES
459                         Uint32  index;
460                          int    i;
461                         
462                         index = sequence_num % TCP_WINDOW_SIZE;
463                         for( i = 0; i < dataLen; i ++ )
464                         {
465                                 Connection->FuturePacketValidBytes[index/8] |= 1 << (index%8);
466                                 Connection->FuturePacketData[index] = dataptr[i];
467                                 // Do a wrap increment
468                                 index ++;
469                                 if(index == TCP_WINDOW_SIZE)    index = 0;
470                         }
471                         #else
472                         tTCPStoredPacket        *pkt, *tmp, *prev = NULL;
473                         
474                         // Allocate and fill cached packet
475                         pkt = malloc( sizeof(tTCPStoredPacket) + dataLen );
476                         pkt->Next = NULL;
477                         pkt->Sequence = ntohl(Header->SequenceNumber);
478                         pkt->Length = dataLen;
479                         memcpy(pkt->Data, dataptr, dataLen);
480                         
481                         Log_Log("TCP", "We missed a packet, caching",
482                                 pkt->Sequence, Connection->NextSequenceRcv);
483                         
484                         // No? Well, let's cache it and look at it later
485                         SHORTLOCK( &Connection->lFuturePackets );
486                         for(tmp = Connection->FuturePackets;
487                                 tmp;
488                                 prev = tmp, tmp = tmp->Next)
489                         {
490                                 if(tmp->Sequence >= pkt->Sequence)      break;
491                         }
492                         
493                         // Add if before first, or sequences don't match 
494                         if( !tmp || tmp->Sequence != pkt->Sequence )
495                         {
496                                 if(prev)
497                                         prev->Next = pkt;
498                                 else
499                                         Connection->FuturePackets = pkt;
500                                 pkt->Next = tmp;
501                         }
502                         // Replace if larger
503                         else if(pkt->Length > tmp->Length)
504                         {
505                                 if(prev)
506                                         prev->Next = pkt;
507                                 pkt->Next = tmp->Next;
508                                 free(tmp);
509                         }
510                         else
511                         {
512                                 free(pkt);      // TODO: Find some way to remove this
513                         }
514                         SHORTREL( &Connection->lFuturePackets );
515                         #endif
516                 }
517                 // Badly out of sequence packet
518                 else
519                 {
520                         Log_Log("TCP", "Fully out of sequence packet (0x%08x not between 0x%08x and 0x%08x), dropped",
521                                 sequence_num, Connection->NextSequenceRcv, Connection->NextSequenceRcv+TCP_WINDOW_SIZE);
522                         // TODO: Spec says we should send an empty ACK with the current state
523                 }
524                 break;
525         
526         // --- Remote close states
527         case TCP_ST_CLOSE_WAIT:
528                 
529                 // Ignore everything, CLOSE_WAIT is terminated by the client
530                 Log_Debug("TCP", "CLOSE WAIT - Ignoring packets");
531                 
532                 break;
533         
534         // LAST-ACK - Waiting for the ACK of FIN (from CLOSE WAIT)
535         case TCP_ST_LAST_ACK:
536                 if( Header->Flags & TCP_FLAG_ACK )
537                 {
538                         Connection->State = TCP_ST_FINISHED;    // Connection completed
539                         Log_Log("TCP", "LAST-ACK to CLOSED - Connection remote closed");
540                         // TODO: Destrory the TCB
541                 }
542                 break;
543         
544         // --- Local close States
545         case TCP_ST_FIN_WAIT1:
546                 if( Header->Flags & TCP_FLAG_FIN )
547                 {
548                         Connection->State = TCP_ST_CLOSING;
549                         Log_Debug("TCP", "Conn %p closed, sent FIN and recieved FIN", Connection);
550                         VFS_MarkError(&Connection->Node, 1);
551                         
552                         // ACK Packet
553                         Header->DestPort = Header->SourcePort;
554                         Header->SourcePort = htons(Connection->LocalPort);
555                         Header->AcknowlegementNumber = Header->SequenceNumber;
556                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
557                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
558                         Header->Flags = TCP_FLAG_ACK;
559                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
560                         break ;
561                 }
562                 
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_FIN_WAIT2;
567                         Log_Debug("TCP", "Conn %p closed, sent FIN ACKed", Connection);
568                         VFS_MarkError(&Connection->Node, 1);
569                         return ;
570                 }
571                 break;
572         
573         case TCP_ST_FIN_WAIT2:
574                 if( Header->Flags & TCP_FLAG_FIN )
575                 {
576                         Connection->State = TCP_ST_TIME_WAIT;
577                         Log_Debug("TCP", "FIN sent and recieved, ACKing and going into TIME WAIT %p FINWAIT-2 -> TIME WAIT", Connection);
578                         // Send ACK
579                         Header->DestPort = Header->SourcePort;
580                         Header->SourcePort = htons(Connection->LocalPort);
581                         Header->AcknowlegementNumber = Header->SequenceNumber;
582                         Header->SequenceNumber = htonl(Connection->NextSequenceSend);
583                         Header->WindowSize = htons(TCP_WINDOW_SIZE);
584                         Header->Flags = TCP_FLAG_ACK;
585                         TCP_SendPacket( Connection, sizeof(tTCPHeader), Header );
586                 }
587                 break;
588         
589         case TCP_ST_CLOSING:
590                 // TODO: Make sure that the packet is actually ACKing the FIN
591                 if( Header->Flags & TCP_FLAG_ACK )
592                 {
593                         Connection->State = TCP_ST_TIME_WAIT;
594                         Log_Debug("TCP", "Conn %p CLOSING -> TIME WAIT", Connection);
595                         VFS_MarkError(&Connection->Node, 1);
596                         return ;
597                 }
598                 break;
599         
600         // --- Closed (or near closed) states) ---
601         case TCP_ST_TIME_WAIT:
602                 Log_Log("TCP", "Packets on Time-Wait, ignored");
603                 break;
604         
605         case TCP_ST_FINISHED:
606                 Log_Log("TCP", "Packets when CLOSED, ignoring");
607                 break;
608         
609         //default:
610         //      Log_Warning("TCP", "Unhandled TCP state %i", Connection->State);
611         //      break;
612         }
613         
614 }
615
616 /**
617  * \brief Appends a packet to the recieved list
618  * \param Connection    Connection structure
619  * \param Data  Packet contents
620  * \param Length        Length of \a Data
621  */
622 void TCP_INT_AppendRecieved(tTCPConnection *Connection, const void *Data, size_t Length)
623 {
624         Mutex_Acquire( &Connection->lRecievedPackets );
625         if(Connection->RecievedBuffer->Length + Length > Connection->RecievedBuffer->Space )
626         {
627                 Log_Error("TCP", "Buffer filled, packet dropped (%s)",
628                 //      TCP_INT_DumpConnection(Connection)
629                         ""
630                         );
631                 return ;
632         }
633         
634         RingBuffer_Write( Connection->RecievedBuffer, Data, Length );
635
636         VFS_MarkAvaliable(&Connection->Node, 1);
637         
638         Mutex_Release( &Connection->lRecievedPackets );
639 }
640
641 /**
642  * \brief Updates the connections recieved list from the future list
643  * \param Connection    Connection structure
644  * 
645  * Updates the recieved packets list with packets from the future (out 
646  * of order) packets list that are now able to be added in direct
647  * sequence.
648  */
649 void TCP_INT_UpdateRecievedFromFuture(tTCPConnection *Connection)
650 {
651         #if CACHE_FUTURE_PACKETS_IN_BYTES
652          int    i, length = 0;
653         Uint32  index;
654         
655         // Calculate length of contiguous bytes
656         length = Connection->HighestSequenceRcvd - Connection->NextSequenceRcv;
657         index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
658         for( i = 0; i < length; i ++ )
659         {
660                 if( Connection->FuturePacketValidBytes[i / 8] == 0xFF ) {
661                         i += 7; index += 7;
662                         continue;
663                 }
664                 else if( !(Connection->FuturePacketValidBytes[i / 8] & (1 << (i%8))) )
665                         break;
666                 
667                 index ++;
668                 if(index > TCP_WINDOW_SIZE)
669                         index -= TCP_WINDOW_SIZE;
670         }
671         length = i;
672         
673         index = Connection->NextSequenceRcv % TCP_WINDOW_SIZE;
674         
675         // Write data to to the ring buffer
676         if( TCP_WINDOW_SIZE - index > length )
677         {
678                 // Simple case
679                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, length );
680         }
681         else
682         {
683                  int    endLen = TCP_WINDOW_SIZE - index;
684                 // 2-part case
685                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData + index, endLen );
686                 RingBuffer_Write( Connection->RecievedBuffer, Connection->FuturePacketData, endLen - length );
687         }
688         
689         // Mark (now saved) bytes as invalid
690         // - Align index
691         while(index % 8 && length)
692         {
693                 Connection->FuturePacketData[index] = 0;
694                 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
695                 index ++;
696                 if(index > TCP_WINDOW_SIZE)
697                         index -= TCP_WINDOW_SIZE;
698                 length --;
699         }
700         while( length > 7 )
701         {
702                 Connection->FuturePacketData[index] = 0;
703                 Connection->FuturePacketValidBytes[index/8] = 0;
704                 length -= 8;
705                 index += 8;
706                 if(index > TCP_WINDOW_SIZE)
707                         index -= TCP_WINDOW_SIZE;
708         }
709         while(length)
710         {
711                 Connection->FuturePacketData[index] = 0;
712                 Connection->FuturePacketData[index/8] &= ~(1 << (index%8));
713                 index ++;
714                 if(index > TCP_WINDOW_SIZE)
715                         index -= TCP_WINDOW_SIZE;
716                 length --;
717         }
718         
719         #else
720         tTCPStoredPacket        *pkt;
721         for(;;)
722         {
723                 SHORTLOCK( &Connection->lFuturePackets );
724                 
725                 // Clear out duplicates from cache
726                 // - If a packet has just been recieved, and it is expected, then
727                 //   (since NextSequenceRcv = rcvd->Sequence + rcvd->Length) all
728                 //   packets in cache that are smaller than the next expected
729                 //   are now defunct.
730                 pkt = Connection->FuturePackets;
731                 while(pkt && pkt->Sequence < Connection->NextSequenceRcv)
732                 {
733                         tTCPStoredPacket        *next = pkt->Next;
734                         free(pkt);
735                         pkt = next;
736                 }
737                 
738                 // If there's no packets left in cache, stop looking
739                 if(!pkt || pkt->Sequence > Connection->NextSequenceRcv) {
740                         SHORTREL( &Connection->lFuturePackets );
741                         return;
742                 }
743                 
744                 // Delete packet from future list
745                 Connection->FuturePackets = pkt->Next;
746                 
747                 // Release list
748                 SHORTREL( &Connection->lFuturePackets );
749                 
750                 // Looks like we found one
751                 TCP_INT_AppendRecieved(Connection, pkt);
752                 Connection->NextSequenceRcv += pkt->Length;
753                 free(pkt);
754         }
755         #endif
756 }
757
758 /**
759  * \fn Uint16 TCP_GetUnusedPort()
760  * \brief Gets an unused port and allocates it
761  */
762 Uint16 TCP_GetUnusedPort()
763 {
764         Uint16  ret;
765
766         // Get Next outbound port
767         ret = giTCP_NextOutPort++;
768         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
769         {
770                 ret ++;
771                 giTCP_NextOutPort++;
772                 if(giTCP_NextOutPort == 0x10000) {
773                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
774                 }
775         }
776
777         // Mark the new port as used
778         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
779
780         return ret;
781 }
782
783 /**
784  * \fn int TCP_AllocatePort(Uint16 Port)
785  * \brief Marks a port as used
786  */
787 int TCP_AllocatePort(Uint16 Port)
788 {
789         // Check if the port has already been allocated
790         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
791                 return 0;
792
793         // Allocate
794         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
795
796         return 1;
797 }
798
799 /**
800  * \fn int TCP_DeallocatePort(Uint16 Port)
801  * \brief Marks a port as unused
802  */
803 int TCP_DeallocatePort(Uint16 Port)
804 {
805         // Check if the port has already been allocated
806         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
807                 return 0;
808
809         // Allocate
810         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
811
812         return 1;
813 }
814
815 // --- Server
816 tVFS_Node *TCP_Server_Init(tInterface *Interface)
817 {
818         tTCPListener    *srv;
819         
820         srv = malloc( sizeof(tTCPListener) );
821
822         if( srv == NULL ) {
823                 Log_Warning("TCP", "malloc failed for listener (%i) bytes", sizeof(tTCPListener));
824                 return NULL;
825         }
826
827         srv->Interface = Interface;
828         srv->Port = 0;
829         srv->NextID = 0;
830         srv->Connections = NULL;
831         srv->ConnectionsTail = NULL;
832         srv->NewConnections = NULL;
833         srv->Next = NULL;
834         srv->Node.Flags = VFS_FFLAG_DIRECTORY;
835         srv->Node.Size = -1;
836         srv->Node.ImplPtr = srv;
837         srv->Node.NumACLs = 1;
838         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
839         srv->Node.ReadDir = TCP_Server_ReadDir;
840         srv->Node.FindDir = TCP_Server_FindDir;
841         srv->Node.IOCtl = TCP_Server_IOCtl;
842         srv->Node.Close = TCP_Server_Close;
843
844         SHORTLOCK(&glTCP_Listeners);
845         srv->Next = gTCP_Listeners;
846         gTCP_Listeners = srv;
847         SHORTREL(&glTCP_Listeners);
848
849         return &srv->Node;
850 }
851
852 /**
853  * \brief Wait for a new connection and return the connection ID
854  * \note Blocks until a new connection is made
855  * \param Node  Server node
856  * \param Pos   Position (ignored)
857  */
858 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
859 {
860         tTCPListener    *srv = Node->ImplPtr;
861         tTCPConnection  *conn;
862         char    *ret;
863         
864         ENTER("pNode iPos", Node, Pos);
865
866         Log_Log("TCP", "Thread %i waiting for a connection", Threads_GetTID());
867         for(;;)
868         {
869                 SHORTLOCK( &srv->lConnections );
870                 if( srv->NewConnections != NULL )       break;
871                 SHORTREL( &srv->lConnections );
872                 Threads_Yield();        // TODO: Sleep until poked
873                 continue;
874         }
875         
876
877         // Increment the new list (the current connection is still on the 
878         // normal list)
879         conn = srv->NewConnections;
880         srv->NewConnections = conn->Next;
881         
882         SHORTREL( &srv->lConnections );
883         
884         LOG("conn = %p", conn);
885         LOG("srv->Connections = %p", srv->Connections);
886         LOG("srv->NewConnections = %p", srv->NewConnections);
887         LOG("srv->ConnectionsTail = %p", srv->ConnectionsTail);
888
889         ret = malloc(9);
890         itoa(ret, conn->Node.ImplInt, 16, 8, '0');
891         Log_Log("TCP", "Thread %i got '%s'", Threads_GetTID(), ret);
892         LEAVE('s', ret);
893         return ret;
894 }
895
896 /**
897  * \brief Gets a client connection node
898  * \param Node  Server node
899  * \param Name  Hexadecimal ID of the node
900  */
901 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, const char *Name)
902 {
903         tTCPConnection  *conn;
904         tTCPListener    *srv = Node->ImplPtr;
905         char    tmp[9];
906          int    id = atoi(Name);
907         
908         ENTER("pNode sName", Node, Name);
909         
910         // Sanity Check
911         itoa(tmp, id, 16, 8, '0');
912         if(strcmp(tmp, Name) != 0) {
913                 LOG("'%s' != '%s' (%08x)", Name, tmp, id);
914                 LEAVE('n');
915                 return NULL;
916         }
917         
918         Log_Debug("TCP", "srv->Connections = %p", srv->Connections);
919         Log_Debug("TCP", "srv->NewConnections = %p", srv->NewConnections);
920         Log_Debug("TCP", "srv->ConnectionsTail = %p", srv->ConnectionsTail);
921         
922         // Search
923         SHORTLOCK( &srv->lConnections );
924         for(conn = srv->Connections;
925                 conn;
926                 conn = conn->Next)
927         {
928                 LOG("conn->Node.ImplInt = %i", conn->Node.ImplInt);
929                 if(conn->Node.ImplInt == id)    break;
930         }
931         SHORTREL( &srv->lConnections );
932         
933         // If not found, ret NULL
934         if(!conn) {
935                 LOG("Connection %i not found", id);
936                 LEAVE('n');
937                 return NULL;
938         }
939         
940         // Return node
941         LEAVE('p', &conn->Node);
942         return &conn->Node;
943 }
944
945 /**
946  * \brief Handle IOCtl calls
947  */
948 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
949 {
950         tTCPListener    *srv = Node->ImplPtr;
951
952         switch(ID)
953         {
954         case 4: // Get/Set Port
955                 if(!Data)       // Get Port
956                         return srv->Port;
957
958                 if(srv->Port)   // Wait, you can't CHANGE the port
959                         return -1;
960
961                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
962                         return -1;
963
964                 // Permissions check
965                 if(Threads_GetUID() != 0
966                 && *(Uint16*)Data != 0
967                 && *(Uint16*)Data < 1024)
968                         return -1;
969
970                 // TODO: Check if a port is in use
971
972                 // Set Port
973                 srv->Port = *(Uint16*)Data;
974                 if(srv->Port == 0)      // Allocate a random port
975                         srv->Port = TCP_GetUnusedPort();
976                 else    // Else, mark this as used
977                         TCP_AllocatePort(srv->Port);
978                 
979                 Log_Log("TCP", "Server %p listening on port %i", srv, srv->Port);
980                 
981                 return srv->Port;
982         }
983         return 0;
984 }
985
986 void TCP_Server_Close(tVFS_Node *Node)
987 {
988         free(Node->ImplPtr);
989 }
990
991 // --- Client
992 /**
993  * \brief Create a client node
994  */
995 tVFS_Node *TCP_Client_Init(tInterface *Interface)
996 {
997         tTCPConnection  *conn = calloc( sizeof(tTCPConnection) + TCP_WINDOW_SIZE + TCP_WINDOW_SIZE/8, 1 );
998
999         conn->State = TCP_ST_CLOSED;
1000         conn->Interface = Interface;
1001         conn->LocalPort = -1;
1002         conn->RemotePort = -1;
1003
1004         conn->Node.ImplPtr = conn;
1005         conn->Node.NumACLs = 1;
1006         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
1007         conn->Node.Read = TCP_Client_Read;
1008         conn->Node.Write = TCP_Client_Write;
1009         conn->Node.IOCtl = TCP_Client_IOCtl;
1010         conn->Node.Close = TCP_Client_Close;
1011
1012         conn->RecievedBuffer = RingBuffer_Create( TCP_RECIEVE_BUFFER_SIZE );
1013         #if 0
1014         conn->SentBuffer = RingBuffer_Create( TCP_SEND_BUFFER_SIZE );
1015         Semaphore_Init(conn->SentBufferSpace, 0, TCP_SEND_BUFFER_SIZE, "TCP SentBuffer", conn->Name);
1016         #endif
1017         
1018         #if CACHE_FUTURE_PACKETS_IN_BYTES
1019         // Future recieved data (ahead of the expected sequence number)
1020         conn->FuturePacketData = (Uint8*)conn + sizeof(tTCPConnection);
1021         conn->FuturePacketValidBytes = conn->FuturePacketData + TCP_WINDOW_SIZE;
1022         #endif
1023
1024         SHORTLOCK(&glTCP_OutbountCons);
1025         conn->Next = gTCP_OutbountCons;
1026         gTCP_OutbountCons = conn;
1027         SHORTREL(&glTCP_OutbountCons);
1028
1029         return &conn->Node;
1030 }
1031
1032 /**
1033  * \brief Wait for a packet and return it
1034  * \note If \a Length is smaller than the size of the packet, the rest
1035  *       of the packet's data will be discarded.
1036  */
1037 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1038 {
1039         tTCPConnection  *conn = Node->ImplPtr;
1040         size_t  len;
1041         
1042         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1043         LOG("conn = %p {State:%i}", conn, conn->State);
1044         
1045         // Check if connection is estabilishing
1046         // - TODO: Sleep instead (maybe using VFS_SelectNode to wait for the
1047         //   data to be availiable
1048         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1049                 Threads_Yield();
1050         
1051         // If the conneciton is not open, then clean out the recieved buffer
1052         if( conn->State != TCP_ST_OPEN )
1053         {
1054                 Mutex_Acquire( &conn->lRecievedPackets );
1055                 len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1056                 Mutex_Release( &conn->lRecievedPackets );
1057                 
1058                 if( len == 0 ) {
1059                         VFS_MarkAvaliable(Node, 0);
1060                         LEAVE('i', -1);
1061                         return -1;
1062                 }
1063                 
1064                 LEAVE('i', len);
1065                 return len;
1066         }
1067         
1068         // Wait
1069         VFS_SelectNode(Node, VFS_SELECT_READ|VFS_SELECT_ERROR, NULL, "TCP_Client_Read");
1070         
1071         // Lock list and read as much as possible (up to `Length`)
1072         Mutex_Acquire( &conn->lRecievedPackets );
1073         len = RingBuffer_Read( Buffer, conn->RecievedBuffer, Length );
1074         
1075         if( len == 0 || conn->RecievedBuffer->Length == 0 ) {
1076                 LOG("Marking as none avaliable (len = %i)", len);
1077                 VFS_MarkAvaliable(Node, 0);
1078         }
1079                 
1080         // Release the lock (we don't need it any more)
1081         Mutex_Release( &conn->lRecievedPackets );
1082
1083         LEAVE('i', len);
1084         return len;
1085 }
1086
1087 /**
1088  * \brief Send a data packet on a connection
1089  */
1090 void TCP_INT_SendDataPacket(tTCPConnection *Connection, size_t Length, void *Data)
1091 {
1092         char    buf[sizeof(tTCPHeader)+Length];
1093         tTCPHeader      *packet = (void*)buf;
1094         
1095         packet->SourcePort = htons(Connection->LocalPort);
1096         packet->DestPort = htons(Connection->RemotePort);
1097         packet->DataOffset = (sizeof(tTCPHeader)/4)*16;
1098         packet->WindowSize = htons(TCP_WINDOW_SIZE);
1099         
1100         packet->AcknowlegementNumber = htonl(Connection->NextSequenceRcv);
1101         packet->SequenceNumber = htonl(Connection->NextSequenceSend);
1102         packet->Flags = TCP_FLAG_PSH|TCP_FLAG_ACK;      // Hey, ACK if you can!
1103         
1104         memcpy(packet->Options, Data, Length);
1105         
1106         Log_Debug("TCP", "Send sequence 0x%08x", Connection->NextSequenceSend);
1107 #if HEXDUMP_OUTGOING
1108         Debug_HexDump("TCP_INT_SendDataPacket: Data = ", Data, Length);
1109 #endif
1110         
1111         TCP_SendPacket( Connection, sizeof(tTCPHeader)+Length, packet );
1112         
1113         Connection->NextSequenceSend += Length;
1114 }
1115
1116 /**
1117  * \brief Send some bytes on a connection
1118  */
1119 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
1120 {
1121         tTCPConnection  *conn = Node->ImplPtr;
1122         size_t  rem = Length;
1123         
1124         ENTER("pNode XOffset XLength pBuffer", Node, Offset, Length, Buffer);
1125         
1126 //      #if DEBUG
1127 //      Debug_HexDump("TCP_Client_Write: Buffer = ",
1128 //              Buffer, Length);
1129 //      #endif
1130         
1131         // Check if connection is open
1132         while( conn->State == TCP_ST_SYN_RCVD || conn->State == TCP_ST_SYN_SENT )
1133                 Threads_Yield();
1134         
1135         if( conn->State != TCP_ST_OPEN ) {
1136                 VFS_MarkError(Node, 1);
1137                 LEAVE('i', -1);
1138                 return -1;
1139         }
1140         
1141         do
1142         {
1143                  int    len = (rem < TCP_MAX_PACKET_SIZE) ? rem : TCP_MAX_PACKET_SIZE;
1144                 
1145                 #if 0
1146                 // Wait for space in the buffer
1147                 Semaphore_Signal( &Connection->SentBufferSpace, len );
1148                 
1149                 // Save data to buffer (and update the length read by the ammount written)
1150                 len = RingBuffer_Write( &Connection->SentBuffer, Buffer, len);
1151                 #endif
1152                 
1153                 // Send packet
1154                 TCP_INT_SendDataPacket(conn, len, Buffer);
1155                 
1156                 Buffer += len;
1157                 rem -= len;
1158         } while( rem > 0 );
1159         
1160         LEAVE('i', Length);
1161         return Length;
1162 }
1163
1164 /**
1165  * \brief Open a connection to another host using TCP
1166  * \param Conn  Connection structure
1167  */
1168 void TCP_StartConnection(tTCPConnection *Conn)
1169 {
1170         tTCPHeader      hdr = {0};
1171
1172         Conn->State = TCP_ST_SYN_SENT;
1173
1174         hdr.SourcePort = htons(Conn->LocalPort);
1175         hdr.DestPort = htons(Conn->RemotePort);
1176         Conn->NextSequenceSend = rand();
1177         hdr.SequenceNumber = htonl(Conn->NextSequenceSend);
1178         hdr.DataOffset = (sizeof(tTCPHeader)/4) << 4;
1179         hdr.Flags = TCP_FLAG_SYN;
1180         hdr.WindowSize = htons(TCP_WINDOW_SIZE);        // Max
1181         hdr.Checksum = 0;       // TODO
1182         
1183         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
1184         
1185         Conn->NextSequenceSend ++;
1186         Conn->State = TCP_ST_SYN_SENT;
1187
1188         return ;
1189 }
1190
1191 /**
1192  * \brief Control a client socket
1193  */
1194 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
1195 {
1196         tTCPConnection  *conn = Node->ImplPtr;
1197         
1198         ENTER("pNode iID pData", Node, ID, Data);
1199
1200         switch(ID)
1201         {
1202         case 4: // Get/Set local port
1203                 if(!Data)
1204                         LEAVE_RET('i', conn->LocalPort);
1205                 if(conn->State != TCP_ST_CLOSED)
1206                         LEAVE_RET('i', -1);
1207                 if(!CheckMem(Data, sizeof(Uint16)))
1208                         LEAVE_RET('i', -1);
1209
1210                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
1211                         LEAVE_RET('i', -1);
1212
1213                 conn->LocalPort = *(Uint16*)Data;
1214                 LEAVE_RET('i', conn->LocalPort);
1215
1216         case 5: // Get/Set remote port
1217                 if(!Data)       LEAVE_RET('i', conn->RemotePort);
1218                 if(conn->State != TCP_ST_CLOSED)        LEAVE_RET('i', -1);
1219                 if(!CheckMem(Data, sizeof(Uint16)))     LEAVE_RET('i', -1);
1220                 conn->RemotePort = *(Uint16*)Data;
1221                 LEAVE_RET('i', conn->RemotePort);
1222
1223         case 6: // Set Remote IP
1224                 if( conn->State != TCP_ST_CLOSED )
1225                         LEAVE_RET('i', -1);
1226                 if( conn->Interface->Type == 4 )
1227                 {
1228                         if(!CheckMem(Data, sizeof(tIPv4)))      LEAVE_RET('i', -1);
1229                         conn->RemoteIP.v4 = *(tIPv4*)Data;
1230                 }
1231                 else if( conn->Interface->Type == 6 )
1232                 {
1233                         if(!CheckMem(Data, sizeof(tIPv6)))      LEAVE_RET('i', -1);
1234                         conn->RemoteIP.v6 = *(tIPv6*)Data;
1235                 }
1236                 LEAVE_RET('i', 0);
1237
1238         case 7: // Connect
1239                 if(conn->LocalPort == 0xFFFF)
1240                         conn->LocalPort = TCP_GetUnusedPort();
1241                 if(conn->RemotePort == -1)
1242                         LEAVE_RET('i', 0);
1243
1244                 {
1245                         tTime   timeout_end = now() + conn->Interface->TimeoutDelay;
1246         
1247                         TCP_StartConnection(conn);
1248                         // TODO: Wait for connection to open
1249                         while( conn->State == TCP_ST_SYN_SENT && timeout_end > now() ) {
1250                                 Threads_Yield();
1251                         }
1252                         if( conn->State == TCP_ST_SYN_SENT )
1253                                 LEAVE_RET('i', 0);
1254                 }
1255
1256                 LEAVE_RET('i', 1);
1257         
1258         // Get recieve buffer length
1259         case 8:
1260                 LEAVE_RET('i', conn->RecievedBuffer->Length);
1261         }
1262
1263         return 0;
1264 }
1265
1266 void TCP_Client_Close(tVFS_Node *Node)
1267 {
1268         tTCPConnection  *conn = Node->ImplPtr;
1269         tTCPHeader      packet;
1270         
1271         ENTER("pNode", Node);
1272         
1273         if( conn->State == TCP_ST_CLOSE_WAIT || conn->State == TCP_ST_OPEN )
1274         {
1275                 packet.SourcePort = htons(conn->LocalPort);
1276                 packet.DestPort = htons(conn->RemotePort);
1277                 packet.DataOffset = (sizeof(tTCPHeader)/4)*16;
1278                 packet.WindowSize = TCP_WINDOW_SIZE;
1279                 
1280                 packet.AcknowlegementNumber = 0;
1281                 packet.SequenceNumber = htonl(conn->NextSequenceSend);
1282                 packet.Flags = TCP_FLAG_FIN;
1283                 
1284                 TCP_SendPacket( conn, sizeof(tTCPHeader), &packet );
1285         }
1286         
1287         switch( conn->State )
1288         {
1289         case TCP_ST_CLOSE_WAIT:
1290                 conn->State = TCP_ST_LAST_ACK;
1291                 break;
1292         case TCP_ST_OPEN:
1293                 conn->State = TCP_ST_FIN_WAIT1;
1294                 while( conn->State == TCP_ST_FIN_WAIT1 )        Threads_Yield();
1295                 break;
1296         default:
1297                 Log_Warning("TCP", "Unhandled connection state in TCP_Client_Close");
1298                 break;
1299         }
1300         
1301         free(conn);
1302         
1303         LEAVE('-');
1304 }
1305
1306 /**
1307  * \brief Checks if a value is between two others (after taking into account wrapping)
1308  */
1309 int WrapBetween(Uint32 Lower, Uint32 Value, Uint32 Higher, Uint32 MaxValue)
1310 {
1311         if( MaxValue < 0xFFFFFFFF )
1312         {
1313                 Lower %= MaxValue + 1;
1314                 Value %= MaxValue + 1;
1315                 Higher %= MaxValue + 1;
1316         }
1317         
1318         // Simple Case, no wrap ?
1319         //       Lower Value Higher
1320         // | ... + ... + ... + ... |
1321
1322         if( Lower < Higher ) {
1323                 return Lower < Value && Value < Higher;
1324         }
1325         // Higher has wrapped below lower
1326         
1327         // Value > Lower ?
1328         //       Higher Lower Value
1329         // | ... +  ... + ... + ... |
1330         if( Value > Lower ) {
1331                 return 1;
1332         }
1333         
1334         // Value < Higher ?
1335         //       Value Higher Lower
1336         // | ... + ... +  ... + ... |
1337         if( Value < Higher ) {
1338                 return 1;
1339         }
1340         
1341         return 0;
1342 }

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