/
server.c
executable file
·499 lines (421 loc) · 13 KB
/
server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <limits.h>
#include <pthread.h>
#include <assert.h>
#include <errno.h>
#include "../lib/libwebsockets.h"
#include "cjson/cJSON.c"
#include "server.h"
struct libwebsocket_context *ctx;
static pthread_mutex_t gamelistlock; // need this lock in order to add/ remove stuff from gamelist
static struct game *lobby, *headgame = 0;
static int usrc = 0; // user count
static int gmc = 1; // game count
static unsigned long serverticks = 0;
static char *gamelist = 0; // JSON string
static int gamelistlen = 0; // strlen of gamelist
static int gamelistage = 0; // servermsecs() on which encodedgamelist was last updated
static char gamelistcurrent = 1; // 0 if gamelist is not up to date
static int lastlogtime, lastwarninglogtime;
static int spam_maxs[SPAM_CAT_COUNT] = {SPAM_JOINLEAVE_MAX, SPAM_CHAT_MAX,
SPAM_SETTINGS_MAX, SPAM_STEERING_MAX};
static int spam_intervals[SPAM_CAT_COUNT] = {SPAM_JOINLEAVE_INTERVAL, SPAM_CHAT_INTERVAL,
SPAM_SETTINGS_INTERVAL, SPAM_STEERING_INTERVAL};
#include "helper.c"
#include "collision-detection.c"
#include "game.c"
#include "ai.c"
#include "game-system.c"
#include "pencil.c"
/* this protocol server (always the first one) just knows how to do HTTP */
static int callback_http(struct libwebsocket_context * context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason, void *user,
void *in, size_t len)
{
if(reason == LWS_CALLBACK_HTTP) {
char *ext, mime[32];
char path[MAX_FILE_REQ_LEN + LOCAL_PATH_LENGTH + 1];
if(ULTRA_VERBOSE)
printf("serving HTTP URI %s\n", (char *) in);
/* making sure request is reasonable */
if(strlen(in) > MAX_FILE_REQ_LEN || strstr(in, ".."))
return 0;
ext = getFileExt(in);
strcpy(path, LOCAL_RESOURCE_PATH);
strcat(path, in);
if(!strcmp(in, "/") || strrchr(in, '?') == (char *) in + 1) // ignore get variables (for now)
strcpy(path + LOCAL_PATH_LENGTH, "/index.html");
if(!strcmp(ext, "ico"))
strcpy(mime, "image/x-icon");
else if(!strcmp(ext, "js"))
strcpy(mime, "text/javascript");
else if(!strcmp(ext, "css"))
strcpy(mime, "text/css");
else if(!strcmp(ext, "ogg"))
strcpy(mime, "audio/ogg");
else if(!strcmp(ext, "mp3"))
strcpy(mime, "audio/mpeg");
else if(!strcmp(ext, "wav"))
strcpy(mime, "audio/wav");
else
strcpy(mime, "text/html");
if(ULTRA_VERBOSE)
printf("serving %s, %s\n", path, mime);
if(libwebsockets_serve_http_file(wsi, path, mime))
warning("Failed to send file %s\n", path);
free(ext);
}
return 0;
}
static int
callback_game(struct libwebsocket_context * context,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len)
{
struct user *u = user;
char *inchar= in;
cJSON *json = 0, *j;
char *mode;
int i, msgsize, bufsize;
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
if(DEBUG_MODE) printf("LWS_CALLBACK_ESTABLISHED\n");
iniuser(u, wsi);
/* new user, tell him house rules */
json = jsoncreate("acceptUser");
jsonaddnum(json, "playerId", u->id);
jsonaddnum(json, "tickLength", TICK_LENGTH);
jsonaddnum(json, "inkMinimumDistance", INK_MIN_DISTANCE);
sendjson(json, u);
jsondel(json);
json = 0;
break;
case LWS_CALLBACK_CLOSED:
logplayer(u, "disconnected\n");
deleteuser(u);
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
if(ULTRA_VERBOSE) printf("LWS_CALLBACK_SERVER_WRITEABLE. %d queued messages\n", u->sbat);
assert(!pthread_mutex_lock(&u->comlock));
for(i = 0; i < u->sbat; i++) {
char *str = u->sb[i];
if(ULTRA_VERBOSE) {
// zero terminate for print
char *tmp = smalloc(u->sbmsglen[i] + 1);
memcpy(tmp, str + PRE_PADDING, u->sbmsglen[i]);
tmp[u->sbmsglen[i]] = 0;
printf("send msg %s to user %d\n", tmp, u->id);
}
libwebsocket_write(wsi, (unsigned char*) str + PRE_PADDING, u->sbmsglen[i], LWS_WRITE_TEXT);
free(str);
}
u->sbat = 0;
pthread_mutex_unlock(&u->comlock);
break;
case LWS_CALLBACK_BROADCAST:
break;
/* TODO: dit stuk moet herschreven worden zodat hij game lockt eerdat hij message behandelt.
* verder mag een game niet meer direct verwijderd worden zodra er geen spelers meer inzitten
* maar moet state op GS_TERMINATED gezet worden zodat de thread zelf netjes de boel kan
* opruimen */
case LWS_CALLBACK_RECEIVE:
msgsize = strlen(inchar);
bufsize = u->recvbuf ? strlen(u->recvbuf) : 0;
if(ULTRA_VERBOSE) printf("received: %s\n", inchar);
/* buffer msg */
if(libwebsockets_remaining_packet_payload(wsi) > 0) {
u->recvbuf = srealloc(u->recvbuf, (bufsize + msgsize + 1) * sizeof(char));
strcpy(u->recvbuf + bufsize, inchar);
break;
}
/* unbuffer msg */
if(u->recvbuf) {
u->recvbuf = srealloc(u->recvbuf, (bufsize + msgsize + 1) * sizeof(char));
strcpy(u->recvbuf + bufsize, inchar);
json = cJSON_Parse(u->recvbuf);
free(u->recvbuf);
u->recvbuf = 0;
}
else
json = cJSON_Parse(inchar);
if(!json) {
warning("invalid json! received: %s\n", inchar);
break;
}
mode = jsongetstr(json, "mode");
if(!mode) {
warning("no mode specified!\n");
break;
}
else if(!strcmp(mode, "kick")) {
kickplayer(u, jsongetint(json, "playerId"));
}
else if(!strcmp(mode, "join")) {
int gameid, kicktimer = 0;
struct game *gm;
if(u->gm != lobby)
break;
gameid = jsongetint(json, "id");
gm = searchgame(gameid);
if(DEBUG_MODE)
printf("Received join package! Game-id: %d, user-id: %d, gm: %p\n",
gameid, u->id, (void *) gm);
if(gm && gm->state == GS_LOBBY && gm->nmax > gm->n &&
!(kicktimer = checkkick(gm, u)) && !checkspam(u, SPAM_CAT_JOINLEAVE))
joingame(gm, u);
else {
j = jsoncreate("joinFailed");
jsonaddnum(j, "id", gameid); // remind client what game he tried to join
if(!gm)
jsonaddstr(j, "reason", "notFound");
else if(gm->state - GS_LOBBY)
jsonaddstr(j, "reason", "started");
else if(kicktimer){
jsonaddstr(j, "reason", "kicked");
jsonaddnum(j, "timer", kicktimer);
}
else
jsonaddstr(j, "reason", "full");
sendjson(j, u);
jsondel(j);
}
}
else if(!strcmp(mode, "chat")) {
char *msg = jsongetstr(json, "message");
if(!u->gm) {
warning("user %d tried to chat, but no one's listening\n", u->id);
break;
}
if(checkspam(u, SPAM_CAT_CHAT)) {
warning("user %d is spamming in chat\n", u->id);
j = jsoncreate("stopSpamming");
sendjson(j, u);
jsondel(j);
break;
}
if(strlen(msg) > MAX_CHAT_LENGTH) {
warning("Chat message by user %d too long. Truncating..\n", u->id);
msg[MAX_CHAT_LENGTH] = 0;
}
logplayer(u, "chat: %s\n", msg);
j = jsoncreate("chat");
jsonaddnum(j, "playerId", u->id);
jsonaddstr(j, "message", duplicatestring(msg));
airjson(j, u->gm, u);
jsondel(j);
}
else if(!strcmp(mode, "getTime")) {
j = jsoncreate("time");
jsonaddnum(j, "time", (int) servermsecs());
sendjson(j, u);
jsondel(j);
}
else if(!strcmp(mode, "joinLobby")) {
// player can join only once
if(u->name)
break;
u->name = checkname(jsongetstr(json, "playerName"));
log("new player, id: %d, name: %s\n", u->id, u->name);
joingame(lobby, u);
}
else if(!strcmp(mode, "requestGame")) {
int nmin = jsongetint(json, "minPlayers");
int nmax = jsongetint(json, "maxPlayers");
if(DEBUG_MODE) printf("user %d requested game\n", u->id);
if(u->gm != lobby || checkspam(u, SPAM_CAT_JOINLEAVE))
break;
if(0 < nmin && nmin <= nmax && nmax <= 8) {
struct game *gm = findgame(nmin, nmax);
if(!gm)
gm = creategame(GT_AUTO, nmin, nmax);
joingame(gm, u);
}
}
else if(!strcmp(mode, "addComputer")) {
char *type;
/* NOTE: it is okay to not lock game here */
if(!u->gm || u->gm->host != u || u->gm->state != GS_LOBBY ||
u->gm->nmax <= u->gm->n) {
warning("user %d tried to add computer, but does not meet reqs\n", u->id);
break;
}
type = jsongetstr(json, "type");
if(!type)
break;
addcomputer(u->gm, type);
}
else if(!strcmp(mode, "createGame")) {
if(DEBUG_MODE) printf("user %d is creating a game\n", u->id);
if(u->gm != lobby) {
warning("user tried to create game. but he is not in lobby."
" he might not have a name etc.\n");
break;
}
joingame(creategame(GT_CUSTOM, 2, 8), u);
}
else if(!strcmp(mode, "leaveGame")) {
if(!checkspam(u, SPAM_CAT_JOINLEAVE) && u->gm && u->gm - lobby)
joingame(lobby, u);
}
else if(!strcmp(mode, "setParams")) {
if(!u->gm || u->gm->type != GT_CUSTOM || u->gm->state != GS_LOBBY ||
u->gm->host != u) {
warning("user %d tried to set params but not host of custom game"
" in lobby state\n", u->id);
break;
}
if(checkspam(u, SPAM_CAT_SETTINGS)) {
warning("user %d is trying to update game params too quickly\n", u->id);
break;
}
if(DEBUG_MODE)
printf("Setting params for game %p.\n", (void *) u->gm);
u->gm->paramupd = servermsecs();
u->gm->w = min(MAX_GAME_WIDTH, max(100, jsongetint(json, "w")));
u->gm->h = min(MAX_GAME_HEIGHT, max(100, jsongetint(json, "h")));
u->gm->v = min(1000, max(1, jsongetint(json, "v")));
u->gm->ts = (int) (min(10, max(0, jsongetdouble(json, "ts"))) * 1000) / 1000.0;
u->gm->hsize = min(1000, max(0, jsongetint(json, "hsize")));
u->gm->hfreq = min(10000, max(0, jsongetint(json, "hfreq")));
u->gm->goal = min(1000, max(1, jsongetint(json, "goal")));
u->gm->nmax = min(MAX_USERS_IN_GAME, max(u->gm->n, jsongetint(json, "nmax")));
u->gm->pencilmode = strtopencilmode(jsongetstr(json, "pencilMode"));
u->gm->inkcap = min(1000, max(0, jsongetint(json, "inkcap")));
u->gm->inkregen = min(1000, max(0, jsongetint(json, "inkregen")));
u->gm->inkdelay = min(20000, max(0, jsongetint(json, "inkdelay")));
u->gm->torus = (0 != jsongetint(json, "torus"));
j = encodegamepars(u->gm);
airjson(j, u->gm, 0);
jsondel(j);
}
else if(!strcmp(mode, "startGame")) {
if(!u->gm || u->gm->type != GT_CUSTOM || u->gm->state != GS_LOBBY ||
u->gm->host != u) {
warning("user %d tried to start game but not host of custom game"
" in lobby state\n", u->id);
break;
}
if(servermsecs() - u->gm->paramupd < UNLOCK_INTERVAL) {
warning("user %d is trying to start game too soon after update\n", u->id);
break;
}
j = jsoncheckjson(json, "segments");
if(j) {
if(u->gm->map)
freemap(u->gm->map);
u->gm->map = createmap(j->child);
airmap(u->gm->map, u->gm, 0);
}
startgame(u->gm);
}
else if(strcmp(mode, "input") == 0) {
interpretinput(json, u);
}
else if(!strcmp(mode, "pencil")) {
if(u->gm && u->gm->state == GS_STARTED && !u->ignoreinput
&& (u->gm->pencilmode == PM_ON
|| (u->gm->pencilmode == PM_ONDEATH && !u->state.alive)))
handlepencilmsg(json, u);
}
else if(!strcmp(mode, "enableInput")) {
u->ignoreinput = 0;
}
else
warning("unkown mode!\n");
break;
default:
break;
}
if(json)
jsondel(json);
return 0;
}
/* list of supported protocols and callbacks */
static struct libwebsocket_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"http-only", /* name */
callback_http, /* callback */
0 /* per_session_data_size */
},
{
"game-protocol",
callback_game,
sizeof(struct user),
},
{
NULL, NULL, 0 /* End of list */
}
};
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "port", required_argument, NULL, 'p' },
{ "killmask", no_argument, NULL, 'k' },
{ "interface", required_argument, NULL, 'i' },
{ "closetest", no_argument, NULL, 'c' },
{ NULL, 0, 0, 0 }
};
int main(int argc, char **argv) {
int n = 0;
int port = 7681;
int opts = 0;
char interface_name[128] = "";
const char *interface = 0;
while (n >= 0) {
n = getopt_long(argc, argv, "ci:khsp:", options, NULL);
if (n < 0)
continue;
switch (n) {
case 'k':
opts = LWS_SERVER_OPTION_DEFEAT_CLIENT_MASK;
break;
case 'p':
port = atoi(optarg);
break;
case 'i':
strncpy(interface_name, optarg, sizeof interface_name);
interface_name[(sizeof interface_name) - 1] = '\0';
interface = interface_name;
break;
case 'h':
printf("Usage: server "
"[-p=<p>]\n");
exit(1);
}
}
ctx = libwebsocket_create_context(port, interface, protocols,
libwebsocket_internal_extensions,
NULL, NULL, -1, -1, opts);
if (!ctx) {
printf("libwebsocket init failed\n");
return -1;
}
lobby = scalloc(1, sizeof(struct game));
lobby->type = GT_LOBBY;
pthread_mutex_init(&gamelistlock, 0);
pthread_mutex_init(&lobby->lock, 0);
pthread_create(&lobby->thread, 0, lobbyloop, (void *) 5000);
printf("server started on port %d\n", port);
/* send queued messages every 10ms */
while(5000)
libwebsocket_service(ctx, 10);
/* sequential code
mainloop(); */
/* fork code
n = libwebsockets_fork_service_loop(context);
if (n < 0) {
fprintf(stderr, "Unable to fork service loop %d\n", n);
return 1;
}
mainloop();*/
libwebsocket_context_destroy(ctx);
return 0;
}