forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathOnlineServices_RoomsInterface.cpp
More file actions
1431 lines (1198 loc) · 48.1 KB
/
OnlineServices_RoomsInterface.cpp
File metadata and controls
1431 lines (1198 loc) · 48.1 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/NGMP_interfaces.h"
#include "GameNetwork/GeneralsOnline/NGMP_include.h"
#include "GameNetwork/GeneralsOnline/NetworkPacket.h"
#include "GameNetwork/GeneralsOnline/NetworkBitstream.h"
#include "GameNetwork/GeneralsOnline/json.hpp"
#include "../OnlineServices_Init.h"
#include "../HTTP/HTTPManager.h"
#include "GameNetwork/GameSpy/PeerDefs.h"
WebSocket::WebSocket()
{
m_pMulti = curl_multi_init();
m_pHeaders = nullptr;
}
WebSocket::~WebSocket()
{
Shutdown();
if (m_pHeaders != nullptr)
{
curl_slist_free_all(m_pHeaders);
m_pHeaders = nullptr;
}
}
int WebSocket::Ping()
{
size_t sent;
CURLcode result = curl_ws_send(m_pCurlWS, "wsping", strlen("wsping"), &sent, 0,
CURLWS_PING);
nlohmann::json j;
j["msg_id"] = EWebSocketMessageID::PING;
std::string strBody = j.dump();
Send(strBody.c_str());
return (int)result;
}
void WebSocket::Connect(const char* url, bool bIsReconnect, std::function<void(void)> fnWebsocketConnectedCallback)
{
if (m_bConnected)
{
return;
}
m_lastPong = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
// TODO_CACHE: Cleanup multi too
if (m_pCurlWS != nullptr)
{
// remove from multi before cleanup (required by libcurl)
if (m_pMulti != nullptr)
{
curl_multi_remove_handle(m_pMulti, m_pCurlWS);
}
// cleanup
curl_easy_cleanup(m_pCurlWS);
m_pCurlWS = nullptr;
}
// Free old headers before creating new ones
if (m_pHeaders != nullptr)
{
curl_slist_free_all(m_pHeaders);
m_pHeaders = nullptr;
}
m_pCurlWS = curl_easy_init();
if (m_pCurlWS != nullptr)
{
m_fnWebsocketConnectedCallback = fnWebsocketConnectedCallback;
int httpResponseCode = -1;
m_strWebsocketAddr = std::string(url);
curl_easy_setopt(m_pCurlWS, CURLOPT_URL, url);
curl_easy_getinfo(m_pCurlWS, CURLINFO_RESPONSE_CODE, &httpResponseCode);
curl_easy_setopt(m_pCurlWS, CURLOPT_CONNECT_ONLY, 2L); /* websocket style */
// HTTP v1 seems to have a higher success rate of bypassing DPI
curl_easy_setopt(m_pCurlWS, CURLOPT_HTTP_VERSION, NGMP_OnlineServicesManager::Settings.Network_GetHTTPVersionForCurl());
#if _DEBUG
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(m_pCurlWS, CURLOPT_VERBOSE, 1L);
#else
if (HTTPManager::IsCACertStoreBad())
{
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYHOST, 0);
}
else
{
std::ifstream certFile("cacert.pem");
if (certFile.good())
{
certFile.close();
curl_easy_setopt(m_pCurlWS, CURLOPT_CAINFO, "cacert.pem");
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYHOST, 2L);
}
else
{
HTTPManager::SetCACertStoreBad();
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(m_pCurlWS, CURLOPT_SSL_VERIFYHOST, 0);
}
}
#endif
// ws needs auth
NGMP_OnlineServices_AuthInterface* pAuthInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_AuthInterface>();
if (pAuthInterface == nullptr)
{
curl_easy_cleanup(m_pCurlWS);
m_pCurlWS = nullptr;
return;
}
char szHeaderBuffer[8192] = { 0 };
sprintf_s(szHeaderBuffer, "Authorization: Bearer %s", pAuthInterface->GetAuthToken().c_str());
m_pHeaders = curl_slist_append(m_pHeaders, szHeaderBuffer);
sprintf_s(szHeaderBuffer, "is-reconnect: %s", bIsReconnect ? "true": "false");
m_pHeaders = curl_slist_append(m_pHeaders, szHeaderBuffer);
curl_easy_setopt(m_pCurlWS, CURLOPT_HTTPHEADER, m_pHeaders);
//curl_easy_setopt(m_pCurl, CURLOPT_TIMEOUT_MS, 1000);
/* Perform the request, res gets the return code */
//CURLcode res = curl_easy_perform(m_pCurl);
curl_multi_add_handle(m_pMulti, m_pCurlWS);
}
}
void WebSocket::SendData_RoomChatMessage(UnicodeString& msg, bool bIsAction)
{
nlohmann::json j;
j["msg_id"] = EWebSocketMessageID::NETWORK_ROOM_CHAT_FROM_CLIENT;
j["message"] = to_utf8(msg.str());
j["action"] = bIsAction;
std::string strBody = j.dump(-1, 32, true);
Send(strBody.c_str());
}
void WebSocket::SendData_MarkReady(bool bReady)
{
nlohmann::json j;
j["msg_id"] = EWebSocketMessageID::NETWORK_ROOM_MARK_READY;
j["ready"] = bReady;
std::string strBody = j.dump();
Send(strBody.c_str());
}
void WebSocket::SendData_JoinNetworkRoom(int roomID)
{
nlohmann::json j;
j["msg_id"] = EWebSocketMessageID::NETWORK_ROOM_CHANGE_ROOM;
j["room"] = roomID;
std::string strBody = j.dump();
Send(strBody.c_str());
}
void WebSocket::Disconnect()
{
if (!m_bConnected)
{
return;
}
if (m_pCurlWS != nullptr)
{
// send close
size_t sent;
(void)curl_ws_send(m_pCurlWS, "", 0, &sent, 0, CURLWS_CLOSE);
// release headers
if (m_pHeaders != nullptr)
{
curl_slist_free_all(m_pHeaders);
m_pHeaders = nullptr;
}
// cleanup
curl_easy_cleanup(m_pCurlWS);
m_pCurlWS = nullptr;
}
m_vecWSPartialBuffer.clear();
m_bConnected = false;
}
void WebSocket::Send(const char* send_payload)
{
if (!AcquireLock())
{
return;
}
if (!m_bConnected)
{
// just queue it instead
m_vecQueuedOutboungMsgs.push_back(std::string(send_payload));
ReleaseLock();
return;
}
size_t sent;
CURLcode result = curl_ws_send(m_pCurlWS, send_payload, strlen(send_payload), &sent, 0, CURLWS_BINARY);
if (result != CURLE_OK)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "curl_ws_send() failed: %s\n", curl_easy_strerror(result));
}
ReleaseLock();
}
class WebSocketMessageBase
{
public:
EWebSocketMessageID msg_id;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessageBase, msg_id)
};
class WebSocketMessage_NetworkStartSignalling : public WebSocketMessageBase
{
public:
int64_t lobby_id;
int64_t user_id;
uint16_t preferred_port;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_NetworkStartSignalling, msg_id, lobby_id, user_id, preferred_port)
};
class WebSocketMessage_NetworkDisconnectPlayer : public WebSocketMessageBase
{
public:
int64_t lobby_id;
int64_t user_id;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_NetworkDisconnectPlayer, msg_id, lobby_id, user_id)
};
class WebSocketMessage_MatchmakingAction_JoinPrearrangedLobby : public WebSocketMessageBase
{
public:
int64_t lobby_id;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_MatchmakingAction_JoinPrearrangedLobby, msg_id, lobby_id)
};
class WebSocketMessage_RoomChatIncoming : public WebSocketMessageBase
{
public:
std::string message;
bool action;
bool admin;
bool name_change;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_RoomChatIncoming, msg_id, message, action, admin, name_change)
};
class WebSocketMessage_Social_FriendChatMessage_Incoming : public WebSocketMessageBase
{
public:
int64_t source_user_id;
int64_t target_user_id;
std::string message;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_Social_FriendChatMessage_Incoming, msg_id, source_user_id, target_user_id, message)
};
class WebSocketMessage_Social_FriendStatusChanged : public WebSocketMessageBase
{
public:
std::string display_name;
bool online;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_Social_FriendStatusChanged, display_name, online)
};
class WebSocketMessage_Social_FriendRequestAccepted : public WebSocketMessageBase
{
public:
std::string display_name;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_Social_FriendRequestAccepted, display_name)
};
class WebSocketMessage_FriendsOverallStatusUpdate : public WebSocketMessageBase
{
public:
int num_online;
int num_pending;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_FriendsOverallStatusUpdate, num_online, num_pending)
};
class WebSocketMessage_NetworkSignal : public WebSocketMessageBase
{
public:
int64_t target_user_id = -1;
std::vector<uint8_t> payload;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_NetworkSignal, target_user_id, payload)
};
class WebSocketMessage_ServerProbe : public WebSocketMessageBase
{
public:
std::string url;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_ServerProbe, msg_id, url)
};
class WebSocketMessage_StartGameResponse : public WebSocketMessageBase
{
public:
std::string screenshot_url;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_StartGameResponse, msg_id, screenshot_url)
};
class WebSocketMessage_LobbyChatIncoming : public WebSocketMessageBase
{
public:
std::string message;
bool action;
bool announcement;
bool show_announcement_to_host;
int64_t user_id;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_LobbyChatIncoming, msg_id, message, action, announcement, show_announcement_to_host, user_id)
};
class WebSocketMessage_MatchmakingMessage : public WebSocketMessageBase
{
public:
std::string message;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_MatchmakingMessage, msg_id, message)
};
class WebSocketMessage_Social_NewFriendRequest : public WebSocketMessageBase
{
public:
std::string display_name;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(WebSocketMessage_Social_NewFriendRequest, msg_id, display_name)
};
static bool JSONDeserialize(const char* szBuffer, nlohmann::json* jsonObject)
{
try
{
*jsonObject = nlohmann::json::parse(szBuffer);
return true;
}
catch (nlohmann::json::exception& jsonException)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "JSONDeserialize: Unparsable JSON: %s (%s)", szBuffer, jsonException.what());
return false;
}
catch (...)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "JSONDeserialize: Unparsable JSON: %s", szBuffer);
return false;
}
return false;
}
template<typename T>
static bool JSONGetAsObject(nlohmann::json& jsonObject, T* outMsg)
{
try
{
*outMsg = jsonObject.get<T>();
return true;
}
catch (nlohmann::json::exception& jsonException)
{
std::string targetTypeName = typeid(T).name();
NetworkLog(ELogVerbosity::LOG_RELEASE, "JSONGetAsObject: Unparsable JSON: Target Type is %s (%s)", targetTypeName.c_str(), jsonException.what());
return false;
}
catch (...)
{
std::string targetTypeName = typeid(T).name();
NetworkLog(ELogVerbosity::LOG_RELEASE, "JSONGetAsObject: Unparsable JSON: Target Type is %s", targetTypeName.c_str());
return false;
}
return false;
}
//static std::string strSignal = "str:1 ";
void WebSocket::Tick()
{
if (!AcquireLock())
{
return;
}
// attempting to reconnect?
if (m_bReconnecting)
{
int64_t currTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
int maxReconnectAttempts = (TheNGMPGame != nullptr && TheNGMPGame->isGameInProgress()) ? maxReconnectAttempts_Ingame : maxReconnectAttempts_Frontend;
if (m_numReconnectAttempts >= maxReconnectAttempts)
{
// fully disconnect
NetworkLog(ELogVerbosity::LOG_RELEASE, "Going to teardown (reconnect 1)");
NGMP_OnlineServicesManager::GetInstance()->SetPendingFullTeardown(EGOTearDownReason::LOST_CONNECTION);
m_bConnected = false;
m_vecWSPartialBuffer.clear();
// clear reconnection flags
m_bReconnecting = false;
m_numReconnectAttempts = 0;
m_lastReconnectAttempt = -1;
}
else
{
int timeBetweenReconnectAttempts = (TheNGMPGame != nullptr && TheNGMPGame->isGameInProgress()) ? timeBetweenReconnectAttempts_Ingame : timeBetweenReconnectAttempts_Frontend;
if (currTime - m_lastReconnectAttempt >= timeBetweenReconnectAttempts)
{
m_lastReconnectAttempt = currTime;
++m_numReconnectAttempts;
Connect(m_strWebsocketAddr.c_str(), true, nullptr);
}
}
}
/*
if (strSignal.length() == 6)
{
for (int i = 0; i < 5000 - 6; ++i)
{
if (i == 5000 - 6 - 1)
{
strSignal += "+";
}
else
{
strSignal += i % 2 == 0 ? 'a' : 'b';
}
}
}
WebSocket* pWS = NGMP_OnlineServicesManager::GetWebSocket();;
pWS->SendData_Signalling(strSignal);
*/
// ping?
int64_t currTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
if ((currTime - m_lastPing) > m_timeBetweenUserPings)
{
m_lastPing = currTime;
Ping();
};
int numReqs = 0;
curl_multi_perform(m_pMulti, &numReqs);
curl_multi_poll(m_pMulti, NULL, 0, 0, NULL);
{
// Check for completed requests (initial connection only)
int msgq = 0;
CURLMsg* m = nullptr;
while ((m = curl_multi_info_read(m_pMulti, &msgq)) != nullptr)
{
if (m->msg == CURLMSG_DONE)
{
CURL* pCurlHandle = m->easy_handle;
if (pCurlHandle == m_pCurlWS) // shouldnt hear about anything else
{
int httpResponseCode = -1;
curl_easy_getinfo(pCurlHandle, CURLINFO_RESPONSE_CODE, &httpResponseCode);
/* Check for errors */
if (m->data.result != CURLE_OK)
{
m_bConnected = false;
m_vecWSPartialBuffer.clear();
NetworkLog(ELogVerbosity::LOG_RELEASE, "[WebSocket] Failed to connect (%d - %s)", m->data.result, curl_easy_strerror(m->data.result));
// reconnecting? give up eventually
if (m_bReconnecting)
{
int maxReconnectAttempts = (TheNGMPGame != nullptr && TheNGMPGame->isGameInProgress()) ? maxReconnectAttempts_Ingame : maxReconnectAttempts_Frontend;
if (m_numReconnectAttempts >= maxReconnectAttempts || (m->data.result == CURLE_HTTP_RETURNED_ERROR && httpResponseCode == 205)) // 205 = need full teardown
{
if (httpResponseCode == 205)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "Going to teardown (reconnect 205)");
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "Going to teardown (reconnect 2)");
}
NGMP_OnlineServicesManager::GetInstance()->SetPendingFullTeardown(EGOTearDownReason::LOST_CONNECTION);
m_bConnected = false;
m_vecWSPartialBuffer.clear();
// clear reconnection flags
m_bReconnecting = false;
m_numReconnectAttempts = 0;
m_lastReconnectAttempt = -1;
}
}
else // give up immediately
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "Going to teardown (initial connect)");
NGMP_OnlineServicesManager::GetInstance()->SetPendingFullTeardown(EGOTearDownReason::LOST_CONNECTION);
m_bConnected = false;
m_vecWSPartialBuffer.clear();
// clear reconnection flags
m_bReconnecting = false;
m_numReconnectAttempts = 0;
m_lastReconnectAttempt = -1;
}
}
else
{
if (m_bReconnecting)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[WebSocket] Re-Connected");
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[WebSocket] Connected");
}
/* connected and ready */
m_bConnected = true;
m_vecWSPartialBuffer.clear();
// clear reconnection flags
m_bReconnecting = false;
m_numReconnectAttempts = 0;
m_lastReconnectAttempt = -1;
// connecting is as good as a pong
m_lastPong = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
if (m_fnWebsocketConnectedCallback != nullptr)
{
m_fnWebsocketConnectedCallback();
}
}
}
}
}
}
if (!m_bConnected)
{
ReleaseLock();
return;
}
// send anything we have buffered (e.g. things that were queued while not connected)
for (std::string& strPayload : m_vecQueuedOutboungMsgs)
{
size_t sent;
CURLcode result = curl_ws_send(m_pCurlWS, strPayload.c_str(), strPayload.length(), &sent, 0, CURLWS_BINARY);
if (result != CURLE_OK)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "curl_ws_send() failed: %s\n", curl_easy_strerror(result));
}
}
m_vecQueuedOutboungMsgs.clear();
// do recv
size_t rlen = 0;
const struct curl_ws_frame* meta = nullptr;
char bufferThisRecv[8196 * 4] = { 0 };
CURLcode ret = CURL_LAST;
ret = curl_ws_recv(m_pCurlWS, bufferThisRecv, sizeof(bufferThisRecv), &rlen, &meta);
if (ret != CURLE_RECV_ERROR && ret != CURL_LAST && ret != CURLE_AGAIN && ret != CURLE_GOT_NOTHING)
{
NetworkLog(ELogVerbosity::LOG_DEBUG, "Got websocket msg: %s", bufferThisRecv);
NetworkLog(ELogVerbosity::LOG_DEBUG, "Got websocket len: %d", rlen);
// what type of message?
if (meta != nullptr)
{
NetworkLog(ELogVerbosity::LOG_DEBUG, "Got websocket flags: %d", meta->flags);
if (meta->flags & CURLWS_PONG) // PONG
{
}
else if (meta->flags & CURLWS_TEXT)
{
bool bMessageComplete = false;
static constexpr size_t MAX_WS_PARTIAL_SIZE = 2 * 1024 * 1024; // 2 MB
if (m_vecWSPartialBuffer.size() + rlen > MAX_WS_PARTIAL_SIZE)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[WebSocket] Partial buffer overflow, discarding message");
m_vecWSPartialBuffer.clear();
return;
}
m_vecWSPartialBuffer.resize(m_vecWSPartialBuffer.size() + rlen);
memcpy_s(m_vecWSPartialBuffer.data() + m_vecWSPartialBuffer.size() - rlen, rlen, bufferThisRecv, rlen);
if (meta->flags & CURLWS_CONT)
{
bMessageComplete = false;
NetworkLog(ELogVerbosity::LOG_DEBUG, "WEBSOCKET PARTIAL (CONT) OF SIZE %d, offset %d, bytes left %d! [MESSAGE COMPLETE: %d]", rlen, meta->offset, meta->bytesleft, bMessageComplete);
}
else if (meta->bytesleft > 0)
{
bMessageComplete = false;
NetworkLog(ELogVerbosity::LOG_DEBUG, "WEBSOCKET PARTIAL (BYTESLEFT) OF SIZE %d, offset %d! [MESSAGE COMPLETE: %d]", rlen, meta->offset, bMessageComplete);
}
else
{
// if we got in here, it's a whole message, or the last part of a fragmented message
bMessageComplete = true;
NetworkLog(ELogVerbosity::LOG_DEBUG, "WEBSOCKET LAST FRAME OF SIZE %d!", rlen);
}
if (bMessageComplete)
{
try
{
// null terminate buffer
m_vecWSPartialBuffer.push_back('\0');
// process it
nlohmann::json jsonObject;
bool bDeserializedOK = JSONDeserialize(m_vecWSPartialBuffer.data(), &jsonObject);
// clear buffer and resize
m_vecWSPartialBuffer.clear();
m_vecWSPartialBuffer.resize(0);
if (bDeserializedOK)
{
if (jsonObject.contains("msg_id"))
{
WebSocketMessageBase msgDetails;
bool bParsedBase = JSONGetAsObject<WebSocketMessageBase>(jsonObject, &msgDetails);
if (bParsedBase)
{
EWebSocketMessageID msgID = msgDetails.msg_id;
switch (msgID)
{
case EWebSocketMessageID::PONG:
{
int64_t currTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
m_lastPong = currTime;
}
break;
case EWebSocketMessageID::NETWORK_ROOM_CHAT_FROM_SERVER:
{
WebSocketMessage_RoomChatIncoming chatData;
bool bParsed = JSONGetAsObject(jsonObject, &chatData);
if (bParsed)
{
SYSTEMTIME systemTime;
GetLocalTime(&systemTime);
UnicodeString unicodeStr;
unicodeStr.format(L"[%2.2d:%2.2d] %s", systemTime.wHour, systemTime.wMinute, from_utf8(chatData.message).c_str());
Color color = DetermineColorForChatMessage(EChatMessageType::CHAT_MESSAGE_TYPE_NETWORK_ROOM, true, chatData.action, chatData.admin, chatData.name_change);
NGMP_OnlineServices_RoomsInterface* pRoomsInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_RoomsInterface>();
if (pRoomsInterface != nullptr && pRoomsInterface->m_OnChatCallback != nullptr)
{
pRoomsInterface->m_OnChatCallback(unicodeStr, color);
}
}
}
break;
case EWebSocketMessageID::SOCIAL_FRIEND_CHAT_MESSAGE_SERVER_TO_CLIENT:
{
WebSocketMessage_Social_FriendChatMessage_Incoming chatData;
bool bParsed = JSONGetAsObject(jsonObject, &chatData);
if (bParsed)
{
UnicodeString unicodeStr(from_utf8(chatData.message).c_str());
NGMP_OnlineServices_SocialInterface* pSocialInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_SocialInterface>();
if (pSocialInterface != nullptr)
{
pSocialInterface->OnChatMessage(chatData.source_user_id, chatData.target_user_id, unicodeStr);
}
}
}
break;
case EWebSocketMessageID::SOCIAL_FRIEND_ONLINE_STATUS_CHANGED:
{
WebSocketMessage_Social_FriendStatusChanged statusChangedData;
bool bParsed = JSONGetAsObject(jsonObject, &statusChangedData);
if (bParsed)
{
NGMP_OnlineServices_SocialInterface* pSocialInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_SocialInterface>();
if (pSocialInterface != nullptr)
{
pSocialInterface->OnOnlineStatusChanged(statusChangedData.display_name, statusChangedData.online);
}
}
}
break;
case EWebSocketMessageID::SOCIAL_FRIEND_FRIEND_REQUEST_ACCEPTED_BY_TARGET:
{
WebSocketMessage_Social_FriendRequestAccepted statusChangedData;
bool bParsed = JSONGetAsObject(jsonObject, &statusChangedData);
if (bParsed)
{
NGMP_OnlineServices_SocialInterface* pSocialInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_SocialInterface>();
if (pSocialInterface != nullptr)
{
pSocialInterface->OnFriendRequestAccepted(statusChangedData.display_name);
}
}
}
break;
case EWebSocketMessageID::SOCIAL_FRIENDS_LIST_DIRTY:
{
// nothing to parse here, it's just an event only
extern void updateBuddyInfo(bool bIsAutoRefresh = false, bool bUseCache = false);
updateBuddyInfo(true);
}
break;
case EWebSocketMessageID::SOCIAL_CANT_ADD_FRIEND_LIST_FULL:
{
// always show this notification, it's tied to a local user action
showNotificationBox(AsciiString::TheEmptyString, UnicodeString(L"Cannot sent friends request. Your friends list is full."));
}
break;
case EWebSocketMessageID::SOCIAL_FRIENDS_OVERALL_STATUS_UPDATE:
{
WebSocketMessage_FriendsOverallStatusUpdate statusUpdateData;
bool bParsed = JSONGetAsObject(jsonObject, &statusUpdateData);
if (bParsed)
{
UnicodeString strFormat = UnicodeString::TheEmptyString;
if (statusUpdateData.num_online > 0 && statusUpdateData.num_pending > 0)
{
strFormat.format(L"You have %d friend(s) online and %d pending friend request(s)", statusUpdateData.num_online, statusUpdateData.num_pending);
}
else if (statusUpdateData.num_online > 0)
{
strFormat.format(L"You have %d friend(s) online.", statusUpdateData.num_online);
}
else if (statusUpdateData.num_pending > 0)
{
strFormat.format(L"You have %d pending friend request(s)", statusUpdateData.num_pending);
}
else
{
strFormat = UnicodeString(L"Press F5 or INSERT to bring up the communicator at any time (including in-game).");
}
// show it on the communicator too
if (statusUpdateData.num_pending > 0)
{
NGMP_OnlineServices_SocialInterface* pSocialInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_SocialInterface>();
if (pSocialInterface != nullptr)
{
pSocialInterface->RegisterInitialPendingRequestsUponLogin(statusUpdateData.num_pending);
}
}
if (!strFormat.isEmpty())
{
// always show this notification
showNotificationBox(AsciiString::TheEmptyString, strFormat);
}
}
}
break;
case EWebSocketMessageID::START_GAME:
{
WebSocketMessage_StartGameResponse startGameData;
bool bParsed = JSONGetAsObject(jsonObject, &startGameData);
if (bParsed)
{
// store URL
NGMP_OnlineServicesManager::GetInstance()->SetScreenshotS3URI_StartMatch(startGameData.screenshot_url.c_str());
}
// always start, even if we couldnt parse the url
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr && pLobbyInterface->m_callbackStartGamePacket != nullptr)
{
pLobbyInterface->m_callbackStartGamePacket();
}
}
break;
case EWebSocketMessageID::FULL_MESH_CONNECTIVITY_CHECK_RESPONSE:
{
// respond with our state
std::vector<int64_t> connectivityMap;
NetworkMesh* pMesh = nullptr;
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr)
{
pMesh = pLobbyInterface->GetNetworkMeshForLobby();
}
if (pMesh != nullptr)
{
for (auto& conn : pMesh->GetAllConnections())
{
int64_t userID = conn.first;
PlayerConnection& playerConn = conn.second;
if (playerConn.GetState() == EConnectionState::CONNECTED_DIRECT)
{
// NOTE: Useful for testing
//if (userID != 1)
{
connectivityMap.push_back(userID);
}
}
}
}
// send response
nlohmann::json j;
j["msg_id"] = EWebSocketMessageID::FULL_MESH_CONNECTIVITY_CHECK_RESPONSE;
j["connectivity_map"] = connectivityMap;
std::string strBody = j.dump();
Send(strBody.c_str());
break;
}
case EWebSocketMessageID::FULL_MESH_CONNECTIVITY_CHECK_RESPONSE_COMPLETE_TO_HOST:
{
// all checks are done, process start for host
bool bMeshComplete = false;
try
{
jsonObject["mesh_complete"].get_to(bMeshComplete);
std::list<std::pair<int64_t, int64_t>> missingConnections;
if (!bMeshComplete)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[FULL_MESH_CONNECTIVITY_CHECK_RESPONSE_COMPLETE_TO_HOST] Mesh is not complete for someone");
for (const auto& missingConnectionEntryIter : jsonObject["missing_connections"])
{
int64_t source_user_id = -1;
int64_t target_user_id = -1;
missingConnectionEntryIter["source_user_id"].get_to(source_user_id);
missingConnectionEntryIter["target_user_id"].get_to(target_user_id);
missingConnections.push_back(std::make_pair(source_user_id, target_user_id));
}
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[FULL_MESH_CONNECTIVITY_CHECK_RESPONSE_COMPLETE_TO_HOST] Mesh is fully complete");
}
// invoke callback
if (m_cbOnConnectivityCheckComplete != nullptr)
{
m_cbOnConnectivityCheckComplete(bMeshComplete, missingConnections);
}
m_cbOnConnectivityCheckComplete = NULL;
}
catch (...)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[FULL_MESH_CONNECTIVITY_CHECK_RESPONSE_COMPLETE_TO_HOST] Error processing response");
break;
}
break;
}
case EWebSocketMessageID::NETWORK_CONNECTION_START_SIGNALLING:
{
WebSocketMessage_NetworkStartSignalling startSignallingData;
bool bParsed = JSONGetAsObject(jsonObject, &startSignallingData);
// TODO_NGMP: Better location for this
// When we find a new player, get their latest stats. Tooltip and loading screen need it, so we'll grab it now and then use cached data later since it cannot possibly change while in a lobby
NGMP_OnlineServices_StatsInterface* pStatsInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_StatsInterface>();
if (pStatsInterface != nullptr)
{
pStatsInterface->findPlayerStatsByID(startSignallingData.user_id, [=](bool bSuccess, PSPlayerStats stats)
{
}, EStatsRequestPolicy::BYPASS_CACHE_FORCE_REQUEST);
}
if (bParsed)
{
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr)
{
NetworkMesh* pMesh = pLobbyInterface->GetNetworkMeshForLobby();
if (pMesh != nullptr)
{
pMesh->StartConnectionSignalling(startSignallingData.user_id, startSignallingData.preferred_port);
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[NETWORK_CONNECTION_START_SIGNALLING] Network mesh is null");
break;
}
}
else
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[NETWORK_CONNECTION_START_SIGNALLING] Lobby interface is null");
break;
}
}
}
break;
case EWebSocketMessageID::NETWORK_CONNECTION_DISCONNECT_PLAYER:
{
WebSocketMessage_NetworkDisconnectPlayer disconnectPlayerData;
bool bParsed = JSONGetAsObject(jsonObject, &disconnectPlayerData);
if (bParsed)
{
NGMP_OnlineServices_LobbyInterface* pLobbyInterface = NGMP_OnlineServicesManager::GetInterface<NGMP_OnlineServices_LobbyInterface>();
if (pLobbyInterface != nullptr)
{
int64_t currentLobbyID = pLobbyInterface->GetCurrentLobby().lobbyID;
if (currentLobbyID == -1 || currentLobbyID != disconnectPlayerData.lobby_id)
{
NetworkLog(ELogVerbosity::LOG_RELEASE, "[NETWORK_CONNECTION_DISCONNECT_PLAYER] Lobby ID mismatch! Expected %lld, got %lld", currentLobbyID, disconnectPlayerData.lobby_id);
break;
}
NetworkMesh* pMesh = pLobbyInterface->GetNetworkMeshForLobby();
if (pMesh != nullptr)
{
pMesh->DisconnectUser(disconnectPlayerData.user_id);
}
else
{