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

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