-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbbscli.py
More file actions
1299 lines (1092 loc) · 58.5 KB
/
bbscli.py
File metadata and controls
1299 lines (1092 loc) · 58.5 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/python3
import json
import argparse
import os
import tempfile
import re
import ipaddress
import pyparsing as pp
class Config:
"""JSON Configuration file wrapper"""
# --- Top Level Keys ---
GLOBAL_KEY_PROXIES = "proxies"
GLOBAL_KEY_CHAINS = "chains"
GLOBAL_KEY_ROUTES = "routes"
GLOBAL_KEY_SERVERS = "servers"
GLOBAL_KEY_HOSTS = "hosts"
# --- Proxy Keys ---
PROXY_KEY_CONNSTRING = "connstring"
PROXY_KEY_USER = "user"
PROXY_KEY_PASS = "pass"
# --- Chain Keys ---
CHAIN_KEY_PROXYDNS = "proxyDns"
CHAIN_KEY_TCPREADTIMEOUT = "tcpReadTimeout"
CHAIN_KEY_TCPCONNECTTIMEOUT = "tcpConnectTimeout"
CHAIN_KEY_PROXIES = "proxies"
# --- Table Keys ---
TABLE_KEY_DEFAULT = "default" # Default route for the table
TABLE_KEY_BLOCKS = "blocks" # List of route blocks in the table
# --- Route Block Keys (Element in the list for a table) ---
ROUTEBLOCK_KEY_COMMENT = "comment"
ROUTEBLOCK_KEY_RULES = "rules" # This holds the parsed rule structure (dict)
ROUTEBLOCK_KEY_ROUTE = "route" # Target chain name or "drop"
ROUTEBLOCK_KEY_DISABLE = "disable"
# --- Route Rule Keys (Used within the 'rules' dict) ---
ROUTERULE_KEY_RULE = "rule" # Type of rule: regexp, subnet, true, rulecombo
ROUTERULE_KEY_VARIABLE = "variable" # For regexp: host, port, addr
ROUTERULE_KEY_CONTENT = "content" # For regexp/subnet: the pattern/CIDR
ROUTERULE_KEY_NEGATE = "negate" # Boolean
# --- Route Rule Combo Keys (Used when rule="rulecombo") ---
ROUTERULECOMBO_KEY_RULE1 = "rule1" # Nested rule dict
ROUTERULECOMBO_KEY_RULE2 = "rule2" # Nested rule dict
ROUTERULECOMBO_KEY_OP = "op" # "and" or "or"
# --- Route Rule Types ---
ROUTERULE_TYPE_REGEX = "regexp"
ROUTERULE_TYPE_SUBNET = "subnet"
ROUTERULE_TYPE_TRUE = "true" # Represents an always-true condition
ROUTERULE_TYPE_COMBO = "rulecombo" # Represents combined rules
# --- Route Targets ---
ROUTERULE_DROP = "drop"
contents = dict()
def __init__(self, path):
self.path = os.path.abspath(path)
self.load()
def load(self):
"""Load JSON config from file"""
try:
with open(self.path) as file:
self.contents = json.load(file)
print(f"Config loaded from {self.path}")
except json.JSONDecodeError as e:
print(f"Error decoding JSON from {self.path}: {e}")
self.contents = {} # Start fresh if decode fails
except FileNotFoundError:
print(f"Config file {self.path} not found. Creating default structure.")
self.contents = {} # Start fresh if not found
except Exception as e:
print(f"Unexpected error loading config {self.path}: {e}")
self.contents = {}
# Ensure default structure exists
self.contents.setdefault(self.GLOBAL_KEY_PROXIES, {})
self.contents.setdefault(self.GLOBAL_KEY_CHAINS, {})
self.contents.setdefault(self.GLOBAL_KEY_ROUTES, {})
self.contents.setdefault(self.GLOBAL_KEY_SERVERS, [])
self.contents.setdefault(self.GLOBAL_KEY_HOSTS, {})
# No initial save here, let operations trigger saves
def save(self):
"""Save JSON config to file atomically"""
try:
directory = os.path.dirname(self.path)
basename = os.path.basename(self.path)
# Ensure directory exists
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
print(f"Created directory {directory}")
fd, tmp = tempfile.mkstemp(prefix=f'.{basename}.', dir=directory)
with os.fdopen(fd, 'w') as file:
json.dump(self.contents, file, indent=4) # Pretty print
file.flush()
os.fsync(fd) # Ensure data is written to disk
os.rename(tmp, self.path)
print(f"Config saved to {self.path}")
except Exception as e:
print(f"Error saving config to {self.path}: {e}")
# --- Proxy Management ---
def _get_unused_proxy_name(self):
names = self.contents[self.GLOBAL_KEY_PROXIES].keys()
for i in range(1, 1000):
name = f"proxy{i}"
if name not in names:
return name
raise ValueError("Could not find an unused proxy name (tried up to proxy999)")
def get_proxy(self, name):
return self.contents[self.GLOBAL_KEY_PROXIES].get(name, None)
def get_proxies(self):
return self.contents[self.GLOBAL_KEY_PROXIES]
def add_proxy(self, name, connstring, user=None, password=None):
if name in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Proxy '{name}' already exists.")
return False
self.contents[self.GLOBAL_KEY_PROXIES][name] = {
self.PROXY_KEY_CONNSTRING: connstring
}
if user:
self.contents[self.GLOBAL_KEY_PROXIES][name][self.PROXY_KEY_USER] = user
if password:
self.contents[self.GLOBAL_KEY_PROXIES][name][self.PROXY_KEY_PASS] = password
self.save()
print(f"Proxy '{name}' added.")
return True
def delete_proxy(self, name=None):
if name is None: # Delete all
if not self.contents[self.GLOBAL_KEY_PROXIES]:
print("No proxies to delete.")
return False
self.contents[self.GLOBAL_KEY_PROXIES] = {}
self.save()
print("All proxies deleted.")
return True
else:
if name not in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Proxy '{name}' does not exist.")
return False
del self.contents[self.GLOBAL_KEY_PROXIES][name]
self.save()
print(f"Proxy '{name}' deleted.")
return True
def update_proxy(self, name, protocol=None, host=None, port=None, user=None, password=None, newName=None):
if name not in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Proxy '{name}' does not exist.")
return False
proxy_data = self.contents[self.GLOBAL_KEY_PROXIES][name]
# Update user/pass directly
if user is not None: # Allow empty string for user
proxy_data[self.PROXY_KEY_USER] = user
if password is not None: # Allow empty string for password
proxy_data[self.PROXY_KEY_PASS] = password
# Update connstring components
oldConnstring = proxy_data.get(self.PROXY_KEY_CONNSTRING, "://:")
try:
parts = oldConnstring.split("://", 1)
oldProtocol = parts[0] if len(parts) > 1 else ""
host_port = parts[1] if len(parts) > 1 else ""
host_port_parts = host_port.split(":", 1)
oldHost = host_port_parts[0] if len(host_port_parts) > 0 else ""
oldPort = host_port_parts[1] if len(host_port_parts) > 1 else ""
except Exception:
print(f"Warning: Could not parse existing connstring '{oldConnstring}' for proxy '{name}'. Updating based on provided values.")
oldProtocol, oldHost, oldPort = "", "", ""
newProtocol = protocol if protocol is not None else oldProtocol
newHost = host if host is not None else oldHost
newPort = port if port is not None else oldPort
proxy_data[self.PROXY_KEY_CONNSTRING] = f"{newProtocol}://{newHost}:{newPort}"
# Handle renaming
if newName and newName != name:
if newName in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Cannot rename proxy to '{newName}', name already exists.")
# Revert changes before renaming attempt? Or save intermediate? Let's save intermediate.
self.contents[self.GLOBAL_KEY_PROXIES][name] = proxy_data # Put potentially modified data back
self.save()
return False
else:
self.contents[self.GLOBAL_KEY_PROXIES][newName] = self.contents[self.GLOBAL_KEY_PROXIES].pop(name)
print(f"Proxy '{name}' updated and renamed to '{newName}'.")
else:
self.contents[self.GLOBAL_KEY_PROXIES][name] = proxy_data
print(f"Proxy '{name}' updated.")
self.save()
return True
# --- Chain Management ---
def _get_unused_chain_name(self):
names = self.contents[self.GLOBAL_KEY_CHAINS].keys()
for i in range(1, 1000):
name = f"chain{i}"
if name not in names:
return name
raise ValueError("Could not find an unused chain name (tried up to chain999)")
def get_chain(self, name):
return self.contents[self.GLOBAL_KEY_CHAINS].get(name, None)
def get_chains(self):
return self.contents[self.GLOBAL_KEY_CHAINS]
def add_chain(self, name, proxies, tcpReadTimeout=None, tcpConnectTimeout=None, proxyDns=None):
if name in self.contents[self.GLOBAL_KEY_CHAINS]:
print(f"Error: Chain '{name}' already exists.")
return False
# Validate proxies exist
for proxy_name in proxies:
if proxy_name not in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Proxy '{proxy_name}' specified in chain '{name}' does not exist.")
return False
chain_data = {self.CHAIN_KEY_PROXIES: proxies}
if tcpReadTimeout is not None:
try:
chain_data[self.CHAIN_KEY_TCPREADTIMEOUT] = int(tcpReadTimeout)
except ValueError:
print(f"Error: tcpReadTimeout '{tcpReadTimeout}' must be an integer.")
return False
if tcpConnectTimeout is not None:
try:
chain_data[self.CHAIN_KEY_TCPCONNECTTIMEOUT] = int(tcpConnectTimeout)
except ValueError:
print(f"Error: tcpConnectTimeout '{tcpConnectTimeout}' must be an integer.")
return False
if proxyDns is not None:
chain_data[self.CHAIN_KEY_PROXYDNS] = bool(proxyDns)
self.contents[self.GLOBAL_KEY_CHAINS][name] = chain_data
self.save()
print(f"Chain '{name}' added.")
return True
def delete_chain(self, name=None):
if name is None: # Delete all
if not self.contents[self.GLOBAL_KEY_CHAINS]:
print("No chains to delete.")
return False
self.contents[self.GLOBAL_KEY_CHAINS] = {}
self.save()
print("All chains deleted.")
return True
else:
if name not in self.contents[self.GLOBAL_KEY_CHAINS]:
print(f"Error: Chain '{name}' does not exist.")
return False
del self.contents[self.GLOBAL_KEY_CHAINS][name]
# TODO: Check if chain is used in routes and warn/prevent?
self.save()
print(f"Chain '{name}' deleted.")
return True
def update_chain(self, name, proxies=None, tcpReadTimeout=None, tcpConnectTimeout=None, proxyDns=None, newName=None):
if name not in self.contents[self.GLOBAL_KEY_CHAINS]:
print(f"Error: Chain '{name}' does not exist.")
return False
chain_data = self.contents[self.GLOBAL_KEY_CHAINS][name]
if proxies:
# Validate new proxies exist
for proxy_name in proxies:
if proxy_name not in self.contents[self.GLOBAL_KEY_PROXIES]:
print(f"Error: Proxy '{proxy_name}' specified for chain '{name}' does not exist.")
return False
chain_data[self.CHAIN_KEY_PROXIES] = proxies
if tcpReadTimeout is not None:
try:
chain_data[self.CHAIN_KEY_TCPREADTIMEOUT] = int(tcpReadTimeout)
except ValueError:
print(f"Error: tcpReadTimeout '{tcpReadTimeout}' must be an integer.")
return False
if tcpConnectTimeout is not None:
try:
chain_data[self.CHAIN_KEY_TCPCONNECTTIMEOUT] = int(tcpConnectTimeout)
except ValueError:
print(f"Error: tcpConnectTimeout '{tcpConnectTimeout}' must be an integer.")
return False
if proxyDns is not None:
chain_data[self.CHAIN_KEY_PROXYDNS] = bool(proxyDns)
# Handle renaming
if newName and newName != name:
if newName in self.contents[self.GLOBAL_KEY_CHAINS]:
print(f"Error: Cannot rename chain to '{newName}', name already exists.")
self.contents[self.GLOBAL_KEY_CHAINS][name] = chain_data # Put potentially modified data back
self.save() # Save intermediate state
return False
else:
# TODO: Update routes using this chain? Difficult without back-refs. Warn user.
print(f"Warning: Renaming chain '{name}' to '{newName}'. Routes using the old name might need manual updates.")
self.contents[self.GLOBAL_KEY_CHAINS][newName] = self.contents[self.GLOBAL_KEY_CHAINS].pop(name)
print(f"Chain '{name}' updated and renamed to '{newName}'.")
else:
self.contents[self.GLOBAL_KEY_CHAINS][name] = chain_data
print(f"Chain '{name}' updated.")
self.save()
return True
# --- Server Management ---
def get_server(self, index):
try:
index = int(index)
return self.contents[self.GLOBAL_KEY_SERVERS][index]
except (ValueError, IndexError):
print(f"Error: Invalid server index {index}")
return None
def get_servers(self):
return self.contents[self.GLOBAL_KEY_SERVERS]
def add_server(self, protocol, host, port, table):
connstring = f"{protocol}://{host}:{port}:{table}"
# Check if server already exists (exact match)
if connstring in self.contents[self.GLOBAL_KEY_SERVERS]:
print(f"Error: Server '{connstring}' already exists.")
return False
# Check if table exists in routes
if table not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Warning: Routing table '{table}' referenced by server does not exist yet. Create it using 'route add'.")
# Allow adding server anyway, but warn.
self.contents[self.GLOBAL_KEY_SERVERS].append(connstring)
self.save()
print(f"Server '{connstring}' added at index {len(self.contents[self.GLOBAL_KEY_SERVERS]) - 1}.")
return True
def add_server_fwd(self, local_host, local_port, chain, remote_host, remote_port):
"""Adds a forwarder server with the format: fwd://local_host:local_port:chain:remote_host:remote_port"""
connstring = f"fwd://{local_host}:{local_port}:{chain}:{remote_host}:{remote_port}"
# Check if server already exists (exact match)
if connstring in self.contents[self.GLOBAL_KEY_SERVERS]:
print(f"Error: Forwarder '{connstring}' already exists.")
return False
# Check if chain exists
if not self.is_route_valid(chain):
print(f"Error: Chain '{chain}' does not exist. Create it first using 'chain add'.")
return False
self.contents[self.GLOBAL_KEY_SERVERS].append(connstring)
self.save()
print(f"Forwarder '{connstring}' added at index {len(self.contents[self.GLOBAL_KEY_SERVERS]) - 1}.")
return True
def delete_server(self, index=None):
if index is None: # Delete all
if not self.contents[self.GLOBAL_KEY_SERVERS]:
print("No servers to delete.")
return False
self.contents[self.GLOBAL_KEY_SERVERS] = []
self.save()
print("All servers deleted.")
return True
try:
index = int(index)
if 0 <= index < len(self.contents[self.GLOBAL_KEY_SERVERS]):
deleted_server = self.contents[self.GLOBAL_KEY_SERVERS].pop(index)
self.save()
print(f"Server '{deleted_server}' at index {index} deleted.")
return True
else:
print(f"Error: Invalid server index {index}.")
return False
except ValueError:
print(f"Error: Server index '{index}' must be an integer.")
return False
def update_server(self, index, protocol=None, host=None, port=None, table=None):
try:
index = int(index)
if not (0 <= index < len(self.contents[self.GLOBAL_KEY_SERVERS])):
print(f"Error: Invalid server index {index}.")
return False
server = self.contents[self.GLOBAL_KEY_SERVERS][index]
try:
parts = server.split("://", 1)
oldProtocol = parts[0]
host_port_table = parts[1].split(":", 2)
oldHost = host_port_table[0]
oldPort = host_port_table[1]
oldTable = host_port_table[2]
except Exception:
print(f"Warning: Could not parse existing server string '{server}'. Updating based on provided values.")
oldProtocol, oldHost, oldPort, oldTable = "", "", "", ""
newProtocol = protocol if protocol is not None else oldProtocol
newHost = host if host is not None else oldHost
newPort = port if port is not None else oldPort
newTable = table if table is not None else oldTable
# Check if new table exists
if newTable not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Warning: New routing table '{newTable}' referenced by server does not exist yet. Create it using 'route add'.")
new_connstring = f"{newProtocol}://{newHost}:{newPort}:{newTable}"
self.contents[self.GLOBAL_KEY_SERVERS][index] = new_connstring
self.save()
print(f"Server at index {index} updated to '{new_connstring}'.")
return True
except ValueError:
print(f"Error: Server index '{index}' must be an integer.")
return False
# --- Host Management ---
def get_host(self, name):
return self.contents[self.GLOBAL_KEY_HOSTS].get(name, None)
def get_hosts(self):
return self.contents[self.GLOBAL_KEY_HOSTS]
def add_host(self, name, ip):
if name in self.contents[self.GLOBAL_KEY_HOSTS]:
print(f"Error: Host '{name}' already exists.")
return False
# Basic IP validation (optional, could be more robust)
try:
ipaddress.ip_address(ip)
except ValueError:
print(f"Warning: '{ip}' does not appear to be a valid IP address. Adding anyway.")
self.contents[self.GLOBAL_KEY_HOSTS][name] = ip
self.save()
print(f"Host '{name}' added with IP '{ip}'.")
return True
def delete_host(self, name=None):
if name is None: # Delete all
if not self.contents[self.GLOBAL_KEY_HOSTS]:
print("No hosts to delete.")
return False
self.contents[self.GLOBAL_KEY_HOSTS] = {}
self.save()
print("All hosts deleted.")
return True
else:
if name not in self.contents[self.GLOBAL_KEY_HOSTS]:
print(f"Error: Host '{name}' does not exist.")
return False
del self.contents[self.GLOBAL_KEY_HOSTS][name]
self.save()
print(f"Host '{name}' deleted.")
return True
def update_host(self, name, ip=None, newName=None):
if name not in self.contents[self.GLOBAL_KEY_HOSTS]:
print(f"Error: Host '{name}' does not exist.")
return False
if ip:
# Validate new IP address
try:
ipaddress.ip_address(ip)
except ValueError:
print(f"Error: '{ip}' does not appear to be a valid IP address.")
return False
self.contents[self.GLOBAL_KEY_HOSTS][name] = ip
print(f"Host '{name}' updated to IP '{ip}'.")
if newName and newName != name:
if newName in self.contents[self.GLOBAL_KEY_HOSTS]:
print(f"Error: Cannot rename host to '{newName}', name already exists.")
return False
self.contents[self.GLOBAL_KEY_HOSTS][newName] = self.contents[self.GLOBAL_KEY_HOSTS].pop(name)
print(f"Renamed '{name}' to '{newName}'.")
self.save()
return True
# --- Route Management ---
def get_routing_tables(self):
"""Returns a list of routing table names."""
return list(self.contents[self.GLOBAL_KEY_ROUTES].keys())
def is_route_valid(self, route_target):
"""Checks if a route target is valid (either 'drop' or an existing chain (or implicit chain based on proxy name))."""
return route_target == self.ROUTERULE_DROP or route_target in self.contents[self.GLOBAL_KEY_CHAINS] or route_target in self.contents[self.GLOBAL_KEY_PROXIES]
def update_default_route(self, table_name, new_default):
"""Updates the default route for a given table."""
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Error: Routing table '{table_name}' does not exist.")
return False
# Validate the new default route (must be 'drop' or an existing chain)
if not self.is_route_valid(new_default):
print(f"Error: Default route '{new_default}' is invalid. Use 'drop' or an existing chain name.")
return False
self.contents[self.GLOBAL_KEY_ROUTES][table_name][self.TABLE_KEY_DEFAULT] = new_default
self.save()
print(f"Default route for table '{table_name}' updated to '{new_default}'.")
return True
def get_routes(self, table_name):
"""Returns the list of route blocks for a given table."""
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
# print(f"Error: Routing table '{table_name}' does not exist.")
return None
return self.contents[self.GLOBAL_KEY_ROUTES][table_name]
def add_route(self, table_name, rule_dict, route_target, comment=None, position=None, disable=False):
"""Adds a new route block to a table."""
# Ensure table exists
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
self.contents[self.GLOBAL_KEY_ROUTES][table_name] = {self.TABLE_KEY_DEFAULT: self.ROUTERULE_DROP, self.TABLE_KEY_BLOCKS: []}
print(f"Routing table '{table_name}' created with default route 'drop'.")
table = self.contents[self.GLOBAL_KEY_ROUTES][table_name]
table_blocks = table.setdefault(self.TABLE_KEY_BLOCKS, [])
# Validate route target (must be a chain or 'drop')
if not self.is_route_valid(route_target):
print(f"Error: Route target chain '{route_target}' does not exist. Use 'drop' or an existing chain name.")
return False
route_block = {
self.ROUTEBLOCK_KEY_RULES: rule_dict,
self.ROUTEBLOCK_KEY_ROUTE: route_target,
self.ROUTEBLOCK_KEY_DISABLE: bool(disable)
}
if comment:
route_block[self.ROUTEBLOCK_KEY_COMMENT] = comment
if position is None:
# Add to the end
table_blocks.append(route_block)
print(f"Route added to table '{table_name}' at the end (index {len(table_blocks) - 1}).")
else:
try:
pos = int(position)
if 0 <= pos <= len(table_blocks): # Allow inserting at the very end
table_blocks.insert(pos, route_block)
print(f"Route inserted into table '{table_name}' at index {pos}.")
else:
print(f"Error: Invalid position {pos}. Must be between 0 and {len(table_blocks)}.")
return False
except ValueError:
print(f"Error: Position '{position}' must be an integer.")
return False
self.save()
return True
def update_route(self, table_name, index, rule_dict=None, route_target=None, comment=None, disable=None, new_index=None):
"""Updates an existing route block in a table by index, including moving it to a new position."""
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Error: Routing table '{table_name}' does not exist.")
return False
table = self.contents[self.GLOBAL_KEY_ROUTES][table_name]
table_blocks = table.get(self.TABLE_KEY_BLOCKS, [])
try:
idx = int(index)
if 0 <= idx < len(table_blocks):
route_block = table_blocks.pop(idx) # Remove the rule from its current position
# Update fields if provided
if rule_dict is not None:
route_block[self.ROUTEBLOCK_KEY_RULES] = rule_dict
if route_target is not None:
# Validate route target (must be a chain or 'drop')
if not self.is_route_valid(route_target):
print(f"Error: Route target chain '{route_target}' does not exist. Use 'drop' or an existing chain name.")
return False
route_block[self.ROUTEBLOCK_KEY_ROUTE] = route_target
if comment is not None:
route_block[self.ROUTEBLOCK_KEY_COMMENT] = comment
if disable is not None:
route_block[self.ROUTEBLOCK_KEY_DISABLE] = bool(disable)
# Handle moving the rule to a new index
if new_index is not None:
try:
new_idx = int(new_index)
if 0 <= new_idx <= len(table_blocks): # Allow inserting at the end
table_blocks.insert(new_idx, route_block)
print(f"Route moved from index {idx} to {new_idx} in table '{table_name}'.")
else:
print(f"Error: Invalid new index {new_idx}. Must be between 0 and {len(table_blocks)}.")
return False
except ValueError:
print(f"Error: New index '{new_index}' must be an integer.")
return False
else:
# If no new index is provided, reinsert the rule at its original position
table_blocks.insert(idx, route_block)
print(f"Route at index {idx} in table '{table_name}' updated.")
self.save()
return True
else:
print(f"Error: Invalid index {idx}. Must be between 0 and {len(table_blocks) - 1}.")
return False
except ValueError:
print(f"Error: Index '{index}' must be an integer.")
return False
def delete_route(self, table_name, index):
"""Deletes a route block from a table by index."""
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Error: Routing table '{table_name}' does not exist.")
return False
table = self.contents[self.GLOBAL_KEY_ROUTES][table_name]
table_blocks = table.get(self.TABLE_KEY_BLOCKS, [])
try:
idx = int(index)
if 0 <= idx < len(table_blocks):
deleted_route = table_blocks.pop(idx)
# If table becomes empty, should we delete the table? Let's keep it for now.
# if not table_routes:
# del self.contents[self.GLOBAL_KEY_ROUTES][table_name]
# print(f"Route at index {idx} deleted. Table '{table_name}' is now empty and removed.")
# else:
print(f"Route at index {idx} deleted from table '{table_name}'.")
self.save()
return True
else:
print(f"Error: Invalid index {idx}. Must be between 0 and {len(table_blocks) - 1}.")
return False
except ValueError:
print(f"Error: Index '{index}' must be an integer.")
return False
def delete_routing_table(self, table_name):
"""Deletes an entire routing table."""
if table_name not in self.contents[self.GLOBAL_KEY_ROUTES]:
print(f"Error: Routing table '{table_name}' does not exist.")
return False
# Check if table is used by any server
used_by_servers = []
for i, server_str in enumerate(self.contents[self.GLOBAL_KEY_SERVERS]):
try:
if server_str.endswith(f":{table_name}"):
used_by_servers.append(f"Server index {i} ('{server_str}')")
except Exception:
pass # Ignore malformed server strings
if used_by_servers:
print(f"Error: Cannot delete table '{table_name}' because it is used by:")
for usage in used_by_servers:
print(f" - {usage}")
print("Update or delete these servers first.")
return False
del self.contents[self.GLOBAL_KEY_ROUTES][table_name]
print(f"Routing table '{table_name}' deleted.")
self.save()
return True
# --- Rule Expression Parser ---
class RuleParser:
"""Parses rule expressions into BBS JSON rule structure."""
def __init__(self, config):
self.config = config # To access constants
self._parser = self._build_parser()
def _build_parser(self):
"""Creates and returns the pyparsing grammar object."""
# --- Parse Actions (Handlers) ---
# These functions are called when a grammar rule is successfully matched.
# They are responsible for transforming the parsed tokens into the desired dictionary structure.
def handle_simple_rule(tokens):
"""
Handles a simple rule like 'host is example.com' or 'not port is 80'.
It constructs the base dictionary for a single rule.
"""
# The Group puts all tokens for this rule into a list.
rule_tokens = tokens[0]
negated = False
if rule_tokens[0].lower() == 'not':
negated = True
rule_tokens = rule_tokens[1:] # Remove 'not' from the list
variable, operator, value = rule_tokens
variable = variable.lower()
operator = operator.lower()
result_dict = {}
# Logic to determine the JSON "rule" type and content based on the expression
if variable == 'host' and operator == 'in':
result_dict = {"rule": "subnet", "content": value}
elif variable == 'host' and operator == 'is':
# Check if the value is an IPv4 address to apply the /32 subnet rule
if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", value):
result_dict = {"rule": "subnet", "content": f"{value}/32"}
else: # Otherwise, treat it as a domain for a regexp rule
result_dict = {"rule": "regexp", "variable": "host", "content": f"^{re.escape(value)}$"}
elif operator == 'is': # For 'port is ...' and 'addr is ...'
result_dict = {"rule": "regexp", "variable": variable, "content": f"^{re.escape(value)}$"}
elif operator == 'like': # For '... like "..."'
result_dict = {"rule": "regexp", "variable": variable, "content": value}
if negated:
result_dict["negate"] = "true"
return result_dict
def handle_binary_op(tokens):
print(tokens)
"""
Handles logical combinations ('and', 'or').
It takes a sequence of operands and operators and nests them correctly.
"""
# The tokens are provided in a nested list, e.g., [[operand1, operator, operand2]]
t = tokens[0]
# Start with the leftmost operand
result_dict = t[0]
# Sequentially apply the operators to create nested structures
# e.g., A and B and C -> ((A and B) and C)
for i in range(1, len(t), 2):
op = t[i].lower()
right_operand = t[i+1]
result_dict = {"rule1": result_dict, "op": op, "rule2": right_operand}
return result_dict
# --- Grammar Definition ---
# Use packrat for better performance on complex grammars
pp.ParserElement.enablePackrat()
# Define keywords and suppress them from the output (we handle them in parse actions)
LPAR, RPAR = map(pp.Suppress, "()")
NOT = pp.Keyword("not", caseless=True)
AND = pp.Keyword("and", caseless=True)
OR = pp.Keyword("or", caseless=True)
IN = pp.Keyword("in", caseless=True)
IS = pp.Keyword("is", caseless=True)
LIKE = pp.Keyword("like", caseless=True)
# Define the terminals of the language
variable = pp.oneOf("host port addr", caseless=True)
operator = IN | IS | LIKE
# A value can be a quoted string (for regexes) or any other word without parentheses
value = pp.QuotedString(quoteChar='"', unquoteResults=True) | pp.QuotedString(quoteChar="'", unquoteResults=True) | pp.Word(pp.printables, excludeChars="()")
# Define the base element of our grammar: a single expression.
# We group it so the parse action gets all its tokens together.
simple_expr = pp.Group(pp.Optional(NOT) + variable + operator + value)
simple_expr.set_parse_action(handle_simple_rule)
# Use infixNotation to handle operator precedence (AND before OR),
# associativity (left-to-right), and parentheses.
expr_parser = pp.infixNotation(
simple_expr,
[
(AND, 2, pp.opAssoc.LEFT, handle_binary_op),
(OR, 2, pp.opAssoc.LEFT, handle_binary_op),
],
)
return expr_parser
def parse(self, expression_string: str) -> str:
"""
Parses a given expression string into a JSON configuration string.
Args:
expression_string: The expression to parse.
Returns:
A compact JSON string representing the configuration, or an error message.
"""
if not expression_string.strip():
return "{}"
try:
# parseString returns a ParseResults object; the actual result is the first element.
result = self._parser.parseString(expression_string, parseAll=True)[0]
# # Convert the final dictionary to a compact JSON string.
# return json.dumps(result, separators=(',', ':'))
return result
except pp.ParseException as e:
return f"Error: Syntax error in expression at char {e.loc}. {e.msg}"
except Exception as e:
return f"An unexpected error occurred: {e}"
# --- Subcommand Functions ---
def subcommand_show(args, config: Config):
# This was a placeholder, let's make it useful or remove it
if args.element == "proxies":
subcommand_proxy_list(args, config)
elif args.element == "chains":
subcommand_chain_list(args, config)
elif args.element == "tables":
subcommand_route_list_tables(args, config) # List tables first
tables = config.get_routing_tables()
if tables:
print("\nUse 'route list <table>' to see rules for a specific table.")
else:
print("No routing tables defined.")
elif args.element == "routes":
for table in config.get_routing_tables():
args.table = table # Temporarily set table for route listing
subcommand_route_list(args, config)
print("")
args.table = None # Reset table
elif args.element == "servers":
subcommand_server_list(args, config)
elif args.element == "hosts":
subcommand_hosts_list(args, config)
elif args.element == "all":
subcommand_server_list(args, config)
print("")
subcommand_proxy_list(args, config)
print("")
subcommand_chain_list(args, config)
print("")
for table in config.get_routing_tables():
args.table = table # Temporarily set table for route listing
subcommand_route_list(args, config)
print("")
args.table = None # Reset table
subcommand_hosts_list(args, config)
print("")
else:
print(f"Unknown element '{args.element}'")
# --- Host Subcommands ---
def subcommand_hosts_list(args, config):
print("--- Hosts ---")
hosts = config.get_hosts()
if not hosts:
print("No hosts defined.")
return
max_len = max(len(name) for name in hosts.keys()) if hosts else 0
for name, ip in hosts.items():
print(f"{name:<{max_len}} -> {ip}")
def subcommand_hosts_add(args, config):
print(f"Adding host '{args.name}' with IP '{args.ip}'...")
config.add_host(args.name, args.ip)
def subcommand_hosts_del(args, config):
if args.name == "all":
print("Deleting all hosts...")
config.delete_host()
else:
print(f"Deleting host '{args.name}'...")
config.delete_host(args.name)
def subcommand_hosts_update(args, config: Config):
print(f"Updating host '{args.name}' to IP '{args.ip}'" + (f" and renaming to '{args.newName}'" if args.newName else "") + "...")
config.update_host(args.name, ip=args.ip, newName=args.newName)
# --- Proxy Subcommands ---
def subcommand_proxy_add(args, config):
name = args.name if args.name else config._get_unused_proxy_name()
connstring = f"{args.protocol}://{args.host}:{args.port}"
print(f"Adding proxy '{name}' ({connstring})...")
config.add_proxy(name, connstring, user=args.user, password=args.password)
def subcommand_proxy_list(args, config: Config):
print("--- Proxies ---")
proxies = config.get_proxies()
if not proxies:
print("No proxies defined.")
return
for name, data in proxies.items():
conn = data.get(Config.PROXY_KEY_CONNSTRING, "N/A")
user = f", User: {data[Config.PROXY_KEY_USER]}" if Config.PROXY_KEY_USER in data else ""
pw = f", Pass: {data[Config.PROXY_KEY_PASS]}" if Config.PROXY_KEY_PASS in data else ""
print(f"{name}: {conn}{user}{pw}")
def subcommand_proxy_del(args, config):
if args.proxy == "all":
print("Deleting all proxies...")
config.delete_proxy()
else:
print(f"Deleting proxy '{args.proxy}'...")
config.delete_proxy(args.proxy)
def subcommand_proxy_update(args, config):
print(f"Updating proxy '{args.proxy}'...")
config.update_proxy(args.proxy, protocol=args.protocol, host=args.host, port=args.port, user=args.user, password=args.password, newName=args.name)
# --- Chain Subcommands ---
def subcommand_chain_list(args, config):
print("--- Chains ---")
chains = config.get_chains()
if not chains:
print("No chains defined.")
return
for name, data in chains.items():
proxies = " -> ".join(data.get(Config.CHAIN_KEY_PROXIES, []))
read_timeout = f"|RT: {data[Config.CHAIN_KEY_TCPREADTIMEOUT]}" if Config.CHAIN_KEY_TCPREADTIMEOUT in data else ""
conn_timeout = f"|CT: {data[Config.CHAIN_KEY_TCPCONNECTTIMEOUT]}" if Config.CHAIN_KEY_TCPCONNECTTIMEOUT in data else ""
proxy_dns = f"ProxyDNS" if Config.CHAIN_KEY_PROXYDNS in data else ""
opts = f"{proxy_dns}{read_timeout}{conn_timeout}"
if opts !="":
opts = f" [{opts}]"
print(f"{name}: {proxies}{opts}")
def subcommand_chain_add(args, config):
name = args.name if args.name else config._get_unused_chain_name()
print(f"Adding chain '{name}' with proxies {args.proxies}...")
config.add_chain(name, args.proxies, tcpReadTimeout=args.tcpReadTimeout, tcpConnectTimeout=args.tcpConnectTimeout, proxyDns=args.proxyDns)
def subcommand_chain_del(args, config):
if args.name == "all":
print("Deleting all chains...")
config.delete_chain()
else:
print(f"Deleting chain '{args.name}'...")
config.delete_chain(args.name)
def subcommand_chain_update(args, config):
print(f"Updating chain '{args.name}'...")
config.update_chain(args.name, proxies=args.proxies, tcpReadTimeout=args.tcpReadTimeout, tcpConnectTimeout=args.tcpConnectTimeout, proxyDns=args.proxyDns, newName=args.newName) # Pass newName correctly
# --- Server Subcommands ---
def subcommand_server_list(args, config):
print("--- Servers ---")
servers = config.get_servers()
if not servers:
print("No servers defined.")
return
for index, server in enumerate(servers):
print(f"{index}: {server}")
def subcommand_server_add(args, config):
print(f"Adding server {args.protocol}://{args.host}:{args.port} using table '{args.table}'...")
config.add_server(args.protocol, args.host, args.port, args.table)
def subcommand_server_add_fwd(args, config: Config):
connstring = f"fwd://{args.local_host}:{args.local_port}:{args.chain}:{args.remote_host}:{args.remote_port}"
print(f"Adding forwarder {connstring}...")
config.add_server_fwd(args.local_host, args.local_port, args.chain, args.remote_host, args.remote_port)
# Note: The `add_server` method may need to be updated to handle the full forwarder format.
def subcommand_server_del(args, config):
if args.index == "all":
print("Deleting all servers...")
config.delete_server()
else:
print(f"Deleting server at index {args.index}...")
config.delete_server(args.index)
def subcommand_server_update(args, config):
print(f"Updating server at index {args.index}...")
config.update_server(args.index, protocol=args.protocol, host=args.host, port=args.port, table=args.table)
# --- Route Subcommands ---
def subcommand_route_list_tables(args, config: Config):
print("--- Routing Tables ---")