More work on TCP, approaching usable (untested)
[tpg/acess2.git] / Modules / IPStack / tcp.c
1 /*
2  * Acess2 IP Stack
3  * - TCP Handling
4  */
5 #include "ipstack.h"
6 #include "ipv4.h"
7 #include "tcp.h"
8
9 #define TCP_MIN_DYNPORT 0xC000
10 #define TCP_MAX_HALFOPEN        1024    // Should be enough
11
12 // === PROTOTYPES ===
13 void    TCP_Initialise();
14 void    TCP_StartConnection(tTCPConnection *Conn);
15 void    TCP_SendPacket(tTCPConnection *Conn, size_t Length, tTCPHeader *Data);
16 void    TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
17 void    TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length);
18 Uint16  TCP_GetUnusedPort();
19  int    TCP_AllocatePort(Uint16 Port);
20  int    TCP_DeallocatePort(Uint16 Port);
21 // --- Server
22 tVFS_Node       *TCP_Server_Init(tInterface *Interface);
23 char    *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
24 tVFS_Node       *TCP_Server_FindDir(tVFS_Node *Node, char *Name);
25  int    TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
26 void    TCP_Server_Close(tVFS_Node *Node);
27 // --- Client
28 tVFS_Node       *TCP_Client_Init(tInterface *Interface);
29 Uint64  TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
30 Uint64  TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
31  int    TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
32 void    TCP_Client_Close(tVFS_Node *Node);
33
34 // === TEMPLATES ===
35 tSocketFile     gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
36 tSocketFile     gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
37
38 // === GLOBALS ===
39  int    giTCP_NumHalfopen = 0;
40 tSpinlock       glTCP_Listeners;
41 tTCPListener    *gTCP_Listeners;
42 tSpinlock       glTCP_OutbountCons;
43 tTCPConnection  *gTCP_OutbountCons;
44 Uint32  gaTCP_PortBitmap[0x800];
45  int    giTCP_NextOutPort = TCP_MIN_DYNPORT;
46
47 // === CODE ===
48 /**
49  * \fn void TCP_Initialise()
50  * \brief Initialise the TCP Layer
51  */
52 void TCP_Initialise()
53 {
54         IPStack_AddFile(&gTCP_ServerFile);
55         IPStack_AddFile(&gTCP_ClientFile);
56         IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
57 }
58
59 /**
60  * \brief Open a connection to another host using TCP
61  */
62 void TCP_StartConnection(tTCPConnection *Conn)
63 {
64         tTCPHeader      hdr;
65
66         hdr.SourcePort = Conn->LocalPort;
67         hdr.DestPort = Conn->RemotePort;
68         Conn->NextSequenceSend = rand();
69         hdr.SequenceNumber = Conn->NextSequenceSend;
70         hdr.DataOffset = (sizeof(tTCPHeader)+3)/4;
71         hdr.Flags = TCP_FLAG_SYN;
72         hdr.WindowSize = 0;     // TODO
73         hdr.Checksum = 0;       // TODO
74         hdr.UrgentPointer = 0;
75         // SEND PACKET
76         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
77         return ;
78 }
79
80 /**
81  * \brief Sends a packet from the specified connection, calculating the checksums
82  * \param Conn  Connection
83  * \param Length        Length of data
84  * \param Data  Packet data
85  */
86 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
87 {
88         size_t  buflen;
89         Uint32  *buf;
90         switch( Conn->Interface->Type )
91         {
92         case 4: // Append IPv4 Pseudo Header
93                 buflen = 4 + 4 + 4 + ((Length+1)&1);
94                 buf = malloc( buflen );
95                 buf[0] = Conn->Interface->IP4.Address.L;
96                 buf[1] = Conn->RemoteIP.v4.L;
97                 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
98                 Data->Checksum = 0;
99                 memcpy( &buf[3], Data, Length );
100                 Data->Checksum = IPv4_Checksum( buf, buflen );
101                 free(buf);
102                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, buflen, buf);
103                 break;
104         }
105 }
106
107 /**
108  * \fn void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
109  * \brief Handles a packet from the IP Layer
110  */
111 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
112 {
113         tTCPHeader      *hdr = Buffer;
114         tTCPListener    *srv;
115         tTCPConnection  *conn;
116
117         Log("[TCP  ] sizeof(tTCPHeader) = %i", sizeof(tTCPHeader));
118         Log("[TCP  ] SourcePort = %i", ntohs(hdr->SourcePort));
119         Log("[TCP  ] DestPort = %i", ntohs(hdr->DestPort));
120         Log("[TCP  ] SequenceNumber = 0x%x", ntohl(hdr->SequenceNumber));
121         Log("[TCP  ] AcknowlegementNumber = 0x%x", ntohl(hdr->AcknowlegementNumber));
122         Log("[TCP  ] DataOffset = %i", hdr->DataOffset >> 4);
123         Log("[TCP  ] Flags = {");
124         Log("[TCP  ]   CWR = %B", !!(hdr->Flags & TCP_FLAG_CWR));
125         Log("[TCP  ]   ECE = %B", !!(hdr->Flags & TCP_FLAG_ECE));
126         Log("[TCP  ]   URG = %B", !!(hdr->Flags & TCP_FLAG_URG));
127         Log("[TCP  ]   ACK = %B", !!(hdr->Flags & TCP_FLAG_ACK));
128         Log("[TCP  ]   PSH = %B", !!(hdr->Flags & TCP_FLAG_PSH));
129         Log("[TCP  ]   RST = %B", !!(hdr->Flags & TCP_FLAG_RST));
130         Log("[TCP  ]   SYN = %B", !!(hdr->Flags & TCP_FLAG_SYN));
131         Log("[TCP  ]   FIN = %B", !!(hdr->Flags & TCP_FLAG_FIN));
132         Log("[TCP  ] }");
133         Log("[TCP  ] WindowSize = %i", htons(hdr->WindowSize));
134         Log("[TCP  ] Checksum = 0x%x", htons(hdr->Checksum));
135         Log("[TCP  ] UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
136
137         // Check Servers
138         {
139                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
140                 {
141                         // Check if the server is active
142                         if(srv->Port == 0)      continue;
143                         // Check the interface
144                         if(srv->Interface && srv->Interface != Interface)       continue;
145                         // Check the destination port
146                         if(srv->Port != hdr->DestPort)  continue;
147
148                         // Is this in an established connection?
149                         for( conn = srv->Connections; conn; conn = conn->Next )
150                         {
151                                 // Check that it is coming in on the same interface
152                                 if(conn->Interface != Interface)        continue;
153
154                                 // Check Source Port
155                                 if(conn->RemotePort != hdr->SourcePort) continue;
156
157                                 // Check Source IP
158                                 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
159                                         continue;
160                                 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
161                                         continue;
162
163                                 // We have a response!
164                                 TCP_INT_HandleConnectionPacket(conn, hdr, Length);
165
166                                 return;
167                         }
168
169                         // Open a new connection (well, check that it's a SYN)
170                         if(hdr->Flags != TCP_FLAG_SYN) {
171                                 Log("[TCP  ] Packet is not a SYN");
172                                 continue;
173                         }
174                         
175                         // TODO: Check for halfopen max
176                         
177                         conn = calloc(1, sizeof(tTCPConnection));
178                         conn->State = TCP_ST_HALFOPEN;
179                         conn->LocalPort = srv->Port;
180                         conn->RemotePort = hdr->SourcePort;
181                         conn->Interface = Interface;
182                         
183                         switch(Interface->Type)
184                         {
185                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
186                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
187                         }
188                         
189                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber );
190                         conn->NextSequenceSend = rand();
191                         
192                         // Create node
193                         conn->Node.NumACLs = 1;
194                         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
195                         conn->Node.ImplInt = srv->NextID ++;
196                         conn->Node.Read = TCP_Client_Read;
197                         conn->Node.Write = TCP_Client_Write;
198                         //conn->Node.Close = TCP_SrvConn_Close;
199                         
200                         // Hmm... Theoretically, this lock will never have to wait,
201                         // as the interface is locked to the watching thread, and this
202                         // runs in the watching thread. But, it's a good idea to have
203                         // it, just in case
204                         LOCK(&srv->lConnections);
205                         conn->Next = srv->Connections;
206                         srv->Connections = conn;
207                         RELEASE(&srv->lConnections);
208
209                         // Send the SYN ACK
210                         Log("[TCP  ] TODO: Sending SYN ACK");
211                         hdr->Flags |= TCP_FLAG_ACK;
212                         hdr->AcknowlegementNumber = hdr->SequenceNumber;
213                         hdr->SequenceNumber = conn->NextSequenceSend;
214                         hdr->DestPort = hdr->SourcePort;
215                         hdr->SourcePort = srv->Port;
216                         TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
217
218                         break;
219                 }
220         }
221
222
223         // Check Open Connections
224         {
225                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
226                 {
227                         // Check that it is coming in on the same interface
228                         if(conn->Interface != Interface)        continue;
229
230                         // Check Source Port
231                         if(conn->RemotePort != hdr->SourcePort) continue;
232
233                         // Check Source IP
234                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
235                                 continue;
236                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
237                                 continue;
238
239                         TCP_INT_HandleConnectionPacket(conn, hdr, Length);
240                 }
241         }
242 }
243
244 /**
245  * \brief Handles a packet sent to a specific connection
246  */
247 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header, int Length)
248 {       
249         tTCPStoredPacket        *pkt;
250          int    dataLen;
251         
252         Connection->State = TCP_ST_OPEN;
253         if(Header->Flags & TCP_FLAG_SYN) {
254                 Connection->NextSequenceRcv = Header->SequenceNumber + 1;
255         }
256         
257         if(Header->Flags & TCP_FLAG_ACK) {
258                 // TODO: Process an ACKed Packet
259                 Log("[TCP  ] Conn %p, Packet 0x%x ACKed", Connection, Header->AcknowlegementNumber);
260                 return ;
261         }
262         
263         // Allocate and fill cached packet
264         dataLen =  Length - (Header->DataOffset&0xF)*4;
265         pkt = malloc( dataLen + sizeof(tTCPStoredPacket) );
266         pkt->Next = NULL;
267         pkt->Sequence = Header->SequenceNumber;
268         memcpy(pkt->Data, (Uint8*)Header + (Header->DataOffset&0xF)*4, dataLen);
269         
270         if( Header->SequenceNumber != Connection->NextSequenceRcv )
271         {
272                 tTCPStoredPacket        *tmp, *prev;
273                 for(tmp = Connection->FuturePackets;
274                         tmp;
275                         prev = tmp, tmp = tmp->Next)
276                 {
277                         if(tmp->Sequence > pkt->Sequence)       break;
278                 }
279                 if(prev)
280                         prev->Next = pkt;
281                 else
282                         Connection->FuturePackets = pkt;
283                 pkt->Next = tmp;
284         }
285         else
286         {
287                 LOCK( &Connection->lRecievedPackets );
288                 if(Connection->RecievedPackets)
289                 {
290                         Connection->RecievedPacketsTail->Next = pkt;
291                         Connection->RecievedPacketsTail = pkt;
292                 }
293                 else
294                 {
295                         Connection->RecievedPackets = pkt;
296                         Connection->RecievedPacketsTail = pkt;
297                 }
298                 RELEASE( &Connection->lRecievedPackets );
299         }
300 }
301
302 /**
303  * \fn Uint16 TCP_GetUnusedPort()
304  * \brief Gets an unused port and allocates it
305  */
306 Uint16 TCP_GetUnusedPort()
307 {
308         Uint16  ret;
309
310         // Get Next outbound port
311         ret = giTCP_NextOutPort++;
312         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
313         {
314                 ret ++;
315                 giTCP_NextOutPort++;
316                 if(giTCP_NextOutPort == 0x10000) {
317                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
318                 }
319         }
320
321         // Mark the new port as used
322         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
323
324         return ret;
325 }
326
327 /**
328  * \fn int TCP_AllocatePort(Uint16 Port)
329  * \brief Marks a port as used
330  */
331 int TCP_AllocatePort(Uint16 Port)
332 {
333         // Check if the port has already been allocated
334         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
335                 return 0;
336
337         // Allocate
338         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
339
340         return 1;
341 }
342
343 /**
344  * \fn int TCP_DeallocatePort(Uint16 Port)
345  * \brief Marks a port as unused
346  */
347 int TCP_DeallocatePort(Uint16 Port)
348 {
349         // Check if the port has already been allocated
350         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
351                 return 0;
352
353         // Allocate
354         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
355
356         return 1;
357 }
358
359 // --- Server
360 tVFS_Node *TCP_Server_Init(tInterface *Interface)
361 {
362         tTCPListener    *srv = malloc( sizeof(tTCPListener) );
363
364         srv->Interface = Interface;
365         srv->Port = 0;
366         srv->NextID = 0;
367         srv->Connections = NULL;
368         srv->Next = NULL;
369         srv->Node.ImplPtr = srv;
370         srv->Node.NumACLs = 1;
371         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
372         srv->Node.ReadDir = TCP_Server_ReadDir;
373         srv->Node.FindDir = TCP_Server_FindDir;
374         srv->Node.IOCtl = TCP_Server_IOCtl;
375         srv->Node.Close = TCP_Server_Close;
376
377         LOCK(&glTCP_Listeners);
378         srv->Next = gTCP_Listeners;
379         gTCP_Listeners = srv;
380         RELEASE(&glTCP_Listeners);
381
382         return &srv->Node;
383 }
384
385 /**
386  * \brief Wait for a new connection and return the connection ID
387  * \note Blocks until a new connection is made
388  * \param Node  Server node
389  * \param Pos   Position (ignored)
390  */
391 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
392 {
393         tTCPListener    *srv = Node->ImplPtr;
394         tTCPConnection  *conn;
395         char    *ret;
396
397         while( srv->NewConnections == NULL )    Threads_Yield();
398
399         conn = srv->NewConnections;
400         srv->NewConnections = conn->Next;
401
402         ret = malloc(9);
403         itoa(ret, Node->ImplInt, 16, '0', 8);
404         return ret;
405 }
406
407 /**
408  * \brief Gets a client connection node
409  * \param Node  Server node
410  * \param Name  Hexadecimal ID of the node
411  */
412 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
413 {
414         return NULL;
415 }
416
417 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
418 {
419         tTCPListener    *srv = Node->ImplPtr;
420
421         switch(ID)
422         {
423         case 4: // Get/Set Port
424                 if(!Data)       // Get Port
425                         return srv->Port;
426
427                 if(srv->Port)   // Wait, you can't CHANGE the port
428                         return -1;
429
430                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
431                         return -1;
432
433                 // Permissions check
434                 if(Threads_GetUID() != 0
435                 && *(Uint16*)Data != 0
436                 && *(Uint16*)Data < 1024)
437                         return -1;
438
439                 // TODO: Check if a port is in use
440
441                 // Set Port
442                 srv->Port = *(Uint16*)Data;
443                 if(srv->Port == 0)      // Allocate a random port
444                         srv->Port = TCP_GetUnusedPort();
445                 else    // Else, mark this as used
446                         TCP_AllocatePort(srv->Port);
447                 return srv->Port;
448         }
449         return 0;
450 }
451
452 void TCP_Server_Close(tVFS_Node *Node)
453 {
454         free(Node->ImplPtr);
455 }
456
457 // --- Client
458 tVFS_Node *TCP_Client_Init(tInterface *Interface)
459 {
460         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
461
462         conn->State = TCP_ST_CLOSED;
463         conn->Interface = Interface;
464         conn->LocalPort = 0;
465         conn->RemotePort = 0;
466         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
467
468         conn->Node.ImplPtr = conn;
469         conn->Node.NumACLs = 1;
470         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
471         conn->Node.Read = TCP_Client_Read;
472         conn->Node.Write = TCP_Client_Write;
473         conn->Node.IOCtl = TCP_Client_IOCtl;
474         conn->Node.Close = TCP_Client_Close;
475
476         LOCK(&glTCP_OutbountCons);
477         conn->Next = gTCP_OutbountCons;
478         gTCP_OutbountCons = conn;
479         RELEASE(&glTCP_OutbountCons);
480
481         return &conn->Node;
482 }
483
484 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
485 {
486         return 0;
487 }
488
489 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
490 {
491         return 0;
492 }
493
494 /**
495  * \brief Control a client socket
496  */
497 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
498 {
499         tTCPConnection  *conn = Node->ImplPtr;
500
501         switch(ID)
502         {
503         case 4: // Get/Set local port
504                 if(!Data)
505                         return conn->LocalPort;
506                 if(conn->State != TCP_ST_CLOSED)
507                         return -1;
508                 if(!CheckMem(Data, sizeof(Uint16)))
509                         return -1;
510
511                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
512                         return -1;
513
514                 conn->LocalPort = *(Uint16*)Data;
515                 return 0;
516
517         case 5: // Get/Set remote port
518                 if(!Data)       return conn->RemotePort;
519                 if(conn->State != TCP_ST_CLOSED)        return -1;
520                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
521                 conn->RemotePort = *(Uint16*)Data;
522                 return 0;
523
524         case 6: // Set Remote IP
525                 if( conn->State != TCP_ST_CLOSED )
526                         return -1;
527                 if( conn->Interface->Type == 4 )
528                 {
529                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
530                         conn->RemoteIP.v4 = *(tIPv4*)Data;
531                 }
532                 else if( conn->Interface->Type == 6 )
533                 {
534                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
535                         conn->RemoteIP.v6 = *(tIPv6*)Data;
536                 }
537                 return 0;
538
539         case 7: // Connect
540                 if(conn->LocalPort == -1)
541                         conn->LocalPort = TCP_GetUnusedPort();
542                 if(conn->RemotePort == -1)
543                         return 0;
544
545                 TCP_StartConnection(conn);
546                 return 1;
547         }
548
549         return 0;
550 }
551
552 void TCP_Client_Close(tVFS_Node *Node)
553 {
554         free(Node->ImplPtr);
555 }

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