-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
title.py
1143 lines (875 loc) · 49.5 KB
/
title.py
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
#import requirement libraries
import os
import uuid
import time
import random
import json
import pycountry_convert as pc
#import web-based libraries
import html
import requests
import socket
import ipaddress
import ssl
import tldextract
import geoip2.database
import json
from dns import resolver, rdatatype
#import regex and encoding libraries
import re
import base64
def is_valid_base64(string_value):
try:
# Decode the string using base64
byte_decoded = base64.b64decode(string_value)
# Encode the decoded bytes back to base64 and compare to the original string
return base64.b64encode(byte_decoded).decode("utf-8") == string_value
except:
# If an exception is raised during decoding, the string is not valid base64
return False
def is_valid_uuid(value):
try:
# Try out to checkout valid UUID and return True
uuid.UUID(str(value))
return True
except ValueError:
# Return False If it's invalid
return False
def is_valid_domain(hostname):
# Extract the TLD, domain, and subdomain from the hostname
ext = tldextract.extract(hostname)
# Check if the domain and TLD are not empty
return ext.domain != "" and ext.suffix != ""
def is_valid_ip_address(ip):
try:
if ip.startswith("[") and ip.endswith("]"):
ip = ip.replace("[", "")
ip = ip.replace("]", "")
# Try out to return True if it's IPV4 or IPV6
ipaddress.ip_address(ip)
return True
except ValueError:
# Else it returns False
return False
def is_ipv6(ip):
try:
# Try out to return True if it's IPV6
ipaddress.ip_address(ip)
if ":" in ip:
return True
else:
# Else it returns False
return False
except ValueError:
return False
def get_ips(node):
try:
res = resolver.Resolver()
res.nameservers = ["8.8.8.8"]
# Retrieve IPV4 and IPV6
answers_ipv4 = res.resolve(node, rdatatype.A, raise_on_no_answer=False)
answers_ipv6 = res.resolve(node, rdatatype.AAAA, raise_on_no_answer=False)
# Initialize set for IPV4 and IPV6
ips = set()
# Append IPV4 and IPV6 into set
for rdata in answers_ipv4:
ips.add(rdata.address)
for rdata in answers_ipv6:
ips.add(rdata.address)
return ips
except Exception:
return None
def get_ip(node):
try:
# Get node and return the current hostname
return socket.gethostbyname(node)
except Exception:
return None
def get_country_from_ip(ip):
if not is_valid_ip_address(ip):
ips_list = list(get_ips(ip))
ip = ips_list[0]
try:
with geoip2.database.Reader("./geoip-lite/geoip-lite-country.mmdb") as reader:
response = reader.country(ip)
country_code = response.country.iso_code
if not country_code is None:
return country_code
else:
# If country code is NoneType, Returns 'NA'
return "NA"
except:
return "NA"
def get_country_flag(country_code):
if country_code == 'NA':
return html.unescape("\U0001F3F4\u200D\u2620\uFE0F")
base = 127397 # Base value for regional indicator symbol letters
codepoints = [ord(c) + base for c in country_code.upper()]
return html.unescape("".join(["&#x{:X};".format(c) for c in codepoints]))
def get_continent(country_code):
continent_code = pc.country_alpha2_to_continent_code(country_code)
if continent_code in ['NA', 'SA']:
continent_emoji = "\U0001F30E"
elif continent_code in ['EU', 'AF', 'AN']:
continent_emoji = "\U0001F30D"
elif continent_code in ['AS', 'OC']:
continent_emoji = "\U0001F30F"
return continent_emoji
def check_port(ip, port, timeout=1):
"""
Check if a port is open on a given IP address.
Args:
ip (str): The IP address.
port (int): The port number.
timeout (int, optional): The timeout in seconds. Defaults to 5.
Returns:
bool: True if the port is open, False otherwise.
"""
try:
sock = socket.create_connection(address=(ip, port), timeout=timeout)
sock.close()
print("Connection Port: Open".upper())
return True
except:
print("Connection Port: Closed\n".upper())
return False
def ping_ip_address(ip, port):
try:
it = time.time()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
ft = time.time()
sock.close()
if result == 0:
return round((ft - it) * 1000, 2)
else:
return round(0, 2)
except:
return round(0, 2)
def get_isp(node):
if node.startswith("[") and node.endswith("]"):
node = node.replace("[", "")
node = node.replace("]", "")
try:
ip_geo_info = requests.get(f'http://ip-api.com/json/{node}')
ip_geo_info_dict = json.loads(ip_geo_info.text)
isp_value = [char for char in list(ip_geo_info_dict["isp"]) if char not in [',', '.', '"']]
isp_value = ''.join(isp_value)
return isp_value
except:
return "Not Available"
def check_modify_config(array_configuration, protocol_type, check_connection = True):
# Initialize list for modified elements of configuration array
modified_array = list()
# Initialize array for security types of configuration
tls_array = list()
non_tls_array = list()
# Initialize array for network types of configuration
tcp_array = list()
ws_array = list()
http_array = list()
grpc_array = list()
if protocol_type == 'SHADOWSOCKS':
for element in array_configuration:
# Define ShadowSocks protocol type pattern
shadowsocks_pattern = r"ss://(?P<id>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)/?#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
shadowsocks_match = re.match(shadowsocks_pattern, element, flags=re.IGNORECASE)
if shadowsocks_match is None:
# Define ShadowSocks protocol type second pattern
shadowsocks_pattern = r"ss://(?P<id>[^#]+)#?(?P<title>(?<=#).*)?(?P<ip>(?:))(?P<port>(?:))"
# Try out to match second pattern and configuration
shadowsocks_match = re.match(shadowsocks_pattern, element, flags=re.IGNORECASE)
if shadowsocks_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": shadowsocks_match.group("id"),
"ip": shadowsocks_match.group("ip"),
"port": shadowsocks_match.group("port"),
"title": shadowsocks_match.group("title"),
}
config["id"] += "=" * ((4 - len(config["id"]) % 4) % 4)
# Checkout config ID type
if not is_valid_base64(config["id"]):
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print(f"INVALID ENCODED STRING: {config['id']}\n")
# Continue for next element
continue
# Try out to match pattern for ShadowSocks config and extract IP and
if config["ip"] == "":
# Define ShadowSocks protocol type Third pattern
shadowsocks_pattern = (r"(?P<id>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)")
# Try out to match pattern and configuration
shadowsocks_match = re.match(shadowsocks_pattern, base64.b64decode(config["id"]).decode("utf-8", errors="ignore"), flags=re.IGNORECASE)
if shadowsocks_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": base64.b64encode(shadowsocks_match.group("id").encode("utf-8")).decode("utf-8"),
"ip": shadowsocks_match.group("ip"),
"port": shadowsocks_match.group("port"),
"title": config["title"],
}
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
'''
# Continue for next IP address if exists in modified array
if any(f"ss://{config['id']}@{config['ip']}:{config['port']}" in array_element for array_element in modified_array):
continue
'''
# Retrieve config network type and security type
config_secrt = 'NA'
config_type = 'TCP'
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 SS-TCP-NA {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
# Append security type array
if config_secrt == 'TLS' or config_secrt == 'REALITY':
tls_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
elif config_secrt == 'NA':
non_tls_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
# Append network type array
if config_type == 'TCP':
tcp_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
elif config_type == 'WS':
ws_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
elif config_type == 'HTTP':
http_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
elif config_type == 'GRPC':
grpc_array.append(f"ss://{config['id']}@{config['ip']}:{config['port']}#{config['title']}")
elif protocol_type == 'TROJAN':
for element in array_configuration:
# Define Trojan protocol type pattern
trojan_pattern = r"trojan://(?P<id>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)/?\??(?P<params>[^#]+)?#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
trojan_match = re.match(trojan_pattern, element, flags=re.IGNORECASE)
if trojan_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": trojan_match.group("id"),
"ip": trojan_match.group("ip"),
"host": trojan_match.group("ip"),
"port": trojan_match.group("port"),
"params": trojan_match.group("params") or "",
"title": trojan_match.group("title"),
}
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Split configuration parameters and initialize dict for parameters
array_params_input = config["params"].split("&")
dict_params = {}
# Iterate over parameters and split based on key value
for pair in array_params_input:
try:
key, value = pair.split("=")
key = re.sub(r"servicename", "serviceName", re.sub(r"headertype", "headerType", re.sub(r"allowinsecure", "allowInsecure", key.lower()),),)
dict_params[key] = value
except:
pass
# Set parameters for servicename and allowinsecure keys
if (dict_params.get("security", "") in ["reality", "tls"] and dict_params.get("sni", "") == "" and is_valid_domain(config["host"])):
dict_params["sni"] = config["host"]
dict_params["allowInsecure"] = 1
# Ignore the configurations with specified security and None servicename
if (dict_params.get("security", "") in ["reality", "tls"] and dict_params.get("sni", "") == ""):
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Define configuration parameters string value and stripped based on & character
config["params"] = f"security={dict_params.get('security', '')}&flow={dict_params.get('flow', '')}&sni={dict_params.get('sni', '')}&encryption={dict_params.get('encryption', '')}&type={dict_params.get('type', '')}&serviceName={dict_params.get('serviceName', '')}&host={dict_params.get('host', '')}&path={dict_params.get('path', '')}&headerType={dict_params.get('headerType', '')}&fp={dict_params.get('fp', '')}&pbk={dict_params.get('pbk', '')}&sid={dict_params.get('sid', '')}&alpn={dict_params.get('alpn', '')}&allowInsecure={dict_params.get('allowInsecure', '')}&"
config["params"] = re.sub(r"\w+=&", "", config["params"])
config["params"] = re.sub(r"(?:encryption=none&)|(?:headerType=none&)", "", config["params"], flags=re.IGNORECASE,)
config["params"] = config["params"].strip("&")
'''
# Continue for next IP address if exists in modified array
if any(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}" in array_element for array_element in modified_array):
continue
'''
# Retrieve config network type and security type
config_type = dict_params.get('type', 'TCP').upper() if dict_params.get('type') not in [None, ''] else 'TCP'
config_secrt = dict_params.get('security', 'TLS').upper() if dict_params.get('security') not in [None, ''] else 'NA'
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 TR-{config_type}-{config_secrt} {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
# Append security type array
if config_secrt == 'TLS' or config_secrt == 'REALITY':
tls_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_secrt == 'NA':
non_tls_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
# Append network type array
if config_type == 'TCP':
tcp_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'WS':
ws_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'HTTP':
http_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'GRPC':
grpc_array.append(f"trojan://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif protocol_type == 'VMESS':
for element in array_configuration:
# Define VMESS protocol type pattern
vmess_pattern = r"vmess://(?P<json>[^#].*)"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
vmess_match = re.match(vmess_pattern, element, flags=re.IGNORECASE)
if vmess_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
json_string = vmess_match.group("json")
json_string += "=" * ((4 - len(json_string) % 4) % 4)
# Checkout config json encoded string
if not is_valid_base64(json_string):
# Append invalid json encoded string config into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print(f"INVALID ENCODED STRING: {json_string}\n")
# Continue for next element
continue
# Decode json string match
json_string = base64.b64decode(json_string).decode("utf-8", errors="ignore")
try:
# Convert decoded json string into dictionary
dict_params = json.loads(json_string)
# Modify dictionary parameters with lower keys and values
dict_params = {k.lower(): v for k, v in dict_params.items()}
except:
# Append invalid json encoded string config into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print(f"INVALID JSON STRING: {json_string}\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": dict_params.get("id", ""),
"ip": dict_params.get("add", ""),
"host": dict_params.get("add", ""),
"port": dict_params.get("port", ""),
"params": "",
"title": dict_params.get("ps", "")
}
# Checkout configuration UUID
if not is_valid_uuid(config["id"]):
print(f"INVALID UUID: {config['id']}\n")
continue
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Set parameters for servicename and allowinsecure keys
if (dict_params.get("tls", "") in ["tls"] and dict_params.get("sni", "") == "" and is_valid_domain(config["host"])):
dict_params["sni"] = config["host"]
dict_params["allowInsecure"] = 1
# Ignore the configurations with specified security and None servicename
if (dict_params.get("tls", "") in ["tls"] and dict_params.get("sni", "") == ""):
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Define configuration parameters string value and stripped based on & character
config["params"] = f"tls={dict_params.get('tls', '')}&sni={dict_params.get('sni', '')}&scy={dict_params.get('scy', '')}&net={dict_params.get('net', '')}&host={dict_params.get('host', '')}&path={dict_params.get('path', '')}&type={dict_params.get('type', '')}&fp={dict_params.get('fp', '')}&alpn={dict_params.get('alpn', '')}&aid={dict_params.get('aid', '')}&v={dict_params.get('v', '')}&allowInsecure={dict_params.get('allowInsecure', '')}&"
config["params"] = re.sub(r"\w+=&", "", config["params"])
config["params"] = re.sub(r"(?:tls=none&)|(?:type=none&)|(?:scy=none&)|(?:scy=auto&)", "", config["params"], flags=re.IGNORECASE,)
config["params"] = config["params"].strip("&")
# Retrieve config network type and security type
config_type = dict_params.get('net', 'TCP').upper() if dict_params.get('net') not in [None, ''] else 'TCP'
config_secrt = dict_params.get('tls','NA').upper() if dict_params.get('tls') not in [None, ''] else 'NA'
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 VM-{config_type}-{config_secrt} {country_flag} {country_code}-{config['ip']}:{config['port']}"
dict_params["add"] = config["ip"]
dict_params["ps"] = config["title"]
# Print out modified configuration
print(f"MODIFIED CONFIG: vmess://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
# Append security type array
if config_secrt == 'TLS' or config_secrt == 'REALITY':
tls_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
elif config_secrt == 'NA':
non_tls_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
# Append network type array
if config_type == 'TCP':
tcp_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
elif config_type == 'WS':
ws_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
elif config_type == 'HTTP':
http_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
elif config_type == 'GRPC':
grpc_array.append(f"vmess://{base64.b64encode(json.dumps(dict_params).encode('utf-8')).decode('utf-8')}")
elif protocol_type == 'VLESS' or protocol_type == 'REALITY':
for element in array_configuration:
# Define VMESS protocol type pattern
vless_pattern = r"vless://(?P<id>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:\-:\_]+?)\]?:(?P<port>[0-9]+)/?\?(?P<params>[^#]+)#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
vless_match = re.match(vless_pattern, element, flags=re.IGNORECASE)
if vless_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": vless_match.group("id"),
"ip": vless_match.group("ip"),
"host": vless_match.group("ip"),
"port": vless_match.group("port"),
"params": vless_match.group("params"),
"title": vless_match.group("title"),
}
# Checkout configuration UUID
if not is_valid_uuid(config["id"]):
print(f"INVALID UUID: {config['id']}\n")
continue
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Split configuration parameters and initialize dict for parameters
array_params_input = config["params"].split("&")
dict_params = {}
# Iterate over parameters and split based on key value
for pair in array_params_input:
try:
key, value = pair.split("=")
key = re.sub(r"servicename", "serviceName", re.sub(r"headertype", "headerType", re.sub(r"allowinsecure", "allowInsecure", key.lower()),),)
dict_params[key] = value
except:
pass
# Set parameters for servicename and allowinsecure keys
if (dict_params.get("security", "") in ["reality", "tls"] and dict_params.get("sni", "") == "" and is_valid_domain(config["host"])):
dict_params["sni"] = config["host"]
dict_params["allowInsecure"] = 1
# Ignore the configurations with specified security and None servicename
if (dict_params.get("security", "") in ["reality", "tls"] and dict_params.get("sni", "") == ""):
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Define configuration parameters string value and stripped based on & character
config["params"] = f"security={dict_params.get('security', '')}&flow={dict_params.get('flow', '')}&sni={dict_params.get('sni', '')}&encryption={dict_params.get('encryption', '')}&type={dict_params.get('type', '')}&serviceName={dict_params.get('serviceName', '')}&host={dict_params.get('host', '')}&path={dict_params.get('path', '')}&headerType={dict_params.get('headerType', '')}&fp={dict_params.get('fp', '')}&pbk={dict_params.get('pbk', '')}&sid={dict_params.get('sid', '')}&alpn={dict_params.get('alpn', '')}&allowInsecure={dict_params.get('allowInsecure', '')}&"
config["params"] = re.sub(r"\w+=&", "", config["params"])
config["params"] = re.sub(r"(?:encryption=none&)|(?:headerType=none&)", "", config["params"], flags=re.IGNORECASE,)
config["params"] = config["params"].strip("&")
'''
# Continue for next IP address if exists in modified array
if any(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}" in array_element for array_element in modified_array):
continue
'''
# Retrieve config network type and security type
config_type = dict_params.get('type', 'TCP').upper() if dict_params.get('type') not in [None, ''] else 'TCP'
config_secrt = dict_params.get('security','NA').upper() if dict_params.get('security') not in [None, ''] else 'NA'
if config_secrt == 'REALITY':
config_secrt = 'RLT'
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 VL-{config_type}-{config_secrt} {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
# Append security type array
if config_secrt == 'TLS' or config_secrt == 'REALITY':
tls_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_secrt == 'NA':
non_tls_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
# Append network type array
if config_type == 'TCP':
tcp_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'WS':
ws_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'HTTP':
http_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif config_type == 'GRPC':
grpc_array.append(f"vless://{config['id']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif protocol_type == 'TUIC':
for element in array_configuration:
# Define ShadowSocks protocol type pattern
tuic_pattern = r"tuic://(?P<id>[^:]+):(?P<pass>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)/?\?(?P<params>[^#]+)#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
tuic_match = re.match(tuic_pattern, element, flags=re.IGNORECASE)
if tuic_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"id": tuic_match.group("id"),
"pass": tuic_match.group("pass"),
"ip": tuic_match.group("ip"),
"port": tuic_match.group("port"),
"params": tuic_match.group("params"),
"title": tuic_match.group("title")
}
# Checkout configuration UUID
if not is_valid_uuid(config["id"]):
print(f"INVALID UUID: {config['id']}\n")
continue
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 TUIC-UDP {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: tuic://{config['id']}:{config['pass']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"tuic://{config['id']}:{config['pass']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif protocol_type == 'HYSTERIA':
for element in array_configuration:
if element.startswith('hysteria'):
# Define ShadowSocks protocol type pattern
hysteria_1_pattern = r"hysteria://\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)/?\?(?P<params>[^#]+)#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
hysteria_match = re.match(hysteria_1_pattern, element, flags=re.IGNORECASE)
if hysteria_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"ip": hysteria_match.group("ip"),
"port": hysteria_match.group("port"),
"params": hysteria_match.group("params"),
"title": hysteria_match.group("title")
}
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 HYSTERIA-UDP {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: hysteria://{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"hysteria://{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
elif element.startswith('hy2'):
# Define ShadowSocks protocol type pattern
hysteria_2_pattern = r"hy2://(?P<pass>[^@]+)@\[?(?P<ip>[a-zA-Z0-9\.:-]+?)\]?:(?P<port>[0-9]+)/?\?(?P<params>[^#]+)#?(?P<title>(?<=#).*)?"
# Print out original element
print(f"ORIGINAL CONFIG: {element}")
# Try out to match pattern and configuration
hysteria_match = re.match(hysteria_2_pattern, element, flags=re.IGNORECASE)
if hysteria_match is None:
# Append no matches ShadowSocks into unmatched file
with open("./splitted/no-match", "a") as no_match_file:
no_match_file.write(f"{element}\n")
print("NO MATCH\n")
# Continue for next element
continue
# Initialize dict to separate match groups by name capturing
config = {
"pass": hysteria_match.group("pass"),
"ip": hysteria_match.group("ip"),
"port": hysteria_match.group("port"),
"params": hysteria_match.group("params"),
"title": hysteria_match.group("title")
}
# Initialize set to append IP addresses
ips_list = {config["ip"]}
# Try out to retrieve config IP adresses if It's url link
if not is_valid_ip_address(config["ip"]):
ips_list = get_ips(config["ip"])
# Continue for next element
if ips_list is None:
print("NO IP\n")
continue
# Iterate over IP addresses to checkout connectivity
for ip_address in ips_list:
# Set config dict IP address
config["ip"] = ip_address
# Checkout IP address and port connectivity
if check_connection:
if not check_port(config["ip"], int(config["port"])):
continue
# config_ping = ping_ip_address(config["ip"], int(config["port"]))
# Try out to retrieve country code
country_code = get_country_from_ip(config["ip"])
country_flag = get_country_flag(country_code)
continent_emoji = get_continent(country_code)
# Modify the IP address if it's IPV6
if is_ipv6(config["ip"]):
config["ip"] = f"[{config['ip']}]"
# Modify configuration title based on server and protocol properties
config["title"] = f"\U0001F512 HYSTERIA-UDP {country_flag} {country_code}-{config['ip']}:{config['port']}"
# Print out modified configuration
print(f"MODIFIED CONFIG: hy2://{config['pass']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}\n")
# Append modified configuration into modified array
modified_array.append(f"hy2://{config['pass']}@{config['ip']}:{config['port']}?{config['params']}#{config['title']}")
else: