-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.cpp
More file actions
1453 lines (1342 loc) · 53.3 KB
/
scanner.cpp
File metadata and controls
1453 lines (1342 loc) · 53.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
// Lightweight proxy-backed port scanner for TCP port 25565 (default).
// Each worker is pinned to a unique proxy. Supports SOCKS5 or HTTP CONNECT proxies.
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <cstdio>
#include <cstdint>
#include <cctype>
#include <fstream>
#include <iomanip>
#include <functional>
#include <iostream>
#include <mutex>
#include <optional>
#include <random>
#include <numeric>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
#include <deque>
#include <cstring>
#include <cerrno>
#ifdef _WIN32
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <commctrl.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
using socket_t = SOCKET;
#else
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
using socket_t = int;
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#endif
namespace {
struct Options {
std::string start_ip;
std::string end_ip;
std::vector<std::string> targets;
std::string target_file;
int port = 25565;
int workers = 32;
double timeout_sec = 3.0;
double duration_sec = -1.0; // negative = unlimited
double ping_timeout_sec = 1.0;
std::string proxies_file = "mullvadproxyips.txt";
int proxy_port = 1080;
std::string proxy_type = "socks5";
bool shuffle_targets = true;
bool verbose = false;
};
struct Result {
std::string target_ip;
std::string proxy_ip;
double elapsed_sec;
std::string mc_status;
};
struct StatSnapshot {
uint64_t scanned = 0;
double scanned_rate = 0.0;
uint64_t replies = 0;
double replies_rate = 0.0;
uint64_t opens = 0;
};
struct ScanCallbacks {
// For GUI/CLI logging. Functions may be empty.
std::function<void(const std::string&)> on_ping_lifecycle; // worker starts ping, ping timeouts/failures
std::function<void(const std::string&)> on_ping_success; // ping replies and port check start
std::function<void(const std::string&)> on_open; // open port found
std::function<void(const std::string&)> on_info; // general info (start/finish)
std::function<void(const std::string&)> on_verbose; // optional verbose failures
std::function<void(const Result&)> on_result; // structured result callback
std::function<void(const StatSnapshot&)> on_stats; // stats update (aggregated)
};
void emit_log(const std::function<void(const std::string&)>& fn, const std::string& msg) {
if (fn) fn(msg);
}
void emit_result(const std::function<void(const Result&)>& fn, const Result& r) {
if (fn) fn(r);
}
void emit_stats(const std::function<void(const StatSnapshot&)>& fn, const StatSnapshot& s) {
if (fn) fn(s);
}
std::string trim_copy(const std::string& s) {
size_t start = 0;
while (start < s.size() && std::isspace(static_cast<unsigned char>(s[start]))) {
++start;
}
size_t end = s.size();
while (end > start && std::isspace(static_cast<unsigned char>(s[end - 1]))) {
--end;
}
return s.substr(start, end - start);
}
struct TargetSet {
bool has_range = false;
uint32_t range_start = 0;
uint32_t range_end = 0;
uint64_t range_count = 0;
uint64_t perm_stride = 1;
uint64_t perm_offset = 0;
std::vector<std::string> list_targets; // explicit list/file
};
std::string usage() {
std::ostringstream out;
out << "Usage: scanner [options]\n"
<< " --start-ip IP Starting IPv4 address (inclusive)\n"
<< " --end-ip IP Ending IPv4 address (inclusive)\n"
<< " --targets IP ... Explicit target IPs\n"
<< " --target-file PATH File with one IP per line\n"
<< " --port N Target TCP port (default: 25565)\n"
<< " --workers N Worker threads (default: 32)\n"
<< " --ping-timeout SEC Ping timeout seconds (default: 1.0)\n"
<< " --timeout SEC Socket timeout seconds (default: 3.0)\n"
<< " --duration SEC Optional max runtime seconds\n"
<< " --proxies-file PATH Proxy list file (default: mullvadproxyips.txt)\n"
<< " --proxy-port N Proxy port (default: 1080)\n"
<< " --proxy-type TYPE socks5 or http (default: socks5)\n"
<< " --shuffle-targets Shuffle targets before scanning\n"
<< " --verbose Log failures/timeouts\n"
<< " --help Show this help\n";
return out.str();
}
bool starts_with_dash(const std::string& s) {
return s.rfind("--", 0) == 0;
}
std::optional<Options> parse_args(int argc, char** argv) {
Options opts;
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
if (arg == "--help" || arg == "-h") {
std::cout << usage();
return std::nullopt;
} else if (arg == "--start-ip") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --start-ip\n";
return std::nullopt;
}
opts.start_ip = argv[++i];
} else if (arg == "--end-ip") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --end-ip\n";
return std::nullopt;
}
opts.end_ip = argv[++i];
} else if (arg == "--targets") {
while (i + 1 < argc && !starts_with_dash(argv[i + 1])) {
opts.targets.emplace_back(argv[++i]);
}
} else if (arg == "--target-file") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --target-file\n";
return std::nullopt;
}
opts.target_file = argv[++i];
} else if (arg == "--port") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --port\n";
return std::nullopt;
}
opts.port = std::stoi(argv[++i]);
} else if (arg == "--workers") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --workers\n";
return std::nullopt;
}
opts.workers = std::stoi(argv[++i]);
} else if (arg == "--timeout") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --timeout\n";
return std::nullopt;
}
opts.timeout_sec = std::stod(argv[++i]);
} else if (arg == "--ping-timeout") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --ping-timeout\n";
return std::nullopt;
}
opts.ping_timeout_sec = std::stod(argv[++i]);
} else if (arg == "--duration") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --duration\n";
return std::nullopt;
}
opts.duration_sec = std::stod(argv[++i]);
} else if (arg == "--proxies-file") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --proxies-file\n";
return std::nullopt;
}
opts.proxies_file = argv[++i];
} else if (arg == "--proxy-port") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --proxy-port\n";
return std::nullopt;
}
opts.proxy_port = std::stoi(argv[++i]);
} else if (arg == "--proxy-type") {
if (i + 1 >= argc) {
std::cerr << "Missing value for --proxy-type\n";
return std::nullopt;
}
opts.proxy_type = argv[++i];
if (opts.proxy_type != "socks5" && opts.proxy_type != "http") {
std::cerr << "proxy-type must be socks5 or http\n";
return std::nullopt;
}
} else if (arg == "--shuffle-targets") {
opts.shuffle_targets = true;
} else if (arg == "--verbose") {
opts.verbose = true;
} else {
std::cerr << "Unknown argument: " << arg << "\n";
return std::nullopt;
}
}
return opts;
}
std::vector<std::string> load_lines(const std::string& path) {
std::ifstream file(path);
std::vector<std::string> lines;
if (!file.is_open()) {
return lines;
}
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#') {
continue;
}
// trim whitespace
while (!line.empty() && (line.back() == '\r' || line.back() == '\n' || line.back() == ' ' || line.back() == '\t')) {
line.pop_back();
}
while (!line.empty() && (line.front() == ' ' || line.front() == '\t')) {
line.erase(line.begin());
}
if (!line.empty()) {
lines.push_back(line);
}
}
return lines;
}
bool parse_ipv4(const std::string& ip, uint32_t& out) {
in_addr addr{};
int rc = inet_pton(AF_INET, ip.c_str(), &addr);
if (rc != 1) {
return false;
}
out = ntohl(addr.s_addr);
return true;
}
std::string ipv4_to_string(uint32_t ip) {
in_addr out_addr{};
out_addr.s_addr = htonl(ip);
return std::string(inet_ntoa(out_addr));
}
bool expand_range(const std::string& start_ip, const std::string& end_ip, std::vector<std::string>& out, std::string& err) {
uint32_t start, end;
if (!parse_ipv4(start_ip, start)) {
err = "Invalid start IP";
return false;
}
if (!parse_ipv4(end_ip, end)) {
err = "Invalid end IP";
return false;
}
if (end < start) {
err = "End IP must be greater than or equal to start IP";
return false;
}
uint64_t count = static_cast<uint64_t>(end) - static_cast<uint64_t>(start) + 1;
out.reserve(static_cast<size_t>(count));
for (uint32_t ip = start; ip <= end; ++ip) {
out.emplace_back(ipv4_to_string(ip));
if (ip == 0xFFFFFFFFu) break; // prevent overflow, though capped above
}
return true;
}
TargetSet collect_targets(const Options& opts, std::string& err) {
TargetSet tset;
if (!opts.start_ip.empty() || !opts.end_ip.empty()) {
if (opts.start_ip.empty() || opts.end_ip.empty()) {
err = "Both --start-ip and --end-ip are required together";
return {};
}
std::vector<std::string> tmp; // unused, only for validation
uint32_t start, end;
if (!parse_ipv4(opts.start_ip, start)) {
err = "Invalid start IP";
return {};
}
if (!parse_ipv4(opts.end_ip, end)) {
err = "Invalid end IP";
return {};
}
if (end < start) {
err = "End IP must be greater than or equal to start IP";
return {};
}
tset.has_range = true;
tset.range_start = start;
tset.range_end = end;
tset.range_count = static_cast<uint64_t>(end) - static_cast<uint64_t>(start) + 1;
// Generate a permutation step and offset for randomized iteration without storing all IPs.
std::mt19937_64 rng(static_cast<uint64_t>(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
std::uniform_int_distribution<uint64_t> offset_dist(0, tset.range_count - 1);
tset.perm_offset = offset_dist(rng);
// Choose a stride coprime with range_count (odd often suffices when count is power of two).
std::uniform_int_distribution<uint64_t> stride_dist(1, tset.range_count - 1);
uint64_t stride = 0;
for (int attempts = 0; attempts < 128; ++attempts) {
uint64_t candidate = stride_dist(rng);
if (std::gcd(candidate, tset.range_count) == 1) {
stride = candidate;
break;
}
}
if (stride == 0) {
// Fallback: use 1 (no permutation) if we somehow failed to find a coprime.
stride = 1;
}
tset.perm_stride = stride;
}
tset.list_targets.insert(tset.list_targets.end(), opts.targets.begin(), opts.targets.end());
if (!opts.target_file.empty()) {
auto more = load_lines(opts.target_file);
tset.list_targets.insert(tset.list_targets.end(), more.begin(), more.end());
}
if (!tset.list_targets.empty()) {
// Deduplicate explicit/file targets.
std::unordered_set<std::string> seen;
std::vector<std::string> deduped;
deduped.reserve(tset.list_targets.size());
for (const auto& ip : tset.list_targets) {
if (seen.insert(ip).second) {
deduped.push_back(ip);
}
}
tset.list_targets.swap(deduped);
}
if (!tset.has_range && tset.list_targets.empty()) {
err = "No targets provided. Use --start-ip/--end-ip, --targets, or --target-file.";
return {};
}
return tset;
}
bool set_blocking(socket_t s, bool blocking) {
#ifdef _WIN32
u_long mode = blocking ? 0 : 1;
return ioctlsocket(s, FIONBIO, &mode) == 0;
#else
int flags = fcntl(s, F_GETFL, 0);
if (flags < 0) return false;
if (!blocking)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
return fcntl(s, F_SETFL, flags) == 0;
#endif
}
void set_socket_timeouts(socket_t s, int timeout_ms) {
#ifdef _WIN32
DWORD tv = static_cast<DWORD>(timeout_ms);
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&tv), sizeof(tv));
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&tv), sizeof(tv));
#else
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
}
void close_socket(socket_t s) {
#ifdef _WIN32
closesocket(s);
#else
close(s);
#endif
}
std::optional<socket_t> connect_with_timeout(const std::string& host, int port, int timeout_ms) {
struct addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* res = nullptr;
std::string port_str = std::to_string(port);
if (getaddrinfo(host.c_str(), port_str.c_str(), &hints, &res) != 0) {
return std::nullopt;
}
std::optional<socket_t> sock_opt;
for (auto* rp = res; rp != nullptr; rp = rp->ai_next) {
socket_t s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (s == INVALID_SOCKET) continue;
set_blocking(s, false);
int ret = connect(s, rp->ai_addr, static_cast<int>(rp->ai_addrlen));
if (ret == 0) {
set_blocking(s, true);
set_socket_timeouts(s, timeout_ms);
sock_opt = s;
break;
}
#ifdef _WIN32
int err = WSAGetLastError();
if (err == WSAEWOULDBLOCK || err == WSAEINPROGRESS) {
#else
int err = errno;
if (err == EINPROGRESS) {
#endif
fd_set wfds;
FD_ZERO(&wfds);
FD_SET(s, &wfds);
struct timeval tv;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
int sel = select(static_cast<int>(s + 1), nullptr, &wfds, nullptr, &tv);
if (sel > 0) {
int so_error = 0;
socklen_t len = sizeof(so_error);
getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&so_error), &len);
if (so_error == 0) {
set_blocking(s, true);
set_socket_timeouts(s, timeout_ms);
sock_opt = s;
break;
}
}
}
close_socket(s);
}
freeaddrinfo(res);
return sock_opt;
}
bool send_all(socket_t s, const std::vector<uint8_t>& data) {
size_t sent = 0;
while (sent < data.size()) {
int n = send(s, reinterpret_cast<const char*>(data.data() + sent), static_cast<int>(data.size() - sent), 0);
if (n <= 0) return false;
sent += static_cast<size_t>(n);
}
return true;
}
bool send_all(socket_t s, const std::string& data) {
size_t sent = 0;
while (sent < data.size()) {
int n = send(s, data.data() + sent, static_cast<int>(data.size() - sent), 0);
if (n <= 0) return false;
sent += static_cast<size_t>(n);
}
return true;
}
bool recv_exact(socket_t s, uint8_t* buf, size_t len) {
size_t got = 0;
while (got < len) {
int n = recv(s, reinterpret_cast<char*>(buf + got), static_cast<int>(len - got), 0);
if (n <= 0) return false;
got += static_cast<size_t>(n);
}
return true;
}
bool socks5_connect(socket_t s, const std::string& target_ip, int target_port) {
std::vector<uint8_t> hello{0x05, 0x01, 0x00};
if (!send_all(s, hello)) return false;
uint8_t resp[2];
if (!recv_exact(s, resp, 2)) return false;
if (resp[0] != 0x05 || resp[1] != 0x00) return false;
in_addr addr{};
if (inet_pton(AF_INET, target_ip.c_str(), &addr) != 1) return false;
uint8_t req[10];
req[0] = 0x05; // version
req[1] = 0x01; // connect
req[2] = 0x00; // reserved
req[3] = 0x01; // IPv4
std::memcpy(req + 4, &addr.s_addr, 4);
req[8] = static_cast<uint8_t>((target_port >> 8) & 0xFF);
req[9] = static_cast<uint8_t>(target_port & 0xFF);
if (!send_all(s, std::vector<uint8_t>(req, req + 10))) return false;
uint8_t rep[10];
if (!recv_exact(s, rep, 10)) return false;
if (rep[1] != 0x00) return false;
return true;
}
bool http_connect(socket_t s, const std::string& target_ip, int target_port) {
std::ostringstream req;
req << "CONNECT " << target_ip << ":" << target_port << " HTTP/1.1\r\n"
<< "Host: " << target_ip << ":" << target_port << "\r\n\r\n";
if (!send_all(s, req.str())) return false;
std::string resp;
char buf[512];
while (resp.find("\r\n\r\n") == std::string::npos && resp.size() < 4096) {
int n = recv(s, buf, sizeof(buf), 0);
if (n <= 0) break;
resp.append(buf, buf + n);
}
auto first_line_end = resp.find("\r\n");
if (first_line_end == std::string::npos) return false;
std::string status_line = resp.substr(0, first_line_end);
std::istringstream iss(status_line);
std::string http_version, status_code;
iss >> http_version >> status_code;
if (status_code != "200") return false;
return true;
}
bool attempt_connect(
const std::string& proxy_ip,
int proxy_port,
const std::string& target_ip,
int target_port,
const std::string& proxy_type,
int timeout_ms,
std::string& error_out) {
auto sock_opt = connect_with_timeout(proxy_ip, proxy_port, timeout_ms);
if (!sock_opt) {
error_out = "connect to proxy failed";
return false;
}
socket_t s = *sock_opt;
bool ok = false;
if (proxy_type == "socks5") {
ok = socks5_connect(s, target_ip, target_port);
if (!ok) error_out = "SOCKS5 connect failed";
} else {
ok = http_connect(s, target_ip, target_port);
if (!ok) error_out = "HTTP CONNECT failed";
}
close_socket(s);
return ok;
}
bool ping_host(const std::string& ip, int timeout_ms) {
#ifdef _WIN32
std::ostringstream cmd;
cmd << "ping -n 1 -w " << timeout_ms << " " << ip << " >nul 2>&1";
#else
// timeout_ms to seconds (rounded up)
int timeout_s = (timeout_ms + 999) / 1000;
if (timeout_s <= 0) timeout_s = 1;
std::ostringstream cmd;
cmd << "ping -c 1 -W " << timeout_s << " " << ip << " >/dev/null 2>&1";
#endif
int rc = std::system(cmd.str().c_str());
return rc == 0;
}
std::string python_command() {
if (const char* env = std::getenv("PYTHON_CMD")) {
return env;
}
#ifdef _WIN32
return "python";
#else
return "python3";
#endif
}
std::string mcstatus_script_path() {
if (const char* env = std::getenv("MCSTATUS_SCRIPT")) {
return env;
}
return "mcstatus_probe.py";
}
bool check_minecraft_server_via_python(const std::string& ip, int port, std::string& message_out, std::string& error_out) {
const double timeout_sec = 3.0;
std::ostringstream cmd;
cmd << "\"" << python_command() << "\" "
<< "\"" << mcstatus_script_path() << "\""
<< " --ip \"" << ip << "\" --port " << port
<< " --timeout " << timeout_sec
<< " 2>&1";
#ifdef _WIN32
FILE* pipe = _popen(cmd.str().c_str(), "r");
#else
FILE* pipe = popen(cmd.str().c_str(), "r");
#endif
if (!pipe) {
error_out = "failed to start mcstatus helper";
return false;
}
std::string output;
char buffer[256];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
output.append(buffer);
}
#ifdef _WIN32
int rc = _pclose(pipe);
#else
int rc = pclose(pipe);
#endif
output = trim_copy(output);
if (rc != 0 || output.empty()) {
error_out = output.empty() ? "mcstatus helper returned no output" : output;
return false;
}
message_out = output;
return true;
}
class StatTracker {
public:
void set_callback(std::function<void(const StatSnapshot&)> cb) { callback_ = std::move(cb); }
void record_scanned() { record_event(EventType::Scanned); }
void record_reply() { record_event(EventType::Reply); }
void record_open() { opens_.fetch_add(1, std::memory_order_relaxed); maybe_emit(true); }
private:
enum class EventType { Scanned, Reply };
void record_event(EventType type) {
auto now = std::chrono::steady_clock::now();
if (type == EventType::Scanned) {
scanned_.fetch_add(1, std::memory_order_relaxed);
} else {
replies_.fetch_add(1, std::memory_order_relaxed);
}
{
std::lock_guard<std::mutex> lock(mu_);
auto& dq = (type == EventType::Scanned) ? scanned_times_ : reply_times_;
dq.push_back(now);
prune_locked(now, dq);
}
maybe_emit(false);
}
void prune_locked(std::chrono::steady_clock::time_point now, std::deque<std::chrono::steady_clock::time_point>& dq) {
auto cutoff = now - std::chrono::seconds(60);
while (!dq.empty() && dq.front() < cutoff) {
dq.pop_front();
}
}
void maybe_emit(bool force) {
if (!callback_) return;
auto now = std::chrono::steady_clock::now();
bool do_emit = force;
{
std::lock_guard<std::mutex> lock(mu_);
if (!force && now - last_emit_ < std::chrono::milliseconds(500)) {
return;
}
last_emit_ = now;
}
StatSnapshot snap = snapshot(now);
emit_stats(callback_, snap);
}
StatSnapshot snapshot(std::chrono::steady_clock::time_point now) {
StatSnapshot snap;
snap.scanned = scanned_.load(std::memory_order_relaxed);
snap.replies = replies_.load(std::memory_order_relaxed);
snap.opens = opens_.load(std::memory_order_relaxed);
std::lock_guard<std::mutex> lock(mu_);
prune_locked(now, scanned_times_);
prune_locked(now, reply_times_);
double window = 60.0;
snap.scanned_rate = scanned_times_.empty() ? 0.0 : scanned_times_.size() / window;
snap.replies_rate = reply_times_.empty() ? 0.0 : reply_times_.size() / window;
return snap;
}
std::atomic<uint64_t> scanned_{0};
std::atomic<uint64_t> replies_{0};
std::atomic<uint64_t> opens_{0};
std::deque<std::chrono::steady_clock::time_point> scanned_times_;
std::deque<std::chrono::steady_clock::time_point> reply_times_;
std::chrono::steady_clock::time_point last_emit_{};
std::mutex mu_;
std::function<void(const StatSnapshot&)> callback_;
};
void worker_loop(
size_t worker_id,
const std::string& proxy_ip,
const Options& opts,
const TargetSet& targets,
uint64_t total_targets,
std::atomic<uint64_t>& next_index,
std::atomic<bool>& stop_flag,
std::optional<std::chrono::steady_clock::time_point> stop_at,
std::mutex& results_mutex,
std::vector<Result>& results,
const ScanCallbacks& callbacks,
StatTracker& stats) {
const int timeout_ms = static_cast<int>(opts.timeout_sec * 1000);
const int ping_timeout_ms = static_cast<int>(opts.ping_timeout_sec * 1000);
while (true) {
if (stop_flag.load()) break;
if (stop_at && std::chrono::steady_clock::now() >= *stop_at) {
stop_flag.store(true);
break;
}
uint64_t idx = next_index.fetch_add(1);
if (idx >= total_targets) break;
std::string target;
if (targets.has_range && idx < targets.range_count) {
uint64_t perm_idx = (idx * targets.perm_stride + targets.perm_offset) % targets.range_count;
uint32_t ip_val = targets.range_start + static_cast<uint32_t>(perm_idx);
target = ipv4_to_string(ip_val);
} else {
uint64_t list_idx = idx - targets.range_count;
if (list_idx < targets.list_targets.size()) {
target = targets.list_targets[static_cast<size_t>(list_idx)];
} else {
continue;
}
}
stats.record_scanned();
// Ping check first.
emit_log(callbacks.on_ping_lifecycle, "[WORKER " + std::to_string(worker_id) + "] pinging " + target);
auto ping_start = std::chrono::steady_clock::now();
bool ping_ok = ping_host(target, ping_timeout_ms);
double ping_elapsed = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - ping_start).count();
if (ping_ok) {
stats.record_reply();
std::ostringstream ping_msg;
ping_msg << "[RECV-PING] " << target << " (" << std::fixed << std::setprecision(1) << ping_elapsed << " ms)";
emit_log(callbacks.on_ping_success, ping_msg.str());
std::ostringstream check_msg;
check_msg << "[CHECK] worker " << worker_id << " testing " << target << ":" << opts.port;
emit_log(callbacks.on_ping_success, check_msg.str());
} else {
std::ostringstream fail_msg;
fail_msg << "[FAIL-PING] " << target << " (>" << ping_timeout_ms << " ms)";
emit_log(callbacks.on_ping_lifecycle, fail_msg.str());
continue;
}
std::string error;
auto start = std::chrono::steady_clock::now();
bool ok = attempt_connect(proxy_ip, opts.proxy_port, target, opts.port, opts.proxy_type, timeout_ms, error);
double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
if (ok) {
std::string mc_message;
std::string mc_error;
bool mc_ok = check_minecraft_server_via_python(target, opts.port, mc_message, mc_error);
if (mc_ok) {
std::ostringstream mc_log;
mc_log << "[MC] " << mc_message << " via " << proxy_ip << ":" << opts.proxy_port
<< " (" << opts.proxy_type << ", port check " << std::fixed << std::setprecision(2) << elapsed << "s)";
emit_log(callbacks.on_open, mc_log.str());
stats.record_open();
Result r{target, proxy_ip, elapsed, mc_message};
{
std::lock_guard<std::mutex> lock(results_mutex);
results.push_back(r);
}
emit_result(callbacks.on_result, r);
} else if (opts.verbose) {
std::ostringstream fail_msg;
fail_msg << "[OPEN NON-MC] " << target << ":" << opts.port << " via " << proxy_ip << ":" << opts.proxy_port
<< " (" << opts.proxy_type << ") -> " << (mc_error.empty() ? "not a Minecraft server" : mc_error);
emit_log(callbacks.on_verbose, fail_msg.str());
}
} else if (opts.verbose) {
std::ostringstream fail_msg;
fail_msg << "[FAIL] " << target << ":" << opts.port << " via " << proxy_ip << ":" << opts.proxy_port
<< " (" << opts.proxy_type << ") -> " << error;
emit_log(callbacks.on_verbose, fail_msg.str());
}
}
}
bool run_scan(const Options& opts_in, const ScanCallbacks& callbacks, std::atomic<bool>& stop_flag, std::vector<Result>& results_out) {
Options opts = opts_in;
stop_flag.store(false);
StatTracker stats;
stats.set_callback(callbacks.on_stats);
if (opts.workers < 1) {
emit_log(callbacks.on_info, "Invalid config: --workers must be >= 1.");
return false;
}
auto proxies = load_lines(opts.proxies_file);
if (proxies.empty()) {
emit_log(callbacks.on_info, "No proxies loaded from " + opts.proxies_file);
return false;
}
std::string target_err;
auto targets = collect_targets(opts, target_err);
if (!targets.has_range && targets.list_targets.empty()) {
emit_log(callbacks.on_info, target_err.empty() ? "No targets provided." : target_err);
return false;
}
if (opts.shuffle_targets && !targets.list_targets.empty()) {
std::mt19937 rng(static_cast<unsigned>(std::chrono::steady_clock::now().time_since_epoch().count()));
std::shuffle(targets.list_targets.begin(), targets.list_targets.end(), rng);
}
size_t worker_count = static_cast<size_t>(opts.workers);
if (worker_count > proxies.size()) {
std::ostringstream warn;
warn << "Requested " << worker_count << " workers but only " << proxies.size()
<< " proxies available; using " << proxies.size() << " workers instead.";
emit_log(callbacks.on_info, warn.str());
worker_count = proxies.size();
}
if (worker_count == 0) {
emit_log(callbacks.on_info, "No workers can be started (no proxies?).");
return false;
}
uint64_t total_targets = targets.range_count + static_cast<uint64_t>(targets.list_targets.size());
std::ostringstream start_msg;
start_msg << "Scanning " << total_targets << " target(s) on port " << opts.port << " with " << worker_count
<< " workers via " << opts.proxy_type << " proxies (timeout=" << opts.timeout_sec
<< "s, duration=" << (opts.duration_sec < 0 ? std::string("unlimited") : std::to_string(opts.duration_sec))
<< ", ping-timeout=" << opts.ping_timeout_sec << "s).";
emit_log(callbacks.on_info, start_msg.str());
std::optional<std::chrono::steady_clock::time_point> stop_at;
if (opts.duration_sec > 0) {
stop_at = std::chrono::steady_clock::now() + std::chrono::milliseconds(static_cast<int64_t>(opts.duration_sec * 1000));
}
std::atomic<uint64_t> next_index{0};
std::mutex results_mutex;
results_out.clear();
results_out.reserve(64);
std::vector<std::thread> threads;
threads.reserve(worker_count);
for (size_t i = 0; i < worker_count; ++i) {
threads.emplace_back(worker_loop, i, proxies[i], std::cref(opts), std::cref(targets), total_targets,
std::ref(next_index), std::ref(stop_flag), stop_at, std::ref(results_mutex),
std::ref(results_out), std::cref(callbacks), std::ref(stats));
}
for (auto& t : threads) {
t.join();
}
std::ostringstream done_msg;
done_msg << "Scan finished. Minecraft servers found: " << results_out.size();
emit_log(callbacks.on_info, done_msg.str());
return true;
}
#ifdef _WIN32
struct WinsockInit {
WinsockInit() {
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
}
~WinsockInit() { WSACleanup(); }
};
#endif
int run_console(int argc, char** argv) {
#ifdef _WIN32
WinsockInit winsock_guard;
#endif
auto opts_opt = parse_args(argc, argv);
if (!opts_opt.has_value()) {
return 0;
}
Options opts = *opts_opt;
std::mutex cout_mutex;
ScanCallbacks callbacks;
callbacks.on_ping_lifecycle = [&](const std::string& msg) {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << msg << "\n";
};
callbacks.on_ping_success = callbacks.on_ping_lifecycle;
callbacks.on_open = callbacks.on_ping_lifecycle;
callbacks.on_verbose = [&](const std::string& msg) {
if (opts.verbose) {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << msg << "\n";
}
};
callbacks.on_info = [&](const std::string& msg) {
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << msg << "\n";
};
std::atomic<bool> stop_flag{false};
std::vector<Result> results;
bool ok = run_scan(opts, callbacks, stop_flag, results);
{
std::lock_guard<std::mutex> lock(cout_mutex);
if (!results.empty()) {
std::cout << "Minecraft servers:\n";
for (const auto& r : results) {
std::string line = r.mc_status.empty() ? (r.target_ip + ":" + std::to_string(opts.port)) : r.mc_status;
std::cout << " - " << line << " via " << r.proxy_ip << ":" << opts.proxy_port
<< " (port check " << std::fixed << std::setprecision(2) << r.elapsed_sec << "s)\n";
}
}
}
return ok ? 0 : 1;
}
#ifdef _WIN32
enum ControlId {
IDC_BTN_START = 2001,
IDC_BTN_STOP,
IDC_EDIT_WORKERS,
IDC_EDIT_START_IP,
IDC_EDIT_END_IP,
IDC_EDIT_PING_TIMEOUT,
IDC_LOG_ACTIVITY,
IDC_LOG_SUCCESS,
IDC_LABEL_START_IP,
IDC_LABEL_END_IP,
IDC_LABEL_WORKERS,
IDC_LABEL_PING,
IDC_LABEL_LOG1,
IDC_LABEL_LOG2,
IDC_LABEL_SCANNED,
IDC_VALUE_SCANNED,
IDC_LABEL_SCAN_RATE,
IDC_VALUE_SCAN_RATE,
IDC_LABEL_REPLIES,
IDC_VALUE_REPLIES,
IDC_LABEL_REPLY_RATE,
IDC_VALUE_REPLY_RATE,
IDC_LABEL_OPENS,
IDC_VALUE_OPENS,
IDC_CHECK_VERBOSE
};
constexpr UINT WM_LOG_PING = WM_APP + 1;
constexpr UINT WM_LOG_RECV = WM_APP + 2;
constexpr UINT WM_LOG_OPEN = WM_APP + 3;
constexpr UINT WM_LOG_SUCCESS = WM_APP + 4;
constexpr UINT WM_SCAN_DONE = WM_APP + 5;
constexpr UINT WM_STATS = WM_APP + 6;
struct GuiState {
HWND hwnd = nullptr;
HWND start_btn = nullptr;
HWND stop_btn = nullptr;
HWND workers_edit = nullptr;
HWND start_ip_edit = nullptr;
HWND end_ip_edit = nullptr;
HWND ping_timeout_edit = nullptr;
HWND verbose_check = nullptr;
HWND stats_scanned = nullptr;
HWND stats_scan_rate = nullptr;
HWND stats_replies = nullptr;
HWND stats_reply_rate = nullptr;
HWND stats_opens = nullptr;
HWND log_activity = nullptr;
HWND log_success = nullptr;
HFONT font = nullptr;
std::thread scan_thread;
std::atomic<bool> stop_flag{false};
bool running = false;
bool verbose = false;
};