-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtproxy.sh
More file actions
executable file
·1953 lines (1693 loc) · 68.4 KB
/
tproxy.sh
File metadata and controls
executable file
·1953 lines (1693 loc) · 68.4 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
#!/bin/sh
readonly SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
# Version (use YY.MM.DD format)
readonly SCRIPT_VERSION="v26.04.16"
export TZ=Asia/Shanghai
# Configuration (modify as needed)
# Proxy core configuration
# Proxy running user and group
readonly DEFAULT_CORE_USER_GROUP="root:net_admin"
# Proxy traffic mark
readonly DEFAULT_ROUTING_MARK=""
readonly DEFAULT_FORCE_MARK_BYPASS=0
# Proxy ports (transparent proxy listening ports)
readonly DEFAULT_PROXY_TCP_PORT="1536"
readonly DEFAULT_PROXY_UDP_PORT="1536"
# Proxy mode: 0=auto (check TPROXY support), 1=force TPROXY, 2=force REDIRECT
readonly DEFAULT_PROXY_MODE=0
# Performance mode (0=normal, 1=performance optimized)
# When enabled, may enable some features (e.g. conntrack) for better speed
readonly DEFAULT_PERFORMANCE_MODE=0
# DNS configuration
# DNS hijack method (0: disabled, 1: tproxy, 2: redirect)
readonly DEFAULT_DNS_HIJACK_ENABLE=1
# DNS listening port
readonly DEFAULT_DNS_PORT="1053"
# Interface definitions
# Mobile data interface
readonly DEFAULT_MOBILE_INTERFACE="rmnet_data+"
# WiFi interface
readonly DEFAULT_WIFI_INTERFACE="wlan0"
# Hotspot interface
readonly DEFAULT_HOTSPOT_INTERFACE="wlan2"
# USB tethering interface
readonly DEFAULT_USB_INTERFACE="rndis+"
# Other interfaces that require bypassing or proxying. Multiple interfaces can be separated by spaces
readonly DEFAULT_OTHER_BYPASS_INTERFACES=""
readonly DEFAULT_OTHER_PROXY_INTERFACES=""
# Proxy switches
readonly DEFAULT_PROXY_MOBILE=1
readonly DEFAULT_PROXY_WIFI=1
readonly DEFAULT_PROXY_HOTSPOT=0
readonly DEFAULT_PROXY_USB=0
readonly DEFAULT_PROXY_TCP=1
readonly DEFAULT_PROXY_UDP=1
# IPv6 proxy control:
# 0 = disable proxy (but IPv6 stack remains active)
# 1 = enable proxy (normal IPv6 proxy)
# -1 = force disable IPv6 stack entirely (disable_ipv6=1 on all interfaces)
readonly DEFAULT_PROXY_IPV6=0
# The use of 100.0.0.0/8 instead of 100.64.0.0/10 is purely due to a mistake by China Telecom's service provider, and you can change it back
readonly DEFAULT_BYPASS_IPv4_LIST="0.0.0.0/8 10.0.0.0/8 100.0.0.0/8 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.0.0.0/24 192.0.2.0/24 192.88.99.0/24 192.168.0.0/16 198.51.100.0/24 203.0.113.0/24 224.0.0.0/4 240.0.0.0/4 255.255.255.255/32"
readonly DEFAULT_BYPASS_IPv6_LIST="::/128 ::1/128 ::ffff:0:0/96 100::/64 64:ff9b::/96 2001::/32 2001:10::/28 2001:20::/28 2001:db8::/32 2002::/16 fe80::/10 ff00::/8"
readonly DEFAULT_PROXY_IPv4_LIST=""
readonly DEFAULT_PROXY_IPv6_LIST=""
# Hotspot subnet when WiFi and hotspot share the same interface (common on older devices)
# Only used when HOTSPOT_INTERFACE == WIFI_INTERFACE
readonly DEFAULT_HOTSPOT_SUBNET_IPV4="192.168.43.0/24"
readonly DEFAULT_HOTSPOT_SUBNET_IPV6="fe80::/10"
# Mark values
readonly DEFAULT_MARK_VALUE=20
readonly DEFAULT_MARK_VALUE6=25
# Routing table ID
readonly DEFAULT_TABLE_ID=2025
# Per-app proxy (use space to separate package names, supports user:package format)
readonly DEFAULT_APP_PROXY_ENABLE=0
readonly DEFAULT_PROXY_APPS_LIST=""
# Example: "com.example.app com.other"
readonly DEFAULT_BYPASS_APPS_LIST=""
# Example: "com.android.shell"
readonly DEFAULT_APP_PROXY_MODE="blacklist"
# "blacklist" or "whitelist"
# CN IP bypass configuration
readonly DEFAULT_BYPASS_CN_IP=0
# CN IP list file name
readonly DEFAULT_CN_IP_FILE="cn.zone"
readonly DEFAULT_CN_IPV6_FILE="cn_ipv6.zone"
# CN IP source URLs
readonly DEFAULT_CN_IP_URL="https://raw.githubusercontent.com/Hackl0us/GeoIP2-CN/release/CN-ip-cidr.txt"
readonly DEFAULT_CN_IPV6_URL="https://ispip.clang.cn/all_cn_ipv6.txt"
# MAC address blacklist/whitelist configuration (hotspot mode)
readonly DEFAULT_MAC_FILTER_ENABLE=0
# MAC address blacklist/whitelist (use space to separate MAC addresses)
readonly DEFAULT_PROXY_MACS_LIST=""
# Example: "AA:BB:CC:DD:EE:FF 11:22:33:44:55:66"
readonly DEFAULT_BYPASS_MACS_LIST=""
# Example: "FF:EE:DD:CC:BB:AA"
readonly DEFAULT_MAC_PROXY_MODE="blacklist"
# "blacklist" or "whitelist"
# block quic
readonly DEFAULT_BLOCK_QUIC=0
# Whether to include timestamp in logs (0=disable, 1=enable)
# Disabling this can improve performance by avoiding a process fork for each log entry.
readonly DEFAULT_LOG_TIMESTAMP=1
# Dry-run mode (disabled by default)
readonly DEFAULT_DRY_RUN=0
log() {
local level="$1"
local message="$2"
local color_code
case "$level" in
Debug) color_code="\033[0;36m" ;;
Info) color_code="\033[1;32m" ;;
Warn) color_code="\033[1;33m" ;;
Error) color_code="\033[1;31m" ;;
*)
level="Unknown"
color_code="\033[0m"
;;
esac
local should_print=0
if [ "$DRY_RUN" -eq 1 ]; then
if [ "$VERBOSE" -eq 1 ]; then
should_print=1
elif [ "$level" = "Debug" ] && case "$message" in "[EXEC] "*) true ;; *) false ;; esac then
should_print=1
fi
else
if [ "$level" = "Info" ] || [ "$level" = "Warn" ] || [ "$level" = "Error" ]; then
should_print=1
elif [ "$VERBOSE" -eq 1 ] && [ "$level" = "Debug" ]; then
should_print=1
fi
fi
[ "$should_print" -eq 0 ] && return 0
local timestamp=""
if [ "$LOG_TIMESTAMP" -eq 1 ]; then
timestamp="$(date +"%Y-%m-%d %H:%M:%S") "
fi
if [ -t 2 ]; then
printf "%b\n" "${color_code}${timestamp}[${level}]: ${message}\033[0m" >&2
else
printf "%s\n" "${timestamp}[${level}]: ${message}" >&2
fi
}
load_config() {
if [ -z "$CONFIG_DIR" ]; then
CONFIG_DIR="$SCRIPT_DIR"
log Warn "CONFIG_DIR not specified, fallback to script directory: $CONFIG_DIR"
fi
if [ -f "$CONFIG_DIR/tproxy.conf" ]; then
log Info "Sourcing configuration file: $CONFIG_DIR/tproxy.conf"
. "$CONFIG_DIR/tproxy.conf"
else
log Info "No tproxy.conf found in $CONFIG_DIR, using script defaults + environment variables"
fi
log Info "Loading configuration from environment or defaults..."
DRY_RUN="${DRY_RUN:-$DEFAULT_DRY_RUN}"
CORE_USER_GROUP="${CORE_USER_GROUP:-$DEFAULT_CORE_USER_GROUP}"
ROUTING_MARK="${ROUTING_MARK:-$DEFAULT_ROUTING_MARK}"
FORCE_MARK_BYPASS="${FORCE_MARK_BYPASS:-$DEFAULT_FORCE_MARK_BYPASS}"
PROXY_TCP_PORT="${PROXY_TCP_PORT:-$DEFAULT_PROXY_TCP_PORT}"
PROXY_UDP_PORT="${PROXY_UDP_PORT:-$DEFAULT_PROXY_UDP_PORT}"
PROXY_MODE="${PROXY_MODE:-$DEFAULT_PROXY_MODE}"
PERFORMANCE_MODE="${PERFORMANCE_MODE:-$DEFAULT_PERFORMANCE_MODE}"
DNS_HIJACK_ENABLE="${DNS_HIJACK_ENABLE:-$DEFAULT_DNS_HIJACK_ENABLE}"
DNS_PORT="${DNS_PORT:-$DEFAULT_DNS_PORT}"
MOBILE_INTERFACE="${MOBILE_INTERFACE:-$DEFAULT_MOBILE_INTERFACE}"
WIFI_INTERFACE="${WIFI_INTERFACE:-$DEFAULT_WIFI_INTERFACE}"
HOTSPOT_INTERFACE="${HOTSPOT_INTERFACE:-$DEFAULT_HOTSPOT_INTERFACE}"
USB_INTERFACE="${USB_INTERFACE:-$DEFAULT_USB_INTERFACE}"
OTHER_BYPASS_INTERFACES="${OTHER_BYPASS_INTERFACES:-$DEFAULT_OTHER_BYPASS_INTERFACES}"
OTHER_PROXY_INTERFACES="${OTHER_PROXY_INTERFACES:-$DEFAULT_OTHER_PROXY_INTERFACES}"
PROXY_MOBILE="${PROXY_MOBILE:-$DEFAULT_PROXY_MOBILE}"
PROXY_WIFI="${PROXY_WIFI:-$DEFAULT_PROXY_WIFI}"
PROXY_HOTSPOT="${PROXY_HOTSPOT:-$DEFAULT_PROXY_HOTSPOT}"
PROXY_USB="${PROXY_USB:-$DEFAULT_PROXY_USB}"
PROXY_TCP="${PROXY_TCP:-$DEFAULT_PROXY_TCP}"
PROXY_UDP="${PROXY_UDP:-$DEFAULT_PROXY_UDP}"
PROXY_IPV6="${PROXY_IPV6:-$DEFAULT_PROXY_IPV6}"
MARK_VALUE="${MARK_VALUE:-$DEFAULT_MARK_VALUE}"
MARK_VALUE6="${MARK_VALUE6:-$DEFAULT_MARK_VALUE6}"
TABLE_ID="${TABLE_ID:-$DEFAULT_TABLE_ID}"
PROXY_IPv4_LIST="${PROXY_IPv4_LIST:-$DEFAULT_PROXY_IPv4_LIST}"
PROXY_IPv6_LIST="${PROXY_IPv6_LIST:-$DEFAULT_PROXY_IPv6_LIST}"
BYPASS_IPv4_LIST="${BYPASS_IPv4_LIST:-$DEFAULT_BYPASS_IPv4_LIST}"
BYPASS_IPv6_LIST="${BYPASS_IPv6_LIST:-$DEFAULT_BYPASS_IPv6_LIST}"
HOTSPOT_SUBNET_IPV4="${HOTSPOT_SUBNET_IPV4:-$DEFAULT_HOTSPOT_SUBNET_IPV4}"
HOTSPOT_SUBNET_IPV6="${HOTSPOT_SUBNET_IPV6:-$DEFAULT_HOTSPOT_SUBNET_IPV6}"
APP_PROXY_ENABLE="${APP_PROXY_ENABLE:-$DEFAULT_APP_PROXY_ENABLE}"
PROXY_APPS_LIST="${PROXY_APPS_LIST:-$DEFAULT_PROXY_APPS_LIST}"
BYPASS_APPS_LIST="${BYPASS_APPS_LIST:-$DEFAULT_BYPASS_APPS_LIST}"
APP_PROXY_MODE="${APP_PROXY_MODE:-$DEFAULT_APP_PROXY_MODE}"
BYPASS_CN_IP="${BYPASS_CN_IP:-$DEFAULT_BYPASS_CN_IP}"
CN_IP_FILE="${CN_IP_FILE:-$DEFAULT_CN_IP_FILE}"
CN_IPV6_FILE="${CN_IPV6_FILE:-$DEFAULT_CN_IPV6_FILE}"
CN_IP_URL="${CN_IP_URL:-$DEFAULT_CN_IP_URL}"
CN_IPV6_URL="${CN_IPV6_URL:-$DEFAULT_CN_IPV6_URL}"
MAC_FILTER_ENABLE="${MAC_FILTER_ENABLE:-$DEFAULT_MAC_FILTER_ENABLE}"
PROXY_MACS_LIST="${PROXY_MACS_LIST:-$DEFAULT_PROXY_MACS_LIST}"
BYPASS_MACS_LIST="${BYPASS_MACS_LIST:-$DEFAULT_BYPASS_MACS_LIST}"
MAC_PROXY_MODE="${MAC_PROXY_MODE:-$DEFAULT_MAC_PROXY_MODE}"
BLOCK_QUIC="${BLOCK_QUIC:-$DEFAULT_BLOCK_QUIC}"
LOG_TIMESTAMP="${LOG_TIMESTAMP:-$DEFAULT_LOG_TIMESTAMP}"
SKIP_CHECK_FEATURE="${SKIP_CHECK_FEATURE:-0}"
if [ "$VERBOSE" -eq 1 ]; then
for _var in DRY_RUN CORE_USER_GROUP ROUTING_MARK FORCE_MARK_BYPASS \
PROXY_TCP_PORT PROXY_UDP_PORT PROXY_MODE PERFORMANCE_MODE \
DNS_HIJACK_ENABLE DNS_PORT \
MOBILE_INTERFACE WIFI_INTERFACE HOTSPOT_INTERFACE USB_INTERFACE \
OTHER_BYPASS_INTERFACES OTHER_PROXY_INTERFACES \
PROXY_MOBILE PROXY_WIFI PROXY_HOTSPOT PROXY_USB \
PROXY_TCP PROXY_UDP PROXY_IPV6 \
MARK_VALUE MARK_VALUE6 TABLE_ID \
PROXY_IPv4_LIST PROXY_IPv6_LIST BYPASS_IPv4_LIST BYPASS_IPv6_LIST \
HOTSPOT_SUBNET_IPV4 HOTSPOT_SUBNET_IPV6 \
APP_PROXY_ENABLE PROXY_APPS_LIST BYPASS_APPS_LIST APP_PROXY_MODE \
BYPASS_CN_IP CN_IP_FILE CN_IPV6_FILE CN_IP_URL CN_IPV6_URL \
MAC_FILTER_ENABLE PROXY_MACS_LIST BYPASS_MACS_LIST MAC_PROXY_MODE \
BLOCK_QUIC LOG_TIMESTAMP SKIP_CHECK_FEATURE; do
eval "log Debug \"$_var: \$$_var\""
done
fi
log Info "Configuration loading completed"
}
save_runtime_config() {
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "Skip saving runtime config"
return 0
fi
local runtime_file="$CONFIG_DIR/runtime_tproxy.conf"
log Info "Saving runtime config to $runtime_file"
{
echo "# Runtime config slice for stop/cleanup only (generated at $(date))"
echo "CONFIG_DIR=$CONFIG_DIR"
echo "CORE_USER_GROUP=$CORE_USER_GROUP"
echo "PROXY_TCP=$PROXY_TCP"
echo "PROXY_UDP=$PROXY_UDP"
echo "PROXY_IPV6=$PROXY_IPV6"
echo "PROXY_MODE=$PROXY_MODE"
echo "OTHER_PROXY_INTERFACES=$OTHER_PROXY_INTERFACES"
echo "BYPASS_CN_IP=$BYPASS_CN_IP"
echo "BLOCK_QUIC=$BLOCK_QUIC"
echo "DNS_HIJACK_ENABLE=$DNS_HIJACK_ENABLE"
echo "TABLE_ID=$TABLE_ID"
echo "MARK_VALUE=$MARK_VALUE"
echo "MARK_VALUE6=$MARK_VALUE6"
echo "USE_TPROXY=$USE_TPROXY"
} > "$runtime_file" || {
log Warn "Failed to save runtime config to $runtime_file"
}
}
load_runtime_config() {
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "Skip loading runtime config"
return 0
fi
local runtime_file="$CONFIG_DIR/runtime_tproxy.conf"
if [ -f "$runtime_file" ]; then
log Info "Loading runtime config from $runtime_file for cleanup"
. "$runtime_file" || {
log Warn "Failed to load runtime config from $runtime_file, using current config"
return 1
}
else
log Warn "No runtime config found at $runtime_file, using current config for cleanup"
return 1
fi
}
init_tmpdir() {
for d in /tmp /data/local/tmp "$CONFIG_DIR/tmp"; do
if [ -d "$d" ] && [ -w "$d" ]; then
export TMPDIR="$d"
log Debug "Using TMPDIR: $TMPDIR"
return 0
fi
done
if mkdir -p "$CONFIG_DIR/tmp" 2> /dev/null && [ -w "$CONFIG_DIR/tmp" ]; then
export TMPDIR="$CONFIG_DIR/tmp"
log Debug "Created fallback TMPDIR: $TMPDIR"
return 0
else
log Error "Failed to find or create writable TMPDIR"
exit 1
fi
}
init_kernel_config_cache() {
[ "$DRY_RUN" -eq 1 ] && return 0
[ "$SKIP_CHECK_FEATURE" = "1" ] && return 0
if [ -f /proc/config.gz ]; then
if zcat /proc/config.gz > "$TMPDIR/kernel_config.cache" 2> /dev/null; then
log Debug "Kernel config cached to $TMPDIR/kernel_config.cache"
else
log Warn "Failed to cache /proc/config.gz"
rm -f "$TMPDIR/kernel_config.cache" 2> /dev/null
fi
fi
}
# Helper: validate a value is a positive integer (zero forks)
is_positive_integer() {
case "$1" in
'' | *[!0-9]*) return 1 ;;
esac
return 0
}
validate_config() {
log Debug "Validating configuration..."
if ! is_positive_integer "$PROXY_TCP_PORT" || [ "$PROXY_TCP_PORT" -lt 1 ] || [ "$PROXY_TCP_PORT" -gt 65535 ]; then
log Error "Invalid PROXY_TCP_PORT: $PROXY_TCP_PORT"
return 1
fi
if ! is_positive_integer "$PROXY_UDP_PORT" || [ "$PROXY_UDP_PORT" -lt 1 ] || [ "$PROXY_UDP_PORT" -gt 65535 ]; then
log Error "Invalid PROXY_UDP_PORT: $PROXY_UDP_PORT"
return 1
fi
case "$PROXY_MODE" in
0 | 1 | 2) ;;
*)
log Error "Invalid PROXY_MODE: $PROXY_MODE (must be 0=auto, 1=force TPROXY, 2=force REDIRECT)"
return 1
;;
esac
case "$DNS_HIJACK_ENABLE" in
0 | 1 | 2) ;;
*)
log Error "Invalid DNS_HIJACK_ENABLE: $DNS_HIJACK_ENABLE (must be 0=disabled, 1=tproxy, 2=redirect)"
return 1
;;
esac
if ! is_positive_integer "$DNS_PORT" || [ "$DNS_PORT" -lt 1 ] || [ "$DNS_PORT" -gt 65535 ]; then
log Error "Invalid DNS_PORT: $DNS_PORT"
return 1
fi
if ! is_positive_integer "$MARK_VALUE" || [ "$MARK_VALUE" -lt 1 ] || [ "$MARK_VALUE" -gt 2147483647 ]; then
log Error "Invalid MARK_VALUE: $MARK_VALUE"
return 1
fi
if ! is_positive_integer "$MARK_VALUE6" || [ "$MARK_VALUE6" -lt 1 ] || [ "$MARK_VALUE6" -gt 2147483647 ]; then
log Error "Invalid MARK_VALUE6: $MARK_VALUE6"
return 1
fi
if ! is_positive_integer "$TABLE_ID" || [ "$TABLE_ID" -lt 1 ] || [ "$TABLE_ID" -gt 65535 ]; then
log Error "Invalid TABLE_ID: $TABLE_ID"
return 1
fi
case "$CORE_USER_GROUP" in
*:*)
CORE_USER="${CORE_USER_GROUP%%:*}"
CORE_GROUP="${CORE_USER_GROUP#*:}"
log Debug "Parsed user:group as '$CORE_USER:$CORE_GROUP'"
;;
esac
if [ -z "$CORE_USER" ] || [ -z "$CORE_GROUP" ]; then
log Warn "Empty user or group detected, Using default user:group 'root:net_admin'"
CORE_USER="root"
CORE_GROUP="net_admin"
fi
case "$APP_PROXY_MODE" in
blacklist | whitelist) ;;
*)
log Error "Invalid APP_PROXY_MODE: $APP_PROXY_MODE"
return 1
;;
esac
case "$MAC_PROXY_MODE" in
blacklist | whitelist) ;;
*)
log Error "Invalid MAC_PROXY_MODE: $MAC_PROXY_MODE"
return 1
;;
esac
log Debug "Configuration validation passed"
return 0
}
check_root() {
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "Skip root check"
return 0
fi
if [ "$(id -u 2> /dev/null || echo 1)" != "0" ]; then
log Error "Must run with root privileges"
exit 1
fi
}
check_dependencies() {
export PATH="$PATH:/data/data/com.termux/files/usr/bin"
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "Skip dependency check"
return 0
fi
local missing=""
local required_commands="ip iptables"
local cmd
for cmd in $required_commands; do
if ! command -v "$cmd" > /dev/null 2>&1; then
missing="$missing $cmd"
fi
done
if [ -n "$missing" ]; then
log Error "Missing required commands: $missing"
log Error "Please check PATH: $PATH"
exit 1
fi
}
setup_busybox() {
if command -v busybox > /dev/null 2>&1; then
log Debug "BusyBox already available in PATH: $(command -v busybox)"
return 0
fi
log Debug "BusyBox not found in PATH, starting detection..."
local bb_paths="
/data/adb/ksu/bin/busybox
/data/adb/ap/bin/busybox
/data/adb/magisk/busybox
"
local found_bb=""
for bb in $bb_paths; do
if [ -f "$bb" ] && [ -x "$bb" ]; then
found_bb="$bb"
break
fi
done
if [ -n "$found_bb" ]; then
local bb_dir=$(dirname "$found_bb")
export PATH="$PATH:$bb_dir"
log Info "BusyBox detected and added to PATH: $found_bb"
else
log Warn "No BusyBox found in common root paths"
fi
}
check_kernel_feature() {
local feature="$1"
local config_name="CONFIG_${feature}"
# Check compile-time config (/proc/config.gz)
if [ -f "$TMPDIR/kernel_config.cache" ]; then
if grep -qE "^${config_name}=[ym]$" "$TMPDIR/kernel_config.cache" 2> /dev/null; then
log Debug "Kernel feature $feature is enabled (config)"
return 0
fi
fi
# check runtime loaded modules (/sys/module/)
local module_name=""
case "$feature" in
IP_SET) module_name="ip_set" ;;
NETFILTER_XT_SET) module_name="xt_set" ;;
NETFILTER_XT_MATCH_ADDRTYPE) module_name="xt_addrtype" ;;
NETFILTER_XT_TARGET_TPROXY) module_name="xt_TPROXY" ;;
esac
if [ -n "$module_name" ] && [ -d "/sys/module/$module_name" ]; then
log Debug "Kernel feature $feature is enabled (loaded module)"
return 0
fi
log Warn "Kernel feature $feature is disabled or not found"
return 1
}
init_feature_flags() {
if [ "$SKIP_CHECK_FEATURE" = "1" ] || [ "$DRY_RUN" -eq 1 ]; then
log Warn "Kernel feature check skipped"
HAS_TPROXY=1
HAS_CONNTRACK=1
HAS_OWNER=1
HAS_MARK_MT=1
HAS_MARK_TG=1
HAS_SOCKET=1
HAS_ADDRTYPE=1
HAS_MAC=1
HAS_IPSET=1
HAS_XT_SET=1
HAS_NAT6=1
HAS_REDIRECT6=1
return 0
fi
log Info "Detecting kernel features..."
check_kernel_feature "NETFILTER_XT_TARGET_TPROXY" && HAS_TPROXY=1
check_kernel_feature "NETFILTER_XT_MATCH_CONNTRACK" && HAS_CONNTRACK=1
check_kernel_feature "NETFILTER_XT_MATCH_OWNER" && HAS_OWNER=1
check_kernel_feature "NETFILTER_XT_MATCH_MARK" && HAS_MARK_MT=1
check_kernel_feature "NETFILTER_XT_TARGET_MARK" && HAS_MARK_TG=1
check_kernel_feature "NETFILTER_XT_MATCH_SOCKET" && HAS_SOCKET=1
check_kernel_feature "NETFILTER_XT_MATCH_ADDRTYPE" && HAS_ADDRTYPE=1
check_kernel_feature "NETFILTER_XT_MATCH_MAC" && HAS_MAC=1
check_kernel_feature "IP_SET" && HAS_IPSET=1
check_kernel_feature "NETFILTER_XT_SET" && HAS_XT_SET=1
check_kernel_feature "IP6_NF_NAT" && HAS_NAT6=1
check_kernel_feature "IP6_NF_TARGET_REDIRECT" && HAS_REDIRECT6=1
}
check_tproxy_support() {
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "TPROXY support check skipped"
return 0
fi
if [ "$HAS_TPROXY" -eq 1 ]; then
log Info "Kernel TPROXY support confirmed"
return 0
else
log Warn "Kernel TPROXY support not available"
return 1
fi
}
# Unified command wrapper functions
run_ipt_command() {
local cmd="$1"
shift
log Debug "[EXEC] $cmd -w 100 $*"
[ "$DRY_RUN" -eq 1 ] && return 0
command "$cmd" -w 100 "$@"
}
iptables() {
run_ipt_command iptables "$@"
}
ip6tables() {
run_ipt_command ip6tables "$@"
}
ip_rule() {
log Debug "[EXEC] ip rule $*"
[ "$DRY_RUN" -eq 1 ] && return 0
command ip rule "$@"
}
ip6_rule() {
log Debug "[EXEC] ip -6 rule $*"
[ "$DRY_RUN" -eq 1 ] && return 0
command ip -6 rule "$@"
}
ip_route() {
log Debug "[EXEC] ip route $*"
[ "$DRY_RUN" -eq 1 ] && return 0
command ip route "$@"
}
ip6_route() {
log Debug "[EXEC] ip -6 route $*"
[ "$DRY_RUN" -eq 1 ] && return 0
command ip -6 route "$@"
}
find_packages_uid() {
[ $# -eq 0 ] && return 0
awk -v tokens="$*" '
BEGIN {
n = split(tokens, t_arr, " ")
for (i = 1; i <= n; i++) {
t = t_arr[i]
if (t ~ /:/) {
split(t, parts, ":")
pfx = parts[1]; pkg = parts[2]
} else {
pfx = 0; pkg = t
}
# Record that we want this package and store its prefix(es)
wanted[pkg] = 1
# Multiple prefixes might exist for the same package
pfxs[pkg] = (pkg in pfxs) ? pfxs[pkg] " " pfx : pfx
}
}
($1 in wanted) {
base_uid = ""
if ($2 ~ /^[0-9]+$/) base_uid = $2
else if ($(NF-1) ~ /^[0-9]+$/) base_uid = $(NF-1)
if (base_uid != "") {
m = split(pfxs[$1], p_arr, " ")
for (j = 1; j <= m; j++) {
# Store result keyed by package and prefix to preserve order later
res[$1, p_arr[j]] = (p_arr[j] * 100000 + base_uid)
}
}
}
END {
final_out = ""
for (i = 1; i <= n; i++) {
t = t_arr[i]
if (t ~ /:/) {
split(t, parts, ":")
pfx = parts[1]; pkg = parts[2]
} else {
pfx = 0; pkg = t
}
if ((pkg, pfx) in res) {
final_out = (final_out == "") ? res[pkg, pfx] : final_out " " res[pkg, pfx]
}
}
print final_out
}
' /data/system/packages.list
}
safe_chain_create() {
local family="$1"
local table="$2"
local chain="$3"
local cmd="iptables"
[ "$family" = "6" ] && cmd="ip6tables"
$cmd -t "$table" -N "$chain" 2> /dev/null || true
$cmd -t "$table" -F "$chain"
}
download_file() {
local url="$1"
local output="$2"
if [ "$DRY_RUN" -eq 1 ]; then
log Debug "[EXEC] download $url -> $output (skipped, dry-run)"
return 0
fi
if command -v curl > /dev/null 2>&1; then
log Debug "[EXEC] curl -fsSL --connect-timeout 10 --retry 3 $url -o $output"
curl -fsSL --connect-timeout 10 --retry 3 "$url" -o "$output"
else
log Debug "[EXEC] busybox wget -q -T 10 -t 3 -O $output $url"
busybox wget -q -T 10 -t 3 -O "$output" "$url"
fi
}
download_cn_ip_list() {
if [ "$BYPASS_CN_IP" -eq 0 ]; then
log Debug "CN IP bypass is disabled, download skipped"
return 0
fi
log Info "Checking/Downloading China mainland IP list to $CONFIG_DIR/$CN_IP_FILE"
# Re-download if file doesn't exist or is older than 7 days
if [ ! -f "$CONFIG_DIR/$CN_IP_FILE" ] || [ "$(find "$CONFIG_DIR/$CN_IP_FILE" -mtime +7 2> /dev/null)" ]; then
log Info "Fetching latest China IP list from $CN_IP_URL"
if ! download_file "$CN_IP_URL" "$CONFIG_DIR/$CN_IP_FILE.tmp"; then
log Error "Failed to download China IP list"
log Debug "[EXEC] rm -f $CONFIG_DIR/$CN_IP_FILE.tmp"
rm -f "$CONFIG_DIR/$CN_IP_FILE.tmp"
return 1
fi
log Debug "[EXEC] mv $CONFIG_DIR/$CN_IP_FILE.tmp $CONFIG_DIR/$CN_IP_FILE"
if [ "$DRY_RUN" -eq 0 ]; then
mv "$CONFIG_DIR/$CN_IP_FILE.tmp" "$CONFIG_DIR/$CN_IP_FILE"
fi
log Info "China IP list saved to $CONFIG_DIR/$CN_IP_FILE"
else
log Debug "Using existing China IP list: $CONFIG_DIR/$CN_IP_FILE"
fi
if [ "$PROXY_IPV6" -eq 1 ]; then
log Info "Checking/Downloading China mainland IPv6 list to $CONFIG_DIR/$CN_IPV6_FILE"
if [ ! -f "$CONFIG_DIR/$CN_IPV6_FILE" ] || [ "$(find "$CONFIG_DIR/$CN_IPV6_FILE" -mtime +7 2> /dev/null)" ]; then
log Info "Fetching latest China IPv6 list from $CN_IPV6_URL"
if ! download_file "$CN_IPV6_URL" "$CONFIG_DIR/$CN_IPV6_FILE.tmp"; then
log Error "Failed to download China IPv6 list"
log Debug "[EXEC] rm -f $CONFIG_DIR/$CN_IPV6_FILE.tmp"
rm -f "$CONFIG_DIR/$CN_IPV6_FILE.tmp"
return 1
fi
log Debug "[EXEC] mv $CONFIG_DIR/$CN_IPV6_FILE.tmp $CONFIG_DIR/$CN_IPV6_FILE"
if [ "$DRY_RUN" -eq 0 ]; then
mv "$CONFIG_DIR/$CN_IPV6_FILE.tmp" "$CONFIG_DIR/$CN_IPV6_FILE"
fi
log Info "China IPv6 list saved to $CONFIG_DIR/$CN_IPV6_FILE"
else
log Debug "Using existing China IPv6 list: $CONFIG_DIR/$CN_IPV6_FILE"
fi
fi
}
setup_cn_ipset() {
if [ "$BYPASS_CN_IP" -eq 0 ]; then
log Debug "CN IP bypass is disabled, ipset setup skipped"
return 0
fi
if ! command -v ipset > /dev/null 2>&1; then
log Error "ipset command not found. Cannot bypass CN IPs"
return 1
fi
log Info "Setting up ipset for China mainland IPs"
log Debug "[EXEC] ipset destroy cnip"
log Debug "[EXEC] ipset destroy cnip6"
if [ "$DRY_RUN" -eq 0 ]; then
ipset destroy cnip 2> /dev/null || true
ipset destroy cnip6 2> /dev/null || true
fi
local ipv4_count
local ipv6_count
if [ -f "$CONFIG_DIR/$CN_IP_FILE" ]; then
log Debug "Loading IPv4 CIDR from $CONFIG_DIR/$CN_IP_FILE"
ipv4_count=$(wc -l < "$CONFIG_DIR/$CN_IP_FILE" 2> /dev/null || echo "0")
log Debug "[EXEC] ipset create cnip hash:net family inet hashsize 8192 maxelem 65536"
log Debug "[EXEC] Generating temporary ipset restore file with $ipv4_count entries"
if [ "$DRY_RUN" -eq 0 ]; then
temp_file=$(mktemp) || {
log Error "Failed to create temporary file for ipset restore"
return 1
}
{
echo "create cnip hash:net family inet hashsize 8192 maxelem 65536"
awk '!/^[[:space:]]*#/ && NF > 0 {printf "add cnip %s\n", $0}' "$CONFIG_DIR/$CN_IP_FILE"
} > "$temp_file" || {
log Error "Failed to write to temporary file: $temp_file"
rm -f "$temp_file"
return 1
}
else
log Debug "[EXEC] Would create temporary file and add $ipv4_count entries to cnip"
fi
log Debug "[EXEC] ipset restore -f \"$temp_file\""
if [ "$DRY_RUN" -eq 0 ]; then
if ipset restore -f "$temp_file" 2> /dev/null; then
log Info "Successfully loaded $ipv4_count IPv4 CIDR entries into ipset 'cnip'"
else
log Error "Failed to create ipset 'cnip' or load IPv4 CIDR entries"
rm -f "$temp_file" 2> /dev/null
return 1
fi
log Debug "[EXEC] rm -f $temp_file"
rm -f "$temp_file"
else
log Debug "[EXEC] Would load $ipv4_count IPv4 CIDR entries via ipset restore"
fi
else
log Error "CN IP file not found: $CONFIG_DIR/$CN_IP_FILE"
return 1
fi
log Info "ipset 'cnip' loaded with China mainland IPs"
if [ "$PROXY_IPV6" -eq 1 ]; then
if [ -f "$CONFIG_DIR/$CN_IPV6_FILE" ]; then
log Debug "Loading IPv6 CIDR from $CONFIG_DIR/$CN_IPV6_FILE"
ipv6_count=$(wc -l < "$CONFIG_DIR/$CN_IPV6_FILE" 2> /dev/null || echo "0")
log Debug "[EXEC] ipset create cnip6 hash:net family inet6 hashsize 8192 maxelem 65536"
log Debug "[EXEC] Generating temporary ipset restore file with $ipv6_count entries"
if [ "$DRY_RUN" -eq 0 ]; then
temp_file6=$(mktemp) || {
log Error "Failed to create temporary file for ipset restore"
return 1
}
{
echo "create cnip6 hash:net family inet6 hashsize 8192 maxelem 65536"
awk '!/^[[:space:]]*#/ && NF > 0 {printf "add cnip6 %s\n", $0}' "$CONFIG_DIR/$CN_IPV6_FILE"
} > "$temp_file6" || {
log Error "Failed to write to temporary file: $temp_file6"
rm -f "$temp_file6"
return 1
}
else
log Debug "[EXEC] Would create temporary file and add $ipv6_count entries to cnip6"
fi
log Debug "[EXEC] ipset restore -f \"$temp_file6\""
if [ "$DRY_RUN" -eq 0 ]; then
if ipset restore -f "$temp_file6" 2> /dev/null; then
log Info "Successfully loaded $ipv6_count IPv6 CIDR entries into ipset 'cnip6'"
else
log Error "Failed to create ipset 'cnip6' or load IPv6 CIDR entries"
rm -f "$temp_file6" 2> /dev/null
return 1
fi
log Debug "[EXEC] rm -f $temp_file6"
rm -f "$temp_file6"
else
log Debug "[EXEC] Would load $ipv6_count IPv6 CIDR entries via ipset restore"
fi
else
log Error "CN IPv6 file not found: $CONFIG_DIR/$CN_IPV6_FILE"
return 1
fi
log Info "ipset 'cnip6' loaded with China mainland IPv6 IPs"
fi
}
# Helper: add sub-chain jump rules with optional performance mode conntrack optimization
# Uses dynamic scoping for $cmd and $table from the calling function
_add_chain_jumps() {
local parent="$1" perf="$2"
shift 2
local target
for target in "$@"; do
if [ "$perf" -eq 1 ]; then
$cmd -t "$table" -A "$parent" -p tcp --syn -j "$target"
$cmd -t "$table" -A "$parent" -p udp -m conntrack --ctstate NEW,RELATED -j "$target"
else
$cmd -t "$table" -A "$parent" -j "$target"
fi
done
}
setup_proxy_chain() {
local family="$1"
local mode="$2" # tproxy or redirect
local suffix=""
local mark="$MARK_VALUE"
local cmd="iptables"
if [ "$family" = "6" ]; then
suffix="6"
mark="$MARK_VALUE6"
cmd="ip6tables"
fi
# Set mode name for logging
local mode_name="$mode"
if [ "$mode" = "tproxy" ]; then
mode_name="TPROXY"
else
mode_name="REDIRECT"
fi
log Info "Setting up $mode_name chains for IPv${family}"
# Define chains based on family
local chains=""
chains="PROXY_PREROUTING$suffix PROXY_OUTPUT$suffix DIVERT$suffix PROXY_IP$suffix BYPASS_IP$suffix BYPASS_INTERFACE$suffix PROXY_INTERFACE$suffix DNS_HIJACK_PRE$suffix DNS_HIJACK_OUT$suffix APP_CHAIN$suffix MAC_CHAIN$suffix"
local table="mangle"
if [ "$mode" = "redirect" ]; then
table="nat"
fi
# Create chains
for c in $chains; do
safe_chain_create "$family" "$table" "$c"
done
if [ "$PERFORMANCE_MODE" -eq 1 ] && [ "$HAS_MARK_TG" -eq 1 ] && [ "$HAS_SOCKET" -eq 1 ]; then
$cmd -t "$table" -A DIVERT$suffix -j MARK --set-mark "$mark"
$cmd -t "$table" -A DIVERT$suffix -j ACCEPT
$cmd -t "$table" -A "PROXY_PREROUTING$suffix" -p tcp -m socket --transparent -j DIVERT$suffix
fi
if [ "$HAS_CONNTRACK" -eq 1 ]; then
$cmd -t "$table" -A "PROXY_PREROUTING$suffix" -m conntrack --ctdir REPLY -j ACCEPT
$cmd -t "$table" -A "PROXY_OUTPUT$suffix" -m conntrack --ctdir REPLY -j ACCEPT
log Info "Added reply connection direction bypass"
fi
local bypass_success=0
if [ "$FORCE_MARK_BYPASS" -eq 1 ] && [ "$HAS_MARK_MT" -eq 1 ] && [ -n "$ROUTING_MARK" ]; then
$cmd -t "$table" -A "PROXY_PREROUTING$suffix" -m mark --mark "$ROUTING_MARK" -j ACCEPT
$cmd -t "$table" -A "PROXY_OUTPUT$suffix" -m mark --mark "$ROUTING_MARK" -j ACCEPT
log Info "Added bypass for marked traffic with core mark $ROUTING_MARK (forced)"
bypass_success=1
elif [ "$HAS_OWNER" -eq 1 ]; then
$cmd -t "$table" -A "PROXY_OUTPUT$suffix" -m owner --uid-owner "$CORE_USER" --gid-owner "$CORE_GROUP" -j ACCEPT
log Info "Added bypass for core user $CORE_USER:$CORE_GROUP"
bypass_success=1
elif [ "$HAS_MARK_MT" -eq 1 ] && [ -n "$ROUTING_MARK" ]; then
$cmd -t "$table" -A "PROXY_OUTPUT$suffix" -m mark --mark "$ROUTING_MARK" -j ACCEPT
log Info "Added bypass for marked traffic with core mark $ROUTING_MARK"
bypass_success=1
fi
if [ "$bypass_success" -eq 0 ]; then
log Error "Core traffic bypass not configured, may cause traffic loop"
fi
# Pre-check performance mode with conntrack
local _perf_ct=0
if [ "$PERFORMANCE_MODE" -eq 1 ] && [ "$HAS_CONNTRACK" -eq 1 ]; then
_perf_ct=1
fi
_add_chain_jumps "PROXY_PREROUTING$suffix" "$_perf_ct" \
"PROXY_IP$suffix" "BYPASS_IP$suffix" "PROXY_INTERFACE$suffix" "MAC_CHAIN$suffix" "DNS_HIJACK_PRE$suffix"
_add_chain_jumps "PROXY_OUTPUT$suffix" "$_perf_ct" \
"PROXY_IP$suffix" "BYPASS_IP$suffix" "BYPASS_INTERFACE$suffix" "APP_CHAIN$suffix" "DNS_HIJACK_OUT$suffix"
local subnet4
local subnet6
if [ "$family" = "6" ]; then
if [ -n "$PROXY_IPv6_LIST" ]; then
for subnet6 in $PROXY_IPv6_LIST; do
$cmd -t "$table" -A "PROXY_IP$suffix" -d "$subnet6" -j RETURN
done
log Info "Added proxy rules for PROXY IPv6 ranges"
fi
else
if [ -n "$PROXY_IPv4_LIST" ]; then
for subnet4 in $PROXY_IPv4_LIST; do
$cmd -t "$table" -A "PROXY_IP$suffix" -d "$subnet4" -j RETURN
done
log Info "Added proxy rules for PROXY IPv4 ranges"
fi
fi
if [ "$HAS_ADDRTYPE" -eq 1 ]; then
$cmd -t "$table" -A "BYPASS_IP$suffix" -m addrtype --dst-type LOCAL -p udp ! --dport 53 -j ACCEPT
$cmd -t "$table" -A "BYPASS_IP$suffix" -m addrtype --dst-type LOCAL ! -p udp -j ACCEPT
log Info "Added local address type bypass"
fi
if [ "$family" = "6" ]; then
for subnet6 in $BYPASS_IPv6_LIST; do
$cmd -t "$table" -A "BYPASS_IP$suffix" -d "$subnet6" -p udp ! --dport 53 -j ACCEPT
$cmd -t "$table" -A "BYPASS_IP$suffix" -d "$subnet6" ! -p udp -j ACCEPT
done
log Info "Added bypass rules for BYPASS IPv6 ranges"
else
for subnet4 in $BYPASS_IPv4_LIST; do
$cmd -t "$table" -A "BYPASS_IP$suffix" -d "$subnet4" -p udp ! --dport 53 -j ACCEPT
$cmd -t "$table" -A "BYPASS_IP$suffix" -d "$subnet4" ! -p udp -j ACCEPT
done
log Info "Added bypass rules for BYPASS IPv4 ranges"
fi