AcessNative - Fixes, now can run again (and spawn/kill new processes)
[tpg/acess2.git] / AcessNative / acesskernel_src / server.c
1 /*
2  * Acess2 Native Kernel
3  * - Acess kernel emulation on another OS using SDL and UDP
4  *
5  * Syscall Server
6  */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <SDL/SDL.h>
11 #ifdef __WIN32__
12 # include <windows.h>
13 # include <winsock.h>
14 #else
15 # include <unistd.h>
16 # include <sys/socket.h>
17 # include <netinet/in.h>
18 #endif
19 #include "../syscalls.h"
20 //#include <debug.h>
21
22 #define USE_TCP 0
23 #define MAX_CLIENTS     16
24
25 // === TYPES ===
26 typedef struct {
27          int    ClientID;
28         SDL_Thread      *WorkerThread;
29         #if USE_TCP
30         #else
31         tRequestHeader  *CurrentRequest;
32         struct sockaddr_in      ClientAddr;
33         SDL_cond        *WaitFlag;
34         SDL_mutex       *Mutex;
35         #endif
36 }       tClient;
37
38 // === IMPORTS ===
39 extern tRequestHeader *SyscallRecieve(tRequestHeader *Request, int *ReturnLength);
40 extern int      Threads_CreateRootProcess(void);
41 extern void     Threads_SetThread(int TID);
42 // HACK: Should have these in a header
43 extern void     Log_Debug(const char *Subsys, const char *Message, ...);
44 extern void     Log_Notice(const char *Subsys, const char *Message, ...);
45
46 // === PROTOTYPES ===
47 tClient *Server_GetClient(int ClientID);
48  int    Server_WorkerThread(void *ClientPtr);
49  int    SyscallServer(void);
50  int    Server_ListenThread(void *Unused);
51
52 // === GLOBALS ===
53 #ifdef __WIN32__
54 WSADATA gWinsock;
55 SOCKET  gSocket = INVALID_SOCKET;
56 #else
57 # define INVALID_SOCKET -1
58  int    gSocket = INVALID_SOCKET;
59 #endif
60 tClient gaServer_Clients[MAX_CLIENTS];
61 SDL_Thread      *gpServer_ListenThread;
62
63 // === CODE ===
64 int Server_GetClientID(void)
65 {
66          int    i;
67         Uint32  thisId = SDL_ThreadID();
68         
69         for( i = 0; i < MAX_CLIENTS; i ++ )
70         {
71                 if( SDL_GetThreadID(gaServer_Clients[i].WorkerThread) == thisId )
72                         return gaServer_Clients[i].ClientID;
73         }
74         
75         fprintf(stderr, "ERROR: Server_GetClientID - Thread is not allocated\n");
76         
77         return 0;
78 }
79
80 tClient *Server_GetClient(int ClientID)
81 {
82         tClient *ret = NULL;
83          int    i;
84         
85         // Allocate an ID if needed
86         if(ClientID == 0)
87                 ClientID = Threads_CreateRootProcess();
88         
89         for( i = 0; i < MAX_CLIENTS; i ++ )
90         {
91                 if( gaServer_Clients[i].ClientID == ClientID ) {
92                         return &gaServer_Clients[i];
93                 }
94                 if(!ret && gaServer_Clients[i].ClientID == 0)
95                         ret = &gaServer_Clients[i];
96         }
97         
98         // Uh oh, no free slots
99         // TODO: Dynamic allocation
100         if( !ret )
101                 return NULL;
102         
103         // Allocate a thread for the process
104         ret->ClientID = ClientID;
105         ret->CurrentRequest = NULL;
106                 
107         if( !ret->WorkerThread ) {
108                 ret->WaitFlag = SDL_CreateCond();
109                 ret->Mutex = SDL_CreateMutex();
110                 SDL_mutexP( ret->Mutex );
111                 ret->WorkerThread = SDL_CreateThread( Server_WorkerThread, ret );
112         }
113         
114         return ret;
115 }
116
117 int Server_WorkerThread(void *ClientPtr)
118 {
119         tClient *Client = ClientPtr;
120         tRequestHeader  *retHeader;
121         tRequestHeader  errorHeader;
122          int    retSize = 0;
123          int    sentSize;
124          int    cur_client_id = 0;
125         
126         #if USE_TCP
127         #else
128         for( ;; )
129         {
130                 // Wait for something to do
131                 while( Client->CurrentRequest == NULL )
132                         SDL_CondWait(Client->WaitFlag, Client->Mutex);
133                 
134                 if(Client->ClientID != cur_client_id) {
135                         Threads_SetThread( Client->ClientID );
136                         cur_client_id = Client->ClientID;
137                 }
138                 
139                 // Get the response
140                 retHeader = SyscallRecieve(Client->CurrentRequest, &retSize);
141
142                 {
143                         int     callid = Client->CurrentRequest->CallID;
144                         Log_Debug("AcessSrv", "Client %i request %i %s",
145                                 Client->ClientID, callid,
146                                 callid < N_SYSCALLS ? casSYSCALL_NAMES[callid] : "UNK"
147                                 );
148                 }
149                 
150                 
151                 if( !retHeader ) {
152                         // Return an error to the client
153                         printf("ERROR: SyscallRecieve failed\n");
154                         errorHeader.CallID = Client->CurrentRequest->CallID;
155                         errorHeader.NParams = 0;
156                         retHeader = &errorHeader;
157                         retSize = sizeof(errorHeader);
158                 }
159                 
160                 // Set ID
161                 retHeader->ClientID = Client->ClientID;
162                 
163                 // Mark the thread as ready for another job
164                 free(Client->CurrentRequest);
165                 Client->CurrentRequest = 0;
166                 
167 //              Log_Debug("AcessSrv", "Sending %i to %x:%i (Client %i)",
168 //                      retSize, ntohl(Client->ClientAddr.sin_addr.s_addr),
169 //                      ntohs(Client->ClientAddr.sin_port),
170 //                      Client->ClientID
171 //                      );
172                 
173                 // Return the data
174                 sentSize = sendto(gSocket, retHeader, retSize, 0,
175                         (struct sockaddr*)&Client->ClientAddr, sizeof(Client->ClientAddr)
176                         );
177                 if( sentSize != retSize ) {
178                         perror("Server_WorkerThread - send");
179                 }
180                 
181                 // Free allocated header
182                 if( retHeader != &errorHeader )
183                         free( retHeader );
184         }
185         #endif
186 }
187
188 int SyscallServer(void)
189 {
190         struct sockaddr_in      server;
191         
192         #ifdef __WIN32__
193         /* Open windows connection */
194         if (WSAStartup(0x0101, &gWinsock) != 0)
195         {
196                 fprintf(stderr, "Could not open Windows connection.\n");
197                 exit(0);
198         }
199         #endif
200         
201         #if USE_TCP
202         // Open TCP Connection
203         gSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
204         #else
205         // Open UDP Connection
206         gSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
207         #endif
208         if (gSocket == INVALID_SOCKET)
209         {
210                 fprintf(stderr, "Could not create socket.\n");
211                 #if __WIN32__
212                 WSACleanup();
213                 #endif
214                 exit(0);
215         }
216         
217         // Set server address
218         memset(&server, 0, sizeof(struct sockaddr_in));
219         server.sin_family = AF_INET;
220         server.sin_port = htons(SERVER_PORT);
221         server.sin_addr.s_addr = htonl(INADDR_ANY);
222         
223         // Bind
224         if( bind(gSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == -1 )
225         {
226                 fprintf(stderr, "Cannot bind address to socket.\n");
227                 perror("SyscallServer - bind");
228                 #if __WIN32__
229                 closesocket(gSocket);
230                 WSACleanup();
231                 #else
232                 close(gSocket);
233                 #endif
234                 exit(0);
235         }
236         
237         #if USE_TCP
238         listen(gSocket, 5);
239         #endif
240         
241         Log_Notice("AcessSrv", "Listening on 0.0.0.0:%i", SERVER_PORT);
242         gpServer_ListenThread = SDL_CreateThread( Server_ListenThread, NULL );
243         return 0;
244 }
245
246 int Server_ListenThread(void *Unused)
247 {       
248         // Wait for something to do :)
249         for( ;; )
250         {
251                 #if USE_TCP
252                 struct sockaddr_in      client;
253                 uint    clientSize = sizeof(client);
254                  int    clientSock = accept(gSocket, (struct sockaddr*)&client, &clientSize);
255                 if( clientSock < 0 ) {
256                         perror("SyscallServer - accept");
257                         break ;
258                 }
259                 
260                 Log("Client connection %x:%i\n",
261                         ntohl(client.sin_addr), ntohs(client.sin_port)
262                         );
263                 
264                 #else
265                 char    data[BUFSIZ];
266                 tRequestHeader  *req = (void*)data;
267                 struct sockaddr_in      addr;
268                 uint    clientSize = sizeof(addr);
269                  int    length;
270                 tClient *client;
271                 
272                 length = recvfrom(gSocket, data, BUFSIZ, 0, (struct sockaddr*)&addr, &clientSize);
273                 
274                 if( length == -1 ) {
275                         perror("SyscallServer - recv");
276                         break;
277                 }
278                 
279                 // Hand off to a worker thread
280                 // - TODO: Actually have worker threads
281 //              Log_Debug("Server", "%i bytes from %x:%i", length,
282 //                      ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
283                 
284                 client = Server_GetClient(req->ClientID);
285                 // NOTE: Hack - Should check if all zero
286                 if( req->ClientID == 0 || client->ClientAddr.sin_port == 0 )
287                 {
288                         memcpy(&client->ClientAddr, &addr, sizeof(addr));
289                 }
290                 else if( memcmp(&client->ClientAddr, &addr, sizeof(addr)) != 0 )
291                 {
292                         printf("ClientID %i used by %x:%i\n",
293                                 client->ClientID, ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
294                         printf(" actually owned by %x:%i\n",
295                                 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
296                         continue;
297                 }
298                 
299                 if( client->CurrentRequest ) {
300                         printf("Worker thread for %x:%i is busy\n",
301                                 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
302                         continue;
303                 }
304                 
305                 Log_Debug("AcessSrv", "Message from Client %i (%p)",
306                         client->ClientID, client);
307
308                 // Make a copy of the request data      
309                 req = malloc(length);
310                 memcpy(req, data, length);
311                 client->CurrentRequest = req;
312                 SDL_CondSignal(client->WaitFlag);
313                 #endif
314         }
315         return -1;
316 }

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