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

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