dd94b92358e37bfc0c951875e3c1db88fc0fd08d
[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_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer);
16 void    TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header);
17 Uint16  TCP_GetUnusedPort();
18  int    TCP_AllocatePort(Uint16 Port);
19  int    TCP_DeallocatePort(Uint16 Port);
20 // --- Server
21 tVFS_Node       *TCP_Server_Init(tInterface *Interface);
22 char    *TCP_Server_ReadDir(tVFS_Node *Node, int Pos);
23 tVFS_Node       *TCP_Server_FindDir(tVFS_Node *Node, char *Name);
24  int    TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data);
25 void    TCP_Server_Close(tVFS_Node *Node);
26 // --- Client
27 tVFS_Node       *TCP_Client_Init(tInterface *Interface);
28 Uint64  TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
29 Uint64  TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer);
30  int    TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data);
31 void    TCP_Client_Close(tVFS_Node *Node);
32
33 // === TEMPLATES ===
34 tSocketFile     gTCP_ServerFile = {NULL, "tcps", TCP_Server_Init};
35 tSocketFile     gTCP_ClientFile = {NULL, "tcpc", TCP_Client_Init};
36
37 // === GLOBALS ===
38  int    giTCP_NumHalfopen = 0;
39 tSpinlock       glTCP_Listeners;
40 tTCPListener    *gTCP_Listeners;
41 tSpinlock       glTCP_OutbountCons;
42 tTCPConnection  *gTCP_OutbountCons;
43 Uint32  gaTCP_PortBitmap[0x800];
44  int    giTCP_NextOutPort = TCP_MIN_DYNPORT;
45
46 // === CODE ===
47 /**
48  * \fn void TCP_Initialise()
49  * \brief Initialise the TCP Layer
50  */
51 void TCP_Initialise()
52 {
53         IPStack_AddFile(&gTCP_ServerFile);
54         IPStack_AddFile(&gTCP_ClientFile);
55         IPv4_RegisterCallback(IP4PROT_TCP, TCP_GetPacket);
56 }
57
58 /**
59  * \brief Open a connection to another host using TCP
60  */
61 void TCP_StartConnection(tTCPConnection *Conn)
62 {
63         tTCPHeader      hdr;
64         
65         hdr->SourcePort = Conn->LocalPort;
66         hdr->DestPort = Conn->RemotePort;
67         Conn->NextSequenceSend = rand();
68         hdr->SequenceNumber = Conn->NextSequenceSend;
69         hdr->DataOffset = (sizeof(tTCPHeader)+3)/4;
70         hdr->Flags = TCP_FLAG_SYN;
71         hdr->WindowSize = 0;    // TODO
72         hdr->Checksum = 0;      // TODO
73         hdr->UrgentPointer = 0;
74         // SEND PACKET
75         TCP_SendPacket( Conn, sizeof(tTCPHeader), &hdr );
76         return ;
77 }
78
79 /**
80  * \brief Sends a packet from the specified connection, calculating the checksums
81  * \param Conn  Connection
82  * \param Length        Length of data
83  * \param Data  Packet data
84  */
85 void TCP_SendPacket( tTCPConnection *Conn, size_t Length, tTCPHeader *Data )
86 {
87         size_t  buflen;
88         Uint32  *buf;
89         switch( Conn->Interface.Type )
90         {
91         case 4:
92                 buflen = 4 + 4 + 4 + ((Length+1)&1);
93                 buf = malloc( buflen );
94                 buf[0] = Conn->Interface.IP4.Address.L;
95                 buf[1] = Conn->RemoteIP.v4.L;
96                 buf[2] = (htons(Length)<<16) | (6<<8) | 0;
97                 Data->Checksum = 0;
98                 memcpy( &buf[3], Data, buflen );
99                 Data->Checksum = IPv4_Checksum( buf, buflen );
100                 free(buf);
101                 IPv4_SendPacket(Conn->Interface, Conn->RemoteIP.v4, IP4PROT_TCP, 0, sizeof(tTCPHeader), &hdr);
102                 break;
103         }
104 }
105
106 /**
107  * \fn void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
108  * \brief Handles a packet from the IP Layer
109  */
110 void TCP_GetPacket(tInterface *Interface, void *Address, int Length, void *Buffer)
111 {
112         tTCPHeader      *hdr = Buffer;
113         tTCPListener    *srv;
114         tTCPConnection  *conn;
115         
116         Log("[TCP  ] sizeof(tTCPHeader) = %i", sizeof(tTCPHeader));
117         Log("[TCP  ] DestPort = %i", ntohs(hdr->DestPort));
118         Log("[TCP  ] DestPort = %i", ntohs(hdr->DestPort));
119         Log("[TCP  ] SequenceNumber = %i", ntohl(hdr->SequenceNumber));
120         Log("[TCP  ] AcknowlegementNumber = %i", ntohl(hdr->AcknowlegementNumber));
121         Log("[TCP  ] DataOffset = %i", hdr->DataOffset >> 4);
122         Log("[TCP  ] Flags = {");
123         Log("[TCP  ]   CWR = %B", !!(hdr->Flags & TCP_FLAG_CWR));
124         Log("[TCP  ]   ECE = %B", !!(hdr->Flags & TCP_FLAG_ECE));
125         Log("[TCP  ]   URG = %B", !!(hdr->Flags & TCP_FLAG_URG));
126         Log("[TCP  ]   ACK = %B", !!(hdr->Flags & TCP_FLAG_ACK));
127         Log("[TCP  ]   PSH = %B", !!(hdr->Flags & TCP_FLAG_PSH));
128         Log("[TCP  ]   RST = %B", !!(hdr->Flags & TCP_FLAG_RST));
129         Log("[TCP  ]   SYN = %B", !!(hdr->Flags & TCP_FLAG_SYN));
130         Log("[TCP  ]   FIN = %B", !!(hdr->Flags & TCP_FLAG_FIN));
131         Log("[TCP  ] }");
132         Log("[TCP  ] WindowSize = %i", htons(hdr->WindowSize));
133         Log("[TCP  ] Checksum = 0x%x", htons(hdr->Checksum));
134         Log("[TCP  ] UrgentPointer = 0x%x", htons(hdr->UrgentPointer));
135         
136         // Check Servers
137         {
138                 for( srv = gTCP_Listeners; srv; srv = srv->Next )
139                 {
140                         // Check if the server is active
141                         if(srv->Port == 0)      continue;
142                         // Check the interface
143                         if(srv->Interface && srv->Interface != Interface)       continue;
144                         // Check the destination port
145                         if(srv->Port != hdr->DestPort)  continue;
146                         
147                         // Is this in an established connection?
148                         for( conn = srv->Connections; conn; conn = conn->Next )
149                         {
150                                 // Check that it is coming in on the same interface
151                                 if(conn->Interface != Interface)        continue;
152                                 
153                                 // Check Source Port
154                                 if(conn->RemotePort != hdr->SourcePort) continue;
155                                 
156                                 // Check Source IP
157                                 if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
158                                         continue;
159                                 if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
160                                         continue;
161                                 
162                                 // We have a response!
163                                 TCP_INT_HandleConnectionPacket(conn, hdr)
164                                 
165                                 return;
166                         }
167                         
168                         // Open a new connection (well, check that it's a SYN)
169                         //TODO
170                         
171                         break;
172                 }
173         }
174         
175         
176         // Check Open Connections
177         {
178                 for( conn = gTCP_OutbountCons; conn; conn = conn->Next )
179                 {
180                         // Check that it is coming in on the same interface
181                         if(conn->Interface != Interface)        continue;
182                         
183                         // Check Source Port
184                         if(conn->RemotePort != hdr->SourcePort) continue;
185                         
186                         // Check Source IP
187                         if(conn->Interface->Type == 6 && !IP6_EQU(conn->RemoteIP.v6, *(tIPv6*)Address))
188                                 continue;
189                         if(conn->Interface->Type == 4 && !IP4_EQU(conn->RemoteIP.v4, *(tIPv4*)Address))
190                                 continue;
191                         
192                         TCP_INT_HandleConnectionPacket(conn, hdr)
193                 }
194         }
195 }
196
197 /**
198  * \brief Handles a packet sent to a specific connection
199  */
200 void TCP_INT_HandleConnectionPacket(tTCPConnection *Connection, tTCPHeader *Header)
201 {
202         
203 }
204
205 /**
206  * \fn Uint16 TCP_GetUnusedPort()
207  * \brief Gets an unused port and allocates it
208  */
209 Uint16 TCP_GetUnusedPort()
210 {
211         Uint16  ret;
212         
213         // Get Next outbound port
214         ret = giTCP_NextOutPort++;
215         while( gaTCP_PortBitmap[ret/32] & (1 << (ret%32)) )
216         {
217                 ret ++;
218                 giTCP_NextOutPort++;
219                 if(giTCP_NextOutPort == 0x10000) {
220                         ret = giTCP_NextOutPort = TCP_MIN_DYNPORT;
221                 }
222         }
223         
224         // Mark the new port as used
225         gaTCP_PortBitmap[ret/32] |= 1 << (ret%32);
226         
227         return ret;
228 }
229
230 /**
231  * \fn int TCP_AllocatePort(Uint16 Port)
232  * \brief Marks a port as used
233  */
234 int TCP_AllocatePort(Uint16 Port)
235 {
236         // Check if the port has already been allocated
237         if( gaTCP_PortBitmap[Port/32] & (1 << (Port%32)) )
238                 return 0;
239         
240         // Allocate
241         gaTCP_PortBitmap[Port/32] |= 1 << (Port%32);
242         
243         return 1;
244 }
245
246 /**
247  * \fn int TCP_DeallocatePort(Uint16 Port)
248  * \brief Marks a port as unused
249  */
250 int TCP_DeallocatePort(Uint16 Port)
251 {
252         // Check if the port has already been allocated
253         if( !(gaTCP_PortBitmap[Port/32] & (1 << (Port%32))) )
254                 return 0;
255         
256         // Allocate
257         gaTCP_PortBitmap[Port/32] &= ~(1 << (Port%32));
258         
259         return 1;
260 }
261
262 // --- Server
263 tVFS_Node *TCP_Server_Init(tInterface *Interface)
264 {
265         tTCPListener    *srv = malloc( sizeof(tTCPListener) );
266         
267         srv->Interface = Interface;
268         srv->Port = 0;
269         srv->NextID = 0;
270         srv->Connections = NULL;
271         srv->Next = NULL;
272         srv->Node.ImplPtr = srv;
273         srv->Node.NumACLs = 1;
274         srv->Node.ACLs = &gVFS_ACL_EveryoneRW;
275         srv->Node.ReadDir = TCP_Server_ReadDir;
276         srv->Node.FindDir = TCP_Server_FindDir;
277         srv->Node.IOCtl = TCP_Server_IOCtl;
278         srv->Node.Close = TCP_Server_Close;
279         
280         LOCK(&glTCP_Listeners);
281         srv->Next = gTCP_Listeners;
282         gTCP_Listeners = srv;
283         RELEASE(&glTCP_Listeners);
284         
285         return &srv->Node;
286 }
287
288 /**
289  * \brief Wait for a new connection and return the connection ID
290  * \note Blocks until a new connection is made
291  * \param Node  Server node
292  * \param Pos   Position (ignored)
293  */
294 char *TCP_Server_ReadDir(tVFS_Node *Node, int Pos)
295 {
296         tTCPListener    *srv = Node->ImplPtr;
297         tTCPConnection  *conn;
298         char    *ret;
299         
300         while( srv->NewConnections == NULL )    Threads_Yield();
301         
302         conn = srv->NewConnections;
303         srv->NewConnections = conn->Next;
304         
305         ret = malloc(9);
306         itoa(ret, conn->ImplInt, 16, '0', 8);
307         return ret;
308 }
309
310 /**
311  * \brief Gets a client connection node
312  * \param Node  Server node
313  * \param Name  Hexadecimal ID of the node
314  */
315 tVFS_Node *TCP_Server_FindDir(tVFS_Node *Node, char *Name)
316 {
317         return NULL;
318 }
319
320 int TCP_Server_IOCtl(tVFS_Node *Node, int ID, void *Data)
321 {
322         tTCPListener    *srv = Node->ImplPtr;
323         
324         switch(ID)
325         {
326         case 4: // Get/Set Port
327                 if(!Data)       // Get Port
328                         return srv->Port;
329                 
330                 if(srv->Port)   // Wait, you can't CHANGE the port
331                         return -1;
332                 
333                 if(!CheckMem(Data, sizeof(Uint16)))     // Sanity check
334                         return -1;
335                 
336                 // Permissions check
337                 if(Threads_GetUID() != 0
338                 && *(Uint16*)Data != 0
339                 && *(Uint16*)Data < 1024)
340                         return -1;
341                 
342                 // TODO: Check if a port is in use
343                 
344                 // Set Port
345                 srv->Port = *(Uint16*)Data;
346                 if(srv->Port == 0)      // Allocate a random port
347                         srv->Port = TCP_GetUnusedPort();
348                 else    // Else, mark this as used
349                         TCP_AllocatePort(srv->Port);
350                 return srv->Port;
351         }
352         return 0;
353 }
354
355 void TCP_Server_Close(tVFS_Node *Node)
356 {
357         free(Node->ImplPtr);
358 }
359
360 // --- Client
361 tVFS_Node *TCP_Client_Init(tInterface *Interface)
362 {
363         tTCPConnection  *conn = malloc( sizeof(tTCPConnection) );
364         
365         conn->State = TCP_ST_CLOSED;
366         conn->Interface = Interface;
367         conn->LocalPort = 0;
368         conn->RemotePort = 0;
369         memset( &conn->RemoteIP, 0, sizeof(conn->RemoteIP) );
370         
371         conn->Node.ImplPtr = conn;
372         conn->Node.NumACLs = 1;
373         conn->Node.ACLs = &gVFS_ACL_EveryoneRW;
374         conn->Node.Read = TCP_Client_Read;
375         conn->Node.Write = TCP_Client_Write;
376         conn->Node.IOCtl = TCP_Client_IOCtl;
377         conn->Node.Close = TCP_Client_Close;
378         
379         LOCK(&glTCP_OutbountCons);
380         conn->Next = gTCP_OutbountCons;
381         gTCP_OutbountCons = conn;
382         RELEASE(&glTCP_OutbountCons);
383         
384         return &conn->Node;
385 }
386
387 Uint64 TCP_Client_Read(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
388 {
389         return 0;
390 }
391
392 Uint64 TCP_Client_Write(tVFS_Node *Node, Uint64 Offset, Uint64 Length, void *Buffer)
393 {
394         return 0;
395 }
396
397 int TCP_Client_IOCtl(tVFS_Node *Node, int ID, void *Data)
398 {
399         tTCPConnection  *conn = Node->ImplPtr;
400         
401         switch(ID)
402         {
403         case 4: // Get/Set local port
404                 if(!Data)
405                         return conn->LocalPort;
406                 if(conn->State != TCP_ST_CLOSED)
407                         return -1;
408                 if(!CheckMem(Data, sizeof(Uint16)))
409                         return -1;
410                 
411                 if(Threads_GetUID() != 0 && *(Uint16*)Data < 1024)
412                         return -1;
413                 
414                 conn->LocalPort = *(Uint16*)Data;
415                 return 0;
416         
417         case 5: // Get/Set remote port
418                 if(!Data)       return conn->RemotePort;
419                 if(conn->State != TCP_ST_CLOSED)        return -1;
420                 if(!CheckMem(Data, sizeof(Uint16)))     return -1;
421                 conn->RemotePort = *(Uint16*)Data;
422                 return 0;
423         
424         case 6: // Set Remote IP
425                 if( conn->State != TCP_ST_CLOSED )
426                         return -1;
427                 if( conn->Interface->Type == 4 )
428                 {
429                         if(!CheckMem(Data, sizeof(tIPv4)))      return -1;
430                         conn->RemoteIP.v4 = *(tIPv4*)Data;
431                 }
432                 else if( conn->Interface->Type == 6 )
433                 {
434                         if(!CheckMem(Data, sizeof(tIPv6)))      return -1;
435                         conn->RemoteIP.v6 = *(tIPv6*)Data;
436                 }
437                 return 0;
438         
439         case 7: // Connect
440                 if(conn->LocalPort == -1)
441                         conn->LocalPort = TCP_GetUnusedPort();
442                 if(conn->RemotePort == -1)
443                         return 0;
444                 
445                 TCP_StartConnection(conn);
446                 return 1;
447         }
448         
449         return 0;
450 }
451
452 void TCP_Client_Close(tVFS_Node *Node)
453 {
454         free(Node->ImplPtr);
455 }

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