-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathddnet_control.cpp
More file actions
2082 lines (1821 loc) · 74.3 KB
/
Copy pathddnet_control.cpp
File metadata and controls
2082 lines (1821 loc) · 74.3 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 <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
#include <chrono>
#include <ctime>
#include <algorithm>
#include <memory>
#include <thread>
#include <sstream>
#include <cstdio>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <tlhelp32.h>
#include <shellapi.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <objbase.h>
#include <cctype>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "ole32.lib")
namespace fs = std::filesystem;
// Undefine Windows macros that clash with enum names
#ifdef ERROR
#undef ERROR
#endif
#ifdef WARNING
#undef WARNING
#endif
#ifdef DEBUG
#undef DEBUG
#endif
// Logger class for consistent logging throughout the application
class Logger {
public:
enum class Level {
DEBUG,
INFO,
WARNING,
ERROR
};
// Convenience aliases so existing calls like Logger::ERROR work
static constexpr Level DEBUG = Level::DEBUG;
static constexpr Level INFO = Level::INFO;
static constexpr Level WARNING = Level::WARNING;
static constexpr Level ERROR = Level::ERROR;
static void log(Level level, const std::string& message) {
std::string level_str;
switch (level) {
case Level::DEBUG: level_str = "DEBUG"; break;
case Level::INFO: level_str = "INFO"; break;
case Level::WARNING: level_str = "WARNING"; break;
case Level::ERROR: level_str = "ERROR"; break;
}
auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
std::string timestamp = std::ctime(&time);
timestamp = timestamp.substr(0, timestamp.length() - 1); // Remove newline
std::string log_message = "[" + timestamp + "] [" + level_str + "] " + message;
// Log to file only (no console output for GUI app)
// Log to file in %APPDATA%/DDNet/maps
static std::ofstream log_file;
if (!log_file.is_open()) {
// Resolve %APPDATA%/DDNet/maps and ensure it exists
char* appDataPath = nullptr; size_t alen = 0;
std::string logPath = "ddnet_control.log"; // fallback
if (_dupenv_s(&appDataPath, &alen, "APPDATA") == 0 && appDataPath) {
try {
fs::path mapsPath = fs::path(appDataPath) / "DDNet" / "maps";
free(appDataPath); appDataPath = nullptr;
std::error_code ec;
if (!fs::exists(mapsPath, ec)) {
fs::create_directories(mapsPath, ec);
}
if (!ec) {
logPath = (mapsPath / "ddnet_control.log").string();
}
} catch (...) {
if (appDataPath) free(appDataPath);
}
}
log_file.open(logPath, std::ios::app);
}
if (log_file.is_open()) {
log_file << log_message << std::endl;
log_file.flush();
}
}
private:
Logger() {} // Prevent instantiation
};
// RAII helper for Winsock initialization
class WsaSession {
public:
bool ok;
WsaSession() : ok(false) {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) == 0) {
ok = true;
} else {
ok = false;
}
}
~WsaSession() {
if (ok) {
WSACleanup();
}
}
};
struct MapInfo {
std::string originalMap; // Original map name before any replacements
std::string backupPath; // Path to original backup
std::string ddnetPath; // Path to new map being used for replacement
};
// Forward declarations
bool set_socket_timeout(SOCKET sock, int timeout_ms);
bool send_command(SOCKET sock, const std::string& command);
bool receive_responses(SOCKET sock, std::vector<std::string>& responses, int timeout_ms = 2000);
bool authenticate(SOCKET sock);
std::string get_current_map(SOCKET sock);
std::string get_maps_directory();
bool file_exists(const std::string& path);
std::string get_map_name(const std::string& path);
bool copy_map_to_server(const std::string& mapPath, SOCKET sock);
bool change_map(SOCKET sock, const std::string& mapName);
bool verify_hot_reload(SOCKET sock, const std::string& expected_map);
bool is_valid_map_file(const fs::path& mapPath, std::string& error);
bool replace_map(MapInfo& mapInfo, SOCKET sock);
bool restore_backup(SOCKET sock);
bool hot_reload_map(SOCKET sock);
SOCKET create_and_connect_socket();
void print_usage(const char* program_name);
bool verify_file_association();
bool verify_permissions(const std::string& path);
bool is_sync_types_command(int argc, char* argv[]);
std::string get_sync_types_mode(int argc, char* argv[]);
int run_sync_types_command(int argc, char* argv[]);
void trigger_background_testing_sync_if_due();
bool send_command(SOCKET sock, const std::string& command);
bool receive_responses(SOCKET sock, std::vector<std::string>& responses, int timeoutMs);
std::vector<std::string> get_responses(SOCKET sock, int maxResponses, int timeoutMs);
// ===== Helpers for lastmapname.txt handling =====
static std::string get_lastmap_file_path() {
std::string mapsDir = get_maps_directory();
if (mapsDir.empty()) return "";
fs::path p = fs::path(mapsDir) / "lastmapname.txt";
return p.string();
}
static bool parse_lastmap_line(const std::string& line, std::string& last_new_map, std::string& last_current_map) {
// Format: "new_map"(current_map)
size_t q1 = line.find('"');
if (q1 == std::string::npos) return false;
size_t q2 = line.find('"', q1 + 1);
if (q2 == std::string::npos || q2 == q1 + 1) return false;
size_t lpar = line.find('(', q2 + 1);
size_t rpar = line.find(')', lpar + 1);
if (lpar == std::string::npos || rpar == std::string::npos || rpar <= lpar + 1) return false;
last_new_map = line.substr(q1 + 1, q2 - q1 - 1);
last_current_map = line.substr(lpar + 1, rpar - lpar - 1);
// trim spaces
auto trim = [](std::string& s){
if (s.empty()) return;
s.erase(0, s.find_first_not_of(" \t\r\n"));
if (!s.empty()) s.erase(s.find_last_not_of(" \t\r\n") + 1);
};
trim(last_new_map);
trim(last_current_map);
return !last_new_map.empty() && !last_current_map.empty();
}
static void read_lastmap(std::string& last_new_map, std::string& last_current_map) {
last_new_map.clear();
last_current_map.clear();
std::string path = get_lastmap_file_path();
if (path.empty()) return;
std::ifstream f(path);
if (!f.is_open()) return;
std::string line;
std::getline(f, line);
parse_lastmap_line(line, last_new_map, last_current_map);
}
static bool write_lastmap(const std::string& new_map, const std::string& current_map) {
std::string path = get_lastmap_file_path();
if (path.empty()) return false;
std::ofstream f(path, std::ios::trunc);
if (!f.is_open()) return false;
f << '"' << new_map << '"' << '(' << current_map << ')';
return true;
}
static void clear_lastmap() {
std::string path = get_lastmap_file_path();
if (path.empty()) return;
std::ofstream f(path, std::ios::trunc);
}
// Save backup info to a file
void save_backup_info(const MapInfo& mapInfo) {
std::string configPath = fs::path(get_maps_directory()).parent_path().string() + "\\backup_info.txt";
std::ofstream file(configPath);
if (file.is_open()) {
file << mapInfo.originalMap << std::endl;
file << mapInfo.backupPath << std::endl;
file.close();
}
}
// Remove old backup files like "*_backup.map" from DDNet maps directory
// Policy: delete backups older than 14 days. Non-fatal on errors.
static void cleanup_old_backups(const fs::path& maps_dir) {
try {
if (maps_dir.empty() || !fs::exists(maps_dir) || !fs::is_directory(maps_dir)) {
return;
}
const auto now = fs::file_time_type::clock::now();
const auto max_age = std::chrono::hours(24 * 14); // 14 days
for (const auto& entry : fs::directory_iterator(maps_dir)) {
if (!entry.is_regular_file()) continue;
const auto& p = entry.path();
const std::string name = p.filename().string();
if (p.extension() == ".map" && name.size() > 12 && name.rfind("_backup.map") == name.size() - 12) {
std::error_code ec;
auto ts = fs::last_write_time(p, ec);
if (ec) {
Logger::log(Logger::WARNING, "Unable to read timestamp for: " + p.string());
continue;
}
if (now - ts > max_age) {
std::error_code rec;
fs::remove(p, rec);
if (!rec) {
Logger::log(Logger::INFO, "Removed old backup: " + p.string());
} else {
Logger::log(Logger::WARNING, "Failed to remove old backup: " + p.string() + " - " + rec.message());
}
}
}
}
} catch (const std::exception& e) {
Logger::log(Logger::WARNING, std::string("cleanup_old_backups error: ") + e.what());
}
}
// Load backup info from file
bool load_backup_info(MapInfo& mapInfo) {
std::string configPath = fs::path(get_maps_directory()).parent_path().string() + "\\backup_info.txt";
std::ifstream file(configPath);
if (file.is_open()) {
std::getline(file, mapInfo.originalMap);
std::getline(file, mapInfo.backupPath);
file.close();
return !mapInfo.originalMap.empty() && !mapInfo.backupPath.empty();
}
return false;
}
bool set_socket_timeout(SOCKET sock, int timeoutMs) {
// Set send timeout
DWORD timeout = timeoutMs;
if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout)) != 0) {
// std::cout << "Failed to set send timeout: " << WSAGetLastError() << std::endl;
return false;
}
// Set receive timeout
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) != 0) {
// std::cout << "Failed to set receive timeout: " << WSAGetLastError() << std::endl;
return false;
}
return true;
}
std::vector<std::string> split_string(const std::string& str, char delim) {
std::vector<std::string> tokens;
std::string token;
std::istringstream token_stream(str);
while (std::getline(token_stream, token, delim)) {
if (!token.empty()) {
tokens.push_back(token);
}
}
return tokens;
}
bool send_command(SOCKET sock, const std::string& command) {
std::string cmd = command + "\n";
if (send(sock, cmd.c_str(), cmd.length(), 0) == SOCKET_ERROR) {
// std::cerr << "Failed to send command: " << WSAGetLastError() << std::endl;
return false;
}
return true;
}
bool receive_responses(SOCKET sock, std::vector<std::string>& responses, int timeout_ms) {
const int BUFFER_SIZE = 4096;
char buffer[BUFFER_SIZE];
std::string accumulated_data;
// Set socket timeout
if (!set_socket_timeout(sock, timeout_ms)) {
return false;
}
while (true) {
int bytes_received = recv(sock, buffer, BUFFER_SIZE - 1, 0);
if (bytes_received == SOCKET_ERROR) {
int error = WSAGetLastError();
if (error == WSAETIMEDOUT) {
break; // Timeout is expected and not an error
}
// std::cerr << "Error receiving data: " << error << std::endl;
return false;
}
if (bytes_received == 0) {
// std::cerr << "Connection closed by server" << std::endl;
return false;
}
buffer[bytes_received] = '\0';
accumulated_data += buffer;
// Check if we've received complete responses
size_t pos;
while ((pos = accumulated_data.find('\n')) != std::string::npos) {
std::string line = accumulated_data.substr(0, pos);
if (!line.empty() && line != "> ") { // Skip empty lines and prompts
responses.push_back(line);
}
accumulated_data.erase(0, pos + 1);
}
// If we have responses and the remaining data ends with a prompt,
// we can assume we're done
if (!responses.empty() && accumulated_data == "> ") {
break;
}
}
return !responses.empty();
}
// === Econ password resolution =============================================
// `ddnet_control.exe` connects to the DDNet server's external console (econ)
// over TCP on `ec_port`. The password it sends is therefore `ec_password`,
// not `sv_rcon_password` (which is the in-game F2 RCON, a different channel).
//
// Resolution order (first non-empty wins):
// 1. DDNETCONTROL_ECON_PASSWORD environment variable
// 2. `econ_password=...` in `ddnet_control.cfg` next to the EXE
// 3. `%APPDATA%\DDNet\autoexec_server.cfg` (USERDIR autoexec — overrides
// anything set in myServerConfig.cfg via `exec` chain)
// 4. running DDNet-Server.exe `data/myServerConfig.cfg`
// 5. running DDNet-Server.exe `data/autoexec_server.cfg`
// 6. Hardcoded fallback "test123" (with a WARNING log)
//
// Within a single file, the LAST `ec_password` line wins, matching DDNet's
// own "later command overrides" semantics.
//
// The chosen source (never the password value itself) is logged once per
// process invocation.
static std::string read_file_to_string(const std::wstring& path) {
std::ifstream ifs(path, std::ios::binary);
if (!ifs) return std::string();
std::ostringstream ss;
ss << ifs.rdbuf();
return ss.str();
}
// Find the LAST `ec_password "value"` (or unquoted) line in a DDNet cfg file.
// Returns empty if absent. Comment-aware (`#`, `//`).
static std::string parse_last_ec_password(const std::wstring& cfg_path) {
std::string content = read_file_to_string(cfg_path);
if (content.empty()) return std::string();
std::istringstream is(content);
std::string line;
const std::string key = "ec_password";
std::string last_value;
while (std::getline(is, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
size_t first = line.find_first_not_of(" \t");
if (first == std::string::npos) continue;
if (line[first] == '#') continue;
if (line[first] == '/' && first + 1 < line.size() && line[first + 1] == '/') continue;
size_t kp = line.find(key, first);
if (kp == std::string::npos) continue;
// Word-boundary check on the left
if (kp > 0) {
unsigned char prev = static_cast<unsigned char>(line[kp - 1]);
if (std::isalnum(prev) || prev == '_') continue;
}
size_t after = kp + key.size();
// Require whitespace immediately after the key (avoids matching e.g. `ec_password_alt`)
if (after >= line.size() || (line[after] != ' ' && line[after] != '\t')) continue;
while (after < line.size() && (line[after] == ' ' || line[after] == '\t')) ++after;
if (after >= line.size()) continue;
if (line[after] == '"') {
size_t end = line.find('"', after + 1);
if (end != std::string::npos) {
last_value = line.substr(after + 1, end - after - 1);
}
} else {
size_t end = line.find_first_of(" \t", after);
if (end == std::string::npos) end = line.size();
last_value = line.substr(after, end - after);
}
}
return last_value;
}
// Find the directory of a running `DDNet-Server.exe` (if any). Empty otherwise.
static std::wstring find_running_ddnet_server_dir() {
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return std::wstring();
PROCESSENTRY32W pe{};
pe.dwSize = sizeof(pe);
std::wstring result;
if (Process32FirstW(snap, &pe)) {
do {
if (_wcsicmp(pe.szExeFile, L"DDNet-Server.exe") == 0) {
HANDLE proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ProcessID);
if (proc) {
wchar_t buf[MAX_PATH] = {};
DWORD size = MAX_PATH;
if (QueryFullProcessImageNameW(proc, 0, buf, &size)) {
std::wstring full(buf);
size_t slash = full.find_last_of(L"\\/");
if (slash != std::wstring::npos) result = full.substr(0, slash);
}
CloseHandle(proc);
if (!result.empty()) break;
}
}
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
return result;
}
// Directory of our own EXE.
static std::wstring get_own_dir() {
wchar_t buf[MAX_PATH] = {};
DWORD len = GetModuleFileNameW(nullptr, buf, MAX_PATH);
if (len == 0) return std::wstring();
std::wstring full(buf);
size_t slash = full.find_last_of(L"\\/");
if (slash != std::wstring::npos) return full.substr(0, slash);
return std::wstring();
}
// %APPDATA%\DDNet (DDNet's USERDIR on Windows).
static std::wstring get_userdir_dir() {
wchar_t* appdata = nullptr;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appdata);
std::wstring result;
if (SUCCEEDED(hr) && appdata) {
result.assign(appdata);
result += L"\\DDNet";
}
if (appdata) CoTaskMemFree(appdata);
return result;
}
// Read a `key=value` (or `key = "value"`) entry from a simple cfg file.
static std::string read_kv_config(const std::wstring& path, const std::string& key) {
std::string content = read_file_to_string(path);
if (content.empty()) return std::string();
std::istringstream is(content);
std::string line;
while (std::getline(is, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
size_t first = line.find_first_not_of(" \t");
if (first == std::string::npos) continue;
if (line[first] == '#') continue;
if (line[first] == '/' && first + 1 < line.size() && line[first + 1] == '/') continue;
size_t eq = line.find('=', first);
if (eq == std::string::npos) continue;
std::string k = line.substr(first, eq - first);
size_t kend = k.find_last_not_of(" \t");
if (kend != std::string::npos) k.erase(kend + 1);
if (k != key) continue;
std::string v = line.substr(eq + 1);
size_t vstart = v.find_first_not_of(" \t");
v = (vstart == std::string::npos) ? std::string() : v.substr(vstart);
size_t vend = v.find_last_not_of(" \t");
if (vend != std::string::npos) v.erase(vend + 1);
if (v.size() >= 2 && v.front() == '"' && v.back() == '"') v = v.substr(1, v.size() - 2);
return v;
}
return std::string();
}
static std::string g_econ_password_cache;
static bool g_econ_password_resolved = false;
static const std::string& resolve_econ_password() {
if (g_econ_password_resolved) return g_econ_password_cache;
g_econ_password_resolved = true;
// 1. Environment variable
{
char buf[512] = {};
DWORD got = GetEnvironmentVariableA("DDNETCONTROL_ECON_PASSWORD", buf, (DWORD)sizeof(buf));
if (got > 0 && got < sizeof(buf)) {
g_econ_password_cache.assign(buf, got);
Logger::log(Logger::INFO, "Econ password source: env DDNETCONTROL_ECON_PASSWORD");
return g_econ_password_cache;
}
}
// 2. ddnet_control.cfg next to the EXE
{
std::wstring own = get_own_dir();
if (!own.empty()) {
std::wstring cfg = own + L"\\ddnet_control.cfg";
std::string pw = read_kv_config(cfg, "econ_password");
if (!pw.empty()) {
g_econ_password_cache = pw;
Logger::log(Logger::INFO, "Econ password source: ddnet_control.cfg");
return g_econ_password_cache;
}
}
}
// 3. USERDIR autoexec_server.cfg (last `ec_password` line wins).
// DDNet executes this from %APPDATA%\DDNet on startup; any value here
// overrides values set earlier by `exec myServerconfig.cfg`.
{
std::wstring userdir = get_userdir_dir();
if (!userdir.empty()) {
std::wstring cfg = userdir + L"\\autoexec_server.cfg";
std::string pw = parse_last_ec_password(cfg);
if (!pw.empty()) {
g_econ_password_cache = pw;
Logger::log(Logger::INFO, "Econ password source: %APPDATA%\\DDNet\\autoexec_server.cfg");
return g_econ_password_cache;
}
}
}
// 4 & 5. Auto-detect from the running DDNet-Server.exe install dir.
{
std::wstring serverDir = find_running_ddnet_server_dir();
if (!serverDir.empty()) {
std::wstring cfg = serverDir + L"\\data\\myServerConfig.cfg";
std::string pw = parse_last_ec_password(cfg);
if (!pw.empty()) {
g_econ_password_cache = pw;
Logger::log(Logger::INFO, "Econ password source: running DDNet-Server.exe data/myServerConfig.cfg");
return g_econ_password_cache;
}
std::wstring cfg2 = serverDir + L"\\data\\autoexec_server.cfg";
pw = parse_last_ec_password(cfg2);
if (!pw.empty()) {
g_econ_password_cache = pw;
Logger::log(Logger::INFO, "Econ password source: running DDNet-Server.exe data/autoexec_server.cfg");
return g_econ_password_cache;
}
}
}
// 6. Hardcoded fallback
g_econ_password_cache = "test123";
Logger::log(Logger::WARNING,
"Econ password source: hardcoded fallback (test123). "
"Set DDNETCONTROL_ECON_PASSWORD or place ddnet_control.cfg "
"(econ_password=...) next to the EXE if your server uses a different password.");
return g_econ_password_cache;
}
bool authenticate(SOCKET sock) {
// Send password immediately without waiting
const std::string& pw = resolve_econ_password();
send_command(sock, pw + "\n");
// Wait for response with shorter timeout
auto responses = get_responses(sock, 2, 500); // Reduced maxResponses to 2 and timeout to 500ms
// Quick check for success
for (const auto& response : responses) {
if (response.find("Authentication successful") != std::string::npos) {
return true;
}
}
return false;
}
std::string get_current_map(SOCKET sock) {
// std::cout << "\n=== Starting Map Query ===" << std::endl;
// std::cout << "Sending sv_map command..." << std::endl;
if (!send_command(sock, "sv_map")) {
return "";
}
std::vector<std::string> responses;
if (!receive_responses(sock, responses)) {
return "";
}
// Find the response containing the map name
std::string response;
for (const auto& r : responses) {
if (r.find("config: Value:") != std::string::npos) {
response = r;
break;
}
}
// std::cout << "Response: " << response << std::endl;
// std::cout << "\n";
// Extract map name from response
size_t valuePos = response.find("Value:");
if (valuePos != std::string::npos) {
// Get everything after "Value: "
std::string mapName = response.substr(valuePos + 7);
// Trim whitespace
mapName.erase(0, mapName.find_first_not_of(" \t\r\n"));
mapName.erase(mapName.find_last_not_of(" \t\r\n") + 1);
return mapName;
}
return "";
}
// Server communication configuration
struct ServerConfig {
static constexpr int DEFAULT_TIMEOUT_MS = 2000;
static constexpr int MAX_RETRIES = 3;
static constexpr int RETRY_DELAY_MS = 500;
static constexpr int CONNECTION_TIMEOUT_MS = 5000;
};
class ServerConnection {
SOCKET sock;
bool connected;
int timeout_ms;
int retries;
public:
ServerConnection() : sock(INVALID_SOCKET), connected(false),
timeout_ms(ServerConfig::DEFAULT_TIMEOUT_MS),
retries(ServerConfig::MAX_RETRIES) {}
bool connect_with_retry() {
for (int attempt = 1; attempt <= retries; ++attempt) {
sock = create_and_connect_socket();
if (sock != INVALID_SOCKET) {
if (set_socket_timeout(sock, timeout_ms)) {
connected = true;
return true;
}
closesocket(sock);
}
// std::cerr << "Connection attempt " << attempt << " failed. ";
if (attempt < retries) {
// std::cerr << "Retrying in " << ServerConfig::RETRY_DELAY_MS << "ms..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(ServerConfig::RETRY_DELAY_MS));
}
}
return false;
}
bool send_command_with_retry(const std::string& command) {
for (int attempt = 1; attempt <= retries; ++attempt) {
if (send_command(sock, command)) {
return true;
}
// std::cerr << "Send attempt " << attempt << " failed. ";
if (attempt < retries) {
// std::cerr << "Retrying..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(ServerConfig::RETRY_DELAY_MS));
}
}
return false;
}
bool receive_with_retry(std::vector<std::string>& responses) {
for (int attempt = 1; attempt <= retries; ++attempt) {
if (receive_responses(sock, responses, timeout_ms)) {
return true;
}
// std::cerr << "Receive attempt " << attempt << " failed. ";
if (attempt < retries) {
// std::cerr << "Retrying..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(ServerConfig::RETRY_DELAY_MS));
}
}
return false;
}
void set_timeout(int ms) {
timeout_ms = ms;
if (connected) {
set_socket_timeout(sock, timeout_ms);
}
}
void set_retries(int count) {
retries = count;
}
SOCKET get_socket() const {
return sock;
}
void disconnect() {
if (sock != INVALID_SOCKET) {
closesocket(sock);
sock = INVALID_SOCKET;
connected = false;
}
}
~ServerConnection() {
disconnect();
}
};
bool hot_reload_map(SOCKET sock) {
ServerConnection conn;
if (!conn.connect_with_retry()) {
// std::cerr << "Failed to establish server connection" << std::endl;
return false;
}
if (!conn.send_command_with_retry("hot_reload")) {
// std::cerr << "Failed to send hot_reload command" << std::endl;
return false;
}
std::vector<std::string> responses;
if (!conn.receive_with_retry(responses)) {
// std::cerr << "Failed to receive response for hot_reload" << std::endl;
return false;
}
return true;
}
bool verify_hot_reload(SOCKET sock, const std::string& expected_map) {
// For hot reload, the map name doesn't change, we just need to verify
// that the server is still responsive after the reload
const int MAX_RETRIES = 3;
const int RETRY_DELAY_MS = 500;
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
std::string current_map = get_current_map(sock);
if (current_map.empty()) {
// std::cerr << "Attempt " << attempt << ": Failed to get current map" << std::endl;
} else {
// For hot reload, we just need to verify the server is responsive
// std::cout << "Hot reload verification successful!" << std::endl;
return true;
}
if (attempt < MAX_RETRIES) {
// std::cout << "Retry " << attempt + 1 << "/" << MAX_RETRIES << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_DELAY_MS));
}
}
// std::cerr << "Failed to verify server response after " << MAX_RETRIES << " attempts" << std::endl;
return false;
}
bool is_valid_map_file(const fs::path& mapPath, std::string& error) {
try {
// First check if file exists
if (!fs::exists(mapPath)) {
error = "Map file does not exist: " + mapPath.string();
return false;
}
// Check if it's a regular file
if (!fs::is_regular_file(mapPath)) {
error = "Path is not a regular file: " + mapPath.string();
return false;
}
// Try to get file size
std::error_code ec;
auto fileSize = fs::file_size(mapPath, ec);
if (ec) {
error = "Cannot read file size: " + ec.message();
return false;
}
// Check if file is empty
if (fileSize == 0) {
error = "Map file is empty";
return false;
}
// Try to open and read first few bytes
std::ifstream file(mapPath, std::ios::binary);
if (!file.is_open()) {
error = "Cannot open map file: " + mapPath.string();
return false;
}
// Read first few bytes to verify it's a valid map file
char header[8];
if (!file.read(header, sizeof(header))) {
error = "Cannot read map file header";
return false;
}
return true;
}
catch (const std::exception& e) {
error = std::string("Error validating map file: ") + e.what();
return false;
}
}
std::string get_maps_directory() {
char* appDataPath;
size_t len;
errno_t err = _dupenv_s(&appDataPath, &len, "APPDATA");
if (err != 0 || appDataPath == nullptr) {
return "";
}
fs::path mapsPath = fs::path(appDataPath) / "DDNet" / "maps";
free(appDataPath);
if (!fs::exists(mapsPath)) {
// Do not fail; caller may want to create it during preflight
return mapsPath.string();
}
return mapsPath.string();
}
// Ensure a directory exists (create if missing). Returns full path string or empty on error.
static std::string ensure_directory(const fs::path& p) {
try {
std::error_code ec;
if (!fs::exists(p, ec)) {
if (!fs::create_directories(p, ec) && ec) {
Logger::log(Logger::ERROR, "Failed to create directory: " + p.string() + " - " + ec.message());
return "";
}
} else if (!fs::is_directory(p)) {
Logger::log(Logger::ERROR, "Path exists but is not a directory: " + p.string());
return "";
}
return p.string();
} catch (const std::exception& e) {
Logger::log(Logger::ERROR, std::string("ensure_directory exception: ") + e.what());
return "";
}
}
static std::string get_or_create_maps_directory() {
std::string maps = get_maps_directory();
if (maps.empty()) return ""; // APPDATA missing
return ensure_directory(fs::path(maps));
}
static std::string get_or_create_backups_directory() {
std::string maps = get_or_create_maps_directory();
if (maps.empty()) return "";
fs::path backups = fs::path(maps) / "backups";
return ensure_directory(backups);
}
// Timestamp as YYYYMMDD-HHMMSS
static std::string make_timestamp() {
using namespace std::chrono;
auto now = system_clock::now();
std::time_t t = system_clock::to_time_t(now);
std::tm tm_buf{};
localtime_s(&tm_buf, &t);
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d%02d%02d-%02d%02d%02d",
tm_buf.tm_year + 1900, tm_buf.tm_mon + 1, tm_buf.tm_mday,
tm_buf.tm_hour, tm_buf.tm_min, tm_buf.tm_sec);
return std::string(buf);
}
// Create marker like "Tutorial map not exist.map", append (1), (2), ... if exists
static fs::path next_marker_path(const fs::path& dir, const std::string& baseNameWithExt) {
fs::path base = dir / baseNameWithExt; // e.g., backups / "Tutorial map not exist.map"
if (!fs::exists(base)) return base;
for (int i = 1; i < 1000; ++i) {
std::string stem = fs::path(baseNameWithExt).stem().string();
std::string ext = fs::path(baseNameWithExt).extension().string();
fs::path cand = dir / (stem + " (" + std::to_string(i) + ")" + ext);
if (!fs::exists(cand)) return cand;
}
return base; // Fallback
}
// Simple change_map implementation
bool change_map(SOCKET sock, const std::string& mapName) {
std::string cmd = std::string("change_map ") + mapName;
if (!send_command(sock, cmd)) return false;
// Brief wait and ping status
Sleep(200);
(void)send_command(sock, "status");
return true; // Assume success if ECON is responsive
}
bool setupFileAssociation() {
// Build command string with current exe path and quoted "%1"
wchar_t exePath[MAX_PATH] = {0};
DWORD len = GetModuleFileNameW(NULL, exePath, MAX_PATH);
if (len == 0 || len >= MAX_PATH) {
Logger::log(Logger::ERROR, "GetModuleFileNameW failed when setting up association");
return false;
}
std::wstring command = L"\""; // opening quote
command += exePath;
command += L"\" \"%1\""; // space then quoted %1
// Use HKCU\Software\Classes to avoid admin requirement
HKEY hkey;
// 1) Set .map default value to our ProgID
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Classes\\.map", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL) != ERROR_SUCCESS) {
Logger::log(Logger::ERROR, "Failed to open/create HKCU\\Software\\Classes\\.map");
return false;
}
const wchar_t* progId = L"DDNetMapFile";
if (RegSetValueExW(hkey, NULL, 0, REG_SZ, (const BYTE*)progId, (DWORD)((wcslen(progId) + 1) * sizeof(wchar_t))) != ERROR_SUCCESS) {
Logger::log(Logger::ERROR, "Failed to set ProgID for .map");
RegCloseKey(hkey);
return false;
}
RegCloseKey(hkey);
// 2) Set command under ProgID
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Classes\\DDNetMapFile\\shell\\open\\command", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL) != ERROR_SUCCESS) {
Logger::log(Logger::ERROR, "Failed to create open\\command key for DDNetMapFile");
return false;
}
if (RegSetValueExW(hkey, NULL, 0, REG_SZ, (const BYTE*)command.c_str(), (DWORD)((command.size() + 1) * sizeof(wchar_t))) != ERROR_SUCCESS) {
Logger::log(Logger::ERROR, "Failed to set open command for DDNetMapFile");
RegCloseKey(hkey);
return false;
}
RegCloseKey(hkey);
// 3) Optional: set a friendly name and default icon (non-blocking if fails)
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Classes\\DDNetMapFile", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL) == ERROR_SUCCESS) {
const wchar_t* friendly = L"DDNet Map File";
RegSetValueExW(hkey, NULL, 0, REG_SZ, (const BYTE*)friendly, (DWORD)((wcslen(friendly) + 1) * sizeof(wchar_t)));
RegCloseKey(hkey);
}
if (RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\Classes\\DDNetMapFile\\DefaultIcon", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkey, NULL) == ERROR_SUCCESS) {
// Use project icon if present; fall back to exe icon automatically
// Note: change below if you want to force ddnet-unstable.ico
std::wstring iconValue = L"\""; iconValue += exePath; iconValue += L"\",0";
RegSetValueExW(hkey, NULL, 0, REG_SZ, (const BYTE*)iconValue.c_str(), (DWORD)((iconValue.size() + 1) * sizeof(wchar_t)));
RegCloseKey(hkey);
}
Logger::log(Logger::INFO, "File association updated for current user (.map -> ddnet_control.exe)");
Logger::log(Logger::INFO, "Command: " + std::string("(wide)") );
return true;
}
bool file_exists(const std::string& path) {
return fs::exists(path);