-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscore-server.cpp
More file actions
2866 lines (2434 loc) · 101 KB
/
score-server.cpp
File metadata and controls
2866 lines (2434 loc) · 101 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
// license:GPLv3+
#include "plugins/MsgPlugin.h"
#include "plugins/LoggingPlugin.h"
#include "plugins/ControllerPlugin.h"
#include "plugins/VPXPlugin.h"
#include "plugins/ScriptablePlugin.h"
#include <string>
#include <vector>
#include <fstream>
#include <filesystem>
#include <cstdint>
#include <sstream>
#include <iomanip>
#include <cstdarg>
#include <chrono>
#include <thread>
#include <mutex>
#include <atomic>
#include <cstring>
// For JSON parsing - using a simple JSON parser approach
#include <map>
#include <set>
#include <algorithm>
// WebSocket support
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#undef TEXT
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
typedef int socklen_t;
#include <windows.h>
#define SHUT_RDWR SD_BOTH
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <dlfcn.h>
#include <limits.h>
typedef int SOCKET;
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket close
#endif
///////////////////////////////////////////////////////////////////////////////
// Minimal portable UDP sockets
// Derived from https://github.com/simondlevy/CppSockets (MIT licensed)
#ifndef _WIN32
#define sprintf_s snprintf
#endif
class UdpClientSocket
{
protected:
SOCKET _sock;
struct sockaddr_in _si_other {};
socklen_t _slen = sizeof(_si_other);
char _message[200];
bool initWinsock()
{
// Winsock initialization is handled by PluginLoad/PluginUnload
return true;
}
void inetPton(const char* host, struct sockaddr_in& saddr_in)
{
#ifdef _WIN32
#ifdef _UNICODE
InetPtonA(AF_INET, host, &(saddr_in.sin_addr.s_addr));
#else
InetPton(AF_INET, host, &(saddr_in.sin_addr.s_addr));
#endif
#else
inet_pton(AF_INET, host, &(saddr_in.sin_addr));
#endif
}
public:
UdpClientSocket(const char* host, const short port)
{
_sock = INVALID_SOCKET;
_message[0] = '\0';
// Initialize Winsock, returning on failure
if (!initWinsock())
return;
// Create socket
_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (_sock == SOCKET_ERROR)
{
sprintf_s(_message, sizeof(_message), "socket() failed");
_sock = INVALID_SOCKET;
return;
}
// Setup address structure
memset((char*)&_si_other, 0, sizeof(_si_other));
_si_other.sin_family = AF_INET;
_si_other.sin_port = htons(port);
inetPton(host, _si_other);
}
~UdpClientSocket()
{
if (_sock != INVALID_SOCKET)
{
closesocket(_sock);
}
}
int sendData(const void* buf, size_t len)
{
if (_sock == INVALID_SOCKET)
return -1;
return sendto(_sock, (const char*)buf, (int)len, 0, (struct sockaddr*)&_si_other, (int)_slen);
}
bool isValid() const { return _sock != INVALID_SOCKET; }
const char* getMessage() const { return _message; }
};
namespace ScoreServer {
const MsgPluginAPI* msgApi = nullptr;
VPXPluginAPI* vpxApi = nullptr;
ScriptablePluginAPI* scriptApi = nullptr;
uint32_t endpointId;
unsigned int getVpxApiId, getScriptApiId, getControllerId, onGameEndId, onGameStartId, onPrepareFrameId;
// Plugin settings
MSGPI_STRING_VAL_SETTING(machineIdProp, "MachineId", "Machine ID", "Unique identifier for this machine", false, "", 256);
// Broadcast mode configuration
const char* broadcastModeLiterals[] = { "WebSocket", "UDP", "Both" };
MSGPI_ENUM_VAL_SETTING(broadcastModeProp, "BroadcastMode", "Broadcast Mode", "Select broadcast method: WebSocket server, UDP endpoint, or Both", false, 1, 3, broadcastModeLiterals, 1);
MSGPI_STRING_VAL_SETTING(udpHostProp, "UdpHost", "UDP Host", "UDP endpoint hostname or IP address (e.g., 192.168.1.100)", false, "", 256);
MSGPI_INT_VAL_SETTING(udpPortProp, "UdpPort", "UDP Port", "UDP endpoint port number (e.g., 9000)", false, 0, 65535, 0);
// UDP client for endpoint broadcasting
UdpClientSocket* udpClient = nullptr;
std::string currentRomName;
std::string nvramMapsPath;
std::string currentMapPath;
std::vector<uint8_t> nvramData;
size_t nvramBaseAddress = 0; // NVRAM base address from platform file
bool nvramFromController = false; // True if NVRAM came from Controller (flat memory), false if from disk (.nv file)
bool nvramHighNibbleOnly = false; // True if NVRAM uses only high nibble (e.g., Bally games)
// TODO: To get NVRAM directly from the Controller, we need the PinMAME plugin to expose
// the Controller object pointer via a message or event. For now, this remains nullptr
// and we fall back to reading from disk files.
void* pinmameController = nullptr; // Pointer to PinMAME Controller object (not currently available)
// Previous game state for change detection
std::vector<std::string> previousScores;
int previousPlayerCount = 0;
int previousCurrentPlayer = 0;
int previousCurrentBall = 0;
bool previousGameOver = false;
bool gameEndSent = false;
bool firstStateCheck = true;
// Game start timestamp for minimum duration check
std::chrono::steady_clock::time_point gameStartTime;
// Sometimes the game_start and game_end events are fired during the
// initialization of the table/plugin. To avoid false positives, we will
// ignore any game that ends within 60 seconds of starting, as it's unlikely to be a valid play session.
// Minimum 60 seconds for a valid game
// Not sure if this could be related to the plugins being still on hard development.
const std::chrono::seconds MIN_GAME_DURATION(60);
// Ball-drop fallback game-over detection
// Stores the scores from the last game_end we sent, so we don't re-trigger
// for the same scores lingering in attract mode after a game ends
std::vector<std::string> lastGameEndScores;
// WebSocket server
std::atomic<bool> wsServerRunning{false};
std::thread wsServerThread;
SOCKET wsServerSocket = INVALID_SOCKET;
std::vector<SOCKET> wsClients;
std::mutex wsClientsMutex;
// Message queue for initial 60 seconds
std::vector<std::string> messageQueue;
std::mutex messageQueueMutex;
std::chrono::steady_clock::time_point serverStartTime;
const std::chrono::seconds MESSAGE_QUEUE_DURATION(60);
PSC_USE_ERROR();
PSC_ERROR_IMPLEMENT(scriptApi);
LPI_IMPLEMENT // Implement shared log support
#define LOGD LPI_LOGD
#define LOGI LPI_LOGI
#define LOGW LPI_LOGW
#define LOGE LPI_LOGE
// Get current timestamp in ISO 8601 format
std::string getTimestamp() {
auto now = std::chrono::system_clock::now();
auto time_t_now = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000;
std::stringstream ss;
ss << std::put_time(std::gmtime(&time_t_now), "%Y-%m-%dT%H:%M:%S");
ss << '.' << std::setfill('0') << std::setw(3) << ms.count() << 'Z';
return ss.str();
}
///////////////////////////////////////////////////////////////////////////////
// Forward declarations
void broadcastWebSocket(const std::string& message);
// Helper to add machine_id field to JSON messages if configured
std::string addMachineIdField() {
const char* machineId = machineIdProp_Get();
if (machineId && machineId[0] != '\0') {
return std::string(",\"machine_id\":\"") + machineId + "\"";
}
return "";
}
///////////////////////////////////////////////////////////////////////////////
// Scriptable table state (for ROM-less tables)
struct TableScore {
int player;
std::string score;
int ball;
};
struct TableHighScore {
std::string label;
std::string initials;
std::string score;
};
std::vector<TableScore> tableScores;
std::vector<TableHighScore> tableHighScores;
std::string tableGameName; // For ROM-less tables
int tablePlayerCount = 0;
int tableCurrentPlayer = 0;
int tableCurrentBall = 0;
std::mutex tableStateMutex; // Protect table state from concurrent access
// Broadcast table scores via WebSocket
void broadcastTableScores() {
std::lock_guard<std::mutex> lock(tableStateMutex);
if (tableGameName.empty()) return;
std::stringstream jsonOutput;
jsonOutput << "{\"type\":\"current_scores\","
<< "\"timestamp\":\"" << getTimestamp() << "\","
<< "\"rom\":\"" << tableGameName << "\""
<< addMachineIdField() << ","
<< "\"players\":" << tablePlayerCount << ","
<< "\"current_player\":" << tableCurrentPlayer << ","
<< "\"current_ball\":" << tableCurrentBall << ","
<< "\"scores\":[";
for (size_t i = 0; i < tableScores.size(); i++) {
if (i > 0) jsonOutput << ",";
jsonOutput << "{\"player\":\"Player " << tableScores[i].player << "\","
<< "\"score\":\"" << tableScores[i].score << "\"}";
}
jsonOutput << "]}";
broadcastWebSocket(jsonOutput.str());
}
// Broadcast table high scores via WebSocket
void broadcastTableHighScores() {
std::lock_guard<std::mutex> lock(tableStateMutex);
if (tableGameName.empty()) return;
std::stringstream jsonOutput;
jsonOutput << "{\"type\":\"high_scores\","
<< "\"timestamp\":\"" << getTimestamp() << "\","
<< "\"rom\":\"" << tableGameName << "\""
<< addMachineIdField() << ","
<< "\"scores\":[";
for (size_t i = 0; i < tableHighScores.size(); i++) {
if (i > 0) jsonOutput << ",";
jsonOutput << "{\"label\":\"" << tableHighScores[i].label << "\","
<< "\"initials\":\"" << tableHighScores[i].initials << "\","
<< "\"score\":\"" << tableHighScores[i].score << "\"}";
}
jsonOutput << "]}";
broadcastWebSocket(jsonOutput.str());
}
// Broadcast a single badge via WebSocket
void broadcastBadge(const std::string& player, const std::string& name, const std::string& description) {
std::lock_guard<std::mutex> lock(tableStateMutex);
if (tableGameName.empty()) return;
std::stringstream jsonOutput;
jsonOutput << "{\"type\":\"badge\","
<< "\"timestamp\":\"" << getTimestamp() << "\","
<< "\"rom\":\"" << tableGameName << "\""
<< addMachineIdField() << ","
<< "\"player\":\"" << player << "\","
<< "\"name\":\"" << name << "\","
<< "\"description\":\"" << description << "\"}";
broadcastWebSocket(jsonOutput.str());
}
///////////////////////////////////////////////////////////////////////////////
// WebSocket implementation
// Base64 encoding for WebSocket handshake
static const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode(const unsigned char* data, size_t len) {
std::string ret;
int i = 0;
unsigned char array_3[3];
unsigned char array_4[4];
while (len--) {
array_3[i++] = *(data++);
if (i == 3) {
array_4[0] = (array_3[0] & 0xfc) >> 2;
array_4[1] = ((array_3[0] & 0x03) << 4) + ((array_3[1] & 0xf0) >> 4);
array_4[2] = ((array_3[1] & 0x0f) << 2) + ((array_3[2] & 0xc0) >> 6);
array_4[3] = array_3[2] & 0x3f;
for(i = 0; i < 4; i++)
ret += base64_chars[array_4[i]];
i = 0;
}
}
if (i) {
for(int j = i; j < 3; j++)
array_3[j] = '\0';
array_4[0] = (array_3[0] & 0xfc) >> 2;
array_4[1] = ((array_3[0] & 0x03) << 4) + ((array_3[1] & 0xf0) >> 4);
array_4[2] = ((array_3[1] & 0x0f) << 2) + ((array_3[2] & 0xc0) >> 6);
for (int j = 0; j < i + 1; j++)
ret += base64_chars[array_4[j]];
while(i++ < 3)
ret += '=';
}
return ret;
}
// SHA-1 hash for WebSocket handshake
void sha1(const std::string& input, unsigned char output[20]) {
// Simplified SHA-1 implementation
uint32_t h0 = 0x67452301;
uint32_t h1 = 0xEFCDAB89;
uint32_t h2 = 0x98BADCFE;
uint32_t h3 = 0x10325476;
uint32_t h4 = 0xC3D2E1F0;
std::vector<uint8_t> msg(input.begin(), input.end());
size_t ml = msg.size() * 8;
msg.push_back(0x80);
while ((msg.size() % 64) != 56) {
msg.push_back(0);
}
for (int i = 7; i >= 0; i--) {
msg.push_back((ml >> (i * 8)) & 0xFF);
}
for (size_t chunk = 0; chunk < msg.size(); chunk += 64) {
uint32_t w[80];
for (int i = 0; i < 16; i++) {
w[i] = (msg[chunk + i*4] << 24) | (msg[chunk + i*4 + 1] << 16) |
(msg[chunk + i*4 + 2] << 8) | msg[chunk + i*4 + 3];
}
for (int i = 16; i < 80; i++) {
uint32_t temp = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
w[i] = (temp << 1) | (temp >> 31);
}
uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
for (int i = 0; i < 80; i++) {
uint32_t f, k;
if (i < 20) {
f = (b & c) | ((~b) & d);
k = 0x5A827999;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
} else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
uint32_t temp = ((a << 5) | (a >> 27)) + f + e + k + w[i];
e = d;
d = c;
c = (b << 30) | (b >> 2);
b = a;
a = temp;
}
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
for (int i = 0; i < 4; i++) {
output[i] = (h0 >> (24 - i * 8)) & 0xFF;
output[i + 4] = (h1 >> (24 - i * 8)) & 0xFF;
output[i + 8] = (h2 >> (24 - i * 8)) & 0xFF;
output[i + 12] = (h3 >> (24 - i * 8)) & 0xFF;
output[i + 16] = (h4 >> (24 - i * 8)) & 0xFF;
}
}
// Send WebSocket frame
void sendWebSocketFrame(SOCKET sock, const std::string& message) {
std::vector<uint8_t> frame;
frame.push_back(0x81); // FIN + text frame
size_t len = message.size();
if (len < 126) {
frame.push_back(static_cast<uint8_t>(len));
} else if (len < 65536) {
frame.push_back(126);
frame.push_back((len >> 8) & 0xFF);
frame.push_back(len & 0xFF);
} else {
frame.push_back(127);
for (int i = 7; i >= 0; i--) {
frame.push_back((len >> (i * 8)) & 0xFF);
}
}
frame.insert(frame.end(), message.begin(), message.end());
send(sock, reinterpret_cast<const char*>(frame.data()), frame.size(), 0);
}
// Broadcast to all WebSocket clients
void broadcastWebSocket(const std::string& message) {
// Send via UDP if UDP mode is enabled
int broadcastMode = broadcastModeProp_Val; // 1=WebSocket, 2=UDP, 3=Both
if ((broadcastMode == 2 || broadcastMode == 3) && udpClient && udpClient->isValid()) {
int sent = udpClient->sendData(message.c_str(), message.length());
if (sent < 0) {
LOGW("Failed to send UDP message");
} else {
LOGI("UDP message sent: %d bytes", sent);
}
} else if (broadcastMode == 2 || broadcastMode == 3) {
LOGW("UDP mode enabled but udpClient is not valid (client=%p, valid=%d)",
udpClient, udpClient ? udpClient->isValid() : 0);
}
// If UDP-only mode, skip WebSocket broadcasting
if (broadcastMode == 2) {
return;
}
std::lock_guard<std::mutex> lock(wsClientsMutex);
// Check if we're within the message queuing window (first 60 seconds)
auto now = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - serverStartTime);
bool withinQueueWindow = elapsed < MESSAGE_QUEUE_DURATION;
// If past queue window and queue is not empty, clear it
if (!withinQueueWindow) {
std::lock_guard<std::mutex> queueLock(messageQueueMutex);
if (!messageQueue.empty()) {
LOGI("Message queue window expired - clearing %zu queued messages", messageQueue.size());
messageQueue.clear();
}
}
// If no clients connected and within queue window, queue the message
if (wsClients.empty() && withinQueueWindow) {
std::lock_guard<std::mutex> queueLock(messageQueueMutex);
messageQueue.push_back(message);
LOGI("No clients connected - queued message (%zu messages in queue, %lld seconds elapsed)",
messageQueue.size(), elapsed.count());
return;
}
// If no clients and past queue window, just drop the message
if (wsClients.empty()) {
return;
}
// Build the frame once for all clients
std::vector<uint8_t> frame;
frame.push_back(0x81); // FIN + text frame
size_t len = message.size();
if (len < 126) {
frame.push_back(static_cast<uint8_t>(len));
} else if (len < 65536) {
frame.push_back(126);
frame.push_back((len >> 8) & 0xFF);
frame.push_back(len & 0xFF);
} else {
frame.push_back(127);
for (int i = 7; i >= 0; i--) {
frame.push_back((len >> (i * 8)) & 0xFF);
}
}
frame.insert(frame.end(), message.begin(), message.end());
// Send to all clients and collect dead ones
std::vector<SOCKET> deadSockets;
for (SOCKET client : wsClients) {
// Validate socket before sending
if (client == INVALID_SOCKET) {
deadSockets.push_back(client);
continue;
}
// Send with error checking - use MSG_NOSIGNAL on Unix to prevent SIGPIPE
int flags = 0;
#ifndef _WIN32
flags = MSG_NOSIGNAL;
#endif
int result = send(client, reinterpret_cast<const char*>(frame.data()), static_cast<int>(frame.size()), flags);
if (result == SOCKET_ERROR || result <= 0) {
// Client disconnected or error
#ifdef _WIN32
int error = WSAGetLastError();
LOGI("Client send failed (WSAError: %d), marking for removal", error);
#else
LOGI("Client send failed (errno: %d), marking for removal", errno);
#endif
deadSockets.push_back(client);
}
}
// Remove dead clients outside the iteration
if (!deadSockets.empty()) {
// Sort and remove duplicates (in case same socket was marked dead multiple times)
std::sort(deadSockets.begin(), deadSockets.end());
deadSockets.erase(std::unique(deadSockets.begin(), deadSockets.end()), deadSockets.end());
for (SOCKET deadSocket : deadSockets) {
auto it = std::find(wsClients.begin(), wsClients.end(), deadSocket);
if (it != wsClients.end()) {
closesocket(*it);
wsClients.erase(it);
}
}
LOGI("Removed %zu disconnected client(s), %zu clients remain", deadSockets.size(), wsClients.size());
}
}
// Get the plugin installation directory
std::string GetPluginDirectory() {
#ifdef _WIN32
HMODULE hm = nullptr;
if (GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR)"ScoreServerPluginLoad", &hm) == 0)
return "";
char path[MAX_PATH];
if (GetModuleFileNameA(hm, path, MAX_PATH) == 0)
return "";
std::string pathStr(path);
size_t pos = pathStr.find_last_of("\\/");
if (pos != std::string::npos)
return pathStr.substr(0, pos);
return "";
#else
Dl_info info{};
if (dladdr((void*)&GetPluginDirectory, &info) == 0 || !info.dli_fname)
return "";
char realBuf[PATH_MAX];
if (!realpath(info.dli_fname, realBuf))
return "";
std::string pathStr(realBuf);
size_t pos = pathStr.find_last_of('/');
if (pos != std::string::npos)
return pathStr.substr(0, pos);
return "";
#endif
}
// Simple JSON value class for parsing
struct JsonValue {
enum Type { STRING, NUMBER, OBJECT, ARRAY, BOOLEAN, NULL_TYPE };
Type type;
std::string strValue;
int64_t numValue;
std::map<std::string, JsonValue*> objValue;
std::vector<JsonValue*> arrayValue;
bool boolValue;
JsonValue() : type(NULL_TYPE), numValue(0), boolValue(false) {}
~JsonValue() {
for (auto& p : objValue)
delete p.second;
for (auto& v : arrayValue)
delete v;
}
const JsonValue* get(const char* key) const {
auto it = objValue.find(key);
return (it != objValue.end()) ? it->second : nullptr;
}
const JsonValue* at(size_t index) const {
return (index < arrayValue.size()) ? arrayValue[index] : nullptr;
}
};
// Simple JSON parser
class SimpleJsonParser {
private:
const char* pos;
const char* end;
void skipWhitespace() {
while (pos < end && (*pos == ' ' || *pos == '\t' || *pos == '\n' || *pos == '\r'))
pos++;
}
std::string parseString() {
if (*pos != '"') return "";
pos++; // skip opening quote
std::string result;
while (pos < end && *pos != '"') {
if (*pos == '\\' && pos + 1 < end) {
pos++;
switch (*pos) {
case 'n': result += '\n'; break;
case 't': result += '\t'; break;
case 'r': result += '\r'; break;
case '\\': result += '\\'; break;
case '"': result += '"'; break;
case 'u': // Unicode escape - simplified handling
pos += 4; // skip the 4 hex digits
result += '?'; // placeholder
break;
default: result += *pos; break;
}
} else {
result += *pos;
}
pos++;
}
if (pos < end) pos++; // skip closing quote
return result;
}
int64_t parseNumber() {
int64_t result = 0;
bool negative = false;
if (*pos == '-') {
negative = true;
pos++;
}
while (pos < end && *pos >= '0' && *pos <= '9') {
result = result * 10 + (*pos - '0');
pos++;
}
// Skip decimal part if present (we only need integers for offsets)
if (pos < end && *pos == '.') {
pos++;
while (pos < end && *pos >= '0' && *pos <= '9')
pos++;
}
return negative ? -result : result;
}
JsonValue* parseValue();
JsonValue* parseObject() {
JsonValue* obj = new JsonValue();
obj->type = JsonValue::OBJECT;
pos++; // skip {
skipWhitespace();
while (pos < end && *pos != '}') {
skipWhitespace();
if (*pos == '}') break;
if (*pos != '"') {
delete obj;
return nullptr;
}
std::string key = parseString();
skipWhitespace();
if (pos >= end || *pos != ':') {
delete obj;
return nullptr;
}
pos++; // skip :
skipWhitespace();
JsonValue* value = parseValue();
if (!value) {
delete obj;
return nullptr;
}
obj->objValue[key] = value;
skipWhitespace();
if (pos < end && *pos == ',') {
pos++;
skipWhitespace();
}
}
if (pos < end) pos++; // skip }
return obj;
}
JsonValue* parseArray() {
JsonValue* arr = new JsonValue();
arr->type = JsonValue::ARRAY;
pos++; // skip [
skipWhitespace();
while (pos < end && *pos != ']') {
skipWhitespace();
if (*pos == ']') break;
JsonValue* value = parseValue();
if (!value) {
delete arr;
return nullptr;
}
arr->arrayValue.push_back(value);
skipWhitespace();
if (pos < end && *pos == ',') {
pos++;
skipWhitespace();
}
}
if (pos < end) pos++; // skip ]
return arr;
}
public:
JsonValue* parse(const std::string& json) {
pos = json.c_str();
end = pos + json.length();
skipWhitespace();
return parseValue();
}
};
JsonValue* SimpleJsonParser::parseValue() {
skipWhitespace();
if (pos >= end) return nullptr;
if (*pos == '"') {
JsonValue* v = new JsonValue();
v->type = JsonValue::STRING;
v->strValue = parseString();
return v;
}
else if (*pos == '{') {
return parseObject();
}
else if (*pos == '[') {
return parseArray();
}
else if (*pos == 't' || *pos == 'f') {
JsonValue* v = new JsonValue();
v->type = JsonValue::BOOLEAN;
if (*pos == 't') {
v->boolValue = true;
pos += 4; // skip "true"
} else {
v->boolValue = false;
pos += 5; // skip "false"
}
return v;
}
else if (*pos == 'n') {
JsonValue* v = new JsonValue();
v->type = JsonValue::NULL_TYPE;
pos += 4; // skip "null"
return v;
}
else if (*pos == '-' || (*pos >= '0' && *pos <= '9')) {
JsonValue* v = new JsonValue();
v->type = JsonValue::NUMBER;
v->numValue = parseNumber();
return v;
}
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////
// WebSocket Server
void webSocketServerThread() {
LOGI("WebSocket server thread starting...");
// Winsock initialization is handled by PluginLoad/PluginUnload
wsServerSocket = socket(AF_INET, SOCK_STREAM, 0);
if (wsServerSocket == INVALID_SOCKET) {
LOGE("Failed to create WebSocket server socket");
return;
}
// Set socket options for reliability
int opt = 1;
setsockopt(wsServerSocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&opt), sizeof(opt));
#ifndef _WIN32
// On Linux, also set SO_REUSEPORT to allow immediate rebind
setsockopt(wsServerSocket, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt));
#endif
// Enable TCP keepalive
setsockopt(wsServerSocket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<const char*>(&opt), sizeof(opt));
// Set SO_LINGER to 0 for immediate close without TIME_WAIT
linger lin{};
lin.l_onoff = 1;
lin.l_linger = 0;
setsockopt(wsServerSocket, SOL_SOCKET, SO_LINGER, reinterpret_cast<const char*>(&lin), sizeof(lin));
sockaddr_in serverAddr{};
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(3131);
if (bind(wsServerSocket, reinterpret_cast<sockaddr*>(&serverAddr), sizeof(serverAddr)) == SOCKET_ERROR) {
#ifdef _WIN32
LOGE("Failed to bind WebSocket server to port 3131 (WSAError: %d)", WSAGetLastError());
#else
LOGE("Failed to bind WebSocket server to port 3131 (errno: %d)", errno);
#endif
closesocket(wsServerSocket);
wsServerSocket = INVALID_SOCKET;
return;
}
if (listen(wsServerSocket, 5) == SOCKET_ERROR) {
#ifdef _WIN32
LOGE("Failed to listen on WebSocket server socket (WSAError: %d)", WSAGetLastError());
#else
LOGE("Failed to listen on WebSocket server socket (errno: %d)", errno);
#endif
closesocket(wsServerSocket);
wsServerSocket = INVALID_SOCKET;
return;
}
LOGI("WebSocket server listening on 0.0.0.0:3131 (all network interfaces)");
while (wsServerRunning) {
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(wsServerSocket, &readfds);
timeval timeout{};
timeout.tv_sec = 0;
timeout.tv_usec = 100000; // 100ms - responsive to new connections
int activity = select(wsServerSocket + 1, &readfds, nullptr, nullptr, &timeout);
if (activity < 0 || !wsServerRunning) break;
if (activity == 0) continue;
if (!wsServerRunning) break; // Check before accept() to avoid operating on closed socket
if (FD_ISSET(wsServerSocket, &readfds)) {
sockaddr_in clientAddr{};
socklen_t clientLen = sizeof(clientAddr);
SOCKET clientSocket = accept(wsServerSocket, reinterpret_cast<sockaddr*>(&clientAddr), &clientLen);
if (clientSocket == INVALID_SOCKET) {
// Accept failed - log and continue
#ifdef _WIN32
LOGW("accept() failed (WSAError: %d)", WSAGetLastError());
#else
LOGW("accept() failed (errno: %d)", errno);
#endif
continue;
}
LOGI("New WebSocket connection from %s", inet_ntoa(clientAddr.sin_addr));
bool handshakeSuccess = false;
// Set socket options for client connection
int opt = 1;
if (setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&opt), sizeof(opt)) != 0) {
LOGW("Failed to set TCP_NODELAY");
}
// Set SO_LINGER to 0 for immediate close
linger clientLin{};
clientLin.l_onoff = 1;
clientLin.l_linger = 0;
if (setsockopt(clientSocket, SOL_SOCKET, SO_LINGER, reinterpret_cast<const char*>(&clientLin), sizeof(clientLin)) != 0) {
LOGW("Failed to set SO_LINGER");
}
// Set receive timeout to avoid hanging
timeval recvTimeout{};
recvTimeout.tv_sec = 5; // 5 second timeout for handshake
recvTimeout.tv_usec = 0;
if (setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&recvTimeout), sizeof(recvTimeout)) != 0) {
LOGW("Failed to set SO_RCVTIMEO");
}
// Read HTTP upgrade request (may need multiple recv calls for slow clients)
char buffer[4096] = {0};
int totalBytesRead = 0;
int bytesRead = 0;
// Read until we have the complete handshake (ends with \r\n\r\n)
do {
bytesRead = recv(clientSocket, buffer + totalBytesRead, sizeof(buffer) - totalBytesRead - 1, 0);
if (bytesRead > 0) {
totalBytesRead += bytesRead;
buffer[totalBytesRead] = '\0';
// Check if we have the complete handshake
if (strstr(buffer, "\r\n\r\n") != nullptr) {
break;
}
} else {
break; // Error or connection closed
}
} while (totalBytesRead < (int)sizeof(buffer) - 1);
if (totalBytesRead > 0) {
std::string request(buffer);
// Extract Sec-WebSocket-Key
size_t keyPos = request.find("Sec-WebSocket-Key: ");
if (keyPos != std::string::npos) {
keyPos += 19;
size_t keyEnd = request.find("\r\n", keyPos);
if (keyEnd != std::string::npos) {
std::string key = request.substr(keyPos, keyEnd - keyPos);
// Generate accept key
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
unsigned char hash[20];
sha1(key, hash);
std::string acceptKey = base64_encode(hash, 20);
// Send WebSocket handshake response
std::string response =
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"