forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathNetworkMesh.cpp
More file actions
1333 lines (1102 loc) · 43.8 KB
/
NetworkMesh.cpp
File metadata and controls
1333 lines (1102 loc) · 43.8 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 "GameNetwork/GeneralsOnline/NetworkMesh.h"
#include "GameNetwork/GeneralsOnline/NGMP_include.h"
#include "GameNetwork/GeneralsOnline/NGMP_interfaces.h"
#include <ws2ipdef.h>
#include "GameNetwork/NetworkDefs.h"
#include "GameNetwork/NetworkInterface.h"
#include "GameLogic/GameLogic.h"
#include "../OnlineServices_RoomsInterface.h"
#include "../json.hpp"
#include "../HTTP/HTTPManager.h"
#include "../OnlineServices_Init.h"
#include "ValveNetworkingSockets/steam/isteamnetworkingutils.h"
#include "ValveNetworkingSockets/steam/steamnetworkingcustomsignaling.h"
bool g_bForceRelay = false;
UnsignedInt m_exeCRCOriginal = 0;
// Static flag to track if NetworkMesh is being destroyed to prevent callback re-entry
static std::atomic<bool> g_bNetworkMeshDestroying = false;
// Called when a connection undergoes a state transition
void OnSteamNetConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t* pInfo)
{
// Early exit if NetworkMesh is being destroyed to prevent use-after-free
if (g_bNetworkMeshDestroying.load())
{
return;
}
NetworkMesh* pMesh = NGMP_OnlineServicesManager::GetNetworkMesh();
if (pMesh == nullptr)
{
return;
}
// find player connection
int64_t connectionID = -1;
std::map<int64_t, PlayerConnection>& connections = pMesh->GetAllConnections();
for (auto& kvPair : connections)
{
if (kvPair.second.m_hSteamConnection == pInfo->m_hConn)
{
connectionID = kvPair.first;
break;
}
}
//if (pPlayerConnection != nullptr)
{
//NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Player Connection was null", pInfo->m_info.m_szConnectionDescription);
//return;
}
// What's the state of the connection?
switch (pInfo->m_info.m_eState)
{
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] %s, reason %d: %s\n",
pInfo->m_info.m_szConnectionDescription,
(pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_ClosedByPeer ? "closed by peer" : "problem detected locally"),
pInfo->m_info.m_eEndReason,
pInfo->m_info.m_szEndDebug
);
// Close our end
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing in callback");
SteamNetworkingSockets()->CloseConnection(pInfo->m_hConn, 0, nullptr, false);
if (connectionID != -1 && pInfo != nullptr)
{
PlayerConnection& plrConnection = connections[connectionID];
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(plrConnection.m_userID);
}
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing connection %lld", plrConnection.m_userID);
ServiceConfig& serviceConf = NGMP_OnlineServicesManager::GetInstance()->GetServiceConfig();
const int numSignallingAttempts = 3;
bool bShouldRetry = plrConnection.m_SignallingAttempts < numSignallingAttempts && serviceConf.retry_signalling;
bool bWasError = pInfo->m_info.m_eState == k_ESteamNetworkingConnectionState_ProblemDetectedLocally || pInfo->m_info.m_eEndReason != k_ESteamNetConnectionEnd_App_Generic;
plrConnection.SetDisconnected(bWasError, pMesh, bShouldRetry && bWasError);
// the highest slot player, should leave. In most cases, this is the most recently joined player, but this may not be 100% accurate due to backfills.
// TODO_NGMP: In the future, we should pick the most recently joined by timestamp
if (bWasError) // only if it wasn't a clean disconnect (e.g. lobby leave)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Determined we didn't connect due to an error, Retrying: %d (currently at %d/%d attempts)", bShouldRetry, plrConnection.m_SignallingAttempts, numSignallingAttempts);
// should we retry signaling?
if (bShouldRetry)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Retrying...");
std::shared_ptr<WebSocket> pWS = NGMP_OnlineServicesManager::GetWebSocket();
if (pWS)
{
NGMP_OnlineServices_AuthInterface* pAuthInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_AuthInterface>();
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr && pAuthInterface != nullptr)
{
int64_t myUserID = pAuthInterface->GetUserID();
// Behavior:
// disconnected slot userID is higher than ours, do nothing, they will signal
// disconnected slot userID is lower than ours, we signal
if ((myUserID > plrConnection.m_userID))
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Send signal start request...");
pWS->SendData_RequestSignalling(plrConnection.m_userID);
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Not sending signal start request, other player should");
}
}
}
else
{
// Should always have a websocket... so lets just fail
bShouldRetry = false;
}
}
if (!bShouldRetry)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Not retrying, handling disconnect as failure...");
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][DISCONNECT HANDLER] Performing local removal for user %lld from lobby due to failure to connect\n", plrConnection.m_userID);
if (pLobbyInterface->m_OnCannotConnectToLobbyCallback != nullptr)
{
pLobbyInterface->m_OnCannotConnectToLobbyCallback();
}
}
}
}
// In this example, we will bail the test whenever this happens.
// Was this a normal termination?
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING]DISCONNECTED OR PROBLEM DETECTED %d\n", pInfo->m_info.m_eEndReason);
}
else
{
// Why are we hearing about any another connection?
//assert(false);
}
break;
case k_ESteamNetworkingConnectionState_None:
// Notification that a connection was destroyed. (By us, presumably.)
// We don't need this, so ignore it.
break;
case k_ESteamNetworkingConnectionState_Connecting:
// Is this a connection we initiated, or one that we are receiving?
if (pMesh->GetListenSocketHandle() != k_HSteamListenSocket_Invalid && pInfo->m_info.m_hListenSocket == pMesh->GetListenSocketHandle())
{
// Somebody's knocking
// Note that we assume we will only ever receive a single connection
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Considering Accepting\n", pInfo->m_info.m_szConnectionDescription);
if (connectionID != -1)
{
PlayerConnection& plrConnection = connections[connectionID];
#if _DEBUG
if (connectionID != -1)
assert(plrConnection.m_hSteamConnection == k_HSteamNetConnection_Invalid); // not really a bug in this code, but a bug in the test
#endif
if (pInfo != nullptr)
{
plrConnection.UpdateState(EConnectionState::CONNECTING_DIRECT, pMesh);
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM CONNECTION] Updating connection from %u to %u on user %lld", plrConnection.m_hSteamConnection, pInfo->m_hConn, plrConnection.m_userID);
SteamNetworkingSockets()->SetConnectionName(pInfo->m_hConn, std::format("Steam Connection User{}", plrConnection.m_userID).c_str());
plrConnection.m_hSteamConnection = pInfo->m_hConn;
}
// check user is in the lobby, otherwise reject
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Rejecting - Lobby interface is null\n", pInfo->m_info.m_szConnectionDescription);
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing connection 2 %lld", plrConnection.m_userID);
SteamNetworkingSockets()->CloseConnection(pInfo->m_hConn, 1000, "Lobby interface is null (Rejected)", false);
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(plrConnection.m_userID);
}
return;
}
auto currentLobby = pLobbyInterface->GetCurrentLobby();
bool bPlayerIsInLobby = false;
for (const auto& member : currentLobby.members)
{
// TODO_NGMP: Use bytes or SteamID instead... string compare is nasty
if (std::to_string(member.user_id) == pInfo->m_info.m_identityRemote.GetGenericString())
{
bPlayerIsInLobby = true;
break;
}
}
if (bPlayerIsInLobby)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Accepting - Player is in lobby\n", pInfo->m_info.m_szConnectionDescription);
SteamNetworkingSockets()->AcceptConnection(pInfo->m_hConn);
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Rejecting - Player is not in lobby\n", pInfo->m_info.m_szConnectionDescription);
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing connection not in lobby %lld", plrConnection.m_userID);
SteamNetworkingSockets()->CloseConnection(pInfo->m_hConn, 1000, "Player is not in lobby (Rejected)", false);
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(plrConnection.m_userID);
}
}
}
}
else
{
// Note that we will get notification when our own connection that
// we initiate enters this state.
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] Entered connecting state\n", pInfo->m_info.m_szConnectionDescription);
if (connectionID != -1)
{
PlayerConnection& plrConnection = connections[connectionID];
#if _DEBUG
if (connectionID != -1)
assert(plrConnection.m_hSteamConnection == pInfo->m_hConn);
#endif
plrConnection.UpdateState(EConnectionState::CONNECTING_DIRECT, pMesh);
}
}
break;
case k_ESteamNetworkingConnectionState_FindingRoute:
// P2P connections will spend a brief time here where they swap addresses
// and try to find a route.
if (connectionID != -1 && pInfo != nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] finding route\n", pInfo->m_info.m_szConnectionDescription);
PlayerConnection& plrConnection = connections[connectionID];
plrConnection.UpdateState(EConnectionState::FINDING_ROUTE, pMesh);
}
break;
case k_ESteamNetworkingConnectionState_Connected:
// We got fully connected
#if _DEBUG
//assert(pInfo->m_hConn == pPlayerConnection->m_hSteamConnection); // We don't initiate or accept any other connections, so this should be out own connection
#endif
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING][%s] connected\n", pInfo->m_info.m_szConnectionDescription);
if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_Unauthenticated)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_Unauthenticated");
}
else if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_Unencrypted)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_Unencrypted");
}
else if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_LoopbackBuffers)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_LoopbackBuffers");
}
else if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_Fast)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_Fast");
}
else if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_Relayed)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_Relayed");
}
else if (pInfo->m_info.m_nFlags & k_nSteamNetworkConnectionInfoFlags_DualWifi)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[CONNECTION FLAGS]: has k_nSteamNetworkConnectionInfoFlags_DualWifi");
}
if (connectionID != -1)
{
PlayerConnection& plrConnection = connections[connectionID];
plrConnection.UpdateState(EConnectionState::CONNECTED_DIRECT, pMesh);
}
break;
default:
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM CALLBACK] Unhandled case");
break;
}
}
/// Implementation of ITrivialSignalingClient
class CSignalingClient : public ISignalingClient
{
// This is the thing we'll actually create to send signals for a particular
// connection.
struct ConnectionSignaling : ISteamNetworkingConnectionSignaling
{
CSignalingClient* const m_pOwner;
int64_t const m_targetUserID;
ConnectionSignaling(CSignalingClient* owner, int64_t target_user_id)
: m_pOwner(owner)
, m_targetUserID(target_user_id)
{
}
//
// Implements ISteamNetworkingConnectionSignaling
//
// This is called from SteamNetworkingSockets to send a signal. This could be called from any thread,
// so we need to be threadsafe, and avoid duoing slow stuff or calling back into SteamNetworkingSockets
virtual bool SendSignal(HSteamNetConnection hConn, const SteamNetConnectionInfo_t& info, const void* pMsg, int cbMsg) override
{
// Silence warnings
(void)info;
(void)hConn;
std::vector<uint8_t> vecPayload(cbMsg);
memcpy_s(vecPayload.data(), vecPayload.size(), pMsg, cbMsg);
m_pOwner->Send(m_targetUserID, vecPayload);
return true;
}
// Self destruct. This will be called by SteamNetworkingSockets when it's done with us.
virtual void Release() override
{
delete this;
}
};
struct QueuedSend
{
int64_t target_user_id;
std::vector<uint8_t> vecPayload;
};
ISteamNetworkingSockets* const m_pSteamNetworkingSockets;
std::deque<QueuedSend> m_queueSend;
void CloseSocket()
{
m_queueSend.clear();
}
public:
CSignalingClient(ISteamNetworkingSockets* pSteamNetworkingSockets)
: m_pSteamNetworkingSockets(pSteamNetworkingSockets)
{
// Save off our identity
SteamNetworkingIdentity identitySelf; identitySelf.Clear();
pSteamNetworkingSockets->GetIdentity(&identitySelf);
if (identitySelf.IsInvalid())
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "CSignalingClient: Local identity is invalid\n");
}
if (identitySelf.IsLocalHost())
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "CSignalingClient: Local identity is localhost\n");
}
}
// Send the signal.
void Send(int64_t target_user_id, std::vector<uint8_t>& vecPayload)
{
std::shared_ptr<WebSocket> pWS = NGMP_OnlineServicesManager::GetWebSocket();
if (pWS)
{
if (!pWS->AcquireLock())
{
return;
}
// If we're getting backed up, delete the oldest entries. Remember,
// we are only required to do best-effort delivery. And old signals are the
// most likely to be out of date (either old data, or the client has already
// timed them out and queued a retry).
while (m_queueSend.size() > 128)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "Signaling send queue is backed up. Discarding oldest signals\n");
m_queueSend.pop_front();
}
QueuedSend newEntry = QueuedSend();
newEntry.target_user_id = target_user_id;
newEntry.vecPayload = vecPayload;
m_queueSend.push_back(newEntry);
pWS->ReleaseLock();
}
}
ISteamNetworkingConnectionSignaling* CreateSignalingForConnection(
const SteamNetworkingIdentity& identityPeer,
SteamNetworkingErrMsg& errMsg
) override {
SteamNetworkingIdentityRender sIdentityPeer(identityPeer);
// FIXME - here we really ought to confirm that the string version of the
// identity does not have spaces, since our protocol doesn't permit it.
NetworkLog(ELogVerbosity::LOG_DEBUG, "Creating signaling session for peer '%s'\n", sIdentityPeer.c_str());
// Silence warnings
(void)errMsg;
int64_t user_id = std::stoll(identityPeer.GetGenericString());
return new ConnectionSignaling(this, user_id);
}
inline int HexDigitVal(char c)
{
if ('0' <= c && c <= '9')
return c - '0';
if ('a' <= c && c <= 'f')
return c - 'a' + 0xa;
if ('A' <= c && c <= 'F')
return c - 'A' + 0xa;
return -1;
}
virtual void Poll() override
{
std::shared_ptr<WebSocket> pWS = NGMP_OnlineServicesManager::GetWebSocket();
if (pWS)
{
if (!pWS->AcquireLock())
{
return;
}
// Drain the socket
// Flush send queue
while (!m_queueSend.empty())
{
QueuedSend sendData = m_queueSend.front();
pWS->SendData_Signalling(sendData.target_user_id, sendData.vecPayload);
m_queueSend.pop_front();
}
// TODO_NGMP: Avoid copy
std::queue<std::vector<uint8_t>> pendingSignals = pWS->m_pendingSignals;
pWS->m_pendingSignals = std::queue<std::vector<uint8_t>>();
pWS->ReleaseLock();
// Now dispatch any buffered signals
if (!pendingSignals.empty())
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[SIGNAL] PROCESS SIGNAL!");
while (!pendingSignals.empty())
{
// NOTE: outbound msg doesnt need sender ID, we only need that to determine target on the server, everything else is included in the payload
//
// Get the next signal
std::vector<uint8_t> signalData = pendingSignals.front();
pendingSignals.pop();
// Setup a context object that can respond if this signal is a connection request.
struct Context : ISteamNetworkingSignalingRecvContext
{
CSignalingClient* m_pOwner;
virtual ISteamNetworkingConnectionSignaling* OnConnectRequest(
HSteamNetConnection hConn,
const SteamNetworkingIdentity& identityPeer,
int nLocalVirtualPort
) override {
// Silence warnings
(void)hConn;
; (void)nLocalVirtualPort;
// We will just always handle requests through the usual listen socket state
// machine. See the documentation for this function for other behaviour we
// might take.
// Also, note that if there was routing/session info, it should have been in
// our envelope that we know how to parse, and we should save it off in this
// context object.
SteamNetworkingErrMsg ignoreErrMsg;
return m_pOwner->CreateSignalingForConnection(identityPeer, ignoreErrMsg);
}
virtual void SendRejectionSignal(
const SteamNetworkingIdentity& identityPeer,
const void* pMsg, int cbMsg
) override {
// We'll just silently ignore all failures. This is actually the more secure
// Way to handle it in many cases. Actively returning failure might allow
// an attacker to just scrape random peers to see who is online. If you know
// the peer has a good reason for trying to connect, sending an active failure
// can improve error handling and the UX, instead of relying on timeout. But
// just consider the security implications.
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING] Sending rejection signal");
// Silence warnings
(void)identityPeer;
(void)pMsg;
(void)cbMsg;
}
};
Context context;
context.m_pOwner = this;
// Dispatch.
// Remember: From inside this function, our context object might get callbacks.
// And we might get asked to send signals, either now, or really at any time
// from any thread! If possible, avoid calling this function while holding locks.
// To process this call, SteamnetworkingSockets will need take its own internal lock.
// That lock may be held by another thread that is asking you to send a signal! So
// be warned that deadlocks are a possibility here.
m_pSteamNetworkingSockets->ReceivedP2PCustomSignal(signalData.data(), (int)signalData.size(), &context);
}
}
}
}
virtual void Release() override
{
// NOTE: Here we are assuming that the calling code has already cleaned
// up all the connections, to keep the example simple.
CloseSocket();
}
};
NetworkMesh::NetworkMesh()
{
// try a shutdown
GameNetworkingSockets_Kill();
NGMP_OnlineServicesManager* pOnlineServicesMgr = NGMP_OnlineServicesManager::GetInstance();
if (pOnlineServicesMgr == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "pOnlineServicesMgr is invalid");
return;
}
NGMP_OnlineServices_AuthInterface* pAuthInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_AuthInterface>();
if (pAuthInterface == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "pAuthInterface is invalid");
return;
}
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "pLobbyInterface is invalid");
return;
}
int64_t localUserID = pAuthInterface->GetUserID();
SteamNetworkingIdentity identityLocal;
identityLocal.Clear();
std::string localUserIDStr = std::to_string(localUserID);
identityLocal.SetGenericString(localUserIDStr.c_str());
if (identityLocal.IsInvalid())
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "SteamNetworkingIdentity is invalid");
return;
}
// initialize Steam Sockets
SteamDatagramErrMsg errMsg;
if (!GameNetworkingSockets_Init(&identityLocal, errMsg))
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "GameNetworkingSockets_Init failed. %s", errMsg);
return;
}
SteamNetworkingUtils()->SetGlobalConfigValueInt32(k_ESteamNetworkingConfig_LogLevel_P2PRendezvous, k_ESteamNetworkingSocketsDebugOutputType_Error);
// TODO_STEAM: Dont hardcode, get everything from service
SteamNetworkingUtils()->SetGlobalConfigValueString(k_ESteamNetworkingConfig_P2P_STUN_ServerList, "stun:stun.playgenerals.online:53,stun:stun.playgenerals.online:3478,stun.l.google.com:19302,stun1.l.google.com:19302,stun2.l.google.com:19302,stun3.l.google.com:19302,stun4.l.google.com:19302");
// comma seperated setting lists
const char* turnList = "turn:turn.playgenerals.online:53?transport=udp,turn:turn.playgenerals.online:3478?transport=udp";
m_strTurnUsername = pLobbyInterface->GetLobbyTurnUsername();
m_strTurnToken = pLobbyInterface->GetLobbyTurnToken();
//const char* szUsername = "g04024f26713bae6e055295b6887b7007533f6c236534b725734b37e26ec15cd,g04024f26713bae6e055295b6887b7007533f6c236534b725734b37e26ec15cd";
//const char* szToken = "9ea6a5e60216c09a1fa7512987b2ce0514e3204f863f04f70fa870a100db740f,9ea6a5e60216c09a1fa7512987b2ce0514e3204f863f04f70fa870a100db740f";
//strUsername = "g04024f26713bae6e055295b6887b7007533f6c236534b725734b37e26ec15cd";
//strToken = "9ea6a5e60216c09a1fa7512987b2ce0514e3204f863f04f70fa870a100db740f";
m_strTurnUsernameString = std::format("{},{}", m_strTurnUsername.c_str(), m_strTurnUsername.c_str());
m_strTurnTokenString = std::format("{},{}", m_strTurnToken.c_str(), m_strTurnToken.c_str());
SteamNetworkingUtils()->SetGlobalConfigValueString(k_ESteamNetworkingConfig_P2P_TURN_ServerList, turnList);
SteamNetworkingUtils()->SetGlobalConfigValueString(k_ESteamNetworkingConfig_P2P_TURN_UserList, m_strTurnUsernameString.c_str());
SteamNetworkingUtils()->SetGlobalConfigValueString(k_ESteamNetworkingConfig_P2P_TURN_PassList, m_strTurnTokenString.c_str());
ServiceConfig& serviceConf = pOnlineServicesMgr->GetServiceConfig();
// Allow sharing of any kind of ICE address.
if (g_bForceRelay || serviceConf.relay_all_traffic)
{
SteamNetworkingUtils()->SetGlobalConfigValueInt32(k_ESteamNetworkingConfig_P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_Relay);
}
else
{
SteamNetworkingUtils()->SetGlobalConfigValueInt32(k_ESteamNetworkingConfig_P2P_Transport_ICE_Enable, k_nSteamNetworkingConfig_P2P_Transport_ICE_Enable_All);
}
m_hListenSock = k_HSteamListenSocket_Invalid;
// create signalling service
m_pSignaling = new CSignalingClient(SteamNetworkingSockets());
if (m_pSignaling == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "CreateTrivialSignalingClient failed. %s", errMsg);
return;
}
SteamNetworkingUtils()->SetGlobalCallback_SteamNetConnectionStatusChanged(OnSteamNetConnectionStatusChanged);
ESteamNetworkingSocketsDebugOutputType logType =
#if defined(_DEBUG)
ESteamNetworkingSocketsDebugOutputType::k_ESteamNetworkingSocketsDebugOutputType_Debug
#else
NGMP_OnlineServicesManager::Settings.Debug_VerboseLogging() ? ESteamNetworkingSocketsDebugOutputType::k_ESteamNetworkingSocketsDebugOutputType_Debug : ESteamNetworkingSocketsDebugOutputType::k_ESteamNetworkingSocketsDebugOutputType_Msg
#endif;
;
SteamNetworkingUtils()->SetGlobalConfigValueInt32(k_ESteamNetworkingConfig_LogLevel_P2PRendezvous, logType);
SteamNetworkingUtils()->SetDebugOutputFunction(logType, [](ESteamNetworkingSocketsDebugOutputType nType, const char* pszMsg)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM NETWORKING LOGFUNC] %s", pszMsg);
});
int localPort = 0;
// create sockets
SteamNetworkingConfigValue_t opt;
opt.SetInt32(k_ESteamNetworkingConfig_SymmetricConnect, 1); // << Note we set symmetric mode on the listen socket
m_hListenSock = SteamNetworkingSockets()->CreateListenSocketP2P(localPort, 1, &opt);
if (m_hListenSock == k_HSteamListenSocket_Invalid)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "CreateListenSocketP2P failed. Sock was invalid");
}
}
void NetworkMesh::Flush()
{
ServiceConfig& serviceConf = NGMP_OnlineServicesManager::GetInstance()->GetServiceConfig();
bool bDoImmediateFlushPerFrame = serviceConf.network_do_immediate_flush_per_frame;
if (bDoImmediateFlushPerFrame)
{
for (auto& connectionData : m_mapConnections)
{
SteamNetworkingSockets()->FlushMessagesOnConnection(connectionData.second.m_hSteamConnection);
}
}
}
void NetworkMesh::RegisterConnectivity(int64_t userID)
{
nlohmann::json j;
j["target"] = userID;
j["direct"] = false;
j["outcome"] = EConnectionState::NOT_CONNECTED;
j["ipv4"] = true;
std::string strPostData = j.dump();
std::string strURI = NGMP_OnlineServicesManager::GetAPIEndpoint("ConnectionOutcome");
std::map<std::string, std::string> mapHeaders;
NGMP_OnlineServicesManager::GetInstance()->GetHTTPManager()->SendPOSTRequest(strURI.c_str(), EIPProtocolVersion::DONT_CARE, mapHeaders, strPostData.c_str(), [=](bool bSuccess, int statusCode, std::string strBody, HTTPRequest* pReq)
{
// dont care about the response
});
}
void NetworkMesh::UpdateConnectivity(PlayerConnection* connection)
{
nlohmann::json j;
j["target"] = connection->m_userID;
j["direct"] = connection->IsDirect();
j["outcome"] = connection->GetState();
j["ipv4"] = connection->IsIPV4();
std::string strPostData = j.dump();
std::string strURI = NGMP_OnlineServicesManager::GetAPIEndpoint("ConnectionOutcome");
std::map<std::string, std::string> mapHeaders;
NGMP_OnlineServicesManager::GetInstance()->GetHTTPManager()->SendPOSTRequest(strURI.c_str(), EIPProtocolVersion::DONT_CARE, mapHeaders, strPostData.c_str(), [=](bool bSuccess, int statusCode, std::string strBody, HTTPRequest* pReq)
{
// dont care about the response
});
}
bool NetworkMesh::HasGamePacket()
{
return !m_queueQueuedGamePackets.empty();
}
QueuedGamePacket NetworkMesh::RecvGamePacket()
{
if (HasGamePacket())
{
QueuedGamePacket frontPacket = m_queueQueuedGamePackets.front();
m_queueQueuedGamePackets.pop();
return frontPacket;
}
return QueuedGamePacket();
}
int NetworkMesh::SendGamePacket(void* pBuffer, uint32_t totalDataSize, int64_t user_id)
{
auto it = m_mapConnections.find(user_id);
if (it != m_mapConnections.end())
{
return it->second.SendGamePacket(pBuffer, totalDataSize);
}
return -2;
}
void NetworkMesh::StartConnectionSignalling(int64_t remoteUserID, uint16_t preferredPort)
{
// if we already have a connection to this use, drop it, having a single-direction connection will break signalling
auto it = m_mapConnections.find(remoteUserID);
if (it != m_mapConnections.end())
{
if (it->second.m_hSteamConnection != k_HSteamNetConnection_Invalid)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing connection %lld, new connection is being negotiated", remoteUserID);
SteamNetworkingSockets()->CloseConnection(it->second.m_hSteamConnection, 0, "Client Disconnecting Gracefully (new connection being negotiated)", false);
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(remoteUserID);
}
}
NetworkLog(ELogVerbosity::LOG_RELEASE, "[ERASE 3] Removing user %lld", it->second.m_userID);
m_mapConnections.erase(it);
}
NGMP_OnlineServicesManager* pOnlineServicesMgr = NGMP_OnlineServicesManager::GetInstance();
NGMP_OnlineServices_AuthInterface* pAuthInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_AuthInterface>();
if (pAuthInterface == nullptr || pOnlineServicesMgr == nullptr)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "NetworkMesh::ConnectToSingleUser - Auth or OSM interface is null");
return;
}
// never connect to ourself
if (remoteUserID == pAuthInterface->GetUserID())
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "NetworkMesh::ConnectToSingleUser - Skipping connection to user %lld - user is local", remoteUserID);
return;
}
SteamNetworkingIdentity identityRemote;
identityRemote.Clear();
std::string remoteUserIDStr = std::to_string(remoteUserID);
identityRemote.SetGenericString(remoteUserIDStr.c_str());
if (identityRemote.IsInvalid())
{
// TODO_STEAM: Handle this better
NetworkLog(ELogVerbosity::LOG_RELEASE, "NetworkMesh::ConnectToSingleUser - SteamNetworkingIdentity is invalid");
return;
}
std::vector<SteamNetworkingConfigValue_t > vecOpts;
ServiceConfig& serviceConf = pOnlineServicesMgr->GetServiceConfig();
int g_nLocalPort = 0;
int g_nVirtualPortRemote = serviceConf.use_mapped_port ? preferredPort : 0;
// Our remote and local port don't match, so we need to set it explicitly
if (g_nVirtualPortRemote != g_nLocalPort)
{
SteamNetworkingConfigValue_t opt;
opt.SetInt32(k_ESteamNetworkingConfig_LocalVirtualPort, g_nLocalPort);
vecOpts.push_back(opt);
}
// Set symmetric connect mode
SteamNetworkingConfigValue_t opt;
opt.SetInt32(k_ESteamNetworkingConfig_SymmetricConnect, 1);
vecOpts.push_back(opt);
NetworkLog(ELogVerbosity::LOG_DEBUG, "Connecting to '%s' in symmetric mode, virtual port %d, from local virtual port %d.\n",
SteamNetworkingIdentityRender(identityRemote).c_str(), g_nVirtualPortRemote, g_nLocalPort);
// create a signaling object for this connection
SteamNetworkingErrMsg errMsg;
ISteamNetworkingConnectionSignaling* pConnSignaling = m_pSignaling->CreateSignalingForConnection(identityRemote, errMsg);
if (pConnSignaling == nullptr)
{
// TODO_STEAM: Handle this better
NetworkLog(ELogVerbosity::LOG_RELEASE, "NetworkMesh::ConnectToSingleUser - Could not create signalling object, error was %s", errMsg);
return;
}
// make a steam connection obj
HSteamNetConnection hSteamConnection = SteamNetworkingSockets()->ConnectP2PCustomSignaling(pConnSignaling, &identityRemote, g_nVirtualPortRemote, (int)vecOpts.size(), vecOpts.data());
if (hSteamConnection == k_HSteamNetConnection_Invalid)
{
// TODO_STEAM: Handle this better
NetworkLog(ELogVerbosity::LOG_RELEASE, "NetworkMesh::ConnectToSingleUser - Steam network connection obj was k_HSteamNetConnection_Invalid");
return;
}
// create a local user type
m_mapConnections[remoteUserID] = PlayerConnection(remoteUserID, hSteamConnection);
// add attempt
++m_mapConnections[remoteUserID].m_SignallingAttempts;
}
void NetworkMesh::DisconnectUser(int64_t remoteUserID)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Dumping all Steam connections");
for (auto& kvPair : m_mapConnections)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Dumped steam connection, Handle %u User %lld (%lld)", kvPair.second.m_hSteamConnection, kvPair.second.m_userID, kvPair.first);
}
if (m_mapConnections.find(remoteUserID) != m_mapConnections.end())
{
if (m_mapConnections[remoteUserID].m_hSteamConnection != k_HSteamNetConnection_Invalid)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Closing connection %lld", remoteUserID);
NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] Steam connection handle is %u", m_mapConnections[remoteUserID].m_hSteamConnection);
SteamNetworkingSockets()->CloseConnection(m_mapConnections[remoteUserID].m_hSteamConnection, 0, "Client Disconnecting Gracefully (Got EWebSocketMessageID::NETWORK_CONNECTION_DISCONNECT_PLAYER from service)", false);
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(remoteUserID);
}
}
if (TheNGMPGame && !TheNGMPGame->isGameInProgress())
{
for (auto it = m_mapConnections.begin(); it != m_mapConnections.end(); )
{
if (it->second.m_userID == remoteUserID)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[ERASE] Removing user %lld", it->second.m_userID);
it = m_mapConnections.erase(it);
break;
}
else
{
++it;
}
}
}
}
}
void NetworkMesh::Disconnect()
{
if (m_bDisconnected)
return;
m_bDisconnected = true;
// Set flag to prevent callbacks from executing during teardown
g_bNetworkMeshDestroying.store(true);
// Unregister the global callback to prevent new callbacks from being queued
if (SteamNetworkingUtils())
{
SteamNetworkingUtils()->SetGlobalCallback_SteamNetConnectionStatusChanged(nullptr);
}
// close every connection
for (auto& connectionData : m_mapConnections)
{
//NetworkLog(ELogVerbosity::LOG_RELEASE, "[DC] FullMesh");
if (SteamNetworkingSockets())
{
SteamNetworkingSockets()->CloseConnection(connectionData.second.m_hSteamConnection, 0, "Client Disconnecting Gracefully", false);
}
if (TheNetwork != nullptr)
{
TheNetwork->GetConnectionManager()->disconnectPlayer(connectionData.first);
}
}
if (SteamNetworkingSockets())
{
SteamNetworkingSockets()->CloseListenSocket(m_hListenSock);
}
// invalidate socket
m_hListenSock = k_HSteamNetConnection_Invalid;
// clear map
m_mapConnections.clear();
// tear down steam sockets
GameNetworkingSockets_Kill();
// Reset flag after teardown is complete
g_bNetworkMeshDestroying.store(false);
}
void NetworkMesh::Tick()
{
// Check for incoming signals, and dispatch them
if (m_pSignaling != nullptr)
{
m_pSignaling->Poll();
}
// Check callbacks
if (SteamNetworkingSockets())
{
SteamNetworkingSockets()->RunCallbacks();
}
// update connection histograms
for (auto& kvPair : m_mapConnections)
{
PlayerConnection& conn = kvPair.second;
conn.UpdateLatencyHistogram();
}
}
PlayerConnection::PlayerConnection(int64_t userID, HSteamNetConnection hSteamConnection)
{
m_userID = userID;
// no connection yet
m_hSteamConnection = hSteamConnection;
NetworkLog(ELogVerbosity::LOG_RELEASE, "[STEAM CONNECTION] Attaching connection %u to user %lld", hSteamConnection, userID);
SteamNetworkingSockets()->SetConnectionName(hSteamConnection, std::format("Steam Connection User{}", userID).c_str());
NetworkMesh* pMesh = NGMP_OnlineServicesManager::GetNetworkMesh();
if (pMesh != nullptr)
{
pMesh->RegisterConnectivity(userID);
}
}
int PlayerConnection::SendGamePacket(void* pBuffer, uint32_t totalDataSize)
{
int sendFlags = k_nSteamNetworkingSend_Reliable | k_nSteamNetworkingSend_AutoRestartBrokenSession; // default from last patch
ServiceConfig& serviceConf = NGMP_OnlineServicesManager::GetInstance()->GetServiceConfig();