-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathsv_sgame.cpp
More file actions
641 lines (532 loc) · 16.4 KB
/
sv_sgame.cpp
File metadata and controls
641 lines (532 loc) · 16.4 KB
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
// sv_game.c -- interface to the game module
#include "server.h"
#include "sg_msgdef.h"
#include "qcommon/crypto.h"
#include "qcommon/sys.h"
#include "framework/CommonVMServices.h"
#include "framework/CommandSystem.h"
#ifndef BUILD_SERVER
#include "client/client.h" // For bot debug draw
#endif
#if USE_VULKAN
#include "../renderer-vulkan/DispatchRawData.h"
#endif
// Suppress warnings for unused [this] lambda captures.
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-lambda-capture"
#endif
// these functions must be used instead of pointer arithmetic, because
// the game allocates gentities with private information after the server shared part
sharedEntity_t *SV_GentityNum( int num )
{
if ( num < 0 || num >= MAX_GENTITIES || sv.gentities == nullptr )
{
Sys::Drop( "SV_GentityNum: bad num %d", num );
}
return reinterpret_cast<sharedEntity_t *>( sv.gentities + sv.gentitySize * num );
}
const OpaquePlayerState *SV_GameClientNum( int num )
{
if ( num < 0 || num >= sv_maxClients.Get() || sv.gameClients == nullptr )
{
Sys::Drop( "SV_GameClientNum: bad num" );
}
return ( OpaquePlayerState * )( ( byte * ) sv.gameClients + sv.gameClientSize * ( num ) );
}
svEntity_t *SV_SvEntityForGentity( sharedEntity_t *gEnt )
{
if ( !gEnt || gEnt->s.number < 0 || gEnt->s.number >= MAX_GENTITIES )
{
Sys::Drop( "SV_SvEntityForGentity: bad gEnt" );
}
return &sv.svEntities[ gEnt->s.number ];
}
/*
===============
SV_GameSendServerCommand
Sends a command string to a client
===============
*/
void SV_GameSendServerCommand( int clientNum, const char *text )
{
if ( clientNum == -1 )
{
SV_SendServerCommand( nullptr, "%s", text );
}
else if ( clientNum == -2 )
{
SV_PrintTranslatedText( text, false, false );
}
else
{
if ( clientNum < 0 || clientNum >= sv_maxClients.Get() )
{
return;
}
SV_SendServerCommand( svs.clients + clientNum, "%s", text );
}
}
/*
===============
SV_GameDropClient
Disconnects the client with a message
===============
*/
void SV_GameDropClient( int clientNum, const char *reason )
{
if ( clientNum < 0 || clientNum >= sv_maxClients.Get() )
{
return;
}
SV_DropClient( svs.clients + clientNum, reason );
}
/*
===============
SV_RSAGenMsg
Generate an encrypted RSA message
===============
*/
int SV_RSAGenMsg( const char *pubkey, char *cleartext, char *encrypted )
{
struct rsa_public_key public_key;
mpz_t message;
unsigned char buffer[ RSA_KEY_LENGTH / 8 - 11 ];
int retval;
Sys::GenRandomBytes( buffer, RSA_KEY_LENGTH / 8 - 11 );
nettle_mpz_init_set_str_256_u( message, RSA_KEY_LENGTH / 8 - 11, buffer );
mpz_get_str( cleartext, 16, message );
rsa_public_key_init( &public_key );
mpz_set_ui( public_key.e, RSA_PUBLIC_EXPONENT );
retval = mpz_set_str( public_key.n, pubkey, 16 ) + 1;
if ( retval )
{
rsa_public_key_prepare( &public_key );
retval = rsa_encrypt( &public_key, nullptr, qnettle_random, RSA_KEY_LENGTH / 8 - 11, buffer, message );
}
rsa_public_key_clear( &public_key );
mpz_get_str( encrypted, 16, message );
mpz_clear( message );
return retval;
}
/*
===============
SV_GetServerinfo
===============
*/
void SV_GetServerinfo( char *buffer, int bufferSize )
{
if ( bufferSize < 1 )
{
Sys::Drop( "SV_GetServerinfo: bufferSize == %i", bufferSize );
}
Q_strncpyz( buffer, Cvar_InfoString( CVAR_SERVERINFO, false ), bufferSize );
}
/*
===============
SV_LocateGameData
===============
*/
void SV_LocateGameData( const IPC::SharedMemory& shmRegion, int numGEntities, int sizeofGEntity_t,
int sizeofGameClient )
{
constexpr size_t playerStateAlignment = 4;
if ( numGEntities < 0 || numGEntities > MAX_GENTITIES || sizeofGEntity_t < 0 || sizeofGameClient < 0
|| sizeofGEntity_t % alignof(sharedEntity_t) || sizeofGEntity_t % playerStateAlignment )
Sys::Drop( "SV_LocateGameData: Invalid game data parameters" );
if ( int64_t(shmRegion.GetSize()) < int64_t(MAX_GENTITIES) * sizeofGEntity_t + int64_t(sv_maxClients.Get()) * sizeofGameClient )
Sys::Drop( "SV_LocateGameData: Shared memory region too small" );
byte* base = static_cast<byte*>(shmRegion.GetBase());
sv.gentities = base;
sv.gentitySize = sizeofGEntity_t;
sv.num_entities = numGEntities;
sv.gameClients = base + MAX_GENTITIES * size_t(sizeofGEntity_t);
sv.gameClientSize = sizeofGameClient;
}
static void UnlocateGameData()
{
sv.gentities = nullptr;
sv.gameClients = nullptr;
}
/*
===============
SV_GetUsercmd
===============
*/
void SV_GetUsercmd( int clientNum, usercmd_t *cmd )
{
if ( clientNum < 0 || clientNum >= sv_maxClients.Get() )
{
Sys::Drop( "SV_GetUsercmd: bad clientNum:%i", clientNum );
}
*cmd = svs.clients[ clientNum ].lastUsercmd;
}
/*
====================
SV_GetTimeString
Truncation is ignored
====================
*/
static void SV_GetTimeString( char *buffer, int length, const char *format, const qtime_t *tm )
{
struct tm t;
t.tm_sec = tm->tm_sec;
t.tm_min = tm->tm_min;
t.tm_hour = tm->tm_hour;
t.tm_mday = tm->tm_mday;
t.tm_mon = tm->tm_mon;
t.tm_year = tm->tm_year;
t.tm_wday = tm->tm_wday;
t.tm_yday = tm->tm_yday;
t.tm_isdst = tm->tm_isdst;
strftime ( buffer, length, format, &t );
}
/*
===============
SV_ShutdownGameProgs
Called every time a map changes
===============
*/
void SV_ShutdownGameProgs()
{
if ( !gvm.IsActive() )
{
return;
}
gvm.GameShutdown( false );
}
/*
==================
SV_InitGameVM
Called for both a full init and a restart
==================
*/
static void SV_InitGameVM()
{
// clear all gentity pointers that might still be set from
// a previous level
for ( int i = 0; i < sv_maxClients.Get(); i++ )
{
svs.clients[ i ].gentity = nullptr;
}
// use the current msec count for a random seed
// init for this gamestate
gvm.GameInit( sv.time, Com_Milliseconds());
}
/*
===================
SV_RestartGameProgs
Called on a map_restart, but not on a map change
===================
*/
void SV_RestartGameProgs()
{
if ( !gvm.IsActive() )
{
return;
}
gvm.GameShutdown( true );
gvm.Start();
SV_InitGameVM();
}
/*
===============
SV_InitGameProgs
Called on a map change, not on a map_restart
===============
*/
void SV_InitGameProgs()
{
// load the game module
gvm.Start();
SV_InitGameVM();
}
static void DispatchRawData( const std::string& data ) {
#if USE_VULKAN
DispatchRawData( data.data() );
#else
Q_UNUSED( data );
#endif
}
static std::string DispatchRawDataSync( const std::string& data ) {
#if USE_VULKAN
void* outMem;
int size;
DispatchRawDataSync( data.data(), &outMem, &size );
out.resize( size );
std::string out { ( const char* ) outMem, size };
return out;
#else
Q_UNUSED( data );
return "";
#endif
}
GameVM::GameVM(): VM::VMBase("sgame", Cvar::NONE), services(nullptr) {
}
void GameVM::Start()
{
services = std::unique_ptr<VM::CommonVMServices>(new VM::CommonVMServices(*this, "SGame", FS::Owner::SGAME, Cmd::SGAME_VM));
this->Create();
this->GameStaticInit();
}
void GameVM::GameStaticInit()
{
this->SendMsg<GameStaticInitMsg>(Sys::Milliseconds());
}
void GameVM::GameInit(int levelTime, int randomSeed)
{
this->SendMsg<GameInitMsg>(levelTime, randomSeed, Com_AreCheatsAllowed(), Com_IsClient());
NetcodeTable psTable;
size_t psSize;
this->SendMsg<VM::GetNetcodeTablesMsg>(psTable, psSize);
MSG_InitNetcodeTables(std::move(psTable), psSize);
}
void GameVM::GameShutdown(bool restart)
{
try {
this->SendMsg<GameShutdownMsg>(restart);
} catch (Sys::DropErr& err) {
Log::Notice("Error during sgame shutdown: %s", err.what());
}
try {
this->Free();
} catch (Sys::DropErr& err) {
Log::Notice("Error while freeing sgame: %s", err.what());
}
services = nullptr;
// Release the shared memory region
this->shmRegion.Close();
UnlocateGameData();
}
bool GameVM::GameClientConnect(char* reason, size_t size, int clientNum, bool firstTime, bool isBot)
{
bool denied;
std::string sentReason;
this->SendMsg<GameClientConnectMsg>(clientNum, firstTime, isBot, denied, sentReason);
if (denied) {
Q_strncpyz(reason, sentReason.c_str(), size);
}
return denied;
}
void GameVM::GameClientBegin(int clientNum)
{
this->SendMsg<GameClientBeginMsg>(clientNum);
}
void GameVM::GameClientUserInfoChanged(int clientNum)
{
this->SendMsg<GameClientUserinfoChangedMsg>(clientNum);
}
void GameVM::GameClientDisconnect(int clientNum)
{
this->SendMsg<GameClientDisconnectMsg>(clientNum);
}
void GameVM::GameClientCommand(int clientNum, const char* command)
{
this->SendMsg<GameClientCommandMsg>(clientNum, command);
}
void GameVM::GameClientThink(int clientNum)
{
this->SendMsg<GameClientThinkMsg>(clientNum);
}
void GameVM::GameRunFrame(int levelTime)
{
this->SendMsg<GameRunFrameMsg>(levelTime);
}
void GameVM::BotAIStartFrame(int)
{
Sys::Drop("GameVM::BotAIStartFrame not implemented");
}
void GameVM::Syscall(uint32_t id, Util::Reader reader, IPC::Channel& channel)
{
int major = id >> 16;
int minor = id & 0xffff;
if (major == VM::QVM) {
this->QVMSyscall(minor, reader, channel);
} else if (major < VM::LAST_COMMON_SYSCALL) {
services->Syscall(major, minor, std::move(reader), channel);
} else {
Sys::Drop("Bad major game syscall number: %d", major);
}
}
void GameVM::QVMSyscall(int syscallNum, Util::Reader& reader, IPC::Channel& channel)
{
switch (syscallNum) {
case G_LOCATE_GAME_DATA1:
IPC::HandleMsg<LocateGameDataMsg1>(channel, std::move(reader), [this](IPC::SharedMemory shm, int numEntities, int entitySize, int playerSize) {
shmRegion = std::move(shm);
SV_LocateGameData(shmRegion, numEntities, entitySize, playerSize);
});
break;
case G_LOCATE_GAME_DATA2:
IPC::HandleMsg<LocateGameDataMsg2>(channel, std::move(reader), [this](int numEntities, int entitySize, int playerSize) {
SV_LocateGameData(shmRegion, numEntities, entitySize, playerSize);
});
break;
case G_ADJUST_AREA_PORTAL_STATE:
IPC::HandleMsg<AdjustAreaPortalStateMsg>(channel, std::move(reader), [this](int entityNum, bool open) {
sharedEntity_t* ent = SV_GentityNum(entityNum);
CM_AdjustAreaPortalState(ent->r.areanum, ent->r.areanum2, open);
});
break;
case G_DROP_CLIENT:
IPC::HandleMsg<DropClientMsg>(channel, std::move(reader), [this](int clientNum, std::string reason) {
SV_GameDropClient(clientNum, reason.c_str());
});
break;
case G_SEND_SERVER_COMMAND:
IPC::HandleMsg<SendServerCommandMsg>(channel, std::move(reader), [this](int clientNum, std::string text) {
SV_GameSendServerCommand(clientNum, text.c_str());
});
break;
case G_SET_CONFIGSTRING:
IPC::HandleMsg<SetConfigStringMsg>(channel, std::move(reader), [this](int index, std::string val) {
SV_SetConfigstring(index, val.c_str());
});
break;
case G_GET_CONFIGSTRING:
IPC::HandleMsg<GetConfigStringMsg>(channel, std::move(reader), [this](int index, int len, std::string& res) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
SV_GetConfigstring(index, buffer.get(), len);
res.assign(buffer.get());
});
break;
case G_SET_CONFIGSTRING_RESTRICTIONS:
IPC::HandleMsg<SetConfigStringRestrictionsMsg>(channel, std::move(reader), [this] {
//Log::Notice("SV_SetConfigstringRestrictions not implemented");
});
break;
case G_SET_USERINFO:
IPC::HandleMsg<SetUserinfoMsg>(channel, std::move(reader), [this](int index, std::string val) {
SV_SetUserinfo(index, val.c_str());
});
break;
case G_GET_USERINFO:
IPC::HandleMsg<GetUserinfoMsg>(channel, std::move(reader), [this](int index, int len, std::string& res) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
SV_GetUserinfo(index, buffer.get(), len);
res.assign(buffer.get());
});
break;
case G_GET_SERVERINFO:
IPC::HandleMsg<GetServerinfoMsg>(channel, std::move(reader), [this](int len, std::string& res) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
SV_GetServerinfo(buffer.get(), len);
res.assign(buffer.get());
});
break;
case G_GET_USERCMD:
IPC::HandleMsg<GetUsercmdMsg>(channel, std::move(reader), [this](int index, usercmd_t& cmd) {
SV_GetUsercmd(index, &cmd);
});
break;
case G_RSA_GENMSG:
IPC::HandleMsg<RSAGenMsgMsg>(channel, std::move(reader), [this](std::string pubkey, int& res, std::string& cleartext, std::string& encrypted) {
char cleartextBuffer[RSA_STRING_LENGTH];
char encryptedBuffer[RSA_STRING_LENGTH];
res = SV_RSAGenMsg(pubkey.c_str(), cleartextBuffer, encryptedBuffer);
cleartext = cleartextBuffer;
encrypted = encryptedBuffer;
});
break;
case G_GEN_FINGERPRINT:
IPC::HandleMsg<GenFingerprintMsg>(channel, std::move(reader), [this](int keylen, const std::vector<char>& key, int len, std::string& res) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
Com_MD5Buffer(key.data(), keylen, buffer.get(), len);
res.assign(buffer.get());
});
break;
case G_GET_PLAYER_PUBKEY:
IPC::HandleMsg<GetPlayerPubkeyMsg>(channel, std::move(reader), [this](int clientNum, int len, std::string& pubkey) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
SV_GetPlayerPubkey(clientNum, buffer.get(), len);
pubkey.assign(buffer.get());
});
break;
case G_GET_TIME_STRING:
IPC::HandleMsg<GetTimeStringMsg>(channel, std::move(reader), [this](int len, std::string format, const qtime_t& time, std::string& res) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
SV_GetTimeString(buffer.get(), len, format.c_str(), &time);
res.assign(buffer.get());
});
break;
case G_GET_PINGS:
IPC::HandleMsg<GetPingsMsg>(channel, std::move(reader), [this](std::vector<int>& pings) {
int count = sv_maxClients.Get();
pings.resize(count);
for (int i = 0; i < count; i++) {
pings[i] = svs.clients[i].ping;
}
});
break;
case BOT_ALLOCATE_CLIENT:
IPC::HandleMsg<BotAllocateClientMsg>(channel, std::move(reader), [this](int& output) {
output = SV_BotAllocateClient();
});
break;
case BOT_FREE_CLIENT:
IPC::HandleMsg<BotFreeClientMsg>(channel, std::move(reader), [this](int input) {
SV_BotFreeClient(input);
});
break;
case BOT_GET_CONSOLE_MESSAGE:
IPC::HandleMsg<BotGetConsoleMessageMsg>(channel, std::move(reader), [this](int client, int len, int& res, std::string& message) {
std::unique_ptr<char[]> buffer(new char[len]);
buffer[0] = '\0';
res = SV_BotGetConsoleMessage(client, buffer.get(), len);
message.assign(buffer.get());
});
break;
case BOT_DEBUG_DRAW:
IPC::HandleMsg<BotDebugDrawMsg>(channel, std::move(reader), [this](std::vector<char> commands) {
#ifdef BUILD_SERVER
Q_UNUSED(commands);
Log::Warn("Can't use BotDebugDrawMsg in a dedicated server");
#else
re.SendBotDebugDrawCommands(std::move(commands));
#endif
});
break;
case DISPATCH_RAWDATA:
IPC::HandleMsg<DispatchRawDataMsg>( channel, std::move( reader ), [this] ( const std::string& data ) {
DispatchRawData( data );
} );
break;
case DISPATCH_RAWDATASYNC:
IPC::HandleMsg<DispatchRawDataSyncMsg>( channel, std::move( reader ), [this]( const std::string& data, std::string& out ) {
out = DispatchRawDataSync( data );
} );
break;
default:
Sys::Drop("Bad game system trap: %d", syscallNum);
}
}