3 * - Acess kernel emulation on another OS using SDL and UDP
16 # include <sys/socket.h>
17 # include <netinet/in.h>
18 # include <arpa/inet.h> // inet_ntop
20 #include "../syscalls.h"
24 #define MAX_CLIENTS 16
29 SDL_Thread *WorkerThread;
33 tRequestHeader *CurrentRequest;
34 struct sockaddr_in ClientAddr;
41 extern tRequestHeader *SyscallRecieve(tRequestHeader *Request, int *ReturnLength);
42 extern int Threads_CreateRootProcess(void);
43 extern void Threads_SetThread(int TID);
44 // HACK: Should have these in a header
45 extern void Log_Debug(const char *Subsys, const char *Message, ...);
46 extern void Log_Notice(const char *Subsys, const char *Message, ...);
47 extern void Log_Warning(const char *Subsys, const char *Message, ...);
50 tClient *Server_GetClient(int ClientID);
51 int Server_WorkerThread(void *ClientPtr);
52 int SyscallServer(void);
53 int Server_ListenThread(void *Unused);
58 SOCKET gSocket = INVALID_SOCKET;
60 # define INVALID_SOCKET -1
61 int gSocket = INVALID_SOCKET;
63 tClient gaServer_Clients[MAX_CLIENTS];
64 SDL_Thread *gpServer_ListenThread;
67 int Server_GetClientID(void)
70 Uint32 thisId = SDL_ThreadID();
72 for( i = 0; i < MAX_CLIENTS; i ++ )
74 if( SDL_GetThreadID(gaServer_Clients[i].WorkerThread) == thisId )
75 return gaServer_Clients[i].ClientID;
78 fprintf(stderr, "ERROR: Server_GetClientID - Thread is not allocated\n");
83 tClient *Server_GetClient(int ClientID)
88 // Allocate an ID if needed
90 ClientID = Threads_CreateRootProcess();
92 for( i = 0; i < MAX_CLIENTS; i ++ )
94 if( gaServer_Clients[i].ClientID == ClientID ) {
95 return &gaServer_Clients[i];
97 if(!ret && gaServer_Clients[i].ClientID == 0)
98 ret = &gaServer_Clients[i];
101 // Uh oh, no free slots
102 // TODO: Dynamic allocation
106 // Allocate a thread for the process
107 ret->ClientID = ClientID;
111 ret->CurrentRequest = NULL;
114 if( !ret->WorkerThread ) {
117 ret->WaitFlag = SDL_CreateCond();
118 ret->Mutex = SDL_CreateMutex();
119 SDL_mutexP( ret->Mutex );
121 ret->WorkerThread = SDL_CreateThread( Server_WorkerThread, ret );
127 int Server_WorkerThread(void *ClientPtr)
129 tClient *Client = ClientPtr;
135 int nfd = Client->Socket+1;
137 FD_SET(Client->Socket, &fds);
139 int rv = select(nfd, &fds, NULL, NULL, NULL); // TODO: Timeouts?
145 if( FD_ISSET(Client->Socket, &fds) )
147 const int ciMaxParamCount = 6;
148 char lbuf[sizeof(tRequestHeader) + ciMaxParamCount*sizeof(tRequestValue)];
149 tRequestHeader *hdr = (void*)lbuf;
150 size_t len = recv(Client->Socket, hdr, sizeof(*hdr), 0);
151 Log_Debug("Server", "%i bytes of header", len);
152 if( len == 0 ) break;
153 if( len != sizeof(*hdr) ) {
155 Log_Warning("Server", "FD%i bad sized (%i != exp %i)",
156 Client->Socket, len, sizeof(*hdr));
160 if( hdr->NParams > ciMaxParamCount ) {
162 Log_Warning("Server", "FD%i too many params (%i > max %i)",
163 Client->Socket, hdr->NParams, ciMaxParamCount);
167 len = recv(Client->Socket, hdr->Params, hdr->NParams*sizeof(tRequestValue), 0);
168 Log_Debug("Server", "%i bytes of params", len);
169 if( len != hdr->NParams*sizeof(tRequestValue) ) {
174 size_t hdrsize = sizeof(tRequestHeader) + hdr->NParams*sizeof(tRequestValue);
175 size_t bufsize = hdrsize;
177 for( i = 0; i < hdr->NParams; i ++ )
179 if( hdr->Params[i].Flags & ARG_FLAG_ZEROED )
182 bufsize += hdr->Params[i].Length;
186 // Allocate full buffer
187 hdr = malloc(bufsize);
188 memcpy(hdr, lbuf, hdrsize);
189 len = recv(Client->Socket, hdr->Params + hdr->NParams, bufsize - hdrsize, 0);
190 Log_Debug("Server", "%i bytes of data", len);
191 if( len != bufsize - hdrsize ) {
196 tRequestHeader *retHeader;
197 retHeader = SyscallRecieve(hdr, &retlen);
199 // Some sort of error
200 Log_Warning("Server", "SyscallRecieve failed?");
204 send(Client->Socket, retHeader, retlen, 0);
211 tRequestHeader *retHeader;
212 tRequestHeader errorHeader;
215 int cur_client_id = 0;
218 // Wait for something to do
219 while( Client->CurrentRequest == NULL )
220 SDL_CondWait(Client->WaitFlag, Client->Mutex);
222 // Log_Debug("AcessSrv", "Worker got message %p", Client->CurrentRequest);
224 if(Client->ClientID != cur_client_id) {
225 // Log_Debug("AcessSrv", "Client thread ID changed from %i to %i",
226 // cur_client_id, Client->ClientID);
227 Threads_SetThread( Client->ClientID );
228 cur_client_id = Client->ClientID;
233 int callid = Client->CurrentRequest->CallID;
234 Log_Debug("AcessSrv", "Client %i request %i %s",
235 Client->ClientID, callid,
236 callid < N_SYSCALLS ? casSYSCALL_NAMES[callid] : "UNK"
241 retHeader = SyscallRecieve(Client->CurrentRequest, &retSize);
244 // Return an error to the client
245 printf("ERROR: SyscallRecieve failed\n");
246 errorHeader.CallID = Client->CurrentRequest->CallID;
247 errorHeader.NParams = 0;
248 retHeader = &errorHeader;
249 retSize = sizeof(errorHeader);
253 retHeader->ClientID = Client->ClientID;
255 // Mark the thread as ready for another job
256 free(Client->CurrentRequest);
257 Client->CurrentRequest = 0;
259 // Log_Debug("AcessSrv", "Sending %i to %x:%i (Client %i)",
260 // retSize, ntohl(Client->ClientAddr.sin_addr.s_addr),
261 // ntohs(Client->ClientAddr.sin_port),
266 sentSize = sendto(gSocket, retHeader, retSize, 0,
267 (struct sockaddr*)&Client->ClientAddr, sizeof(Client->ClientAddr)
269 if( sentSize != retSize ) {
270 perror("Server_WorkerThread - send");
273 // Free allocated header
274 if( retHeader != &errorHeader )
280 int SyscallServer(void)
282 struct sockaddr_in server;
285 /* Open windows connection */
286 if (WSAStartup(0x0101, &gWinsock) != 0)
288 fprintf(stderr, "Could not open Windows connection.\n");
294 // Open TCP Connection
295 gSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
297 // Open UDP Connection
298 gSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
300 if (gSocket == INVALID_SOCKET)
302 fprintf(stderr, "Could not create socket.\n");
309 // Set server address
310 memset(&server, 0, sizeof(struct sockaddr_in));
311 server.sin_family = AF_INET;
312 server.sin_port = htons(SERVER_PORT);
313 server.sin_addr.s_addr = htonl(INADDR_ANY);
316 if( bind(gSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == -1 )
318 fprintf(stderr, "Cannot bind address to socket.\n");
319 perror("SyscallServer - bind");
321 closesocket(gSocket);
333 Log_Notice("AcessSrv", "Listening on 0.0.0.0:%i", SERVER_PORT);
334 gpServer_ListenThread = SDL_CreateThread( Server_ListenThread, NULL );
338 int Server_ListenThread(void *Unused)
340 // Wait for something to do :)
344 struct sockaddr_in clientaddr;
345 socklen_t clientSize = sizeof(clientaddr);
346 int clientSock = accept(gSocket, (struct sockaddr*)&clientaddr, &clientSize);
347 if( clientSock < 0 ) {
348 perror("SyscallServer - accept");
352 char addrstr[4*8+8+1];
353 inet_ntop(clientaddr.sin_family, &clientaddr.sin_addr, addrstr, sizeof(addrstr));
354 Log_Debug("Server", "Client connection %s:%i\n", addrstr, ntohs(clientaddr.sin_port));
358 tRequestAuthHdr authhdr;
359 len = recv(clientSock, &authhdr, sizeof(authhdr), 0);
360 if( len != sizeof(authhdr) ) {
361 // Some form of error?
362 Log_Warning("Server", "Client auth block bad size (%i != exp %i)",
363 len, sizeof(authhdr));
367 Log_Debug("Server", "Client assumed PID %i", authhdr.pid);
370 if( authhdr.pid == 0 ) {
371 // Allocate PID and client structure/thread
372 client = Server_GetClient(0);
373 client->Socket = clientSock;
374 authhdr.pid = client->ClientID;
377 // Get client structure and make sure it's unused
378 // - Auth token / verifcation?
379 client = Server_GetClient(authhdr.pid);
380 if( client->Socket != 0 ) {
381 Log_Warning("Server", "Client (%i)%p owned by FD%i but %s:%i tried to use it",
382 authhdr.pid, client, addrstr, clientaddr.sin_port);
386 client->Socket = clientSock;
389 Log_Debug("Server", "Client given PID %i", authhdr.pid);
391 len = send(clientSock, &authhdr, sizeof(authhdr), 0);
392 if( len != sizeof(authhdr) ) {
393 // Ok, this is an error
394 perror("Sending auth reply");
397 // All done, client thread should be watching now
401 tRequestHeader *req = (void*)data;
402 struct sockaddr_in addr;
403 uint clientSize = sizeof(addr);
407 length = recvfrom(gSocket, data, BUFSIZ, 0, (struct sockaddr*)&addr, &clientSize);
410 perror("SyscallServer - recv");
414 // Hand off to a worker thread
415 // - TODO: Actually have worker threads
416 // Log_Debug("Server", "%i bytes from %x:%i", length,
417 // ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
419 client = Server_GetClient(req->ClientID);
420 // NOTE: Hack - Should check if all zero
421 if( req->ClientID == 0 || client->ClientAddr.sin_port == 0 )
423 memcpy(&client->ClientAddr, &addr, sizeof(addr));
425 else if( memcmp(&client->ClientAddr, &addr, sizeof(addr)) != 0 )
427 printf("ClientID %i used by %x:%i\n",
428 client->ClientID, ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
429 printf(" actually owned by %x:%i\n",
430 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
434 if( client->CurrentRequest ) {
435 printf("Worker thread for %x:%i is busy\n",
436 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
440 // Log_Debug("AcessSrv", "Message from Client %i (%p)",
441 // client->ClientID, client);
443 // Make a copy of the request data
444 req = malloc(length);
445 memcpy(req, data, length);
446 client->CurrentRequest = req;
447 SDL_CondSignal(client->WaitFlag);