AcessNative - Huge changes, cleaning up and getting it to work
[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 // HACK: Should have these in a header
42 extern void     Log_Debug(const char *Subsys, const char *Message, ...);
43 extern void     Log_Notice(const char *Subsys, const char *Message, ...);
44
45 // === PROTOTYPES ===
46 tClient *Server_GetClient(int ClientID);
47  int    Server_WorkerThread(void *ClientPtr);
48  int    SyscallServer(void);
49
50 // === GLOBALS ===
51 #ifdef __WIN32__
52 WSADATA gWinsock;
53 SOCKET  gSocket = INVALID_SOCKET;
54 #else
55 # define INVALID_SOCKET -1
56  int    gSocket = INVALID_SOCKET;
57 #endif
58 tClient gaServer_Clients[MAX_CLIENTS];
59
60 // === CODE ===
61 int Server_GetClientID(void)
62 {
63          int    i;
64         Uint32  thisId = SDL_ThreadID();
65         
66         for( i = 0; i < MAX_CLIENTS; i ++ )
67         {
68                 if( SDL_GetThreadID(gaServer_Clients[i].WorkerThread) == thisId )
69                         return gaServer_Clients[i].ClientID;
70         }
71         
72         fprintf(stderr, "ERROR: Server_GetClientID - Thread is not allocated\n");
73         
74         return 0;
75 }
76
77 tClient *Server_GetClient(int ClientID)
78 {
79         tClient *ret = NULL;
80          int    i;
81         
82         // Allocate an ID if needed
83         if(ClientID == 0)
84                 ClientID = Threads_CreateRootProcess();
85         
86         for( i = 0; i < MAX_CLIENTS; i ++ )
87         {
88                 if( gaServer_Clients[i].ClientID == ClientID ) {
89                         return &gaServer_Clients[i];
90                 }
91                 if(!ret && gaServer_Clients[i].ClientID == 0)
92                         ret = &gaServer_Clients[i];
93         }
94         
95         // Uh oh, no free slots
96         // TODO: Dynamic allocation
97         if( !ret )
98                 return NULL;
99         
100         // Allocate a thread for the process
101         ret->ClientID = ClientID;
102         ret->CurrentRequest = NULL;
103                 
104         if( !ret->WorkerThread ) {
105                 ret->WaitFlag = SDL_CreateCond();
106                 ret->Mutex = SDL_CreateMutex();
107                 SDL_mutexP( ret->Mutex );
108                 ret->WorkerThread = SDL_CreateThread( Server_WorkerThread, ret );
109         }
110         
111         return ret;
112 }
113
114 int Server_WorkerThread(void *ClientPtr)
115 {
116         tClient *Client = ClientPtr;
117         tRequestHeader  *retHeader;
118         tRequestHeader  errorHeader;
119          int    retSize = 0;
120          int    sentSize;
121         
122         #if USE_TCP
123         #else
124         for( ;; )
125         {
126                 // Wait for something to do
127                 while( Client->CurrentRequest == NULL )
128                         SDL_CondWait(Client->WaitFlag, Client->Mutex);
129                 
130                 Log_Debug("AcessSrv", "Worker %i takes %p",
131                         Client->ClientID, Client->CurrentRequest);
132                 
133                 // Get the response
134                 retHeader = SyscallRecieve(Client->CurrentRequest, &retSize);
135                 
136                 if( !retHeader ) {
137                         // Return an error to the client
138                         printf("ERROR: SyscallRecieve failed\n");
139                         errorHeader.CallID = Client->CurrentRequest->CallID;
140                         errorHeader.NParams = 0;
141                         retHeader = &errorHeader;
142                         retSize = sizeof(errorHeader);
143                 }
144                 
145                 // Set ID
146                 retHeader->ClientID = Client->ClientID;
147                 
148                 // Mark the thread as ready for another job
149                 Client->CurrentRequest = 0;
150                 
151                 Log_Debug("AcessSrv", "Sending %i to %x:%i (Client %i)",
152                         retSize, ntohl(Client->ClientAddr.sin_addr.s_addr),
153                         ntohs(Client->ClientAddr.sin_port),
154                         Client->ClientID
155                         );
156                 
157                 // Return the data
158                 sentSize = sendto(gSocket, retHeader, retSize, 0,
159                         (struct sockaddr*)&Client->ClientAddr, sizeof(Client->ClientAddr)
160                         );
161                 if( sentSize != retSize ) {
162                         perror("Server_WorkerThread - send");
163                 }
164                 
165                 // Free allocated header
166                 if( retHeader != &errorHeader )
167                         free( retHeader );
168         }
169         #endif
170 }
171
172 int SyscallServer(void)
173 {
174         struct sockaddr_in      server;
175         
176         #ifdef __WIN32__
177         /* Open windows connection */
178         if (WSAStartup(0x0101, &gWinsock) != 0)
179         {
180                 fprintf(stderr, "Could not open Windows connection.\n");
181                 exit(0);
182         }
183         #endif
184         
185         #if USE_TCP
186         // Open TCP Connection
187         gSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
188         #else
189         // Open UDP Connection
190         gSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
191         #endif
192         if (gSocket == INVALID_SOCKET)
193         {
194                 fprintf(stderr, "Could not create socket.\n");
195                 #if __WIN32__
196                 WSACleanup();
197                 #endif
198                 exit(0);
199         }
200         
201         // Set server address
202         memset(&server, 0, sizeof(struct sockaddr_in));
203         server.sin_family = AF_INET;
204         server.sin_port = htons(SERVER_PORT);
205         server.sin_addr.s_addr = htonl(INADDR_ANY);
206         
207         // Bind
208         if( bind(gSocket, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) == -1 )
209         {
210                 fprintf(stderr, "Cannot bind address to socket.\n");
211                 perror("SyscallServer - bind");
212                 #if __WIN32__
213                 closesocket(gSocket);
214                 WSACleanup();
215                 #else
216                 close(gSocket);
217                 #endif
218                 exit(0);
219         }
220         
221         #if USE_TCP
222         listen(gSocket, 5);
223         #endif
224         
225         Log_Notice("AcessSrv", "Listening on 0.0.0.0:%i", SERVER_PORT);
226         
227         // Wait for something to do :)
228         for( ;; )
229         {
230                 #if USE_TCP
231                 struct sockaddr_in      client;
232                 uint    clientSize = sizeof(client);
233                  int    clientSock = accept(gSocket, (struct sockaddr*)&client, &clientSize);
234                 if( clientSock < 0 ) {
235                         perror("SyscallServer - accept");
236                         break ;
237                 }
238                 
239                 Log("Client connection %x:%i\n",
240                         ntohl(client.sin_addr), ntohs(client.sin_port)
241                         );
242                 
243                 #else
244                 char    data[BUFSIZ];
245                 tRequestHeader  *req = (void*)data;
246                 struct sockaddr_in      addr;
247                 uint    clientSize = sizeof(addr);
248                  int    length = recvfrom(gSocket, data, BUFSIZ, 0, (struct sockaddr*)&addr, &clientSize);
249                 tClient *client;
250                 
251                 if( length == -1 ) {
252                         perror("SyscallServer - recv");
253                         break;
254                 }
255                 
256                 // Hand off to a worker thread
257                 // - TODO: Actually have worker threads
258                 printf("%i bytes from %x:%i\n", length,
259                         ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
260                 
261                 client = Server_GetClient(req->ClientID);
262                 if( req->ClientID == 0 )
263                 {
264                         memcpy(&client->ClientAddr, &addr, sizeof(addr));
265                 }
266                 else if( memcmp(&client->ClientAddr, &addr, sizeof(addr)) != 0 )
267                 {
268                         printf("ClientID %i used by %x:%i\n",
269                                 client->ClientID, ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));
270                         printf(" actually owned by %x:%i\n",
271                                 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
272                         continue;
273                 }
274                 
275                 if( client->CurrentRequest ) {
276                         printf("Worker thread for %x:%i is busy\n",
277                                 ntohl(client->ClientAddr.sin_addr.s_addr), ntohs(client->ClientAddr.sin_port));
278                         continue;
279                 }
280                 
281                 Log_Debug("AcessSrv", "Message from Client %i (%p)",
282                         client->ClientID, client);
283                 
284                 client->CurrentRequest = req;
285                 SDL_CondSignal(client->WaitFlag);
286                 #endif
287         }
288         
289         return -1;
290 }

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