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

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