Repository navigation
Expand file tree
/
Copy pathplugin_eac.cpp
More file actions
2997 lines (2490 loc) · 96.7 KB
/
Copy pathplugin_eac.cpp
File metadata and controls
2997 lines (2490 loc) · 96.7 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
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 "plugin_eac.h"
#include <unordered_map>
#include <unordered_set>
#include "EOS/Include/eos_metrics.h"
#include "EOS/Include/eos_p2p_types.h"
// ------------------------------------------------------------
// Global definitions (declared extern in plugin_eac.h)
// ------------------------------------------------------------
std::atomic<LoggingFunc> g_fnLoggingFunc{ nullptr };
std::atomic<LoggingFunc> g_fnLobbyChatOutput{ nullptr };
EOS_HPlatform g_EOSPlatformHandle = nullptr;
std::recursive_mutex g_StateMutex;
// Last reported EOS network connection type per middleware user ID, used by
// IsConnectionRelayed(). Written from EOS worker threads in
// ReportConnectionState(), read on the game thread, so it carries its own lock.
std::unordered_map<std::string, EOS_ENetworkConnectionType> g_ConnectionType;
std::mutex g_ConnectionTypeMutex;
EOS_ProductUserId g_EOSUserID = nullptr;
uint32_t g_goUserID = 0;
ACIntegrityViolationCallbackFunc g_fnAnticheatIntegrityViolationOccurredCallback = nullptr;
ACPlayerActionRequiredCallbackFunc g_fnAnticheatActionCallback = nullptr;
SendMessageViaTransportFunc g_fnSendMessageViaTransport = nullptr;
ConnectionStateChangedCallbackFunc g_fnConnectionStateChanged = nullptr;
bool g_bEventsHooked = false;
// Global notification IDs for callback cleanup
EOS_NotificationId g_NotifyClientIntegrityViolatedId = 0;
EOS_NotificationId g_NotifyMessageToPeerId = 0;
EOS_NotificationId g_NotifyPeerAuthStatusChangedId = 0;
EOS_NotificationId g_NotifyPeerActionRequiredId = 0;
// The P2P connection notifications are scoped to the login, not to a session:
// they stay registered from login until Shutdown() so the plugin is never deaf
// to an incoming connection request while the player is between lobbies.
static bool g_bP2PEventsHooked = false;
typedef void (*LoginCallback)(bool bSuccess);
LoginCallback g_LoginCallback = nullptr;
// Maps a middleware (EOS ProductUserId) string to the game's user ID.
// Read from EOS worker threads inside the P2P notification handlers and written
// by RegisterPlayer()/DeregisterPlayer(), so it carries its own lock. If both
// locks are needed, g_StateMutex must always be acquired first.
std::unordered_map<std::string, uint32_t> g_UserMap;
static std::mutex g_UserMapMutex;
// Middleware user IDs whose incoming connection request arrived before the game
// had registered them. EOS never re-delivers a connection request, so remember
// it here and accept it as soon as RegisterPlayer() vouches for the peer.
// Guarded by g_UserMapMutex.
static std::unordered_set<std::string> g_PendingConnectionRequests;
// Round-trip latency per middleware user ID, in milliseconds. Populated by the
// ping/pong exchange driven from Tick(); read by GetConnectionLatencyForUser()
// on the game thread.
static std::unordered_map<std::string, uint32_t> g_LatencyMs;
static std::mutex g_LatencyMutex;
// ------------------------------------------------------------
// EOS deployment credentials
//
// These MUST be supplied by the builder, e.g.
// cmake -DEAC_EOS_PRODUCT_ID=... (see README)
// or by defining them on the compiler command line. The "TODO" fallbacks exist
// only so the file compiles standalone; Initialize() refuses to run with them.
// ------------------------------------------------------------
#ifndef EAC_EOS_PRODUCT_ID
#define EAC_EOS_PRODUCT_ID "TODO"
#endif
#ifndef EAC_EOS_SANDBOX_ID
#define EAC_EOS_SANDBOX_ID "TODO"
#endif
#ifndef EAC_EOS_DEPLOYMENT_ID
#define EAC_EOS_DEPLOYMENT_ID "TODO"
#endif
#ifndef EAC_EOS_CLIENT_ID
#define EAC_EOS_CLIENT_ID "TODO"
#endif
#ifndef EAC_EOS_CLIENT_SECRET
#define EAC_EOS_CLIENT_SECRET "TODO"
#endif
// Return codes from Initialize()
enum EInitializeResult
{
EInitializeResult_Success = 0,
EInitializeResult_BadEnvironment = 1,
EInitializeResult_ContainerFailed = 2,
EInitializeResult_SDKInitFailed = 3,
EInitializeResult_PlatformCreateFailed = 4,
EInitializeResult_MissingCredentials = 5
};
// Forward declaration so DllMain can call Shutdown() defined later in this file.
PLUGIN_API void Shutdown();
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID /*lpReserved*/)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
::DisableThreadLibraryCalls(hModule);
break;
}
case DLL_PROCESS_DETACH:
{
// NOTE: Do NOT tear down the EOS SDK here. EOS_Platform_Release() and
// EOS_Shutdown() join worker threads, unload dependent modules and
// re-enter user code - all of which deadlock or fault when performed
// under the Windows loader lock. Acquiring g_StateMutex here is unsafe
// for the same reason.
//
// The host application is responsible for calling the exported
// Shutdown() before unloading this module.
break;
}
}
return TRUE;
}
void PluginLog(const char* fmt, ...)
{
if (fmt == nullptr)
{
return;
}
// This function is called from EOS SDK worker threads (via the EOS logging
// callback) as well as from game threads. It deliberately takes no lock: the
// sink is read atomically and invoked without holding g_StateMutex, so a
// thread inside an EOS call cannot deadlock against an EOS logging thread.
LoggingFunc sink = g_fnLoggingFunc.load(std::memory_order_acquire);
if (sink == nullptr)
{
return;
}
char buffer[8192];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
buffer[sizeof(buffer) - 1] = 0;
va_end(args);
sink(buffer);
}
// Writes a line to the game's lobby chat window, if the host has installed a
// sink. Like PluginLog() this takes no lock so it is safe to call from EOS
// worker threads.
static void LobbyChatLog(const char* fmt, ...)
{
if (fmt == nullptr)
{
return;
}
LoggingFunc sink = g_fnLobbyChatOutput.load(std::memory_order_acquire);
if (sink == nullptr)
{
return;
}
char buffer[8192];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
buffer[sizeof(buffer) - 1] = 0;
va_end(args);
sink(buffer);
}
// Returns the anti-cheat client interface, or nullptr if the platform has not
// been initialised. EOS_Platform_GetAntiCheatClientInterface() dereferences its
// argument, so the platform handle must never be passed through as null.
// Must be called with g_StateMutex held.
static EOS_HAntiCheatClient GetAntiCheatHandle()
{
if (g_EOSPlatformHandle == nullptr)
{
return nullptr;
}
return EOS_Platform_GetAntiCheatClientInterface(g_EOSPlatformHandle);
}
// Returns the P2P interface, or nullptr if the platform has not been
// initialised (EOS_Platform_GetP2PInterface() dereferences its argument).
// Must be called with g_StateMutex held.
static EOS_HP2P GetP2PHandle()
{
if (g_EOSPlatformHandle == nullptr)
{
return nullptr;
}
return EOS_Platform_GetP2PInterface(g_EOSPlatformHandle);
}
// Returns the metrics interface, or nullptr if the platform has not been
// initialised. Must be called with g_StateMutex held.
static EOS_HMetrics GetMetricsHandle()
{
if (g_EOSPlatformHandle == nullptr)
{
return nullptr;
}
return EOS_Platform_GetMetricsInterface(g_EOSPlatformHandle);
}
// EOS_ProductUserId_ToString() requires a buffer of EOS_PRODUCTUSERID_MAX_LENGTH + 1
// bytes; anything smaller fails with EOS_LimitExceeded and leaves the buffer
// untouched, so the result must always be checked before reading it.
static bool ProductUserIdToString(EOS_ProductUserId userId, std::string& outString)
{
if (userId == nullptr)
{
return false;
}
char buffer[EOS_PRODUCTUSERID_MAX_LENGTH + 1] = {};
int32_t outLength = (int32_t)sizeof(buffer);
if (EOS_ProductUserId_ToString(userId, buffer, &outLength) != EOS_EResult::EOS_Success)
{
return false;
}
outString.assign(buffer);
return true;
}
// Thread-safe lookup of the game user ID associated with a middleware user ID.
static bool TryGetGoUserID(const std::string& middlewareUserID, uint32_t& outGoUserID)
{
std::lock_guard<std::mutex> lock(g_UserMapMutex);
auto it = g_UserMap.find(middlewareUserID);
if (it == g_UserMap.end())
{
return false;
}
outGoUserID = it->second;
return true;
}
// Reverse of TryGetGoUserID(): finds the middleware user ID the game knows as
// goUserID. Used by the anti-cheat transport, which is handed game user IDs by
// the EOS anti-cheat interface but has to address peers by product user ID.
static bool TryGetMiddlewareUserID(uint32_t goUserID, std::string& outMiddlewareUserID)
{
std::lock_guard<std::mutex> lock(g_UserMapMutex);
for (const auto& entry : g_UserMap)
{
if (entry.second == goUserID && !entry.first.empty())
{
outMiddlewareUserID = entry.first;
return true;
}
}
return false;
}
// Reports a peer's connection state change to the game. Shared by all four P2P
// notification handlers, which run on EOS worker threads: the user map needs its
// own lock and the host callbacks may be null.
static void ReportConnectionState(EOS_ProductUserId remoteUserId, const char* description, EConnectionState state, EOS_ENetworkConnectionType connectionType)
{
if (state == EConnectionState::CONNECTED_DIRECT)
{
std::lock_guard<std::mutex> lock(g_ConnectionTypeMutex);
char szBuffer[EOS_PRODUCTUSERID_MAX_LENGTH + 1] = { 0 };
int32_t outLen = sizeof(szBuffer);
EOS_ProductUserId_ToString(remoteUserId, szBuffer, &outLen);
g_ConnectionType[szBuffer] = connectionType;
if (connectionType == EOS_ENetworkConnectionType::EOS_NCT_NoConnection)
{
PluginLog("[EAC] Connection type is NoConnection, invalid state");
}
}
std::string middlewareUserID;
if (!ProductUserIdToString(remoteUserId, middlewareUserID))
{
PluginLog("[EAC] %s: could not resolve remote product user ID", description);
return;
}
uint32_t goUserID = 0;
if (!TryGetGoUserID(middlewareUserID, goUserID))
{
// Not a player we know about - ignore rather than reporting a bogus user
// ID of 0 to the game.
PluginLog("[EAC] %s: unknown peer %s, ignoring", description, middlewareUserID.c_str());
return;
}
// Every connection state transition is logged: without this the successful
// paths are completely silent, so a log can't distinguish "the peer never
// connected" from "it connected and we just didn't say so".
PluginLog("[EAC] %s: %s (%u) - state %u", description, middlewareUserID.c_str(), goUserID, (unsigned)state);
auto fn = g_fnLobbyChatOutput.load();
if (fn != nullptr)
{
std::string strMessage = std::format("{} {} [{}]", description, middlewareUserID, goUserID);
fn(strMessage.c_str());
}
ConnectionStateChangedCallbackFunc stateCallback = nullptr;
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
stateCallback = g_fnConnectionStateChanged;
}
if (stateCallback != nullptr)
{
stateCallback(middlewareUserID.c_str(), goUserID, state);
}
}
// ------------------------------------------------------------
// NAT type detection
// ------------------------------------------------------------
// Most recent NAT type reported by EOS. Written from an EOS worker thread in
// the query callback and read from game threads, so it is atomic.
static std::atomic<EOS_ENATType> g_LocalNATType{ EOS_ENATType::EOS_NAT_Unknown };
static const char* NATTypeToString(EOS_ENATType natType)
{
switch (natType)
{
case EOS_ENATType::EOS_NAT_Open:
return "Open - all peers can connect directly to you";
case EOS_ENATType::EOS_NAT_Moderate:
return "Moderate - you can connect directly to Open and Moderate peers";
case EOS_ENATType::EOS_NAT_Strict:
return "Strict - you can only connect directly to Open peers, other traffic is relayed";
case EOS_ENATType::EOS_NAT_Unknown:
default:
return "Unknown - EOS could not determine your NAT type";
}
}
// Asks EOS to determine how strict the local NAT is. The query is asynchronous;
// the answer is logged and echoed into lobby chat from the completion callback,
// which runs on an EOS worker thread during EOS_Platform_Tick().
static void QueryLocalNATType()
{
EOS_HP2P p2pHandle = nullptr;
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
p2pHandle = GetP2PHandle();
}
if (p2pHandle == nullptr)
{
PluginLog("[EAC] NAT: P2P interface unavailable, cannot query NAT type");
return;
}
// EOS caches the last known result, so report it immediately rather than
// leaving the player with nothing while the (slow) query runs.
EOS_P2P_GetNATTypeOptions getOptions = {};
getOptions.ApiVersion = EOS_P2P_GETNATTYPE_API_LATEST;
EOS_ENATType cachedNATType = EOS_ENATType::EOS_NAT_Unknown;
EOS_EResult getResult = EOS_P2P_GetNATType(p2pHandle, &getOptions, &cachedNATType);
if (getResult == EOS_EResult::EOS_Success && cachedNATType != EOS_ENATType::EOS_NAT_Unknown)
{
g_LocalNATType.store(cachedNATType, std::memory_order_release);
PluginLog("[EAC] NAT: cached NAT type is %s", NATTypeToString(cachedNATType));
LobbyChatLog("[NAT] Your NAT type: %s", NATTypeToString(cachedNATType));
}
EOS_P2P_QueryNATTypeOptions queryOptions = {};
queryOptions.ApiVersion = EOS_P2P_QUERYNATTYPE_API_LATEST;
PluginLog("[EAC] NAT: querying NAT type...");
EOS_P2P_QueryNATType(p2pHandle, &queryOptions, nullptr,
[](const EOS_P2P_OnQueryNATTypeCompleteInfo* Data)
{
if (Data == nullptr)
{
return;
}
if (Data->ResultCode != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] NAT: query failed: %s", EOS_EResult_ToString(Data->ResultCode));
LobbyChatLog("[NAT] Could not determine your NAT type (%s)", EOS_EResult_ToString(Data->ResultCode));
return;
}
const EOS_ENATType previousNATType = g_LocalNATType.exchange(Data->NATType, std::memory_order_acq_rel);
PluginLog("[EAC] NAT: local NAT type is %s", NATTypeToString(Data->NATType));
// Only spam lobby chat when this actually tells the player something
// new - QueryLocalNATType() already printed any cached value.
if (previousNATType != Data->NATType)
{
LobbyChatLog("[NAT] Your NAT type: %s", NATTypeToString(Data->NATType));
}
if (Data->NATType == EOS_ENATType::EOS_NAT_Strict)
{
LobbyChatLog("[NAT] A strict NAT can cause connection problems. Enabling UPnP or forwarding ports on your router will help.");
}
});
}
// ------------------------------------------------------------
// EOS metrics player sessions
//
// A metrics player session brackets the time the player spends in a match and
// is what populates the Played Sessions view in the EOS developer portal.
// ------------------------------------------------------------
// Optional display name reported to the metrics backend. The host can supply
// one via SetPlayerDisplayName(); otherwise the product user ID is used.
static std::string g_strMetricsDisplayName;
// Tracks whether a metrics session is open, so EndPlayerSession is only ever
// called for one that was actually started and BeginPlayerSession is never
// issued twice.
static bool g_bMetricsSessionActive = false;
void SetPlayerDisplayName(const char* displayName)
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
g_strMetricsDisplayName = (displayName != nullptr) ? displayName : "";
}
// Must be called with g_StateMutex held.
static void BeginMetricsPlayerSession()
{
if (g_bMetricsSessionActive)
{
return;
}
EOS_HMetrics metricsHandle = GetMetricsHandle();
if (metricsHandle == nullptr)
{
PluginLog("[EAC] Metrics: interface unavailable, cannot begin player session");
return;
}
std::string localUserID;
if (!ProductUserIdToString(g_EOSUserID, localUserID))
{
PluginLog("[EAC] Metrics: no local product user ID, cannot begin player session");
return;
}
// The metrics backend wants something human-readable; fall back to the
// product user ID so sessions are still attributable without a name.
const std::string& displayName = g_strMetricsDisplayName.empty() ? localUserID : g_strMetricsDisplayName;
EOS_Metrics_BeginPlayerSessionOptions opts = {};
opts.ApiVersion = EOS_METRICS_BEGINPLAYERSESSION_API_LATEST;
opts.AccountIdType = EOS_EMetricsAccountIdType::EOS_MAIT_External;
opts.AccountId.External = localUserID.c_str();
opts.DisplayName = displayName.c_str();
opts.ControllerType = EOS_EUserControllerType::EOS_UCT_MouseKeyboard;
// Peer to peer, so there is no game server address to report.
opts.ServerIp = nullptr;
opts.GameSessionId = nullptr;
EOS_EResult result = EOS_Metrics_BeginPlayerSession(metricsHandle, &opts);
if (result != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] Metrics: BeginPlayerSession failed: %s", EOS_EResult_ToString(result));
return;
}
g_bMetricsSessionActive = true;
PluginLog("[EAC] Metrics: began player session for %s", displayName.c_str());
}
// Must be called with g_StateMutex held.
static void EndMetricsPlayerSession()
{
if (!g_bMetricsSessionActive)
{
return;
}
// Cleared up front: a failed end must not leave the flag set, or the next
// BeginPlayerSession would be skipped and every later session lost.
g_bMetricsSessionActive = false;
EOS_HMetrics metricsHandle = GetMetricsHandle();
if (metricsHandle == nullptr)
{
PluginLog("[EAC] Metrics: interface unavailable, cannot end player session");
return;
}
std::string localUserID;
if (!ProductUserIdToString(g_EOSUserID, localUserID))
{
PluginLog("[EAC] Metrics: no local product user ID, cannot end player session");
return;
}
EOS_Metrics_EndPlayerSessionOptions opts = {};
opts.ApiVersion = EOS_METRICS_ENDPLAYERSESSION_API_LATEST;
opts.AccountIdType = EOS_EMetricsAccountIdType::EOS_MAIT_External;
opts.AccountId.External = localUserID.c_str();
EOS_EResult result = EOS_Metrics_EndPlayerSession(metricsHandle, &opts);
if (result != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] Metrics: EndPlayerSession failed: %s", EOS_EResult_ToString(result));
}
else
{
PluginLog("[EAC] Metrics: ended player session");
}
}
// Atomically detaches the pending login callback and invokes it without holding
// g_StateMutex, so the host can safely re-enter the plugin and a stale callback
// can never be fired twice.
static void FireLoginCallback(bool bSuccess)
{
LoginCallback localCallback = nullptr;
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
localCallback = g_LoginCallback;
g_LoginCallback = nullptr;
}
if (localCallback != nullptr)
{
localCallback(bSuccess);
}
}
void SetLoggingFunction(LoggingFunc cb)
{
g_fnLoggingFunc.store(cb, std::memory_order_release);
}
void SetLobbyChatOutputFunction(LoggingFunc cb)
{
g_fnLobbyChatOutput.store(cb, std::memory_order_release);
}
void SetACActionRequiredCallback(ACPlayerActionRequiredCallbackFunc cb)
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
g_fnAnticheatActionCallback = cb;
}
void SetACIntegrityViolationOccurredCallback(ACIntegrityViolationCallbackFunc cb)
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
g_fnAnticheatIntegrityViolationOccurredCallback = cb;
}
void SetSendMessageViaTransportCallback(SendMessageViaTransportFunc cb)
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
g_fnSendMessageViaTransport = cb;
}
void ACMessageArrivedViaTransport(uint32_t sourceUserID, void* data, uint32_t dataLen)
{
if (data == nullptr || dataLen == 0)
{
PluginLog("[AC][EAC][REMOTE] ERROR: Invalid message data (null or zero length)");
return;
}
// Exactly one transport carries anti-cheat traffic. When the plugin owns the
// connection it drains its own anti-cheat channel in Tick(), so anything
// arriving through the game is either a duplicate or a leftover from the
// other transport and must not be replayed into the anti-cheat interface.
if (DoesACPluginProvideSecureGameTransport())
{
PluginLog("[AC][EAC][REMOTE] Ignoring %u bytes from user %u delivered via the game transport - the plugin owns the anti-cheat transport",
dataLen, sourceUserID);
return;
}
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
EOS_HAntiCheatClient acHandle = GetAntiCheatHandle();
if (acHandle == nullptr)
{
PluginLog("[AC][EAC][REMOTE] ERROR: AC handle is null");
return;
}
EOS_AntiCheatClient_ReceiveMessageFromPeerOptions receiveOpts = {};
receiveOpts.ApiVersion = EOS_ANTICHEATCLIENT_RECEIVEMESSAGEFROMPEER_API_LATEST;
receiveOpts.PeerHandle = (void*)sourceUserID;
receiveOpts.Data = data;
receiveOpts.DataLengthBytes = dataLen;
EOS_EResult receiveRes = EOS_AntiCheatClient_ReceiveMessageFromPeer(acHandle, &receiveOpts);
if (receiveRes != EOS_EResult::EOS_Success)
{
PluginLog("[AC][EAC][REMOTE] MIDDLEWARE ERROR, EOS_AntiCheatClient_ReceiveMessageFromPeer: %s!", EOS_EResult_ToString(receiveRes));
}
else
{
PluginLog("[AC][EAC][REMOTE] AC RECEIVED MESSAGE FROM PEER: %u bytes (User %u)", dataLen, sourceUserID);
}
}
// ------------------------------------------------------------
// Ping / pong latency measurement
//
// Every PING_INTERVAL the plugin sends a timestamped ping to each registered
// peer on ENetworkChannels::Ping. Peers echo the payload back byte-for-byte on
// ENetworkChannels::Pong, so the original sender can derive a round-trip time
// against its own clock - neither side needs a synchronised clock. The game
// never sees these channels; it only reads the result via
// GetConnectionLatencyForUser().
// ------------------------------------------------------------
#pragma pack(push, 1)
struct PingPayload
{
uint32_t Magic;
uint64_t SentMicroseconds;
};
#pragma pack(pop)
// 'GOPG' - guards against a stray packet on the ping channels being treated as
// a timestamp.
static constexpr uint32_t PING_PAYLOAD_MAGIC = 0x474F5047u;
static constexpr std::chrono::milliseconds PING_INTERVAL{ 1000 };
// Anything above this is treated as a bogus sample rather than real latency.
static constexpr uint64_t PING_MAX_PLAUSIBLE_RTT_MICROSECONDS = 30ull * 1000ull * 1000ull;
static std::chrono::steady_clock::time_point g_LastPingSendTime{};
// Defined below the transport section; driven from Tick().
static void ProcessIncomingPings();
static void ProcessIncomingPongs();
static void SendPingsIfDue();
static void ProcessIncomingACMessages();
static uint64_t NowMicroseconds()
{
return (uint64_t)std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
void Tick()
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
if (g_EOSPlatformHandle != nullptr)
{
EOS_Platform_Tick(g_EOSPlatformHandle);
// Answer any pings we have been sent, then fold the replies to our own
// pings into the latency table, then send the next round.
ProcessIncomingPings();
ProcessIncomingPongs();
SendPingsIfDue();
// When the plugin owns the transport it also carries anti-cheat
// traffic, so drain that channel here rather than relying on the game.
if (DoesACPluginProvideSecureGameTransport())
{
ProcessIncomingACMessages();
}
}
}
bool IsLoggedIn()
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
return g_EOSUserID != nullptr;
}
bool GetMiddlewareAuthToken(char* buffer, size_t bufferSize)
{
// Validate caller-supplied buffer to prevent NULL dereference
if (buffer == nullptr || bufferSize == 0)
{
PluginLog("[EAC] GetMiddlewareAuthToken: Invalid buffer (null or zero size)");
return false;
}
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
if (g_EOSPlatformHandle == nullptr)
{
PluginLog("[EAC] MIDDLEWARE ERROR: Platform not initialized!");
return false;
}
if (g_EOSUserID == nullptr)
{
PluginLog("[EAC] MIDDLEWARE ERROR: Not logged in!");
return false;
}
EOS_HConnect ConnectHandle = EOS_Platform_GetConnectInterface(g_EOSPlatformHandle);
if (ConnectHandle == nullptr)
{
PluginLog("[EAC] MIDDLEWARE ERROR: Connect handle is null!");
return false;
}
EOS_Connect_IdToken* epicToken = nullptr;
EOS_Connect_CopyIdTokenOptions opts = {};
opts.ApiVersion = EOS_CONNECT_COPYIDTOKEN_API_LATEST;
opts.LocalUserId = g_EOSUserID;
EOS_EResult res = EOS_Connect_CopyIdToken(ConnectHandle, &opts, &epicToken);
if (res != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] MIDDLEWARE ERROR: %s!", EOS_EResult_ToString(res));
return false;
}
if (epicToken == nullptr)
{
PluginLog("[EAC] MIDDLEWARE ERROR: Token pointer is null!");
return false;
}
// From here on the token is owned by us and must be released on every path.
bool bSuccess = false;
if (epicToken->JsonWebToken == nullptr)
{
PluginLog("[EAC] MIDDLEWARE ERROR: JsonWebToken is null!");
}
else
{
const char* msg = epicToken->JsonWebToken;
size_t len = strlen(msg) + 1;
// Validate token length doesn't exceed a reasonable size
if (len > 8192)
{
PluginLog("[EAC] MIDDLEWARE ERROR: Token too large!");
}
else if (bufferSize < len)
{
PluginLog("[EAC] MIDDLEWARE BAD SIZE!");
}
else
{
memcpy(buffer, msg, len);
bSuccess = true;
}
}
EOS_Connect_IdToken_Release(epicToken);
return bSuccess;
}
EOS_NotificationId g_ConnectionRequestNotificationId = EOS_INVALID_NOTIFICATIONID;
EOS_NotificationId g_ConnectionEstablishedNotificationId = EOS_INVALID_NOTIFICATIONID;
EOS_NotificationId g_ConnectionInterruptedNotificationId = EOS_INVALID_NOTIFICATIONID;
EOS_NotificationId g_ConnectionClosedNotificationId = EOS_INVALID_NOTIFICATIONID;
EOS_P2P_SocketId g_SocketId = {};
// Registers the P2P connection notifications, which is what binds us to the
// socket. Self-guarding and safe to call repeatedly; defined further down.
static void HookupP2PNotifications();
// Removes every P2P notification we registered. Safe to call with a null handle
// or with nothing registered. Must be called with g_StateMutex held, and always
// before the platform that owns the notifications is released.
static void RemoveP2PNotifications(EOS_HP2P p2pHandle)
{
if (p2pHandle != nullptr)
{
if (g_ConnectionRequestNotificationId != EOS_INVALID_NOTIFICATIONID)
{
EOS_P2P_RemoveNotifyPeerConnectionRequest(p2pHandle, g_ConnectionRequestNotificationId);
}
if (g_ConnectionEstablishedNotificationId != EOS_INVALID_NOTIFICATIONID)
{
EOS_P2P_RemoveNotifyPeerConnectionEstablished(p2pHandle, g_ConnectionEstablishedNotificationId);
}
if (g_ConnectionInterruptedNotificationId != EOS_INVALID_NOTIFICATIONID)
{
EOS_P2P_RemoveNotifyPeerConnectionInterrupted(p2pHandle, g_ConnectionInterruptedNotificationId);
}
if (g_ConnectionClosedNotificationId != EOS_INVALID_NOTIFICATIONID)
{
EOS_P2P_RemoveNotifyPeerConnectionClosed(p2pHandle, g_ConnectionClosedNotificationId);
}
}
// Always reset the IDs: they belong to the platform that is going away and
// must never be reused against a future one.
g_bP2PEventsHooked = false;
g_ConnectionRequestNotificationId = EOS_INVALID_NOTIFICATIONID;
g_ConnectionEstablishedNotificationId = EOS_INVALID_NOTIFICATIONID;
g_ConnectionInterruptedNotificationId = EOS_INVALID_NOTIFICATIONID;
g_ConnectionClosedNotificationId = EOS_INVALID_NOTIFICATIONID;
}
int Initialize(ConnectionStateChangedCallbackFunc connectionStateChangedCB)
{
std::lock_guard<std::recursive_mutex> lock(g_StateMutex);
g_SocketId.ApiVersion = EOS_P2P_SOCKETID_API_LATEST;
strncpy_s(g_SocketId.SocketName, sizeof(g_SocketId.SocketName), "GO_SOCKET", _TRUNCATE);
// The game hands this in on every Initialize() call, keep the latest one even
// if we early out below so a re-init can't leave a stale pointer behind.
g_fnConnectionStateChanged = connectionStateChangedCB;
// Check if already initialized
if (g_EOSPlatformHandle != nullptr)
{
PluginLog("[EAC] Already initialized - skipping re-initialization");
return EInitializeResult_Success;
}
// NOTE: only wipe the player map on a genuine (re-)initialisation. Doing this
// above the early-out would clear every registered player if the game called
// Initialize() again mid-session.
{
std::lock_guard<std::mutex> userMapLock(g_UserMapMutex);
g_UserMap.clear();
g_PendingConnectionRequests.clear();
}
{
std::lock_guard<std::mutex> latencyLock(g_LatencyMutex);
g_LatencyMs.clear();
}
// Refuse to run with placeholder credentials: EOS_Platform_Create() would
// return a null handle and every subsequent call would fail obscurely.
{
const char* credentials[] =
{
EAC_EOS_PRODUCT_ID,
EAC_EOS_SANDBOX_ID,
EAC_EOS_DEPLOYMENT_ID,
EAC_EOS_CLIENT_ID,
EAC_EOS_CLIENT_SECRET
};
for (const char* credential : credentials)
{
if (credential == nullptr || credential[0] == '\0' || strcmp(credential, "TODO") == 0)
{
PluginLog("[EAC] FATAL ERROR: EOS deployment credentials have not been configured.");
PluginLog("[EAC] FATAL ERROR: Define EAC_EOS_PRODUCT_ID / EAC_EOS_SANDBOX_ID / EAC_EOS_DEPLOYMENT_ID / EAC_EOS_CLIENT_ID / EAC_EOS_CLIENT_SECRET at build time.");
return EInitializeResult_MissingCredentials;
}
}
}
// Init EOS SDK
EOS_InitializeOptions SDKOptions = {};
SDKOptions.ApiVersion = EOS_INITIALIZE_API_LATEST;
SDKOptions.AllocateMemoryFunction = nullptr;
SDKOptions.ReallocateMemoryFunction = nullptr;
SDKOptions.ReleaseMemoryFunction = nullptr;
static char szBuffer[MAX_PATH] = { 0 };
strcpy_s(szBuffer, sizeof(szBuffer), "GOClient");
SDKOptions.ProductName = szBuffer;
SDKOptions.ProductVersion = "1.0";
SDKOptions.Reserved = nullptr;
SDKOptions.SystemInitializeOptions = nullptr;
SDKOptions.OverrideThreadAffinity = nullptr;
EOS_EResult InitResult = EOS_Initialize(&SDKOptions);
if (InitResult == EOS_EResult::EOS_Success)
{
// LOGGING
EOS_EResult SetLogCallbackResult = EOS_Logging_SetCallback([](const EOS_LogMessage* Message)
{
if (Message == nullptr)
{
return;
}
const char* category = Message->Category ? Message->Category : "UNKNOWN";
const char* msg = Message->Message ? Message->Message : "(null)";
PluginLog("[EOS - %s] %s", category, msg);
});
if (SetLogCallbackResult != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] Set Logging Callback Failed!");
}
else
{
PluginLog("[EAC] Logging Callback Set");
#if _DEBUG
const EOS_ELogLevel logLevel = EOS_ELogLevel::EOS_LOG_Verbose;
#else
// Shipping builds only surface errors - VeryVerbose floods the game
// log and costs measurable frame time.
const EOS_ELogLevel logLevel = EOS_ELogLevel::EOS_LOG_Error;
#endif
EOS_EResult SetLogLevelResult = EOS_Logging_SetLogLevel(EOS_ELogCategory::EOS_LC_ALL_CATEGORIES, logLevel);
if (SetLogLevelResult != EOS_EResult::EOS_Success)
{
PluginLog("[EAC] Set Logging Level Failed!");
}
}
std::filesystem::path tempPath = std::filesystem::current_path();
tempPath.append("cache");
std::string strCachePath = tempPath.string();
// PLATFORM OPTIONS
EOS_Platform_Options PlatformOptions = {};
PlatformOptions.ApiVersion = EOS_PLATFORM_OPTIONS_API_LATEST;
PlatformOptions.bIsServer = EOS_FALSE;
PlatformOptions.OverrideCountryCode = nullptr;
PlatformOptions.OverrideLocaleCode = nullptr;
PlatformOptions.Flags = EOS_PF_WINDOWS_ENABLE_OVERLAY_D3D9 | EOS_PF_WINDOWS_ENABLE_OVERLAY_D3D10;
PlatformOptions.CacheDirectory = strCachePath.c_str();
PlatformOptions.ProductId = EAC_EOS_PRODUCT_ID;
PlatformOptions.SandboxId = EAC_EOS_SANDBOX_ID;
// Only used by Player Data Storage / Title Storage, neither of which this
// plugin touches. eos_types.h requires it to be null when unused, or
// exactly EOS_PLATFORM_OPTIONS_ENCRYPTIONKEY_LENGTH (64) hex characters -
// a shorter placeholder is rejected rather than ignored.
PlatformOptions.EncryptionKey = nullptr;
PlatformOptions.DeploymentId = EAC_EOS_DEPLOYMENT_ID;
PlatformOptions.ClientCredentials.ClientId = EAC_EOS_CLIENT_ID;
PlatformOptions.ClientCredentials.ClientSecret = EAC_EOS_CLIENT_SECRET;
// Seconds, not milliseconds. Static so the pointer stays valid for the
// lifetime of the platform regardless of when the SDK reads it.
static double s_taskNetworkTimeoutSeconds = 5.0;
PlatformOptions.TaskNetworkTimeoutSeconds = &s_taskNetworkTimeoutSeconds;
EOS_Platform_RTCOptions RtcOptions = {};
RtcOptions.ApiVersion = EOS_PLATFORM_RTCOPTIONS_API_LATEST;
#ifdef _WIN32
// Get absolute path for xaudio2_9redist.dll file
char CurDir[MAX_PATH + 1] = {};
::GetCurrentDirectoryA(MAX_PATH, CurDir);
// get exe path
char buffer[MAX_PATH] = {};
GetModuleFileNameA(NULL, buffer, MAX_PATH - 1);
buffer[MAX_PATH - 1] = '\0'; // Ensure null termination
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
if (pos == std::string::npos)
{
PluginLog("FATAL ERROR: Failed to parse executable path");
EOS_Shutdown();
return EInitializeResult_BadEnvironment;
}
std::string ExePath = std::string(buffer).substr(0, pos);