-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathNetLibrary.cpp
1117 lines (871 loc) · 26.3 KB
/
NetLibrary.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
/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "StdInc.h"
#include "NetLibrary.h"
#include <base64.h>
#include "ICoreGameInit.h"
#include <mutex>
#include <mmsystem.h>
#include <yaml-cpp/yaml.h>
#include <SteamComponentAPI.h>
#include <LegitimacyAPI.h>
#include <Error.h>
fwEvent<const std::string&> OnRichPresenceSetTemplate;
fwEvent<int, const std::string&> OnRichPresenceSetValue;
std::unique_ptr<NetLibraryImplBase> CreateNetLibraryImplV2(INetLibraryInherit* base);
inline ISteamComponent* GetSteam()
{
auto steamComponent = Instance<ISteamComponent>::Get();
// if Steam isn't running, return an error
if (!steamComponent->IsSteamRunning())
{
steamComponent->Initialize();
if (!steamComponent->IsSteamRunning())
{
return nullptr;
}
}
return steamComponent;
}
static uint32_t m_tempGuid = GetTickCount();
uint16_t NetLibrary::GetServerNetID()
{
return m_serverNetID;
}
uint16_t NetLibrary::GetServerSlotID()
{
return m_serverSlotID;
}
uint16_t NetLibrary::GetHostNetID()
{
return m_hostNetID;
}
void NetLibrary::HandleConnected(int serverNetID, int hostNetID, int hostBase, int slotID)
{
m_serverNetID = serverNetID;
m_hostNetID = hostNetID;
m_hostBase = hostBase;
m_serverSlotID = slotID;
trace("connectOK, our id %d (slot %d), host id %d\n", m_serverNetID, m_serverSlotID, m_hostNetID);
OnConnectOKReceived(m_currentServer);
m_connectionState = CS_CONNECTED;
}
bool NetLibrary::GetOutgoingPacket(RoutingPacket& packet)
{
return m_outgoingPackets.try_pop(packet);
}
bool NetLibrary::WaitForRoutedPacket(uint32_t timeout)
{
{
std::lock_guard<std::mutex> guard(m_incomingPacketMutex);
if (!m_incomingPackets.empty())
{
return true;
}
}
WaitForSingleObject(m_receiveEvent, timeout);
{
std::lock_guard<std::mutex> guard(m_incomingPacketMutex);
return (!m_incomingPackets.empty());
}
}
void NetLibrary::EnqueueRoutedPacket(uint16_t netID, const std::string& packet)
{
{
std::lock_guard<std::mutex> guard(m_incomingPacketMutex);
RoutingPacket routePacket;
routePacket.netID = netID;
routePacket.payload = std::move(packet);
routePacket.genTime = timeGetTime();
m_incomingPackets.push(std::move(routePacket));
}
SetEvent(m_receiveEvent);
}
bool NetLibrary::DequeueRoutedPacket(char* buffer, size_t* length, uint16_t* netID)
{
{
std::lock_guard<std::mutex> guard(m_incomingPacketMutex);
if (m_incomingPackets.empty())
{
return false;
}
auto packet = m_incomingPackets.front();
m_incomingPackets.pop();
memcpy(buffer, packet.payload.c_str(), packet.payload.size());
*netID = packet.netID;
*length = packet.payload.size();
// store metrics
auto timeval = (timeGetTime() - packet.genTime);
m_metricSink->OnRouteDelayResult(timeval);
}
ResetEvent(m_receiveEvent);
return true;
}
void NetLibrary::RoutePacket(const char* buffer, size_t length, uint16_t netID)
{
RoutingPacket routePacket;
routePacket.netID = netID;
routePacket.payload = std::string(buffer, length);
m_outgoingPackets.push(routePacket);
}
#define BIG_INFO_STRING 8192 // used for system info key only
#define BIG_INFO_KEY 8192
#define BIG_INFO_VALUE 8192
/*
===============
Info_ValueForKey
Searches the string for the given
key and returns the associated value, or an empty string.
FIXME: overflow check?
===============
*/
char *Info_ValueForKey(const char *s, const char *key)
{
char pkey[BIG_INFO_KEY];
static char value[2][BIG_INFO_VALUE]; // use two buffers so compares
// work without stomping on each other
static int valueindex = 0;
char *o;
if (!s || !key)
{
return "";
}
if (strlen(s) >= BIG_INFO_STRING)
{
return "";
}
valueindex ^= 1;
if (*s == '\\')
s++;
while (1)
{
o = pkey;
while (*s != '\\')
{
if (!*s)
return "";
*o++ = *s++;
}
*o = 0;
s++;
o = value[valueindex];
while (*s != '\\' && *s)
{
*o++ = *s++;
}
*o = 0;
if (!_stricmp(key, pkey))
return value[valueindex];
if (!*s)
break;
s++;
}
return "";
}
#define Q_IsColorString( p ) ( ( p ) && *( p ) == '^' && *( ( p ) + 1 ) && isdigit( *( ( p ) + 1 ) ) ) // ^[0-9]
void StripColors(const char* in, char* out, int max)
{
max--; // \0
int current = 0;
while (*in != 0 && current < max)
{
if (!Q_IsColorString(in))
{
*out = *in;
out++;
current++;
}
else
{
*in++;
}
*in++;
}
*out = '\0';
}
void NetLibrary::ProcessOOB(const NetAddress& from, const char* oob, size_t length)
{
if (from == m_currentServer)
{
if (!_strnicmp(oob, "infoResponse", 12))
{
const char* infoString = &oob[13];
m_infoString = infoString;
{
auto steam = GetSteam();
char hostname[256] = { 0 };
strncpy(hostname, Info_ValueForKey(infoString, "hostname"), 255);
char cleaned[256];
StripColors(hostname, cleaned, 256);
#ifdef GTA_FIVE
SetWindowText(FindWindow(L"grcWindow", nullptr), va(L"FiveM - %s", ToWide(cleaned)));
#endif
auto richPresenceSetTemplate = [&](const auto& tpl)
{
OnRichPresenceSetTemplate(tpl);
if (steam)
{
steam->SetRichPresenceTemplate(tpl);
}
};
auto richPresenceSetValue = [&](int idx, const std::string& val)
{
OnRichPresenceSetValue(idx, val);
if (steam)
{
steam->SetRichPresenceValue(idx, val);
}
};
richPresenceSetTemplate("{0}\n{1}");
richPresenceSetValue(0, fmt::sprintf(
"%s%s",
std::string(cleaned).substr(0, 110),
(strlen(cleaned) > 110) ? "..." : ""
));
richPresenceSetValue(1, "Connecting...");
}
// until map reloading is in existence
std::string thisWorld = Info_ValueForKey(infoString, "world");
if (thisWorld.empty())
{
thisWorld = "gta5";
}
static std::string lastWorld = thisWorld;
if (lastWorld != thisWorld && Instance<ICoreGameInit>::Get()->GetGameLoaded())
{
GlobalError("Was loaded in world %s, but this server is world %s. Restart the game to join.", lastWorld, thisWorld);
return;
}
lastWorld = thisWorld;
// finalize connecting
m_connectionState = CS_CONNECTING;
m_lastConnect = 0;
m_connectAttempts = 0;
}
else if (!_strnicmp(oob, "error", 5))
{
if (from != m_currentServer)
{
trace("Received 'error' request was not from the host\n");
return;
}
if (length >= 6)
{
const char* errorStr = &oob[6];
GlobalError("%s", std::string(errorStr, length - 6));
}
}
}
}
void NetLibrary::SetHost(uint16_t netID, uint32_t base)
{
m_hostNetID = netID;
m_hostBase = base;
}
void NetLibrary::SetBase(uint32_t base)
{
m_serverBase = base;
}
uint32_t NetLibrary::GetHostBase()
{
return m_hostBase;
}
void NetLibrary::SetMetricSink(fwRefContainer<INetMetricSink>& sink)
{
m_metricSink = sink;
}
void NetLibrary::HandleReliableCommand(uint32_t msgType, const char* buf, size_t length)
{
auto range = m_reliableHandlers.equal_range(msgType);
std::for_each(range.first, range.second, [&] (std::pair<uint32_t, ReliableHandlerType> handler)
{
handler.second(buf, length);
});
}
RoutingPacket::RoutingPacket()
{
//genTime = timeGetTime();
genTime = 0;
}
void NetLibrary::SendReliableCommand(const char* type, const char* buffer, size_t length)
{
m_impl->SendReliableCommand(HashRageString(type), buffer, length);
}
static std::string g_disconnectReason;
static std::mutex g_netFrameMutex;
inline uint64_t GetGUID()
{
auto steamComponent = GetSteam();
if (steamComponent)
{
IClientEngine* steamClient = steamComponent->GetPrivateClient();
InterfaceMapper steamUser(steamClient->GetIClientUser(steamComponent->GetHSteamUser(), steamComponent->GetHSteamPipe(), "CLIENTUSER_INTERFACE_VERSION001"));
if (steamUser.IsValid())
{
uint64_t steamID;
steamUser.Invoke<void>("GetSteamID", &steamID);
return steamID;
}
}
return (uint64_t)(0x210000100000000 | m_tempGuid);
}
void NetLibrary::RunFrame()
{
if (!g_netFrameMutex.try_lock())
{
return;
}
if (m_connectionState != m_lastConnectionState)
{
OnStateChanged(m_connectionState, m_lastConnectionState);
m_lastConnectionState = m_connectionState;
}
if (m_impl)
{
m_impl->RunFrame();
}
switch (m_connectionState)
{
case CS_INITRECEIVED:
// change connection state to CS_DOWNLOADING
m_connectionState = CS_DOWNLOADING;
// trigger task event
OnConnectionProgress("Downloading content", 0, 1);
OnInitReceived(m_currentServer);
break;
case CS_DOWNLOADCOMPLETE:
m_connectionState = CS_FETCHING;
m_lastConnect = 0;
m_connectAttempts = 0;
OnConnectionProgress("Downloading completed", 1, 1);
break;
case CS_FETCHING:
if ((GetTickCount() - m_lastConnect) > 5000)
{
SendOutOfBand(m_currentServer, "getinfo xyz");
m_lastConnect = GetTickCount();
m_connectAttempts++;
// advertise status
auto specStatus = (m_connectAttempts > 1) ? fmt::sprintf(" (attempt %d)", m_connectAttempts) : "";
OnConnectionProgress(fmt::sprintf("Fetching info from server...%s", specStatus), 1, 1);
}
if (m_connectAttempts > 3)
{
g_disconnectReason = "Fetching info timed out.";
FinalizeDisconnect();
OnConnectionTimedOut();
GlobalError("Failed to getinfo server after 3 attempts.");
}
break;
case CS_CONNECTING:
if ((GetTickCount() - m_lastConnect) > 5000)
{
m_impl->SendConnect(fmt::sprintf("token=%s&guid=%llu", m_token, (uint64_t)GetGUID()));
m_lastConnect = GetTickCount();
m_connectAttempts++;
// advertise status
auto specStatus = (m_connectAttempts > 1) ? fmt::sprintf(" (attempt %d)", m_connectAttempts) : "";
OnConnectionProgress(fmt::sprintf("Connecting to server...%s", specStatus), 1, 1);
}
if (m_connectAttempts > 3)
{
g_disconnectReason = "Connection timed out.";
FinalizeDisconnect();
OnConnectionTimedOut();
GlobalError("Failed to connect to server after 3 attempts.");
}
break;
case CS_ACTIVE:
if (m_impl->HasTimedOut())
{
g_disconnectReason = "Connection timed out.";
OnConnectionTimedOut();
GlobalError("Server connection timed out after 15 seconds.");
m_connectionState = CS_IDLE;
m_currentServer = NetAddress();
}
break;
}
g_netFrameMutex.unlock();
}
void NetLibrary::Death()
{
g_netFrameMutex.unlock();
}
void NetLibrary::Resurrection()
{
g_netFrameMutex.lock();
}
static void tohex(unsigned char* in, size_t insz, char* out, size_t outsz)
{
unsigned char* pin = in;
const char* hex = "0123456789ABCDEF";
char* pout = out;
for (; pin < in + insz; pout += 2, pin++)
{
pout[0] = hex[(*pin >> 4) & 0xF];
pout[1] = hex[*pin & 0xF];
if (pout + 3 - out > outsz)
{
break;
}
}
pout[0] = 0;
}
typedef uint32 HAuthTicket;
const HAuthTicket k_HAuthTicketInvalid = 0;
struct GetAuthSessionTicketResponse_t
{
enum { k_iCallback = 100 + 63 };
HAuthTicket m_hAuthTicket;
int m_eResult;
};
void NetLibrary::ConnectToServer(const net::PeerAddress& address)
{
if (m_connectionState != CS_IDLE)
{
Disconnect("Connecting to another server.");
FinalizeDisconnect();
}
// late-initialize error state in ICoreGameInit
// this happens here so it only tries capturing if connection was attempted
static struct ErrorState
{
ErrorState(NetLibrary* lib)
{
Instance<ICoreGameInit>::Get()->OnTriggerError.Connect([=] (const std::string& errorMessage)
{
if (lib->m_connectionState != CS_ACTIVE)
{
lib->OnConnectionError(errorMessage.c_str());
lib->m_connectionState = CS_IDLE;
return false;
}
else if (lib->m_connectionState != CS_IDLE)
{
auto nlPos = errorMessage.find_first_of('\n');
if (nlPos == std::string::npos || nlPos > 100)
{
nlPos = 100;
}
lib->Disconnect(errorMessage.substr(0, nlPos).c_str());
if (!Instance<ICoreGameInit>::Get()->GetGameLoaded())
{
lib->FinalizeDisconnect();
}
}
return true;
});
}
} es(this);
m_currentServer = NetAddress(address.GetSocketAddress());
m_currentServerPeer = address;
m_connectionState = CS_INITING;
AddCrashometry("last_server", "%s", address.ToString());
if (m_impl)
{
m_impl->Reset();
}
m_outSequence = 0;
static fwMap<fwString, fwString> postMap;
postMap["method"] = "initConnect";
postMap["name"] = GetPlayerName();
postMap["protocol"] = va("%d", NETWORK_PROTOCOL);
static std::function<void()> performRequest;
postMap["guid"] = va("%lld", GetGUID());
static bool isLegacyDeferral;
isLegacyDeferral = false;
static fwAction<bool, const char*, size_t> handleAuthResult;
handleAuthResult = [=] (bool result, const char* connDataStr, size_t size) mutable
{
if (m_connectionState != CS_INITING)
{
return;
}
std::string connData(connDataStr, size);
if (!result)
{
// TODO: add UI output
m_connectionState = CS_IDLE;
//nui::ExecuteRootScript("citFrames[\"mpMenu\"].contentWindow.postMessage({ type: 'connectFailed', message: 'General handshake failure.' }, '*');");
OnConnectionError(va("Failed handshake to server %s:%d%s%s.", m_currentServer.GetAddress(), m_currentServer.GetPort(), connData.length() > 0 ? " - " : "", connData));
return;
}
else if (!isLegacyDeferral)
{
OnConnectionError(va("Failed handshake to server %s:%d - it closed the connection while deferring.", m_currentServer.GetAddress(), m_currentServer.GetPort()));
}
};
static std::function<bool(const std::string&)> handleAuthResultData;
handleAuthResultData = [=](const std::string& chunk)
{
// FIXME: for now, assume the chunk will always be a full JSON message
// this will not always be the case, but for initial prototyping this'll work...
if (m_connectionState != CS_INITING)
{
return false;
}
std::string connData(chunk);
try
{
auto node = YAML::Load(connData);
if (node["token"].IsDefined())
{
m_token = node["token"].as<std::string>();
Instance<ICoreGameInit>::Get()->SetData("connectionToken", m_token);
}
if (node["defer"].IsDefined())
{
if (node["deferVersion"].IsDefined())
{
// new deferral system
OnConnectionProgress(node["message"].as<std::string>(), 133, 133);
return true;
}
isLegacyDeferral = true;
OnConnectionProgress(node["status"].as<std::string>(), 133, 133);
static fwMap<fwString, fwString> newMap;
newMap["method"] = "getDeferState";
newMap["guid"] = va("%lld", GetGUID());
newMap["token"] = m_token;
HttpRequestOptions options;
options.streamingCallback = handleAuthResultData;
m_httpClient->DoPostRequest(fmt::sprintf("http://%s/client", address.ToString()), m_httpClient->BuildPostString(newMap), options, handleAuthResult);
return true;
}
if (node["error"].IsDefined())
{
OnConnectionError(node["error"].as<std::string>().c_str());
m_connectionState = CS_IDLE;
return true;
}
if (!node["sH"].IsDefined())
{
OnConnectionError("Invalid server response from initConnect (missing JSON data), is this server running a broken resource?");
m_connectionState = CS_IDLE;
return true;
}
else
{
Instance<ICoreGameInit>::Get()->ShAllowed = node["sH"].as<bool>(true);
}
m_httpClient->DoGetRequest(fmt::sprintf("https://runtime.fivem.net/policy/shdisable?server=%s_%d", address.GetHost(), address.GetPort()), [=](bool success, const char* data, size_t length)
{
if (success)
{
if (std::string(data, length).find("yes") != std::string::npos)
{
Instance<ICoreGameInit>::Get()->ShAllowed = false;
}
}
});
Instance<ICoreGameInit>::Get()->EnhancedHostSupport = (node["enhancedHostSupport"].IsDefined() && node["enhancedHostSupport"].as<bool>(false));
Instance<ICoreGameInit>::Get()->OneSyncEnabled = (node["onesync"].IsDefined() && node["onesync"].as<bool>(false));
m_serverProtocol = node["protocol"].as<uint32_t>();
auto steam = GetSteam();
if (steam)
{
steam->SetConnectValue(fmt::sprintf("+connect %s:%d", m_currentServer.GetAddress(), m_currentServer.GetPort()));
}
if (Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
m_httpClient->DoGetRequest(fmt::sprintf("https://runtime.fivem.net/policy/onesync?server=%s_%d", address.GetHost(), address.GetPort()), [=](bool success, const char* data, size_t length)
{
if (success)
{
if (std::string(data, length).find("yes") != std::string::npos)
{
m_connectionState = CS_INITRECEIVED;
return;
}
}
OnConnectionError("OneSync is not whitelisted for this server, or requesting whitelist status failed. You'll have to wait a little while longer!");
m_connectionState = CS_IDLE;
});
}
else
{
m_connectionState = CS_INITRECEIVED;
}
if (node["netlibVersion"].as<int>(1) == 2)
{
m_impl = CreateNetLibraryImplV2(this);
}
else
{
OnConnectionError("Legacy servers are incompatible with this version of FiveM. Please tell the server owner to the server to the latest FXServer build. See https://fivem.net/ for more info.");
m_connectionState = CS_IDLE;
return true;
}
}
catch (YAML::Exception& e)
{
OnConnectionError(e.what());
m_connectionState = CS_IDLE;
}
return true;
};
performRequest = [=]()
{
HttpRequestOptions options;
options.streamingCallback = handleAuthResultData;
m_httpClient->DoPostRequest(fmt::sprintf("http://%s/client", address.ToString()), m_httpClient->BuildPostString(postMap), options, handleAuthResult);
};
m_httpClient->DoGetRequest(fmt::sprintf("https://runtime.fivem.net/blacklist/%s_%d", address.GetHost(), address.GetPort()), [=](bool success, const char* data, size_t length)
{
if (success)
{
FatalError("This server has been blocked from the FiveM platform. Stated reason: %sIf you manage this server and you feel this is not justified, please contact your Technical Account Manager.", std::string(data, length));
}
});
m_httpClient->DoGetRequest(fmt::sprintf("https://runtime.fivem.net/blacklist/%s", address.GetHost()), [=](bool success, const char* data, size_t length)
{
if (success)
{
FatalError("This server has been blocked from the FiveM platform. Stated reason: %sIf you manage this server and you feel this is not justified, please contact your Technical Account Manager.", std::string(data, length));
}
});
auto continueRequest = [=]()
{
auto steamComponent = GetSteam();
if (steamComponent)
{
static uint32_t ticketLength;
static uint8_t ticketBuffer[4096];
static int lastCallback = -1;
IClientEngine* steamClient = steamComponent->GetPrivateClient();
InterfaceMapper steamUtils(steamClient->GetIClientUtils(steamComponent->GetHSteamPipe(), "CLIENTUTILS_INTERFACE_VERSION001"));
InterfaceMapper steamUser(steamClient->GetIClientUser(steamComponent->GetHSteamUser(), steamComponent->GetHSteamPipe(), "CLIENTUSER_INTERFACE_VERSION001"));
if (steamUser.IsValid())
{
auto removeCallback = []()
{
if (lastCallback != -1)
{
GetSteam()->RemoveSteamCallback(lastCallback);
lastCallback = -1;
}
};
removeCallback();
lastCallback = steamComponent->RegisterSteamCallback<GetAuthSessionTicketResponse_t>([=](GetAuthSessionTicketResponse_t* response)
{
removeCallback();
if (response->m_eResult != 1) // k_EResultOK
{
OnConnectionError(va("Failed to obtain Steam ticket, EResult %d.", response->m_eResult));
}
else
{
// encode the ticket buffer
char outHex[16384];
tohex(ticketBuffer, ticketLength, outHex, sizeof(outHex));
postMap["authTicket"] = outHex;
performRequest();
}
});
int appID = steamUtils.Invoke<int>("GetAppID");
trace("Getting auth ticket for pipe appID %d - should be 218.\n", appID);
steamUser.Invoke<int>("GetAuthSessionTicket", ticketBuffer, (int)sizeof(ticketBuffer), &ticketLength);
OnConnectionProgress("Obtaining Steam ticket...", 0, 100);
}
else
{
performRequest();
}
}
else
{
performRequest();
}
};
m_httpClient->DoPostRequest("https://lambda.fivem.net/api/ticket/create", { { "token", ros::GetEntitlementSource() }, { "server", address.ToString() }, { "guid", fmt::sprintf("%lld", GetGUID()) } }, [=](bool success, const char* data, size_t dataLen)
{
if (success)
{
auto node = YAML::Load(std::string(data, dataLen));
if (node["error"].IsDefined())
{
OnConnectionError(va("%s", node["error"].as<std::string>()));
m_connectionState = CS_IDLE;
return;
}
else if (node["ticket"].IsDefined())
{
postMap["cfxTicket"] = node["ticket"].as<std::string>();
}
}
continueRequest();
});
}
void NetLibrary::CancelDeferredConnection()
{
if (m_connectionState == CS_INITING)
{
m_connectionState = CS_IDLE;
}
}
void NetLibrary::Disconnect(const char* reason)
{
g_disconnectReason = reason;
OnAttemptDisconnect(reason);
//GameInit::KillNetwork((const wchar_t*)1);
}
static std::mutex g_disconnectionMutex;
void NetLibrary::FinalizeDisconnect()
{
std::unique_lock<std::mutex> lock(g_disconnectionMutex);
if (m_connectionState == CS_CONNECTING || m_connectionState == CS_ACTIVE)
{
SendReliableCommand("msgIQuit", g_disconnectReason.c_str(), g_disconnectReason.length() + 1);
m_impl->Flush();
OnFinalizeDisconnect(m_currentServer);
m_connectionState = CS_IDLE;
m_currentServer = NetAddress();
}
}
void NetLibrary::CreateResources()
{
m_httpClient = Instance<HttpClient>::Get();
}
void NetLibrary::SendOutOfBand(const NetAddress& address, const char* format, ...)
{
static char buffer[32768];
*(int*)buffer = -1;
va_list ap;
va_start(ap, format);
int length = _vsnprintf(&buffer[4], 32764, format, ap);
va_end(ap);
if (length >= 32764)
{
GlobalError("Attempted to overrun string in call to SendOutOfBand()!");
}
buffer[32767] = '\0';
SendData(address, buffer, strlen(buffer));
}
const char* NetLibrary::GetPlayerName()
{
/*
ProfileManager* profileManager = Instance<ProfileManager>::Get();
fwRefContainer<Profile> profile = profileManager->GetPrimaryProfile();*/
if (!m_playerName.empty()) return m_playerName.c_str();
auto steamComponent = GetSteam();
if (steamComponent)
{
IClientEngine* steamClient = steamComponent->GetPrivateClient();
if (steamClient)
{
InterfaceMapper steamFriends(steamClient->GetIClientFriends(steamComponent->GetHSteamUser(), steamComponent->GetHSteamPipe(), "CLIENTFRIENDS_INTERFACE_VERSION001"));
if (steamFriends.IsValid())
{
// TODO: name changing
static std::string personaName = steamFriends.Invoke<const char*>("GetPersonaName");
return personaName.c_str();
}
}
}
const char* returnName = nullptr;
/*
if (profile.GetRef())
{
returnName = profile->GetDisplayName();
}
else
{
static char computerName[64];
DWORD nameSize = sizeof(computerName);
GetComputerNameA(computerName, &nameSize);
returnName = computerName;