-
-
Notifications
You must be signed in to change notification settings - Fork 453
/
Copy pathCGame.cpp
5022 lines (4371 loc) · 210 KB
/
CGame.cpp
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
*
* PROJECT: Multi Theft Auto
* LICENSE: See LICENSE in the top level directory
* FILE: Server/mods/deathmatch/logic/CGame.cpp
* PURPOSE: Server game class
*
* Multi Theft Auto is available from https://multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
#include "CGame.h"
#include "CAccessControlListManager.h"
#include "ASE.h"
#include "CPerfStatManager.h"
#include "CSettings.h"
#include "CZoneNames.h"
#include "CRemoteCalls.h"
#include "luadefs/CLuaDefs.h"
#include "CRegistry.h"
#include "CLanBroadcast.h"
#include "CRegisteredCommands.h"
#include "CTickRateSettings.h"
#include "CBuildingRemovalManager.h"
#include "CDebugHookManager.h"
#include "CTrainTrackManager.h"
#include "lua/CLuaCallback.h"
#include "CWeaponStatManager.h"
#include "CPedSync.h"
#include "CHTTPD.h"
#include "CBan.h"
#include "CPlayerCamera.h"
#include "CPacketTranslator.h"
#include "CAccountManager.h"
#include "CWaterManager.h"
#include "CResourceManager.h"
#include "CMapManager.h"
#include "CMarkerManager.h"
#include "CHandlingManager.h"
#include "CScriptDebugging.h"
#include "CBandwidthSettings.h"
#include "CMainConfig.h"
#include "CUnoccupiedVehicleSync.h"
#include "CRegistryManager.h"
#include "CLatentTransferManager.h"
#include "CCommandFile.h"
#include "packets/CVoiceEndPacket.h"
#include "packets/CEntityAddPacket.h"
#include "packets/CUpdateInfoPacket.h"
#include "packets/CPlayerWastedPacket.h"
#include "packets/CElementRPCPacket.h"
#include "packets/CReturnSyncPacket.h"
#include "packets/CPlayerNoSocketPacket.h"
#include "packets/CPlayerConnectCompletePacket.h"
#include "packets/CPlayerJoinCompletePacket.h"
#include "packets/CPlayerResourceStartPacket.h"
#include "packets/CPlayerNetworkStatusPacket.h"
#include "packets/CPlayerListPacket.h"
#include "packets/CPlayerClothesPacket.h"
#include "packets/CPlayerWorldSpecialPropertyPacket.h"
#include "packets/CServerInfoSyncPacket.h"
#include "packets/CLuaPacket.h"
#include "../utils/COpenPortsTester.h"
#include "../utils/CMasterServerAnnouncer.h"
#include "../utils/CHqComms.h"
#include "../utils/CFunctionUseLogger.h"
#include "Utils.h"
#include "CStaticFunctionDefinitions.h"
#include "lua/CLuaFunctionParseHelpers.h"
#include "CZipMaker.h"
#include "version.h"
#include "net/SimHeaders.h"
#include <signal.h>
#include <regex>
#define MAX_BULLETSYNC_DISTANCE 400.0f
#define MAX_EXPLOSION_SYNC_DISTANCE 400.0f
#define MAX_PROJECTILE_SYNC_DISTANCE 400.0f
#define RELEASE_MIN_CLIENT_VERSION "1.6.0-0.00000"
#define FIREBALLDESTRUCT_MIN_CLIENT_VERSION "1.6.0-9.22199"
#define DEFAULT_GRAVITY 0.008f
#define DEFAULT_GAME_SPEED 1.0f
#define DEFAULT_JETPACK_MAXHEIGHT 100
#define DEFAULT_AIRCRAFT_MAXHEIGHT 800
#define DEFAULT_AIRCRAFT_MAXVELOCITY 1.5f
#define DEFAULT_MINUTE_DURATION 1000
#ifndef WIN32
#include <limits.h>
#ifndef MAX_PATH
#define MAX_PATH PATH_MAX
#endif
#endif
CGame* g_pGame = NULL;
char szProgress[4] = {'-', '\\', '|', '/'};
unsigned char ucProgress = 0;
unsigned char ucProgressSkip = 0;
pthread_mutex_t mutexhttp;
#ifdef WIN32
BOOL WINAPI ConsoleEventHandler(DWORD dwCtrlType)
{
if (dwCtrlType == CTRL_CLOSE_EVENT)
{
// Close button pressed or task ended in task manager
if (g_pGame)
{
// Warning message if server started
if (g_pGame->IsServerFullyUp())
{
printf("\n** TERMINATING SERVER WITHOUT SAVING **\n");
printf("\nUse Ctrl-C next time!\n");
Sleep(3000);
}
}
// Don't call g_pGame->SetIsFinished() as Windows could terminate the process mid-shutdown
return TRUE;
}
else if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT)
{
if (g_pGame)
{
// If we have nothing in the input buffer, let's close the server, otherwise just reset input
if (!g_pServerInterface->ResetInput())
{
// Graceful close on Ctrl-C or Ctrl-Break
g_pGame->SetIsFinished(true);
}
return TRUE;
}
}
return FALSE;
}
#else
void sighandler(int sig)
{
if (sig == SIGTERM || sig == SIGINT)
{
// If we received a Ctrl-C, let's try resetting input buffer first, otherwise close the server
if (g_pGame && (sig != SIGINT || (sig == SIGINT && !g_pServerInterface->ResetInput())))
{
// Graceful close on Ctrl-C or 'kill'
g_pGame->SetIsFinished(true);
}
}
}
#endif
CGame::CGame() : m_FloodProtect(4, 30000, 30000) // Max of 4 connections per 30 seconds, then 30 second ignore
{
// Set our global pointer
g_pGame = this;
m_bServerFullyUp = false;
// Initialize random number generator and time
RandomizeRandomSeed();
m_bBeingDeleted = false;
m_pUnoccupiedVehicleSync = NULL;
m_pConsole = NULL;
m_pMapManager = NULL;
m_HandlingManager = nullptr;
m_pLuaManager = NULL;
m_pPacketTranslator = NULL;
m_pMarkerManager = NULL;
m_pRadarAreaManager = NULL;
m_pPlayerManager = NULL;
m_pVehicleManager = NULL;
m_pPickupManager = NULL;
m_pObjectManager = NULL;
m_pColManager = NULL;
m_pBlipManager = NULL;
m_pClock = NULL;
m_pScriptDebugging = NULL;
m_pBanManager = NULL;
m_pTeamManager = NULL;
m_pMainConfig = NULL;
m_pDatabaseManager = NULL;
m_pLuaCallbackManager = NULL;
m_pRegistryManager = NULL;
m_pRegistry = NULL;
m_pAccountManager = NULL;
m_pPedManager = NULL;
m_pResourceManager = NULL;
m_pLatentTransferManager = NULL;
m_pHTTPD = NULL;
m_pACLManager = NULL;
m_pRegisteredCommands = NULL;
m_pZoneNames = NULL;
m_pGroups = NULL;
m_pSettings = NULL;
m_pRemoteCalls = NULL;
m_pRPCFunctions = NULL;
m_pLanBroadcast = NULL;
m_pPedSync = NULL;
m_pWaterManager = NULL;
m_pWeaponStatsManager = NULL;
m_pBuildingRemovalManager = NULL;
m_pCustomWeaponManager = NULL;
m_pFunctionUseLogger = NULL;
#ifdef WITH_OBJECT_SYNC
m_pObjectSync = NULL;
#endif
m_bInteriorSoundsEnabled = true;
m_bOverrideRainLevel = false;
m_bOverrideSunSize = false;
m_bOverrideSunColor = false;
m_bOverrideWindVelocity = false;
m_bOverrideFarClip = false;
m_bOverrideFogDistance = false;
m_bOverrideMoonSize = false;
m_pASE = NULL;
ResetMapInfo();
m_usFPS = 0;
m_usFrames = 0;
m_llLastFPSTime = 0;
m_szCurrentFileName = NULL;
m_pConsoleClient = NULL;
m_bIsFinished = false;
// Setup game glitch defaults ( false = disabled )
m_Glitches[GLITCH_QUICKRELOAD] = false;
m_Glitches[GLITCH_FASTFIRE] = false;
m_Glitches[GLITCH_FASTMOVE] = false;
m_Glitches[GLITCH_CROUCHBUG] = false;
m_Glitches[GLITCH_CLOSEDAMAGE] = false;
m_Glitches[GLITCH_HITANIM] = false;
m_Glitches[GLITCH_FASTSPRINT] = false;
m_Glitches[GLITCH_BADDRIVEBYHITBOX] = false;
m_Glitches[GLITCH_QUICKSTAND] = false;
m_Glitches[GLITCH_KICKOUTOFVEHICLE_ONMODELREPLACE] = false;
for (int i = 0; i < WEAPONTYPE_LAST_WEAPONTYPE; i++)
m_JetpackWeapons[i] = false;
// Setup world special properties
m_WorldSpecialProps[WorldSpecialProperty::HOVERCARS] = false;
m_WorldSpecialProps[WorldSpecialProperty::AIRCARS] = false;
m_WorldSpecialProps[WorldSpecialProperty::EXTRABUNNY] = false;
m_WorldSpecialProps[WorldSpecialProperty::EXTRAJUMP] = false;
m_WorldSpecialProps[WorldSpecialProperty::RANDOMFOLIAGE] = true;
m_WorldSpecialProps[WorldSpecialProperty::SNIPERMOON] = false;
m_WorldSpecialProps[WorldSpecialProperty::EXTRAAIRRESISTANCE] = true;
m_WorldSpecialProps[WorldSpecialProperty::UNDERWORLDWARP] = true;
m_WorldSpecialProps[WorldSpecialProperty::VEHICLESUNGLARE] = false;
m_WorldSpecialProps[WorldSpecialProperty::CORONAZTEST] = true;
m_WorldSpecialProps[WorldSpecialProperty::WATERCREATURES] = true;
m_WorldSpecialProps[WorldSpecialProperty::BURNFLIPPEDCARS] = true;
m_WorldSpecialProps[WorldSpecialProperty::FIREBALLDESTRUCT] = true;
m_WorldSpecialProps[WorldSpecialProperty::EXTENDEDWATERCANNONS] = true;
m_WorldSpecialProps[WorldSpecialProperty::ROADSIGNSTEXT] = true;
m_WorldSpecialProps[WorldSpecialProperty::TUNNELWEATHERBLEND] = true;
m_WorldSpecialProps[WorldSpecialProperty::IGNOREFIRESTATE] = false;
m_WorldSpecialProps[WorldSpecialProperty::FLYINGCOMPONENTS] = true;
m_WorldSpecialProps[WorldSpecialProperty::VEHICLEBURNEXPLOSIONS] = true;
m_JetpackWeapons[WEAPONTYPE_MICRO_UZI] = true;
m_JetpackWeapons[WEAPONTYPE_TEC9] = true;
m_JetpackWeapons[WEAPONTYPE_PISTOL] = true;
// Glitch names (for Lua interface)
m_GlitchNames["quickreload"] = GLITCH_QUICKRELOAD;
m_GlitchNames["fastfire"] = GLITCH_FASTFIRE;
m_GlitchNames["fastmove"] = GLITCH_FASTMOVE;
m_GlitchNames["crouchbug"] = GLITCH_CROUCHBUG;
m_GlitchNames["highcloserangedamage"] = GLITCH_CLOSEDAMAGE;
m_GlitchNames["hitanim"] = GLITCH_HITANIM;
m_GlitchNames["fastsprint"] = GLITCH_FASTSPRINT;
m_GlitchNames["baddrivebyhitbox"] = GLITCH_BADDRIVEBYHITBOX;
m_GlitchNames["quickstand"] = GLITCH_QUICKSTAND;
m_GlitchNames["kickoutofvehicle_onmodelreplace"] = GLITCH_KICKOUTOFVEHICLE_ONMODELREPLACE;
m_bCloudsEnabled = true;
m_pOpenPortsTester = NULL;
m_bTrafficLightsLocked = false;
m_ucTrafficLightState = 0;
m_llLastTrafficUpdate = 0;
m_bOcclusionsEnabled = true;
memset(&m_bGarageStates[0], 0, sizeof(m_bGarageStates));
// init our mutex
pthread_mutex_init(&mutexhttp, NULL);
}
void CGame::ResetMapInfo()
{
// Add variables to get reset in resetMapInfo here
m_fGravity = 0.008f;
m_fGameSpeed = 1.0f;
m_fJetpackMaxHeight = 100;
m_fAircraftMaxHeight = 800;
m_fAircraftMaxVelocity = 1.5f;
if (m_pWaterManager)
{
m_pWaterManager->ResetWorldWaterLevel();
m_pWaterManager->SetGlobalWaveHeight(0.0f);
}
m_ucSkyGradientTR = 0, m_ucSkyGradientTG = 0, m_ucSkyGradientTB = 0;
m_ucSkyGradientBR = 0, m_ucSkyGradientBG = 0, m_ucSkyGradientBB = 0;
m_bHasSkyGradient = false;
m_HeatHazeSettings = SHeatHazeSettings();
m_bHasHeatHaze = false;
m_bCloudsEnabled = true;
m_bTrafficLightsLocked = false;
m_ucTrafficLightState = 0;
m_llLastTrafficUpdate = 0;
g_pGame->SetHasWaterColor(false);
g_pGame->SetInteriorSoundsEnabled(true);
g_pGame->SetHasFarClipDistance(false);
g_pGame->SetHasFogDistance(false);
g_pGame->SetHasRainLevel(false);
g_pGame->SetHasSunColor(false);
g_pGame->SetHasSunSize(false);
g_pGame->SetHasWindVelocity(false);
g_pGame->SetHasMoonSize(false);
}
CGame::~CGame()
{
m_bBeingDeleted = true;
// Stop the web server first to avoid threading issues
if (m_pHTTPD)
m_pHTTPD->StopHTTPD();
// Stop the performance stats modules
if (CPerfStatManager::GetSingleton() != NULL)
CPerfStatManager::GetSingleton()->Stop();
// Stop and flush sim packet handling
CSimControl::EnableSimSystem(false);
// Disconnect all players
if (m_pPlayerManager)
{
std::list<CPlayer*>::const_iterator iter = m_pPlayerManager->IterBegin();
for (; iter != m_pPlayerManager->IterEnd(); iter++)
DisconnectPlayer(this, **iter, CPlayerDisconnectedPacket::SHUTDOWN);
}
// Stop networking
Stop();
// Stop async task scheduler
SAFE_DELETE(m_pAsyncTaskScheduler);
// Destroy our stuff
SAFE_DELETE(m_pResourceManager);
// Delete everything we have undeleted
m_ElementDeleter.DoDeleteAll();
SAFE_DELETE(m_pUnoccupiedVehicleSync);
SAFE_DELETE(m_pPedSync);
#ifdef WITH_OBJECT_SYNC
SAFE_DELETE(m_pObjectSync);
#endif
SAFE_DELETE(m_pConsole);
SAFE_DELETE(m_pLuaManager);
SAFE_DELETE(m_pMapManager);
SAFE_DELETE(m_pRemoteCalls);
SAFE_DELETE(m_pPacketTranslator);
SAFE_DELETE(m_pMarkerManager);
SAFE_DELETE(m_pRadarAreaManager);
SAFE_DELETE(m_pPlayerManager);
SAFE_DELETE(m_pVehicleManager);
SAFE_DELETE(m_pPickupManager);
SAFE_DELETE(m_pObjectManager);
SAFE_DELETE(m_pColManager);
SAFE_DELETE(m_pBlipManager);
SAFE_DELETE(m_pClock);
SAFE_DELETE(m_pScriptDebugging);
SAFE_DELETE(m_pBanManager);
SAFE_DELETE(m_pTeamManager);
SAFE_DELETE(m_pMainConfig);
if (m_pRegistryManager)
m_pRegistryManager->CloseRegistry(m_pRegistry);
m_pRegistry = NULL;
SAFE_DELETE(m_pConsoleClient);
SAFE_DELETE(m_pAccountManager);
SAFE_DELETE(m_pRegistryManager);
SAFE_DELETE(m_pDatabaseManager);
SAFE_DELETE(m_pLuaCallbackManager);
SAFE_DELETE(m_pRegisteredCommands);
SAFE_DELETE(m_pPedManager);
SAFE_DELETE(m_pLatentTransferManager);
SAFE_DELETE(m_pDebugHookManager);
SAFE_DELETE(m_pHTTPD);
SAFE_DELETE(m_pACLManager);
SAFE_DELETE(m_pGroups);
SAFE_DELETE(m_pZoneNames);
SAFE_DELETE(m_pASE);
SAFE_DELETE(m_pSettings);
SAFE_DELETE(m_pRPCFunctions);
SAFE_DELETE(m_pWaterManager);
SAFE_DELETE(m_pWeaponStatsManager);
SAFE_DELETE(m_pBuildingRemovalManager);
SAFE_DELETE(m_pCustomWeaponManager);
SAFE_DELETE(m_pFunctionUseLogger);
SAFE_DELETE(m_pOpenPortsTester);
SAFE_DELETE(m_pMasterServerAnnouncer);
SAFE_DELETE(m_pASE);
SAFE_RELEASE(m_pHqComms);
CSimControl::Shutdown();
// Clear our global pointer
g_pGame = NULL;
// Remove our console control handler
#ifdef WIN32
SetConsoleCtrlHandler(ConsoleEventHandler, FALSE);
#else
signal(SIGTERM, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
#endif
}
void CGame::GetTag(char* szInfoTag, int iInfoTag)
{
// Construct the info tag
SString strInfoTag("%c[%c%c%c] MTA: San Andreas %c:%c: %d/%d players %c:%c: %u resources", 132, 135, szProgress[ucProgress], 132, 130, 130,
m_pPlayerManager->Count(), m_pMainConfig->GetMaxPlayers(), 130, 130, m_pResourceManager->GetResourceLoadedCount());
if (!GetConfig()->GetThreadNetEnabled())
{
strInfoTag += SString(" %c:%c: %u fps", 130, 130, g_pGame->GetServerFPS());
}
else
{
strInfoTag += SString(" %c:%c: %u fps (%u)", 130, 130, g_pGame->GetSyncFPS(), g_pGame->GetServerFPS());
}
STRNCPY(szInfoTag, *strInfoTag, iInfoTag);
}
void CGame::HandleInput(char* szCommand)
{
// Lock the critical section so http server won't interrupt in the middle of our pulse
Lock();
// Handle the input
m_pConsole->HandleInput(szCommand, m_pConsoleClient, m_pConsoleClient);
// Unlock the critical section again
Unlock();
}
void CGame::DoPulse()
{
// Lock the critical section so http server won't interrupt in the middle of our pulse
Lock();
UpdateModuleTickCount64();
// Calculate FPS
long long llCurrentTime = SharedUtil::GetModuleTickCount64();
long long ulDiff = llCurrentTime - m_llLastFPSTime;
// Calculate the server-side fps
if (ulDiff >= 1000)
{
m_usFPS = m_usFrames;
m_usFrames = 0;
m_llLastFPSTime = llCurrentTime;
}
m_usFrames++;
// Update the progress rotator
uchar ucDelta = (uchar)llCurrentTime - ucProgressSkip;
ushort usReqDelta = 80 - (100 - std::min<ushort>(100, m_usFPS)) / 5;
if (ucDelta > usReqDelta)
{
// Clamp ucProgress between 0 and 3
ucProgress = (ucProgress + 1) & 3;
ucProgressSkip = (uchar)llCurrentTime;
}
// Handle critical things
CSimControl::DoPulse();
CNetBufferWatchDog::DoPulse();
CLOCK_SET_SECTION("CGame::DoPulse");
CLOCK1("HTTPDownloadManager");
GetRemoteCalls()->ProcessQueuedFiles();
g_pNetServer->GetHTTPDownloadManager(EDownloadMode::ASE)->ProcessQueuedFiles();
UNCLOCK1("HTTPDownloadManager");
CLOCK_CALL1(m_pPlayerManager->DoPulse(););
// Pulse the net interface
CLOCK_CALL1(g_pNetServer->DoPulse(););
if (m_pLanBroadcast)
{
CLOCK_CALL1(m_pLanBroadcast->DoPulse(););
}
// Pulse our stuff
CLOCK_CALL1(m_pMapManager->DoPulse(););
CLOCK_CALL1(m_pUnoccupiedVehicleSync->DoPulse(););
CLOCK_CALL1(m_pPedSync->DoPulse(););
#ifdef WITH_OBJECT_SYNC
CLOCK_CALL1(m_pObjectSync->DoPulse(););
#endif
CLOCK_CALL1(m_pBanManager->DoPulse(););
CLOCK_CALL1(m_pAccountManager->DoPulse(););
CLOCK_CALL1(m_pRegistryManager->DoPulse(););
CLOCK_CALL1(m_pACLManager->DoPulse(););
// Handle the traffic light sync
if (m_bTrafficLightsLocked == false)
{
CLOCK_CALL1(ProcessTrafficLights(llCurrentTime););
}
// Pulse ASE
if (m_pASE)
{
CLOCK_CALL1(m_pASE->DoPulse(););
}
// Pulse the scripting system
if (m_pLuaManager)
{
CLOCK_CALL1(m_pLuaManager->DoPulse(););
}
CLOCK_CALL1(m_pDatabaseManager->DoPulse(););
// Process our resource stop/restart queue
CLOCK_CALL1(m_pResourceManager->ProcessQueue(););
ProcessClientTriggeredEventSpam();
// Delete all items requested
CLOCK_CALL1(m_ElementDeleter.DoDeleteAll(););
CLOCK_CALL1(CPerfStatManager::GetSingleton()->DoPulse(););
if (m_pMasterServerAnnouncer)
m_pMasterServerAnnouncer->Pulse();
if (m_pHqComms)
m_pHqComms->Pulse();
CLOCK_CALL1(m_pFunctionUseLogger->Pulse(););
CLOCK_CALL1(m_lightsyncManager.DoPulse(););
CLOCK_CALL1(m_pLatentTransferManager->DoPulse(););
CLOCK_CALL1(m_pAsyncTaskScheduler->CollectResults());
CLOCK_CALL1(m_pMapManager->GetWeather()->DoPulse(););
PrintLogOutputFromNetModule();
m_pScriptDebugging->UpdateLogOutput();
// Unlock the critical section again
Unlock();
}
bool CGame::Start(int iArgumentCount, char* szArguments[])
{
// Init
m_pASE = NULL;
IsMainThread();
// Startup the getElementsByType from root optimizations
CElement::StartupEntitiesFromRoot();
CSimControl::Startup();
try
{
m_pGroups = new CGroups;
m_pClock = new CClock;
m_pBlipManager = new CBlipManager;
m_pColManager = new CColManager;
m_pObjectManager = new CObjectManager;
m_pPickupManager = new CPickupManager(m_pColManager);
m_pPlayerManager = new CPlayerManager;
m_pRadarAreaManager = new CRadarAreaManager;
m_pMarkerManager = new CMarkerManager(m_pColManager);
m_HandlingManager = std::make_unique<CHandlingManager>();
m_pVehicleManager = new CVehicleManager;
m_pPacketTranslator = new CPacketTranslator(m_pPlayerManager);
m_pBanManager = new CBanManager;
m_pTeamManager = new CTeamManager;
m_pPedManager = new CPedManager;
m_pWaterManager = new CWaterManager;
m_pScriptDebugging = new CScriptDebugging();
m_pMapManager = new CMapManager(m_pBlipManager, m_pObjectManager, m_pPickupManager, m_pPlayerManager, m_pRadarAreaManager, m_pMarkerManager,
m_pVehicleManager, m_pTeamManager, m_pPedManager, m_pColManager, m_pWaterManager, m_pClock, m_pGroups, &m_Events,
m_pScriptDebugging, &m_ElementDeleter);
m_pACLManager = new CAccessControlListManager;
m_pHqComms = new CHqComms;
m_pRegisteredCommands = new CRegisteredCommands(m_pACLManager);
m_pLuaManager = new CLuaManager(m_pObjectManager, m_pPlayerManager, m_pVehicleManager, m_pBlipManager, m_pRadarAreaManager, m_pRegisteredCommands,
m_pMapManager, &m_Events);
m_pConsole = new CConsole(m_pBlipManager, m_pMapManager, m_pPlayerManager, m_pRegisteredCommands, m_pVehicleManager, m_pBanManager, m_pACLManager);
m_pMainConfig = new CMainConfig(m_pConsole);
m_pRPCFunctions = new CRPCFunctions;
m_pWeaponStatsManager = new CWeaponStatManager();
m_pBuildingRemovalManager = new CBuildingRemovalManager;
m_pCustomWeaponManager = new CCustomWeaponManager();
m_pTrainTrackManager = std::make_shared<CTrainTrackManager>();
}
catch (const std::bad_alloc& e)
{
std::cout << "ERROR: Memory allocations failed: " << e.what() << std::endl;
return false;
}
catch (const std::exception& e)
{
std::cout << "ERROR: Constructors failed: " << e.what() << std::endl;
return false;
}
// Parse the commandline
if (!m_CommandLineParser.Parse(iArgumentCount, szArguments))
{
return false;
}
// Check pcre has been built correctly
int iPcreConfigUtf8 = 0;
pcre_config(PCRE_CONFIG_UTF8, &iPcreConfigUtf8);
if (iPcreConfigUtf8 == 0)
{
CLogger::ErrorPrintf("PCRE built without UTF8 support\n");
return false;
}
// Check json has precision mod - #8853 (toJSON passes wrong floats)
json_object* pJsonObject = json_object_new_double(5.12345678901234);
SString strJsonResult = json_object_to_json_string_ext(pJsonObject, JSON_C_TO_STRING_PLAIN);
json_object_put(pJsonObject);
if (strJsonResult != "5.12345678901234")
{
CLogger::ErrorPrintf("JSON built without precision modification\n");
}
// Grab the path to the main config
SString strBuffer;
const char* szMainConfig;
if (m_CommandLineParser.GetMainConfig(szMainConfig))
{
strBuffer = g_pServerInterface->GetModManager()->GetAbsolutePath(szMainConfig);
}
else
{
strBuffer = g_pServerInterface->GetModManager()->GetAbsolutePath("mtaserver.conf");
m_bUsingMtaServerConf = true;
}
m_pMainConfig->SetFileName(strBuffer);
// Load the main config base
if (!m_pMainConfig->Load())
return false;
// Let the main config handle selecting settings from the command line where appropriate
m_pMainConfig->SetCommandLineParser(&m_CommandLineParser);
// Do basic backup
HandleBackup();
// Encrypt crash dumps for uploading
HandleCrashDumpEncryption();
// Check Windows server is using correctly compiled Lua dll
#ifndef MTA_DEBUG
#ifdef WIN32
HMODULE hModule = LoadLibrary("lua5.1.dll");
// Release server should not have this function
PVOID pFunc = static_cast<PVOID>(GetProcAddress(hModule, "luaX_is_apicheck_enabled"));
FreeLibrary(hModule);
if (pFunc)
{
CLogger::ErrorPrintf("Problem with Lua dll\n");
return false;
}
#endif
#endif
// Read some settings
m_pACLManager->SetFileName(m_pMainConfig->GetAccessControlListFile().c_str());
const SString strServerIP = m_pMainConfig->GetServerIP();
const SString strServerIPList = m_pMainConfig->GetServerIPList();
unsigned short usServerPort = m_pMainConfig->GetServerPort();
unsigned int uiMaxPlayers = m_pMainConfig->GetMaxPlayers();
// Start async task scheduler
m_pAsyncTaskScheduler = new SharedUtil::CAsyncTaskScheduler(2);
// Create the account manager
strBuffer = g_pServerInterface->GetModManager()->GetAbsolutePath("internal.db");
m_pDatabaseManager = NewDatabaseManager();
m_pDebugHookManager = new CDebugHookManager();
m_pLuaCallbackManager = new CLuaCallbackManager();
m_pRegistryManager = new CRegistryManager();
m_pAccountManager = new CAccountManager(strBuffer);
// Create and start the HTTP server
m_pHTTPD = new CHTTPD;
m_pLatentTransferManager = new CLatentTransferManager();
// Enable it if required
if (m_pMainConfig->IsHTTPEnabled())
{
// Slight hack for internal HTTPD: Listen on all IPs if multiple IPs declared
SString strUseIP = (strServerIP == strServerIPList) ? strServerIP : "";
if (!m_pHTTPD->StartHTTPD(strUseIP, m_pMainConfig->GetHTTPPort()))
{
CLogger::ErrorPrintf("Could not start HTTP server on interface '%s' and port '%u'!\n", strUseIP.c_str(), m_pMainConfig->GetHTTPPort());
return false;
}
}
m_pFunctionUseLogger = new CFunctionUseLogger(m_pMainConfig->GetLoadstringLogFilename());
// Setup server id
if (!g_pNetServer->InitServerId(m_pMainConfig->GetIdFile()))
{
CLogger::ErrorPrintf("Could not read or create server-id keys file at '%s'\n", *m_pMainConfig->GetIdFile());
return false;
}
// Eventually set the logfiles
bool bLogFile = CLogger::SetLogFile(m_pMainConfig->GetLogFile().c_str());
CLogger::SetAuthFile(m_pMainConfig->GetAuthFile().c_str());
// Trim the logfile name for the output
char szLogFileNameOutput[MAX_PATH];
char* pszLogFileName = szLogFileNameOutput;
strncpy(szLogFileNameOutput, m_pMainConfig->GetLogFile().c_str(), MAX_PATH);
size_t sizeLogFileName = strlen(szLogFileNameOutput);
if (sizeLogFileName > 45)
{
pszLogFileName += (sizeLogFileName - 45);
pszLogFileName[0] = '.';
pszLogFileName[1] = '.';
}
// Prepare our voice string
SString strVoice = "Disabled";
if (m_pMainConfig->IsVoiceEnabled())
switch (m_pMainConfig->GetVoiceSampleRate())
{
case 0:
strVoice = SString("Quality [%i]; Sample Rate: [8000Hz]", m_pMainConfig->GetVoiceQuality());
break;
case 1:
strVoice = SString("Quality [%i]; Sample Rate: [16000Hz]", m_pMainConfig->GetVoiceQuality());
break;
case 2:
strVoice = SString("Quality [%i]; Sample Rate: [32000Hz]", m_pMainConfig->GetVoiceQuality());
break;
default:
break;
}
if (m_pMainConfig->GetVoiceBitrate())
strVoice += SString("; Bitrate: [%ibps]", m_pMainConfig->GetVoiceBitrate());
// Make bandwidth reduction string
SString strBandwidthSaving = m_pMainConfig->GetSetting("bandwidth_reduction");
strBandwidthSaving = strBandwidthSaving.Left(1).ToUpper() + strBandwidthSaving.SubStr(1);
if (g_pBandwidthSettings->bLightSyncEnabled)
strBandwidthSaving += SString(" with lightweight sync rate of %dms", g_TickRateSettings.iLightSync);
// Show the server header
CLogger::LogPrintfNoStamp(
"==================================================================\n"
"= Multi Theft Auto: San Andreas v%s\n"
"==================================================================\n"
"= Server name : %s\n"
"= Server IP address: %s\n"
"= Server port : %u\n"
"= \n"
"= Log file : %s\n"
"= Maximum players : %u\n"
"= HTTP port : %u\n"
"= Voice Chat : %s\n"
"= Bandwidth saving : %s\n"
"==================================================================\n",
MTA_DM_BUILDTAG_SHORT
#ifdef ANY_x64
" [64 bit]"
#elif defined(ANY_arm)
" [arm]"
#elif defined(ANY_arm64)
" [arm64]"
#endif
,
m_pMainConfig->GetServerName().c_str(), strServerIPList.empty() ? "auto" : strServerIPList.c_str(), usServerPort, pszLogFileName, uiMaxPlayers,
m_pMainConfig->IsHTTPEnabled() ? m_pMainConfig->GetHTTPPort() : 0, strVoice.c_str(), *strBandwidthSaving);
if (!bLogFile)
CLogger::ErrorPrintf("Unable to save logfile to '%s'\n", m_pMainConfig->GetLogFile().c_str());
// Show startup messages from net module
PrintLogOutputFromNetModule();
// Show some warnings if applicable
if (m_pMainConfig->IsFakeLagCommandEnabled())
{
CLogger::LogPrintf("WARNING: ase disabled due to fakelag command\n");
}
if (m_pMainConfig->GetAseInternetListenEnabled())
{
// Check if IP is one of the most common private IP addresses
in_addr serverIp;
serverIp.s_addr = inet_addr(strServerIP);
uchar a = ((uchar*)&serverIp.s_addr)[0];
uchar b = ((uchar*)&serverIp.s_addr)[1];
if (a == 10 || a == 127 || (a == 169 && b == 254) || (a == 192 && b == 168))
{
CLogger::LogPrintf("WARNING: Private IP '%s' with ase enabled! Use: <serverip>auto</serverip>\n", *strServerIP);
}
}
// Check accounts database and print message if there is a problem
if (!m_pAccountManager->IntegrityCheck())
return false;
// Setup resource-cache directory
{
SString strResourceCachePath("%s/resource-cache", g_pServerInterface->GetServerModPath());
SString strResourceCacheUnzippedPath("%s/unzipped", strResourceCachePath.c_str());
SString strResourceCacheHttpClientFilesPath("%s/http-client-files", strResourceCachePath.c_str());
SString strResourceCacheHttpClientFilesNoClientCachePath("%s/http-client-files-no-client-cache", strResourceCachePath.c_str());
// Make sure the resource-cache directories exists
MakeSureDirExists((strResourceCacheUnzippedPath + "/").c_str());
MakeSureDirExists((strResourceCacheHttpClientFilesPath + "/").c_str());
MakeSureDirExists((strResourceCacheHttpClientFilesNoClientCachePath + "/").c_str());
// Rename old dirs to show that they are no longer used
FileRename(PathJoin(g_pServerInterface->GetServerModPath(), "resourcecache"), strResourceCachePath + "/_old_resourcecache.delete-me");
FileRename(strResourceCachePath + "/http-client-files-protected", strResourceCachePath + "/_old_http-client-files-protected.delete-me");
// Create cache readme
SString strReadmeFilename("%s/DO_NOT_MODIFY_Readme.txt", strResourceCachePath.c_str());
FILE* fh = File::Fopen(strReadmeFilename, "w");
if (fh)
{
fprintf(fh, "---------------------------------------------------------------------------\n");
fprintf(fh, "The content of this directory is automatically generated by the server.\n\n");
fprintf(fh, "Do not modify or delete anything in here while the server is running.\n\n");
fprintf(fh, "When the server is not running, you can do what you want, including clearing\n");
fprintf(fh, "out all the cached files by deleting the resource-cache directory.\n");
fprintf(fh, "(It will get recreated when the server is next started)\n");
fprintf(fh, "---------------------------------------------------------------------------\n\n");
fprintf(fh, "The 'http-client-files' directory always contains the correct client files\n");
fprintf(fh, "for hosting on a web server.\n");
fprintf(fh, "* If the web server is on the same machine, you can simply link the appropriate\n");
fprintf(fh, " web server directory to 'http-client-files'.\n");
fprintf(fh, "* If the web server is on a separate machine, ensure it has access to\n");
fprintf(fh, " 'http-client-files' via a network path, or maintain a remote copy using\n");
fprintf(fh, " synchronization software.\n");
fprintf(fh, "---------------------------------------------------------------------------\n\n");
fclose(fh);
}
}
// Load the ACL's
if (!m_pACLManager->Load())
return false;
m_pRemoteCalls = new CRemoteCalls();
m_pRegistry = m_pRegistryManager->OpenRegistry("");
m_pResourceManager = new CResourceManager;
m_pSettings = new CSettings(m_pResourceManager);
if (!m_pResourceManager->Refresh())
return false; // Load cancelled
m_pUnoccupiedVehicleSync = new CUnoccupiedVehicleSync(m_pPlayerManager, m_pVehicleManager);
m_pPedSync = new CPedSync(m_pPlayerManager, m_pPedManager);
#ifdef WITH_OBJECT_SYNC
m_pObjectSync = new CObjectSync(m_pPlayerManager, m_pObjectManager);
#endif
// Must be created before all clients
m_pConsoleClient = new CConsoleClient(m_pConsole);
m_pZoneNames = new CZoneNames;
CStaticFunctionDefinitions(this);
CLuaDefs::Initialize(this);
m_pPlayerManager->SetScriptDebugging(m_pScriptDebugging);
// Set our console control handler
#ifdef WIN32
SetConsoleCtrlHandler(ConsoleEventHandler, TRUE);
// Hide the close box
// DeleteMenu ( GetSystemMenu ( GetConsoleWindow(), FALSE ), SC_CLOSE, MF_BYCOMMAND );
#else
signal(SIGTERM, &sighandler);
signal(SIGINT, &sighandler);
signal(SIGPIPE, SIG_IGN);
#endif
// Add our builtin events
AddBuiltInEvents();
// Load the vehicle colors before the main config
strBuffer = g_pServerInterface->GetModManager()->GetAbsolutePath("vehiclecolors.conf");
if (!m_pVehicleManager->GetColorManager()->Load(strBuffer))
{
// Try to generate a new one and load it again
if (m_pVehicleManager->GetColorManager()->Generate(strBuffer))
{
if (!m_pVehicleManager->GetColorManager()->Load(strBuffer))
{
CLogger::ErrorPrintf("%s", "Loading 'vehiclecolors.conf' failed\n ");
}
}
else
{
CLogger::ErrorPrintf("%s", "Generating a new 'vehiclecolors.conf' failed\n ");
}
}
// Load the registry
strBuffer = g_pServerInterface->GetModManager()->GetAbsolutePath("registry.db");
m_pRegistry->Load(strBuffer);
// Check accounts database and print a message if there is a problem
m_pRegistry->IntegrityCheck();
// Load the accounts
m_pAccountManager->Load();
// Register our packethandler
g_pNetServer->RegisterPacketHandler(CGame::StaticProcessPacket);
// Try to start the network
if (!g_pNetServer->StartNetwork(strServerIPList, usServerPort, uiMaxPlayers, m_pMainConfig->GetServerName().c_str()))
{
CLogger::ErrorPrintf("Could not bind the server on interface '%s' and port '%u'!\n", strServerIPList.c_str(), usServerPort);
return false;
}
// Load the banlist
m_pBanManager->LoadBanList();
// If the server is passworded
if (m_pMainConfig->HasPassword())
{
// Check it for validity
const char* szPassword = m_pMainConfig->GetPassword().c_str();
if (m_pMainConfig->IsValidPassword(szPassword))
{
// Store the server password
CLogger::LogPrintf("Server password set to '%s'\n", szPassword);
}
else
{
CLogger::LogPrint("Invalid password in config, no password is used\n");
}
}
// Init ASE
m_pASE = new ASE(m_pMainConfig, m_pPlayerManager, static_cast<int>(usServerPort), strServerIPList);
if (m_pMainConfig->GetSerialVerificationEnabled())
m_pASE->SetRuleValue("SerialVerification", "yes");
// Set the Rules loaded from config
for (const auto& [key, value] : m_pMainConfig->GetRulesForASE())
m_pASE->SetRuleValue(key, value);
ApplyAseSetting();
m_pMasterServerAnnouncer = new CMasterServerAnnouncer();
m_pMasterServerAnnouncer->Pulse();
// Now load the rest of the config
if (!m_pMainConfig->LoadExtended())
return false; // Fail or cancelled