Cleanup commit, fixes to UDP, TCP and ICMP
[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 0x1000
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);
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);
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                         conn = calloc(1, sizeof(tTCPConnection));
176                         conn->State = TCP_ST_HALFOPEN;
177                         conn->LocalPort = srv->Port;
178                         conn->RemotePort = hdr->SourcePort;
179                         conn->Interface = Interface;
180                         
181                         switch(Interface->Type)
182                         {
183                         case 4: conn->RemoteIP.v4 = *(tIPv4*)Address;   break;
184                         case 6: conn->RemoteIP.v6 = *(tIPv6*)Address;   break;
185                         }
186                         
187                         conn->NextSequenceRcv = ntohl( hdr->SequenceNumber );
188                         conn->NextSequenceSend = rand();
189                         
190                         // Create node
191                         conn->Node.NumACLs = 1;
192                         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
193                         conn->Node.ImplInt = srv->NextID ++;
194                         conn->Node.Read = TCP_Client_Read;
195                         conn->Node.Write = TCP_Client_Write;
196                         //conn->Node.Close = TCP_SrvConn_Close;
197                         
198                         // Hmm... Theoretically, this lock will never have to wait,
199                         // as the interface is locked to the watching thread, and this
200                         // runs in the watching thread. But, it's a good idea to have
201                         // it, just in case
202                         LOCK(&srv->lConnections);
203                         conn->Next = srv->Connections;
204                         srv->Connections = conn;
205                         RELEASE(&srv->lConnections);
206
207                         // Send the SYN ACK
208                         Log("[TCP  ] TODO: Sending SYN ACK");
209                         hdr->Flags |= TCP_FLAG_ACK;
210                         hdr->AcknowlegementNumber = hdr->SequenceNumber;
211                         hdr->SequenceNumber = conn->NextSequenceSend;
212                         hdr->DestPort = hdr->SourcePort;
213                         hdr->SourcePort = srv->Port;
214                         TCP_SendPacket( conn, sizeof(tTCPHeader), hdr );
215
216                         break;
217                 }
218         }
219
220
221         // Check Open Connections
222         {
223                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
224                 {
225                         // Check that it is coming in on the same interface
226                         if(conn->Interface != Interface)        continue;
227
228                         // Check Source Port
229                         if(conn->RemotePort != hdr->SourcePort) continue;
230
231                         // Check Source IP
232                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
233                                 continue;
234                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
235                                 continue;
236
237                         TCP_INT_HandleConnectionPacket(conn, hdr);
238                 }
239         }
240 }
241
242 /**
243  * \brief Handles a packet sent to a specific connection
244  */
245 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header)
246 {
247
248 }
249
250 /**
251  * \fn Uint16 TCP_GetUnusedPort()
252  * \brief Gets an unused port and allocates it
253  */
254 Uint16 TCP_GetUnusedPort()
255 {
256         Uint16  ret;
257
258         // Get Next outbound port
259         ret = giTCP_NextOutPort++;
260         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
261         {
262                 ret ++;
263                 giTCP_NextOutPort++;
264                 if(giTCP_NextOutPort == 0x10000) {
265                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
266                 }
267         }
268
269         // Mark the new port as used
270         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
271
272         return ret;
273 }
274
275 /**
276  * \fn int TCP_AllocatePort(Uint16 Port)
277  * \brief Marks a port as used
278  */
279 int TCP_AllocatePort(Uint16 Port)
280 {
281         // Check if the port has already been allocated
282         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
283                 return 0;
284
285         // Allocate
286         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
287
288         return 1;
289 }
290
291 /**
292  * \fn int TCP_DeallocatePort(Uint16 Port)
293  * \brief Marks a port as unused
294  */
295 int TCP_DeallocatePort(Uint16 Port)
296 {
297         // Check if the port has already been allocated
298         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
299                 return 0;
300
301         // Allocate
302         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
303
304         return 1;
305 }
306
307 // --- Server
308 tVFS_Node *TCP_Server_Init(tInterface *Interface)
309 {
310         tTCPListener    *srv = malloc( sizeof(tTCPListener) );
311
312         srv->Interface = Interface;
313         srv->Port = 0;
314         srv->NextID = 0;
315         srv->Connections = NULL;
316         srv->Next = NULL;
317         srv->Node.ImplPtr = srv;
318         srv->Node.NumACLs = 1;
319         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
320         srv->Node.ReadDir = TCP_Server_ReadDir;
321         srv->Node.FindDir = TCP_Server_FindDir;
322         srv->Node.IOCtl = TCP_Server_IOCtl;
323         srv->Node.Close = TCP_Server_Close;
324
325         LOCK(&glTCP_Listeners);
326         srv->Next = gTCP_Listeners;
327         gTCP_Listeners = srv;
328         RELEASE(&glTCP_Listeners);
329
330         return &srv->Node;
331 }
332
333 /**
334  * \brief Wait for a new connection and return the connection ID
335  * \note Blocks until a new connection is made
336  * \param Node  Server node
337  * \param Pos   Position (ignored)
338  */
339 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
340 {
341         tTCPListener    *srv = Node->ImplPtr;
342         tTCPConnection  *conn;
343         char    *ret;
344
345         while( srv->NewConnections == NULL )    Threads_Yield();
346
347         conn = srv->NewConnections;
348         srv->NewConnections = conn->Next;
349
350         ret = malloc(9);
351         itoa(ret, Node->ImplInt, 16, '0', 8);
352         return ret;
353 }
354
355 /**
356  * \brief Gets a client connection node
357  * \param Node  Server node
358  * \param Name  Hexadecimal ID of the node
359  */
360 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
361 {
362         return NULL;
363 }
364
365 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
366 {
367         tTCPListener    *srv = Node->ImplPtr;
368
369         switch(ID)
370         {
371         case 4: // Get/Set Port
372                 if(!Data)       // Get Port
373                         return srv->Port;
374
375                 if(srv->Port)   // Wait, you can't CHANGE the port
376                         return -1;
377
378                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
379                         return -1;
380
381                 // Permissions check
382                 if(Threads_GetUID() != 0
383                 && *(Uint16*)Data != 0
384                 && *(Uint16*)Data < 1024)
385                         return -1;
386
387                 // TODO: Check if a port is in use
388
389                 // Set Port
390                 srv->Port = *(Uint16*)Data;
391                 if(srv->Port == 0)      // Allocate a random port
392                         srv->Port = TCP_GetUnusedPort();
393                 else    // Else, mark this as used
394                         TCP_AllocatePort(srv->Port);
395                 return srv->Port;
396         }
397         return 0;
398 }
399
400 void TCP_Server_Close(tVFS_Node *Node)
401 {
402         free(Node->ImplPtr);
403 }
404
405 // --- Client
406 tVFS_Node *TCP_Client_Init(tInterface *Interface)
407 {
408         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
409
410         conn->State = TCP_ST_CLOSED;
411         conn->Interface = Interface;
412         conn->LocalPort = 0;
413         conn->RemotePort = 0;
414         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
415
416         conn->Node.ImplPtr = conn;
417         conn->Node.NumACLs = 1;
418         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
419         conn->Node.Read = TCP_Client_Read;
420         conn->Node.Write = TCP_Client_Write;
421         conn->Node.IOCtl = TCP_Client_IOCtl;
422         conn->Node.Close = TCP_Client_Close;
423
424         LOCK(&glTCP_OutbountCons);
425         conn->Next = gTCP_OutbountCons;
426         gTCP_OutbountCons = conn;
427         RELEASE(&glTCP_OutbountCons);
428
429         return &conn->Node;
430 }
431
432 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
433 {
434         return 0;
435 }
436
437 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
438 {
439         return 0;
440 }
441
442 /**
443  * \brief Control a client socket
444  */
445 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
446 {
447         tTCPConnection  *conn = Node->ImplPtr;
448
449         switch(ID)
450         {
451         case 4: // Get/Set local port
452                 if(!Data)
453                         return conn->LocalPort;
454                 if(conn->State != TCP_ST_CLOSED)
455                         return -1;
456                 if(!CheckMem(Data, sizeof(Uint16)))
457                         return -1;
458
459                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
460                         return -1;
461
462                 conn->LocalPort = *(Uint16*)Data;
463                 return 0;
464
465         case 5: // Get/Set remote port
466                 if(!Data)       return conn->RemotePort;
467                 if(conn->State != TCP_ST_CLOSED)        return -1;
468                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
469                 conn->RemotePort = *(Uint16*)Data;
470                 return 0;
471
472         case 6: // Set Remote IP
473                 if( conn->State != TCP_ST_CLOSED )
474                         return -1;
475                 if( conn->Interface->Type == 4 )
476                 {
477                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
478                         conn->RemoteIP.v4 = *(tIPv4*)Data;
479                 }
480                 else if( conn->Interface->Type == 6 )
481                 {
482                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
483                         conn->RemoteIP.v6 = *(tIPv6*)Data;
484                 }
485                 return 0;
486
487         case 7: // Connect
488                 if(conn->LocalPort == -1)
489                         conn->LocalPort = TCP_GetUnusedPort();
490                 if(conn->RemotePort == -1)
491                         return 0;
492
493                 TCP_StartConnection(conn);
494                 return 1;
495         }
496
497         return 0;
498 }
499
500 void TCP_Client_Close(tVFS_Node *Node)
501 {
502         free(Node->ImplPtr);
503 }

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