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

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