-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
3677 lines (3391 loc) · 153 KB
/
scanner.py
File metadata and controls
3677 lines (3391 loc) · 153 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Clean IP Scanner — Xray Core (Windows-friendly)
Wizard mode:
py -3.12 .\\scanner.py
CLI mode:
py -3.12 .\\scanner.py -cf config.txt -rf .\\ranges\\cloudflare_ipv4.txt -n 200 -w 12
"""
import os, sys, json, time, random, socket, signal, zipfile, platform, argparse, tempfile, threading, subprocess, ipaddress, shutil, urllib.request, hashlib, csv, re, ssl, math, statistics, atexit
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from typing import List, Tuple
from datetime import datetime
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
requests = None
try:
import socks # noqa
HAS_SOCKS = True
except ImportError:
HAS_SOCKS = False
def _check_deps():
if not HAS_REQUESTS:
print("[!] requests library is required. Please install it.")
sys.exit(1)
if not HAS_SOCKS:
print("[!] PySocks library is required for SOCKS support. Please install it.")
sys.exit(1)
try:
import rich # noqa: F401
from rich.console import Console
from rich.table import Table
from rich.live import Live
from rich import box
from rich.panel import Panel
from rich.align import Align
from rich.text import Text
from rich.layout import Layout
from rich.progress import Progress, SpinnerColumn, BarColumn, TimeRemainingColumn
from rich.spinner import Spinner
HAS_RICH = True
except ImportError:
HAS_RICH = False
Console = None
Table = None
Live = None
box = None
Panel = None
Align = None
Text = None
Layout = None
except Exception:
# Rich is installed but something went wrong at import-time.
# Fall back gracefully instead of crashing.
HAS_RICH = False
Console = None
Table = None
Live = None
box = None
Panel = None
Align = None
Text = None
Layout = None
DEFAULT_PORTS = [443]
CONCURRENCY = 8
TIMEOUT = 5
MAX_LATENCY = 500
SCAN_COUNT = 100
DOWNLOAD_TEST_SIZE = 100 # KB
UPLOAD_TEST_SIZE = 50 # KB
SPEED_TEST_SECONDS = 5.0 # realistic throughput window
SPEED_TEST_CHUNK_KB = 1024
DEFAULT_REAL_DELAY_HOST = "1.1.1.1"
DEFAULT_REAL_DELAY_PORT = 443
DEFAULT_XRAY_WORKERS = 24
DOWNLOAD_TEST_URLS = [
"https://speed.cloudflare.com/__down?bytes={}",
"https://speed.hetzner.de/1MB.bin",
"https://cachefly.cachefly.net/1mb.test",
]
UPLOAD_TEST_URLS = [
"https://speed.cloudflare.com/__up",
"https://httpbin.org/post",
]
# Default multi-endpoint latency URLs (can be overridden via CLI)
DEFAULT_LATENCY_URLS = [
"https://cp.cloudflare.com/generate_204",
"https://www.google.com/generate_204",
"https://www.cloudflare.com/cdn-cgi/trace",
]
RANGES_DIR = "ranges"
CACHE_FILE = "cache.json"
LOG_DIR = "logs"
class Colors:
RESET="\033[0m"; BOLD="\033[1m"; DIM="\033[2m"
RED="\033[91m"; GREEN="\033[92m"; YELLOW="\033[93m"; BLUE="\033[94m"; MAGENTA="\033[95m"; CYAN="\033[96m"; WHITE="\033[97m"
@staticmethod
def disable():
for a in dir(Colors):
if a.isupper() and not a.startswith("_"):
setattr(Colors, a, "")
if sys.platform == "win32":
os.system("color")
class PortManager:
"""Thread-safe port allocation for Xray instances (range 10000-60000)."""
_PORT_START = 10000
_PORT_END = 60000
_lock = threading.Lock()
_used_ports = set()
@classmethod
def acquire_port(cls) -> int:
"""Allocate an unused port in the range [10000, 60000)."""
with cls._lock:
# Start from random offset instead of always port 10000
# This avoids "stuck" ports if previous session left zombie processes
start = random.randint(cls._PORT_START, cls._PORT_END - 2000)
# Try from random start, then wrap around if needed
for offset in range(cls._PORT_END - cls._PORT_START):
port = start + offset
if port >= cls._PORT_END:
port = cls._PORT_START + (port - cls._PORT_END)
if port not in cls._used_ports:
cls._used_ports.add(port)
return port
raise RuntimeError("No ports available in range 10000-60000 (all exhausted)")
@classmethod
def release_port(cls, port: int) -> None:
"""Release a port back to the pool."""
with cls._lock:
cls._used_ports.discard(port)
@classmethod
def reset(cls) -> None:
"""Reset all port allocations (for cleanup)."""
with cls._lock:
cls._used_ports.clear()
# Global process tracking and cleanup
_global_active_procs = set()
_global_proc_lock = threading.Lock()
def _register_global_proc(proc):
"""Register a process for automatic cleanup."""
if proc:
with _global_proc_lock:
_global_active_procs.add(proc)
def _cleanup_all_processes():
"""Kill all registered processes immediately upon exit."""
with _global_proc_lock:
procs = list(_global_active_procs)
for p in procs:
try:
if p and p.poll() is None:
p.terminate()
except Exception:
pass
for p in procs:
try:
if p and p.poll() is None:
p.kill()
except Exception:
pass
with _global_proc_lock:
_global_active_procs.clear()
# Register cleanup to run at exit
atexit.register(_cleanup_all_processes)
class LiveTUI:
"""
Simple htop-like live table. Cross-platform best-effort.
Keys:
s = sort by score
l = sort by latency median
j = sort by jitter
o = sort by loss
t = sort by TLS
d = sort by DL
u = sort by UL
q = quit TUI (scan continues, but stops drawing)
"""
def __init__(self, title:str="Clean IP Scanner", sort_key:str="score", top:int=20, scan_order:str="random"):
self.title = title
self.sort_key = sort_key
self.scan_order = scan_order or "random"
self.top = top
self._lock = threading.Lock()
self._items = []
self._stop = False
self._quit_draw = False
self._status_line = ""
self._thread = None
def start(self):
self._thread=threading.Thread(target=self._loop, daemon=True)
self._thread.start()
def stop(self):
self._stop=True
if self._thread:
try: self._thread.join(timeout=1.0)
except Exception: pass
def update(self, items:list, status_line:str=""):
with self._lock:
self._items=list(items)
self._status_line=status_line
def _get_key(self):
# Windows non-blocking
try:
if os.name=="nt":
import msvcrt
if msvcrt.kbhit():
ch=msvcrt.getch()
try: return ch.decode("utf-8", errors="ignore")
except Exception: return ""
else:
import sys, select
dr,_,_=select.select([sys.stdin],[],[],0)
if dr:
return sys.stdin.read(1)
except Exception:
return ""
return ""
def _sort_items(self, arr):
k=self.sort_key
def val(r):
if k=="lat":
return getattr(r,"latency_median",999999)
if k=="jitter":
return getattr(r,"jitter_stddev",999999)
if k=="loss":
return getattr(r,"loss",999999)
if k=="tls":
return getattr(r,"tls_time",999999)
if k=="dl":
return -getattr(r,"download_speed",0.0)
if k=="ul":
return -getattr(r,"upload_speed",0.0)
return getattr(r,"score",999999)
return sorted(arr, key=val)
def _render(self):
with self._lock:
items = list(self._items)
status = self._status_line
items = self._sort_items([r for r in items if str(getattr(r, "status", "")).lower() == "clean"])[:self.top]
clear_console()
# Boxed header
box_width = 86
sys.stdout.write("┌" + "─" * (box_width - 2) + "┐\n")
sys.stdout.write(f"│ 🔎 Clean IP Scanner Demo | Runtime: {int(time.time() - getattr(self, '_start_time', time.time()))}s".ljust(box_width - 1) + "│\n")
sys.stdout.write(f"│ ✅ {len(items)} ❌ 0 ⏱ 0 ⚠ 0 │ Total: {len(items)}/{len(items)}".ljust(box_width - 1) + "│\n")
sys.stdout.write("├" + "─" * (box_width - 2) + "┤\n")
# Table header
sys.stdout.write(f"│ {'IP':<18} {'Delay':>6} {'JIT':>6} {'LOSS':>6} {'TLS':>6} {'DL':>6} {'UL':>6} {'SCORE':>7} {'CDN':<8} {'H2':>2} {'H3':>2} │\n")
sys.stdout.write("├" + "─" * (box_width - 2) + "┤\n")
# Table rows
# Star scoring system
scores = [getattr(r, 'score', 999999) for r in items]
if scores:
min_score = min(scores)
max_score = max(scores)
if max_score == min_score:
max_score = min_score + 1
else:
min_score = 0
max_score = 1
def stars_for(score):
# 6 stars for best, 1 for worst
if max_score == min_score:
return '⭐️' * 6
norm = (score - min_score) / (max_score - min_score)
n_stars = 6 - int(norm * 5 + 0.5)
n_stars = max(1, min(6, n_stars))
return '⭐️' * n_stars
# Compose all IP rows and pretty info into the box
box_rows = []
for r in items:
ip = f"{r.ip}:{r.port}"
cdn = (getattr(r, "cdn_vendor", "") or "")
if getattr(r, "cdn_ok", True) is False:
cdn = "FAKE"
row = f"│ {ip:<18} {getattr(r,'real_delay_ms',0.0):6.1f} {r.jitter_stddev:6.1f} {r.loss:6.1f} {r.tls_time:6.1f} {r.download_speed:6.2f} {r.upload_speed:6.2f} {r.score:7.1f} {cdn:<8} {('Y' if getattr(r,'h2',False) else '-'):>2} {('Y' if getattr(r,'h3',False) else '-'):>2} │ {stars_for(getattr(r, 'score', 999999))}"
box_rows.append(row)
# Add pretty info as extra lines inside the box, indented
box_rows.append(f"│ {ip} {stars_for(getattr(r, 'score', 999999))}".ljust(box_width - 1) + "│")
box_rows.append(f"│ Delay: {getattr(r,'real_delay_ms',0.0):.1f} ms".ljust(box_width - 1) + "│")
box_rows.append(f"│ JIT: {r.jitter_stddev:.1f} ms".ljust(box_width - 1) + "│")
box_rows.append(f"│ LOSS: {r.loss:.1f} %".ljust(box_width - 1) + "│")
box_rows.append(f"│ TLS: {r.tls_time:.1f} ms".ljust(box_width - 1) + "│")
box_rows.append(f"│ DL: {r.download_speed:.2f} Mbps".ljust(box_width - 1) + "│")
box_rows.append(f"│ UL: {r.upload_speed:.2f} Mbps".ljust(box_width - 1) + "│")
box_rows.append(f"│ SCORE: {r.score:.1f}".ljust(box_width - 1) + "│")
box_rows.append(f"│ CDN: {getattr(r, 'cdn_vendor', '')}".ljust(box_width - 1) + "│")
box_rows.append(f"│ H2: {'Y' if getattr(r,'h2',False) else '-'}".ljust(box_width - 1) + "│")
box_rows.append(f"│ H3: {'Y' if getattr(r,'h3',False) else '-'}".ljust(box_width - 1) + "│")
box_rows.append(f"│".ljust(box_width - 1) + "│")
for row in box_rows:
sys.stdout.write(row + "\n")
sys.stdout.write("└" + "─" * (box_width - 2) + "┘\n")
sys.stdout.write(status + "\n")
sys.stdout.flush()
def _loop(self):
# Ensure VT sequences on Windows terminals
try:
if os.name=="nt":
os.system("")
except Exception:
pass
while not self._stop:
ch=self._get_key()
if ch:
ch=ch.lower()
if ch=="q":
self._quit_draw=True
elif ch=="s":
self.sort_key="score"
elif ch=="l":
self.sort_key="lat"
elif ch=="j":
self.sort_key="jitter"
elif ch=="o":
self.sort_key="loss"
elif ch=="t":
self.sort_key="tls"
elif ch=="d":
self.sort_key="dl"
elif ch=="u":
self.sort_key="ul"
if not self._quit_draw:
self._render()
time.sleep(0.4)
def clear_console():
"""Clear terminal screen (best-effort)."""
try:
# ANSI clear + cursor home (works on most modern terminals, including Windows Terminal/PowerShell)
print("\x1b[2J\x1b[H", end="")
except Exception:
pass
try:
import os
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
except Exception:
pass
def banner():
# Big colorful 'exelite' splash
logo_lines = [
r"███████╗██╗ ██╗███████╗██╗ ██╗████████╗███████╗",
r"██╔════╝╚██╗██╔╝██╔════╝██║ ██║╚══██╔══╝██╔════╝",
r"█████╗ ╚███╔╝ █████╗ ██║ ██║ ██║ █████╗ ",
r"██╔══╝ ██╔██╗ ██╔══╝ ██║ ██║ ██║ ██╔══╝ ",
r"███████╗██╔╝ ██╗███████╗███████╗██║ ██║ ███████╗",
r"╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚══════╝",
]
splash_colors = [Colors.MAGENTA, Colors.CYAN, Colors.BLUE, Colors.GREEN, Colors.YELLOW, Colors.RED]
for i, ln in enumerate(logo_lines):
print(splash_colors[i % len(splash_colors)] + Colors.BOLD + ln + Colors.RESET)
print()
print(f"""{Colors.CYAN}{Colors.BOLD}
╔══════════════════════════════════════════════════════════════╗
║ Clean IP Scanner — Xray Core ║
║ Wizard + CLI (Windows Ready) ║
╠══════════════════════════════════════════════════════════════╣
║ Tests: Latency | TLS | Download | Upload ║
╚══════════════════════════════════════════════════════════════╝
{Colors.RESET}""")
def info(m): print(f" {Colors.CYAN}▶{Colors.RESET} {m}")
def ok(m): print(f" {Colors.GREEN}✓{Colors.RESET} {m}")
def warn(m): print(f" {Colors.YELLOW}⚠{Colors.RESET} {m}")
def err(m): print(f" {Colors.RED}✗{Colors.RESET} {m}")
def section(t):
"""Print a section header (skip if Rich TUI is active to avoid layout disruption)."""
# Only print if we're not running with Rich TUI (to avoid console clutter)
w=62
print(f"\n {Colors.BLUE}{'─'*w}{Colors.RESET}")
print(f" {Colors.BOLD}{Colors.BLUE} {t}{Colors.RESET}")
print(f" {Colors.BLUE}{'─'*w}{Colors.RESET}")
def finished():
"""Display a large 'Finished' banner (no colors)."""
print("\n")
print("╔══════════════════════════════════════════════════════════════════════════╗")
print("║ ║")
print("║ ███████╗██╗███╗ ██╗██╗███████╗██╗ ██╗███████╗ ║")
print("║ ██╔════╝██║████╗ ██║██║██╔════╝██║ ██║██╔════╝ ║")
print("║ █████╗ ██║██╔██╗ ██║██║███████╗███████║█████╗ ║")
print("║ ██╔══╝ ██║██║╚██╗██║██║╚════██║██╔══██║██╔══╝ ║")
print("║ ██║ ██║██║ ╚████║██║███████║██║ ██║███████╗ ║")
print("║ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ║")
print("║ ║")
print("╚══════════════════════════════════════════════════════════════════════════╝")
print("\n")
@dataclass
class ScanResult:
ip:str; port:int
# Aggregated latency stats across endpoints (ms)
latency_min:float=0.0
latency_mean:float=0.0
latency_median:float=0.0
jitter_stddev:float=0.0
# Back-compat quick fields
latency:float=0.0
download_speed:float=0.0
upload_speed:float=0.0
download_stddev:float=0.0
upload_stddev:float=0.0
speed_rounds:int=1
loss:float=0.0
tls_time:float=0.0
samples:int=0
endpoints_ok:int=0
endpoints_total:int=0
endpoint_breakdown:dict=None
# Extra checks
icmp_loss:float=0.0
tcp_loss:float=0.0
cdn_ok:bool=True
cdn_vendor:str=""
h2:bool=False
h3:bool=False
real_delay_ms:float=0.0
stability_uptime:float=0.0
stability_variance_ms:float=0.0
stability_spikes:int=0
stability_traffic_mbps:float=0.0
geo:dict=None
status:str="pending"; region:str=""; error_msg:str=""
_phase:str="pending" # Track current scan phase: latency, tls, dl, ul, finished
@property
def score(self)->float:
"""Lower is better. Combines latency/jitter/loss/TLS/stability/speed and speed consistency."""
if self.status != "clean":
return 99999.0
lat = float(self.latency_median or self.latency or 99999.0)
jit = float(self.jitter_stddev or 0.0)
loss = float(self.loss or 0.0)
tls = float(self.tls_time or 0.0)
rtt = float(self.real_delay_ms or 0.0)
dl = float(self.download_speed or 0.0)
ul = float(self.upload_speed or 0.0)
dl_std = float(self.download_stddev or 0.0)
ul_std = float(self.upload_stddev or 0.0)
# Stability: higher uptime is better; variance/spikes are worse
uptime = float(self.stability_uptime or 0.0) # percent
var_ms = float(self.stability_variance_ms or 0.0)
spikes = float(self.stability_spikes or 0.0)
# Normalize / weights
# Base penalties (ms-scale)
score = 0.0
score += lat * 2.2
score += jit * 1.4
score += loss * 35.0
score += tls * 0.8
if rtt > 0:
score += rtt * 1.1
# Speed rewards (Mbps) -> subtract; cap so it doesn't dominate
score -= min(dl, 50.0) * 2.0
score -= min(ul, 20.0) * 1.2
# **CONSISTENCY PENALTIES** (higher stddev worse) - EMPHASIZE THIS
# Penalize speed variance heavily - we want consistent IPs
score += dl_std * 5.0 # Increased from 3.0
score += ul_std * 4.0 # Increased from 2.0
# Variance ratio penalty: if stddev is > 50% of mean, heavily penalize
if dl > 0 and dl_std > dl * 0.5:
score += (dl_std / dl) * 10.0
if ul > 0 and ul_std > ul * 0.5:
score += (ul_std / ul) * 8.0
# Stability (if ran): reward uptime, penalize variance/spikes
if uptime > 0:
score -= uptime * 0.8 # Increased reward for good uptime
score += var_ms * 1.2 # Increased penalty for latency variance
score += spikes * 10.0 # Increased penalty for spikes
if self.stability_traffic_mbps > 0:
score -= min(float(self.stability_traffic_mbps), 40.0) * 0.7
# Keep score in a sensible range
if score < 0:
score = 0.0
return float(round(score, 2))
class XrayManager:
XRAY_VERSION="1.8.24"
XRAY_RELEASES_URL="https://github.com/XTLS/Xray-core/releases/download"
def __init__(self, work_dir=None):
self.work_dir = work_dir or os.path.join(tempfile.gettempdir(),"clean_ip_scanner")
os.makedirs(self.work_dir, exist_ok=True)
self.xray_path = os.path.join(self.work_dir, "xray.exe" if platform.system().lower()=="windows" else "xray")
def is_installed(self)->bool:
return os.path.isfile(self.xray_path) and os.access(self.xray_path, os.X_OK)
def _platform_zip(self)->str:
sysn=platform.system().lower(); mach=platform.machine().lower()
if sysn=="windows":
return "Xray-windows-64.zip" if mach in ("amd64","x86_64") else "Xray-windows-32.zip"
if sysn=="linux": return "Xray-linux-64.zip"
if sysn=="darwin": return "Xray-macos-64.zip"
return "Xray-linux-64.zip"
def download_xray(self)->bool:
fn=self._platform_zip()
url=f"{self.XRAY_RELEASES_URL}/v{self.XRAY_VERSION}/{fn}"
zpath=os.path.join(self.work_dir, fn)
section("Downloading Xray Core")
info(f"Version: {self.XRAY_VERSION}")
info(f"URL: {url}")
try:
req=urllib.request.Request(url, headers={"User-Agent":"Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=60) as r:
total=int(r.headers.get("Content-Length",0))
got=0
with open(zpath,"wb") as f:
while True:
ch=r.read(8192)
if not ch: break
f.write(ch); got+=len(ch)
if total>0:
pct=got/total*100
bar_len=30
filled=int(bar_len*got/total)
bar="█"*filled+"░"*(bar_len-filled)
sys.stdout.write(f"\r ⏳ [{bar}] {pct:5.1f}%")
sys.stdout.flush()
print()
info("Extracting...")
with zipfile.ZipFile(zpath,"r") as zf:
zf.extractall(self.work_dir)
if platform.system().lower()!="windows":
os.chmod(self.xray_path,0o755)
os.remove(zpath)
ok(f"Xray installed: {self.xray_path}")
return True
except Exception as e:
err(f"Failed to download xray-core: {e}")
return False
def ensure_xray(self)->bool:
p=shutil.which("xray")
if p:
self.xray_path=p; ok(f"Found xray in PATH: {p}"); return True
# Check for a user-provided Xray binary bundled next to the script/package (preferred)
# e.g. copy xray.exe from v2rayN here if you need newer transports like xhttp.
script_dir = os.path.dirname(os.path.abspath(__file__))
candidates = [
os.path.join(script_dir, "xray.exe"),
os.path.join(script_dir, "xray", "xray.exe"),
os.path.join(script_dir, "bin", "xray.exe"),
os.path.join(script_dir, "xray-core", "xray.exe"),
]
for c in candidates:
if os.path.isfile(c):
self.xray_path = c
ok(f"Using bundled/user-provided xray: {c}")
return True
if self.is_installed():
ok(f"Found xray: {self.xray_path}"); return True
warn("Xray not found — downloading...")
return self.download_xray()
def parse_config(self, config_str:str)->dict:
config_str = (config_str or "").strip()
# URI shortcuts
if config_str.startswith("vless://"): return self._parse_vless(config_str)
if config_str.startswith("vmess://"): return self._parse_vmess(config_str)
if config_str.startswith("trojan://"): return self._parse_trojan(config_str)
# If a path to a file was provided, try to load it
try:
if os.path.isfile(config_str):
with open(config_str, "r", encoding="utf-8") as f:
txt = f.read().strip()
# If file contains a single URI, recurse
if txt.startswith(("vless://","vmess://","trojan://")):
return self.parse_config(txt)
# If file contains JSON, try to parse
try:
obj = json.loads(txt)
except Exception:
obj = None
if obj:
# Expecting full Xray config JSON with outbounds
if isinstance(obj, dict) and obj.get("outbounds"):
# Use first outbound as parsed representation
out = obj["outbounds"][0]
return {"outbound": out, "original_host": out.get("settings",{}).get("vnext", [{}])[0].get("address", ""), "original_port": out.get("settings",{}).get("vnext", [{}])[0].get("port", 0)}
except Exception:
pass
# Try raw JSON string (user pasted full xray config)
if config_str.startswith("{"):
try:
obj = json.loads(config_str)
if isinstance(obj, dict) and obj.get("outbounds"):
out = obj["outbounds"][0]
return {"outbound": out, "original_host": out.get("settings",{}).get("vnext", [{}])[0].get("address", ""), "original_port": out.get("settings",{}).get("vnext", [{}])[0].get("port", 0)}
except Exception:
pass
# Fallback: not a supported URI or JSON-config
raise ValueError("Unsupported config. Use vless:// vmess:// trojan:// or pass full Xray JSON config/file")
def _parse_vless(self, uri:str)->dict:
import urllib.parse
uri=uri[8:]
if "#" in uri: uri,_=uri.rsplit("#",1)
uuid,rest=uri.split("@",1)
if "?" in rest:
host_port,params_str=rest.split("?",1)
params=dict(urllib.parse.parse_qsl(params_str))
else:
host_port,params=rest,{}
if host_port.startswith("["):
host,port=host_port.rsplit(":",1); host=host.strip("[]")
else:
host,port=host_port.rsplit(":",1)
port=int(port)
outbound={"protocol":"vless","settings":{"vnext":[{"address":host,"port":port,"users":[{"id":uuid,"encryption":params.get("encryption","none"),"flow":params.get("flow","")}]}]},"streamSettings":self._build_stream_settings(params,host)}
if not outbound["settings"]["vnext"][0]["users"][0].get("flow"):
outbound["settings"]["vnext"][0]["users"][0].pop("flow",None)
return {"outbound":outbound,"original_host":host,"original_port":port,"sni":params.get("sni",params.get("serverName",host)),"host":params.get("host",host),"protocol":outbound.get("protocol",""),"transport":outbound.get("streamSettings",{}).get("network",""),"security":outbound.get("streamSettings",{}).get("security","none")}
def _parse_vmess(self, uri:str)->dict:
import base64
enc=uri[8:]
pad=4-len(enc)%4
if pad!=4: enc+="="*pad
try:
obj=json.loads(base64.b64decode(enc).decode("utf-8"))
except Exception:
raise ValueError("Invalid VMess config")
host=obj.get("add",""); port=int(obj.get("port",443))
uuid=obj.get("id",""); aid=int(obj.get("aid",0))
net=obj.get("net","tcp"); tls=obj.get("tls",""); sni=obj.get("sni",host)
ws_host=obj.get("host",host); ws_path=obj.get("path","/")
params={"type":net,"security":tls if tls else "none","sni":sni,"host":ws_host,"path":ws_path}
outbound={"protocol":"vmess","settings":{"vnext":[{"address":host,"port":port,"users":[{"id":uuid,"alterId":aid,"security":obj.get("scy","auto")}]}]},"streamSettings":self._build_stream_settings(params,host)}
return {"outbound":outbound,"original_host":host,"original_port":port,"sni":sni,"host":ws_host}
def _parse_trojan(self, uri:str)->dict:
import urllib.parse
uri=uri[9:]
if "#" in uri: uri,_=uri.rsplit("#",1)
password,rest=uri.split("@",1)
if "?" in rest:
host_port,params_str=rest.split("?",1)
params=dict(urllib.parse.parse_qsl(params_str))
else:
host_port,params=rest,{}
if host_port.startswith("["):
host,port=host_port.rsplit(":",1); host=host.strip("[]")
else:
host,port=host_port.rsplit(":",1)
port=int(port)
params.setdefault("security","tls")
outbound={"protocol":"trojan","settings":{"servers":[{"address":host,"port":port,"password":password}]},"streamSettings":self._build_stream_settings(params,host)}
return {"outbound":outbound,"original_host":host,"original_port":port,"sni":params.get("sni",host),"host":params.get("host",host)}
def _build_stream_settings(self, params:dict, default_host:str)->dict:
network=params.get("type", params.get("network","tcp"))
# Note: transports like "xhttp" require a recent Xray binary. We still parse them and let Xray handle support.
security=params.get("security","tls")
sni=params.get("sni",params.get("serverName",default_host))
alpn=params.get("alpn","h2,http/1.1")
fp=params.get("fp","chrome")
host=params.get("host",default_host)
path=params.get("path","/")
stream={"network":network}
if security=="tls":
stream["security"]="tls"
stream["tlsSettings"]={"serverName":sni,"allowInsecure":False,"alpn":alpn.split(",") if alpn else ["h2","http/1.1"],"fingerprint":fp}
elif security=="reality":
stream["security"]="reality"
stream["realitySettings"]={"serverName":sni,"fingerprint":fp,"publicKey":params.get("pbk",""),"shortId":params.get("sid",""),"spiderX":params.get("spx","")}
else:
stream["security"]="none"
if network=="ws":
stream["wsSettings"]={"path":path,"headers":{"Host":host}}
elif network=="grpc":
stream["grpcSettings"]={"serviceName":params.get("serviceName",""),"multiMode":params.get("mode","gun")=="multi"}
elif network=="tcp" and params.get("headerType")=="http":
stream["tcpSettings"]={"header":{"type":"http","request":{"path":[path],"headers":{"Host":[host]}}}}
elif network in ("h2","http"):
stream["httpSettings"]={"host":[host],"path":path}
elif network == "xhttp":
xhs = {}
# Common params: host, path, mode, extra (JSON string)
if params.get("host"):
xhs["host"] = params.get("host")
if params.get("path"):
xhs["path"] = params.get("path")
if params.get("mode"):
xhs["mode"] = params.get("mode")
extra = params.get("extra")
if extra:
try:
xhs["extra"] = json.loads(extra)
except Exception:
# If extra is not valid JSON, pass it through as-is
xhs["extra"] = extra
stream["xhttpSettings"] = xhs
return stream
def generate_xray_config(self, parsed:dict, target_ip:str, target_port:int, socks_port:int)->dict:
outbound=json.loads(json.dumps(parsed["outbound"]))
if "vnext" in outbound.get("settings",{}):
outbound["settings"]["vnext"][0]["address"]=target_ip
outbound["settings"]["vnext"][0]["port"]=target_port
elif "servers" in outbound.get("settings",{}):
outbound["settings"]["servers"][0]["address"]=target_ip
outbound["settings"]["servers"][0]["port"]=target_port
return {"log":{"loglevel":"error"},
"inbounds":[{"tag":"socks-in","port":socks_port,"listen":"127.0.0.1","protocol":"socks","settings":{"auth":"noauth","udp":False}}],
"outbounds":[outbound,{"protocol":"freedom","tag":"direct"},{"protocol":"blackhole","tag":"block"}]}
def start_xray(self, config:dict, instance_id:str):
cfg_path=os.path.join(self.work_dir, f"config_{instance_id}.json")
with open(cfg_path,"w",encoding="utf-8") as f:
json.dump(config,f,indent=2)
proc=subprocess.Popen([self.xray_path,"run","-c",cfg_path], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform=="win32" else 0)
return proc,cfg_path
def _sample_ipv4_hosts(net, k):
start=int(net.network_address)+1
end=int(net.broadcast_address)-1
if end<start: return []
n=end-start+1
k=min(k,n)
picked=set()
while len(picked)<k:
picked.add(random.randint(start,end))
return [str(ipaddress.ip_address(i)) for i in picked]
def _sample_ipv6_hosts(net, k):
# IPv6 sampling without iterating the full space.
# We generate random interface identifiers within the prefix.
if net.prefixlen>=127:
return [str(net.network_address)]
host_bits=128-net.prefixlen
k=max(1,int(k))
out=set()
base=int(net.network_address)
maxv=(1<<host_bits)-1
for _ in range(min(k*4, 50000)):
rnd=random.getrandbits(host_bits)
out.add(base+rnd)
if len(out)>=k:
break
return [str(ipaddress.ip_address(i)) for i in out]
def parse_ip_ranges(text, max_ips=10000, ip_version=4, scan_order:str='random'):
ips=[]
for line in text.strip().splitlines():
line=line.strip()
if not line or line.startswith("#"): continue
try:
if "/" in line:
net=ipaddress.ip_network(line, strict=False)
if net.version!=ip_version: continue
if ip_version==4:
ips.extend(_sample_ipv4_hosts(net, 1000))
else:
ips.extend(_sample_ipv6_hosts(net, 400))
elif "-" in line:
a,b=[p.strip() for p in line.split("-",1)]
start_ip=ipaddress.ip_address(a)
if start_ip.version!=ip_version: continue
if ip_version==6:
# For IPv6 ranges, require full end address: a-b
end_ip=ipaddress.ip_address(b)
else:
if "." in b: end_ip=ipaddress.ip_address(b)
else:
base=str(start_ip).rsplit(".",1)[0]
end_ip=ipaddress.ip_address(f"{base}.{b}")
si,ei=int(start_ip),int(end_ip)
if ei<si: si,ei=ei,si
span=ei-si+1
if span>1000:
take=1000 if ip_version==4 else 400
# random.sample on huge IPv6 ranges is expensive; use randint.
if ip_version==6:
picked={random.randint(si,ei) for _ in range(take*2)}
picked=list(picked)[:take]
else:
if scan_order=='ordered':
picked=list(range(si, min(ei, si+take-1)+1))
else:
picked=random.sample(range(si,ei+1), take)
ips.extend([str(ipaddress.ip_address(i)) for i in picked])
else:
ips.extend([str(ipaddress.ip_address(i)) for i in range(si,ei+1)])
else:
ip=ipaddress.ip_address(line)
if ip.version==ip_version: ips.append(str(ip))
except ValueError:
continue
seen=set(); clean=[]
for ip in ips:
if ip in seen: continue
seen.add(ip)
if ip_version==4:
last=int(ip.split(".")[-1])
if last not in (0,255): clean.append(ip)
else:
clean.append(ip)
if scan_order!='ordered':
random.shuffle(clean)
return clean[:max_ips]
class RichTUI:
"""
Professional Rich-based Dashboard Layout:
┌─────────────────────────────────────────┐
│ Header (title, runtime, counters) │
├───────────────────────┬─────────────────┤
│ Results Table (70%) │ Stats (30%) │
│ │ Yellow border │
├───────────────────────┴─────────────────┤
│ Footer (progress bar + status) │
└─────────────────────────────────────────┘
"""
def __init__(self, title: str = "Clean IP Scanner", sort_key: str = "score", top: int = 15):
self.title = title
self.sort_key = sort_key or "score"
self.top = top
self._items = []
self._status_line = ""
self._stats = {"clean": 0, "dirty": 0, "timeout": 0, "error": 0, "total": 0, "done": 0}
self._lock = threading.Lock()
self._stop = False
self._live = None
self._spin_frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
self._spin_i = 0
self._console = Console() if HAS_RICH else None
self._start_time = None
self._recent_results = []
self._current_testing = None # Track IP currently being tested (ip, port, start_time)
self._testing_history = [] # Recent IPs being tested
def start(self):
self._stop = False
self._start_time = time.time()
def stop(self):
self._stop = True
try:
if self._live:
self._live.stop()
except Exception:
pass
def set_current_testing(self, ip: str, port: int):
"""Mark an IP as currently being tested (for visual indicator)."""
with self._lock:
self._current_testing = {"ip": ip, "port": port, "start_time": time.time()}
self._testing_history.append({"ip": ip, "port": port})
if len(self._testing_history) > 20:
self._testing_history.pop(0)
def clear_current_testing(self):
"""Clear the current testing IP (when test completes)."""
with self._lock:
self._current_testing = None
def _get_breathing_color(self):
"""Get a smoothly breathing color that cycles through blue/cyan gradient."""
# Create smooth color cycle: blue -> dodger_blue2 -> deep_sky_blue1 -> cyan -> white -> back
colors = ["blue", "dodger_blue2", "deep_sky_blue1", "cyan", "cyan3", "dodger_blue2", "blue"]
elapsed = time.time() - self._start_time if self._start_time else 0
# Slower cycle: complete cycle every 3 seconds
cycle_position = (elapsed / 3.0) % len(colors)
color_index = int(cycle_position) % len(colors)
return colors[color_index]
def update(self, items: list, status_line: str = "", stats: dict = None):
if self._stop or not HAS_RICH:
return
with self._lock:
self._items = list(items)
self._status_line = status_line or ""
if stats:
self._stats.update(stats)
self._spin_i = (self._spin_i + 1) % len(self._spin_frames)
# Track recent results for sidebar
if items and (not self._recent_results or items[-1].ip != self._recent_results[-1].ip):
self._recent_results.append(items[-1])
if len(self._recent_results) > 15:
self._recent_results.pop(0)
layout = self._render_dashboard()
if self._live is None:
self._live = Live(layout, refresh_per_second=15, console=self._console, transient=False)
self._live.start()
else:
try:
self._live.update(layout)
except Exception:
pass
def _render_dashboard(self):
"""Build the dashboard layout with header, body (table + stats), and footer."""
layout = Layout()
layout.split_column(
Layout(name="header", size=6),
Layout(name="main", ratio=1),
Layout(name="footer", size=5)
)
layout["header"].update(self._render_header())
layout["main"].split_row(
Layout(name="table", ratio=7, minimum_size=40),
Layout(name="sidebar", ratio=3, minimum_size=20)
)
layout["main"]["table"].update(self._render_table())
layout["main"]["sidebar"].update(self._render_sidebar())
layout["footer"].update(self._render_footer())
return layout
def _render_header(self):
"""Header: Title + Runtime | Clean/Dirty/Timeout/Error Counters."""
elapsed = int(time.time() - self._start_time) if self._start_time else 0
with self._lock:
stats = self._stats.copy()
title_text = Text()
title_text.append("🔎 ", style="bold white")
title_text.append("Clean IP Scanner", style="bold cyan")
title_text.append(f" | Runtime: {elapsed}s", style="cyan")
counters_text = Text()
counters_text.append("✅ ", style="bold green")
counters_text.append(f"{stats['clean']} ", style="green")
counters_text.append("❌ ", style="bold red")
counters_text.append(f"{stats['dirty']} ", style="red")
counters_text.append("⏱ ", style="bold yellow")
counters_text.append(f"{stats['timeout']} ", style="yellow")
counters_text.append("⚠ ", style="bold magenta")
counters_text.append(f"{stats['error']}", style="magenta")
counters_text.append(" │ ", style="dim")
counters_text.append(f"Total: {stats['done']}/{stats['total']}", style="cyan")
content = Text.assemble(title_text, "\n", counters_text)
return Panel(
Align.center(content),
border_style=self._get_breathing_color(),
box=box.ROUNDED,
padding=(0, 2)
)
def _render_table(self):
"""Main results table with IP, Delay, Jitter, Loss, DL, UL, Score."""
with self._lock: