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

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