-
Notifications
You must be signed in to change notification settings - Fork 2k
/
GameServer.cpp
1368 lines (1072 loc) · 36.7 KB
/
GameServer.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
#include "StdInc.h"
#include <ServerInstanceBase.h>
#include <GameServer.h>
#include <ResourceManager.h>
#include <ResourceEventComponent.h>
#include "ServerEventComponent.h"
#include <NetBuffer.h>
#include <StructuredTrace.h>
#include <state/ServerGameStatePublic.h>
#include <PrintListener.h>
#include <msgpack.hpp>
#include <UvLoopManager.h>
#include <UvTcpServer.h> // for UvCallback
#include <MonoThreadAttachment.h>
#include <HttpClient.h>
#include <TcpListenManager.h>
#include <ServerLicensingComponent.h>
#include <json.hpp>
#include <nng/protocol/reqrep0/req.h>
#include <nng/protocol/reqrep0/rep.h>
#include <KeyedRateLimiter.h>
#include <prometheus/histogram.h>
#include <ServerPerfComponent.h>
#ifdef _WIN32
#include <ResumeComponent.h>
#endif
#include <InfoHttpHandler.h>
#include "ClientDropReasons.h"
constexpr const char kDefaultServerList[] = "https://servers-ingress-live.fivem.net/ingress";
static fx::GameServer* g_gameServer;
extern fwEvent<> OnEnetReceive;
namespace fx
{
DLL_EXPORT object_pool<GameServerPacket> m_packetPool;
GameServer::GameServer()
: m_residualTime(0), m_serverTime(msec().count()), m_nextHeartbeatTime(0), m_hasSettled(false)
{
g_gameServer = this;
// TODO: re-enable this when we actually figure out threading
//seCreateContext(&m_seContext);
m_seContext = seGetCurrentContext();
m_seContext->MakeCurrent();
m_seContext->AddAccessControlEntry(se::Principal{ "system.console" }, se::Object{ "command" }, se::AccessType::Allow);
m_seContext->AddAccessControlEntry(se::Principal{ "builtin.everyone" }, se::Object{ "command.help" }, se::AccessType::Allow);
}
GameServer::~GameServer()
{
// TODO: fix if ever multi-instancing
m_thread.detach();
}
void GameServer::AttachToObject(ServerInstanceBase* instance)
{
m_instance = instance;
m_gamename = std::make_shared<ConVar<GameName>>("gamename", ConVar_ServerInfo, GameName::GTA5);
m_lastGameName = m_gamename->GetHelper()->GetValue();
#ifdef _WIN32
OnAbnormalTermination.Connect([this](void* reason)
{
auto realReason = fmt::sprintf("Server shutting down: %s", (const char*)reason);
m_clientRegistry->ForAllClients([this, realReason](const fx::ClientSharedPtr& client)
{
if (client->GetPeer())
{
auto oob = fmt::sprintf("error %s", realReason);
m_net->SendOutOfBand(client->GetAddress(), oob);
}
});
});
#endif
m_net = fx::CreateGSNet(this);
if (m_interceptor)
{
m_net->AddRawInterceptor(m_interceptor);
}
OnAttached(instance);
m_rconPassword = instance->AddVariable<std::string>("rcon_password", ConVar_None, "");
m_hostname = instance->AddVariable<std::string>("sv_hostname", ConVar_ServerInfo, "default FXServer");
m_masters[0] = instance->AddVariable<std::string>("sv_master1", ConVar_None, kDefaultServerList);
m_masters[1] = instance->AddVariable<std::string>("sv_master2", ConVar_None, "");
m_masters[2] = instance->AddVariable<std::string>("sv_master3", ConVar_None, "");
m_listingIpOverride = instance->AddVariable<std::string>("sv_listingIpOverride", ConVar_None, "");
m_useAccurateSendsVar = instance->AddVariable<bool>("sv_useAccurateSends", ConVar_None, true);
// sv_forceIndirectListing will break listings if the proxy host can not be reached
m_forceIndirectListing = instance->AddVariable<bool>("sv_forceIndirectListing", ConVar_None, false);
// sv_listingHostOverride specifies a host to use as reverse proxy endpoint instead of the default
// reverse TCP server
m_listingHostOverride = instance->AddVariable<std::string>("sv_listingHostOverride", ConVar_None, "");
m_heartbeatCommand = instance->AddCommand("heartbeat", [=]()
{
ForceHeartbeat();
});
m_mainThreadCallbacks = std::make_unique<CallbackListNng>("inproc://main_client", 0);
instance->OnRequestQuit.Connect([this](const std::string& reason)
{
m_clientRegistry->ForAllClients([this, &reason](const fx::ClientSharedPtr& client)
{
DropClientWithReason(client, fx::serverDropResourceName, ClientDropReason::SERVER_SHUTDOWN, "Server shutting down: %s", reason);
});
});
instance->OnInitialConfiguration.Connect([=]()
{
if (!m_net->SupportsUvUdp())
{
m_thread = std::thread([=]()
{
SetThreadName(-1, "[Cfx] Server Thread");
m_mainThreadCallbacks->AttachToThread();
Run();
});
}
else
{
m_mainThreadLoop = Instance<net::UvLoopManager>::Get()->GetOrCreate("svMain");
static std::shared_ptr<uvw::SignalHandle> sigint = m_mainThreadLoop->Get()->resource<uvw::SignalHandle>();
sigint->start(SIGINT);
static std::shared_ptr<uvw::SignalHandle> sighup = m_mainThreadLoop->Get()->resource<uvw::SignalHandle>();
sighup->start(SIGHUP);
sigint->on<uvw::SignalEvent>([this](const uvw::SignalEvent& ev, uvw::SignalHandle& sig)
{
se::ScopedPrincipal principalScope(se::Principal{ "system.console" });
m_instance->GetComponent<console::Context>()->ExecuteSingleCommandDirect(ProgramArguments{ "quit", "SIGINT received" });
});
sighup->on<uvw::SignalEvent>([this](const uvw::SignalEvent& ev, uvw::SignalHandle& sig)
{
se::ScopedPrincipal principalScope(se::Principal{ "system.console" });
m_instance->GetComponent<console::Context>()->ExecuteSingleCommandDirect(ProgramArguments{ "quit", "SIGHUP received" });
});
auto asyncInitHandle = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();;
*asyncInitHandle = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(m_mainThreadLoop->GetLoop(), (*asyncInitHandle)->get(), UvPersistentCallback((*asyncInitHandle)->get(), [this, asyncInitHandle](uv_async_t*)
{
// private data for the net thread
struct MainPersistentData
{
UvHandleContainer<uv_timer_t> tickTimer;
std::shared_ptr<std::unique_ptr<UvHandleContainer<uv_async_t>>> callbackAsync;
std::chrono::milliseconds lastTime;
};
auto mainData = std::make_shared<MainPersistentData>();
mainData->lastTime = msec();
auto loop = m_mainThreadLoop->GetLoop();
// periodic timer for main ticks
auto frameTime = 1000 / 20;
auto mpd = mainData.get();
static auto& collector = prometheus::BuildHistogram()
.Name("tickTime")
.Help("Time spent on server ticks")
.Register(*m_instance->GetComponent<ServerPerfComponent>()->GetRegistry())
.Add({ {"name", "svMain"} }, prometheus::Histogram::BucketBoundaries{
0.001, 0.002, 0.004, 0.006, 0.008, 0.010, 0.015, 0.020, 0.030, 0.050, 0.070, 0.100, 0.150, 0.250
});
uv_timer_init(loop, &mainData->tickTimer);
uv_timer_start(&mainData->tickTimer, UvPersistentCallback(&mainData->tickTimer, [this, mpd](uv_timer_t*)
{
auto now = msec();
auto thisTime = now - mpd->lastTime;
mpd->lastTime = now;
if (thisTime > 150ms)
{
trace("server thread hitch warning: timer interval of %d milliseconds\n", thisTime.count());
StructuredTrace({ "type", "hitch" }, { "thread", "svMain" }, { "time", thisTime.count() });
}
ProcessServerFrame(thisTime.count());
auto atEnd = msec();
collector.Observe((atEnd - now).count() / 1000.0);
}), frameTime, frameTime);
// event handle for callback list evaluation
// unique_ptr wrapper is a workaround for libc++ bug (fixed in LLVM r340823)
mainData->callbackAsync = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();
*mainData->callbackAsync = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(loop, (*mainData->callbackAsync)->get(), UvPersistentCallback((*mainData->callbackAsync)->get(), [this](uv_async_t*)
{
m_mainThreadCallbacks->Run();
}));
// run remaining callbacks before we remove this callback list
if (m_mainThreadCallbacks)
{
m_mainThreadCallbacks->Run();
}
m_mainThreadCallbacks = std::make_unique<CallbackListUv>(mainData->callbackAsync);
m_mainThreadCallbacks->AttachToThread();
// store the pointer in the class for lifetime purposes
m_mainThreadData = std::move(mainData);
}));
uv_async_send((*asyncInitHandle)->get());
}
}, 100);
m_clientRegistry = instance->GetComponent<ClientRegistry>().GetRef();
std::thread([=]()
{
while (true)
{
for (auto& master : m_masters)
{
// if the master is set
std::string masterName = master->GetValue();
if (!masterName.empty() && masterName.find("https://") != 0 && masterName.find("http://") != 0)
{
// look up if not cached
auto address = net::PeerAddress::FromString(masterName, 30110, net::PeerAddress::LookupType::ResolveName);
if (address)
{
if (m_masterCache[masterName] != *address)
{
trace("Resolved %s to %s\n", masterName, address->ToString());
m_masterCache[masterName] = *address;
}
}
}
}
std::this_thread::sleep_for(60s);
}
}).detach();
if (m_net->SupportsUvUdp())
{
InitializeNetUv();
}
else
{
InitializeNetThread();
}
InitializeSyncUv();
}
void GameServer::InitializeNetUv()
{
m_netThreadLoop = Instance<net::UvLoopManager>::Get()->GetOrCreate("svNetwork");
auto asyncInitHandle = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();
*asyncInitHandle = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(m_netThreadLoop->GetLoop(), (*asyncInitHandle)->get(), UvPersistentCallback((*asyncInitHandle)->get(), [this, asyncInitHandle](uv_async_t*)
{
// private data for the net thread
struct NetPersistentData
{
UvHandleContainer<uv_timer_t> tickTimer;
UvHandleContainer<uv_timer_t> sendTimer;
std::shared_ptr<std::unique_ptr<UvHandleContainer<uv_async_t>>> callbackAsync;
std::chrono::milliseconds lastTime;
};
auto netData = std::make_shared<NetPersistentData>();
auto loop = m_netThreadLoop->GetLoop();
netData->lastTime = msec();
// periodic timer for network ticks
auto frameTime = 1000 / 100;
auto sendTime = 1000 / 40;
auto mpd = netData.get();
static auto& collector = prometheus::BuildHistogram()
.Name("tickTime")
.Help("Time spent on server ticks")
.Register(*m_instance->GetComponent<ServerPerfComponent>()->GetRegistry())
.Add({ {"name", "svNetwork"} }, prometheus::Histogram::BucketBoundaries{
0.001, 0.002, 0.004, 0.006, 0.008, 0.010, 0.015, 0.020, 0.030, 0.050, 0.070, 0.100, 0.150, 0.250
});
auto processSendList = [this]()
{
while (auto *packet = m_netSendList.pop_until_empty(&fx::GameServerPacket::queueKey))
{
m_net->SendPacket(packet->peer, packet->channel, packet->buffer, packet->type);
m_packetPool.destruct(packet);
}
};
auto tcb = UvPersistentCallback(&netData->tickTimer, [this, mpd, processSendList](uv_timer_t*)
{
auto now = msec();
auto thisTime = now - mpd->lastTime;
mpd->lastTime = now;
if (thisTime > 150ms)
{
trace("network thread hitch warning: timer interval of %d milliseconds\n", thisTime.count());
StructuredTrace({ "type", "hitch" }, { "thread", "svNetwork" }, { "time", thisTime.count() });
}
OnNetworkTick();
if (m_useAccurateSendsVar->GetValue())
{
// process send list in between
processSendList();
}
// process game push
m_net->Process();
auto atEnd = msec();
collector.Observe((atEnd - now).count() / 1000.0);
});
uv_timer_init(loop, &netData->tickTimer);
uv_timer_start(&netData->tickTimer, tcb, frameTime, frameTime);
uv_timer_init(loop, &netData->sendTimer);
uv_timer_start(&netData->sendTimer, UvPersistentCallback(&netData->sendTimer, [this, processSendList](uv_timer_t*)
{
if (!m_useAccurateSendsVar->GetValue())
{
processSendList();
}
}), sendTime, sendTime);
// event handle for callback list evaluation
// unique_ptr wrapper is a workaround for libc++ bug (fixed in LLVM r340823)
netData->callbackAsync = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();
*netData->callbackAsync = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(loop, (*netData->callbackAsync)->get(), UvPersistentCallback((*netData->callbackAsync)->get(), [this](uv_async_t*)
{
m_netThreadCallbacks->Run();
}));
m_netThreadCallbacks = std::make_unique<CallbackListUv>(netData->callbackAsync);
m_netThreadCallbacks->AttachToThread();
// process hosts on a command
// #TODO1SBIG: add bigmode check/convar?
/*OnEnetReceive.Connect([this]()
{
m_net->Process();
});*/
// store the pointer in the class for lifetime purposes
m_netThreadData = std::move(netData);
}));
uv_async_send((*asyncInitHandle)->get());
}
// #TODO: this is a weird copy of the same function above
void GameServer::InitializeSyncUv()
{
m_syncThreadLoop = Instance<net::UvLoopManager>::Get()->GetOrCreate("svSync");
// #TODO: make these actually send to loop properly using the async set *in* the loop wrapper?
auto asyncInitHandle = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();
*asyncInitHandle = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(m_syncThreadLoop->GetLoop(), (*asyncInitHandle)->get(), UvPersistentCallback((*asyncInitHandle)->get(), [this, asyncInitHandle](uv_async_t*)
{
// private data for the net thread
struct NetPersistentData
{
UvHandleContainer<uv_timer_t> tickTimer;
std::shared_ptr<std::unique_ptr<UvHandleContainer<uv_async_t>>> callbackAsync;
std::chrono::milliseconds lastTime;
};
auto netData = std::make_shared<NetPersistentData>();
auto loop = m_syncThreadLoop->GetLoop();
netData->lastTime = msec();
// periodic timer for sync ticks
auto frameTime = 1000 / 120;
auto mpd = netData.get();
static auto& collector = prometheus::BuildHistogram()
.Name("tickTime")
.Help("Time spent on server ticks")
.Register(*m_instance->GetComponent<ServerPerfComponent>()->GetRegistry())
.Add({ {"name", "svSync"} }, prometheus::Histogram::BucketBoundaries{
0.001, 0.002, 0.004, 0.006, 0.008, 0.010, 0.015, 0.020, 0.030, 0.050, 0.070, 0.100, 0.150, 0.250
});
uv_timer_init(loop, &netData->tickTimer);
uv_timer_start(&netData->tickTimer, UvPersistentCallback(&netData->tickTimer, [this, mpd](uv_timer_t*)
{
auto now = msec();
auto thisTime = now - mpd->lastTime;
mpd->lastTime = now;
if (thisTime > 100ms)
{
trace("sync thread hitch warning: timer interval of %d milliseconds\n", thisTime.count());
StructuredTrace({ "type", "hitch" }, { "thread", "svSync" }, { "time", thisTime.count() });
}
OnSyncTick();
auto atEnd = msec();
collector.Observe((atEnd - now).count() / 1000.0);
}), frameTime + (frameTime / 2), frameTime);
// event handle for callback list evaluation
// unique_ptr wrapper is a workaround for libc++ bug (fixed in LLVM r340823)
netData->callbackAsync = std::make_shared<std::unique_ptr<UvHandleContainer<uv_async_t>>>();
*netData->callbackAsync = std::make_unique<UvHandleContainer<uv_async_t>>();
uv_async_init(loop, (*netData->callbackAsync)->get(), UvPersistentCallback((*netData->callbackAsync)->get(), [this](uv_async_t*)
{
m_syncThreadCallbacks->Run();
}));
m_syncThreadCallbacks = std::make_unique<CallbackListUv>(netData->callbackAsync);
m_syncThreadCallbacks->AttachToThread();
// store the pointer in the class for lifetime purposes
m_syncThreadData = std::move(netData);
}));
uv_async_send((*asyncInitHandle)->get());
}
void GameServer::InitializeNetThread()
{
m_netThreadCallbacks = std::make_unique<CallbackListNng>("inproc://netlib_client", 1);
std::thread([this]()
{
SetThreadName(-1, "[Cfx] Network Thread");
m_netThreadCallbacks->AttachToThread();
nng_socket netSocket;
nng_rep0_open(&netSocket);
nng_listener listener;
nng_listen(netSocket, "inproc://netlib_client", &listener, NNG_FLAG_NONBLOCK);
auto lastTime = msec().count();
uint64_t residualTime = 0;
auto frameTime = 1000 / 30;
while (true)
{
// service enet with our remaining waits
int rcvFd;
nng_getopt_int(netSocket, NNG_OPT_RECVFD, &rcvFd);
m_net->Select({ uintptr_t(rcvFd) }, frameTime);
{
m_seContext->MakeCurrent();
m_net->Process();
}
{
auto now = msec().count() - lastTime;
if (now >= 150)
{
trace("hitch warning: net frame time of %d milliseconds\n", now);
}
// clamp time to 200ms to reduce effects of excessive hitches
if (now > 200)
{
now = 200;
}
residualTime += now;
lastTime = msec().count();
// intervals
if (residualTime > frameTime)
{
OnNetworkTick();
residualTime = 0;
}
}
{
void* msgBuffer;
size_t msgLen;
while (nng_recv(netSocket, &msgBuffer, &msgLen, NNG_FLAG_NONBLOCK | NNG_FLAG_ALLOC) == 0)
{
nng_free(msgBuffer, msgLen);
int ok = 0;
nng_send(netSocket, &ok, 4, NNG_FLAG_NONBLOCK);
m_netThreadCallbacks->Run();
}
}
}
}).detach();
}
void GameServer::InternalRunMainThreadCbs(nng_socket socket)
{
void* msgBuffer;
size_t msgLen;
while (nng_recv(socket, &msgBuffer, &msgLen, NNG_FLAG_NONBLOCK | NNG_FLAG_ALLOC) == 0)
{
nng_free(msgBuffer, msgLen);
int ok = 0;
nng_send(socket, &ok, 4, NNG_FLAG_NONBLOCK);
m_mainThreadCallbacks->Run();
}
}
void GameServer::InternalGetPeer(int peerId, fx::NetPeerStackBuffer& stackBuffer)
{
m_net->GetPeer(peerId, stackBuffer);
}
void GameServer::InternalResetPeer(int peerId)
{
m_net->ResetPeer(peerId);
}
void GameServer::InternalSendPacket(fx::Client* client, int peer, int channel, const net::Buffer& buffer, NetPacketType type)
{
GameServerPacket* packet = m_packetPool.construct(peer, channel, buffer, type);
m_netSendList.push(&packet->queueKey);
}
void GameServer::Run()
{
if (m_runLoop)
{
m_runLoop();
}
}
void GameServer::AddRawInterceptor(const std::function<bool(const uint8_t *, size_t, const net::PeerAddress &)>& interceptor)
{
m_interceptor = interceptor;
}
void GameServer::CreateUdpHost(const net::PeerAddress& address)
{
m_net->CreateUdpHost(address);
}
std::string GameServer::GetVariable(const std::string& key)
{
auto consoleCtx = m_instance->GetComponent<console::Context>();
auto variable = consoleCtx->GetVariableManager()->FindEntryRaw(key);
if (!variable)
{
return "";
}
return variable->GetValue();
}
void GameServer::ProcessPacket(NetPeerBase* peer, const uint8_t* data, size_t size)
{
// create a netbuffer and read the message type
net::Buffer msg(data, size);
uint32_t msgType = msg.Read<uint32_t>();
// get the client
auto peerId = peer->GetId();
auto client = m_clientRegistry->GetClientByPeer(peerId);
// handle connection handshake message
if (msgType == 1)
{
if (!client)
{
std::vector<char> dataBuffer(msg.GetRemainingBytes());
msg.Read(dataBuffer.data(), dataBuffer.size());
auto postMap = ParsePOSTString(std::string_view(dataBuffer.data(), dataBuffer.size()));
auto guid = postMap["guid"];
auto token = postMap["token"];
client = m_clientRegistry->GetClientByGuid(guid);
if (client)
{
if (token != client->GetConnectionToken())
{
SendOutOfBand(peer->GetAddress(), "error Invalid connection token received.");
m_clientRegistry->RemoveClient(client);
return;
}
if (!client->GetData("passedValidation"))
{
SendOutOfBand(peer->GetAddress(), "error Invalid connection.");
m_clientRegistry->RemoveClient(client);
return;
}
client->Touch();
client->SetPeer(peerId, peer->GetAddress());
if (IsOneSync())
{
if (!client->HasSlotId())
{
SendOutOfBand(peer->GetAddress(), "error Not enough client slot IDs.");
m_clientRegistry->RemoveClient(client);
return;
}
}
bool wasNew = false;
auto oldNetID = client->GetNetId();
if (!client->HasConnected())
{
m_clientRegistry->HandleConnectingClient(client);
wasNew = true;
}
peer->OnSendConnectOK();
// send a connectOK
net::Buffer outMsg;
outMsg.Write(1);
auto host = m_clientRegistry->GetHost();
uint32_t bigModeSlot = (m_instance->GetComponent<fx::GameServer>()->GetGameName() == fx::GameName::GTA5) ? 128 : 16;
auto outStr = fmt::sprintf(
" %d %d %d %d %lld",
client->GetNetId(),
(host) ? host->GetNetId() : -1,
(host) ? host->GetNetBase() : -1,
(IsOneSync())
? ((fx::IsBigMode())
? bigModeSlot
: client->GetSlotId())
: -1,
(IsOneSync()) ? msec().count() : -1);
outMsg.Write(outStr.c_str(), outStr.size());
client->SendPacket(0, outMsg, NetPacketType_Reliable);
if (wasNew)
{
gscomms_execute_callback_on_main_thread([this, client, oldNetID]()
{
m_clientRegistry->HandleConnectedClient(client, oldNetID);
});
if (IsOneSync())
{
m_instance->GetComponent<fx::ServerGameStatePublic>()->SendObjectIds(client, fx::IsBigMode() ? 4 : 64);
}
ForceHeartbeatSoon();
}
}
}
return;
}
// if not type 1, and no client, bail out
if (!client)
{
return;
}
auto principalScope = client->EnterPrincipalScope();
if (m_packetHandler)
{
m_packetHandler(msgType, client, msg);
}
if (client->GetNetworkMetricsRecvCallback())
{
client->GetNetworkMetricsRecvCallback()(client.get(), msgType, msg);
}
client->Touch();
}
void GameServer::Broadcast(const net::Buffer& buffer)
{
m_clientRegistry->ForAllClients([&](const fx::ClientSharedPtr& client)
{
client->SendPacket(0, buffer, NetPacketType_Reliable);
});
}
void GameServer::DeferCall(int inMsec, const std::function<void()>& fn)
{
static std::atomic<int> cbIdx;
// find an empty slot first
for (auto& pair : m_deferCallbacks)
{
if (std::get<int>(pair.second) == 0)
{
pair.second = { m_serverTime + inMsec, fn };
return;
}
}
m_deferCallbacks.insert({ cbIdx.fetch_add(1), { m_serverTime + inMsec, fn } });
}
void GameServer::CallbackListBase::Add(const std::function<void()>& fn, bool force)
{
if (threadId == std::this_thread::get_id() && !force)
{
fn();
return;
}
// add to the queue
callbacks.enqueue(fn);
// signal the waiting thread
SignalThread();
}
void GameServer::CallbackListBase::Run()
{
// TODO: might need memory barriers for single-consumer too?
std::function<void()> fn;
while (callbacks.try_dequeue(fn))
{
fn();
}
}
void GameServer::CallbackListNng::SignalThread()
{
// submit to the owning thread
static thread_local nng_socket sockets[2];
static thread_local nng_dialer dialers[2];
int i = m_socketIdx;
if (!sockets[i].id)
{
nng_req0_open(&sockets[i]);
nng_dial(sockets[i], m_socketName.c_str(), &dialers[i], 0);
}
std::vector<int> idxList(1);
idxList[0] = 0xFEED;
nng_send(sockets[i], &idxList[0], idxList.size() * sizeof(int), NNG_FLAG_NONBLOCK);
}
void GameServer::CallbackListUv::SignalThread()
{
auto async = m_async.lock();
if (async)
{
uv_async_send((*async)->get());
}
}
void GameServer::ProcessServerFrame(int frameTime)
{
MonoEnsureThreadAttached();
m_seContext->MakeCurrent();
m_serverTime += frameTime;
m_hasSettled = true;
// check callbacks
for (auto& cb : m_deferCallbacks)
{
if (std::get<int>(cb.second) == 0)
{
continue;
}
if (m_serverTime >= std::get<int>(cb.second))
{
std::get<1>(cb.second)();
cb.second = {};
}
}
{
std::vector<fx::ClientSharedPtr> toRemove;
uint8_t syncStyle = (uint8_t)m_instance->GetComponent<fx::ServerGameStatePublic>()->GetSyncStyle();
m_clientRegistry->ForAllClients([&](fx::ClientSharedPtr client)
{
auto peer = client->GetPeer();
if (peer)
{
auto lm = client->GetData("lockdownMode");
auto lf = client->GetData("lastFrame");
auto ss = client->GetData("syncStyle");
bool lockdownMode = m_instance->GetComponent<fx::ServerGameStatePublic>()->GetEntityLockdownMode(client) == fx::EntityLockdownMode::Strict;
if (!lm || fx::AnyCast<bool>(lm) != lockdownMode ||
!ss || fx::AnyCast<uint8_t>(ss) != syncStyle ||
!lf ||
(m_serverTime - fx::AnyCast<uint64_t>(lf)) > 1000)
{
net::Buffer outMsg;
outMsg.Write(HashRageString("msgFrame"));
outMsg.Write<uint32_t>(0);
outMsg.Write<uint8_t>(lockdownMode);
outMsg.Write<uint8_t>(syncStyle);
client->SendPacket(0, outMsg, NetPacketType_Reliable);
client->SetData("lockdownMode", lockdownMode);
client->SetData("syncStyle", syncStyle);
client->SetData("lastFrame", m_serverTime);
}
}
// time out the client if needed
if (client->IsDead())
{
toRemove.push_back(client);
}
});
for (auto& client : toRemove)
{
auto lastSeen = (msec() - client->GetLastSeen());
// if this happened fairly early, try to find out why
if (lastSeen < 1500ms)
{
auto timeoutInfo = m_net->GatherTimeoutInfo(client->GetPeer());
if (!timeoutInfo.bigCommandList.empty())
{
std::stringstream commandListFormat;
for (const auto& bigCmd : timeoutInfo.bigCommandList)
{
std::string name = (bigCmd.eventName.empty()) ? fmt::sprintf("%08x", bigCmd.type) : bigCmd.eventName;
commandListFormat << fmt::sprintf("%s (%d B, %d msec ago)\n", name, bigCmd.size, bigCmd.timeAgo);
}
DropClientWithReason(client, fx::serverDropResourceName, ClientDropReason::CLIENT_CONNECTION_TIMED_OUT_WITH_PENDING_COMMANDS, "Server->client connection timed out. Pending commands: %d.\nCommand list:\n%s", timeoutInfo.pendingCommands, commandListFormat.str());
continue;
}
}
DropClientWithReason(client, fx::serverDropResourceName, ClientDropReason::CLIENT_CONNECTION_TIMED_OUT, "Server->client connection timed out. Last seen %d msec ago.", lastSeen.count());
}
}
// if we should heartbeat
if (msec() >= m_nextHeartbeatTime)
{
auto sendHttpHeartbeat = [this](std::string_view masterName, bool isPrivate)
{
auto var = m_instance->GetComponent<console::Context>()->GetVariableManager()->FindEntryRaw("sv_licenseKeyToken");
if (var && !var->GetValue().empty())
{
console::DPrintf("citizen-server-impl", "Sending heartbeat to %s\n", masterName);
nlohmann::json playersJson, infoJson, dynamicJson;
auto ihh = m_instance->GetComponent<InfoHttpHandlerComponent>();
ihh->GetJsonData(&infoJson, &dynamicJson, &playersJson);
auto json = nlohmann::json::object({
{ "port", m_instance->GetComponent<fx::TcpListenManager>()->GetPrimaryPort() },
{ "listingToken", m_instance->GetComponent<ServerLicensingComponent>()->GetListingToken() },
{ "ipOverride", m_listingIpOverride->GetValue() },
{ "forceIndirectListing", m_forceIndirectListing->GetValue() },
{ "private", isPrivate },
{ "fallbackData", nlohmann::json::object({
{ "players", playersJson },
{ "info", infoJson },
{ "dynamic", dynamicJson },
})}
});
if (!m_listingHostOverride->GetValue().empty())
{
json["hostOverride"] = m_listingHostOverride->GetValue();
}
HttpRequestOptions ro;
ro.ipv4 = true;
ro.headers = std::map<std::string, std::string>{
{ "Content-Type", "application/json; charset=utf-8" }
};
ro.addErrorBody = true;
static bool firstRun = true;
Instance<HttpClient>::Get()->DoPostRequest(std::string{ masterName }, json.dump(), ro, [](bool success, const char* d, size_t s)
{
if (!success)
{
console::DPrintf("citizen-server-impl", "error submitting to ingress: %s\n", std::string{ d, s });
return;
}
try
{
// don't return a query error for the first run (may be residual)