Repository navigation
Expand file tree
/
Copy pathmole.sh
More file actions
5894 lines (5407 loc) · 238 KB
/
Copy pathmole.sh
File metadata and controls
5894 lines (5407 loc) · 238 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
# OpenWRT 24.10 / BusyBox ash
# Subscription manager for Podkop
# Developer: Salvatore (GitHub: @tickcount)
set -eu
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || echo "$0")"
MOLE_VERSION="0.2.2"
MOLE_REPO="tickcount/podkop-subscriptions"
MOLE_RAW_URL="https://raw.githubusercontent.com/${MOLE_REPO}/refs/heads/main/mole.sh"
# ─── UCI config: /etc/config/mole ──────────────────────────────────
# ensure_mole_config — create /etc/config/mole with defaults if absent;
# migrate existing config (add missing settings section,
# bump schema where needed)
ensure_mole_config() {
if [ -f /etc/config/mole ]; then
uci -q get mole.settings >/dev/null 2>&1 || {
uci set mole.settings=settings
uci commit mole
}
# ── Schema v1: switch default UA from clash-verge (triggers YAML on
# Remnawave) to v2raytun/ios (plain base64 URI list).
_sv="$(uci -q get mole.settings.schema_version 2>/dev/null || echo 0)"
case "$_sv" in ''|*[!0-9]*) _sv=0 ;; esac
if [ "$_sv" -lt 1 ]; then
_cur_ua="$(uci -q get mole.settings.user_agent 2>/dev/null || echo "")"
case "$_cur_ua" in
clash-verge/*|clash-*|Clash*|Mihomo*|v2rayN/*|'')
uci set mole.settings.user_agent='v2raytun/ios'
;;
esac
uci set mole.settings.schema_version='1'
uci commit mole
fi
# ── Schema v2: decode stale `announce=base64:<b64>` values that
# the earlier decode_announce (which gated on LC_ALL=C
# [[:print:]]) failed to unwrap for UTF-8 Cyrillic.
if [ "$_sv" -lt 2 ]; then
_mig_subs="$(uci -q show mole 2>/dev/null \
| awk -F'[.=]' '/^mole\.[^.@]+=subscription$/ {print $2}')"
for _mig_s in $_mig_subs; do
_mig_a="$(uci -q get "mole.${_mig_s}.announce" 2>/dev/null || echo "")"
case "$_mig_a" in
"base64:"*)
_mig_b="${_mig_a#base64:}"
_mig_d="$(printf '%s' "$_mig_b" | base64 -d 2>/dev/null || true)"
if [ -n "$_mig_d" ]; then
uci set "mole.${_mig_s}.announce=${_mig_d}"
fi
;;
esac
done
uci set mole.settings.schema_version='2'
uci commit mole
fi
return 0
fi
cat > /etc/config/mole <<'UCICFG'
config settings 'settings'
option schema_version '2'
option cron_schedule '0 */3 * * *'
option cron_enabled '0'
option download_timeout '40'
option connect_timeout '10'
option user_agent 'v2raytun/ios'
option ping_count '1'
option ping_timeout '2'
option enrich_enabled '1'
option enrich_source 'cymru'
option enrich_cache_ttl '604800'
option log_path '/tmp/mole.log'
option pool_dir '/etc/mole/pool'
option cache_dir '/tmp/mole'
UCICFG
uci commit mole
}
# _scfg KEY DEFAULT — read a mole.settings option with fallback
_scfg() { uci -q get "mole.settings.$1" 2>/dev/null || echo "$2"; }
# mole_config_load — populate CFG_* variables from UCI
mole_config_load() {
CFG_CRON_SCHEDULE="$(_scfg cron_schedule '0 */3 * * *')"
CFG_CRON_ENABLED="$(_scfg cron_enabled '0')"
CFG_DOWNLOAD_TIMEOUT="$(_scfg download_timeout '40')"
CFG_CONNECT_TIMEOUT="$(_scfg connect_timeout '10')"
CFG_USER_AGENT="$(_scfg user_agent 'clash-verge/v1.5.11')"
CFG_ENRICH_ENABLED="$(_scfg enrich_enabled '1')"
CFG_ENRICH_SOURCE="$(_scfg enrich_source 'cymru')"
CFG_ENRICH_CACHE_TTL="$(_scfg enrich_cache_ttl '604800')"
CFG_LOG_PATH="$(_scfg log_path '/tmp/mole.log')"
CFG_POOL_DIR="$(_scfg pool_dir '/etc/mole/pool')"
CFG_CACHE_DIR="$(_scfg cache_dir '/tmp/mole')"
DOWNLOAD_RETRIES=3
}
ensure_mole_config
mole_config_load
mkdir -p "$CFG_POOL_DIR" "$CFG_CACHE_DIR" 2>/dev/null || true
# ─── Package manager abstraction ─────────────────────────────────────
PKG_IS_APK=0
command -v apk >/dev/null 2>&1 && PKG_IS_APK=1
pkg_update() {
if [ "$PKG_IS_APK" -eq 1 ]; then apk update; else opkg update; fi
}
pkg_install() {
if [ "$PKG_IS_APK" -eq 1 ]; then
apk add --allow-untrusted "$@"
else
opkg install "$@"
fi
}
pkg_is_installed() {
if [ "$PKG_IS_APK" -eq 1 ]; then
apk list --installed 2>/dev/null | grep -q "$1"
else
opkg list-installed 2>/dev/null | grep -q "$1"
fi
}
pkg_version() {
if [ "$PKG_IS_APK" -eq 1 ]; then
apk list --installed 2>/dev/null | grep "$1" | head -n1 | awk '{print $1}' | sed "s/^${1}-//"
else
opkg list-installed 2>/dev/null | grep "$1" | head -n1 | awk '{print $3}'
fi
}
# ─── Colors (soft white-blue-violet palette — matches liminal) ───────
W="\033[38;5;255m" # clean bright white
B="\033[38;5;111m" # soft blue
V="\033[38;5;141m" # soft violet
A="\033[38;5;146m" # soft steel blue (labels)
DIM="\033[2m\033[38;5;240m" # very faded — box frames only
DIM2="\033[38;5;245m" # readable dim gray — inline content hints
OK="\033[38;5;114m" # soft green
WARN_C="\033[38;5;180m" # soft wheat/amber
ERR="\033[38;5;174m" # soft rose/red
NC="\033[0m"
# ─── Icons & box-drawing ─────────────────────────────────────────────
# First 3 bytes of a UTF-8 regional-indicator symbol (U+1F1E6–U+1F1FF).
# Used to detect flag emoji at the start of a node name so we don't double
# it with the Cymru-derived flag column.
RI_PREFIX="$(printf '\xf0\x9f\x87')"
ICO_ON="${OK}●${NC}"
ICO_OFF="${ERR}●${NC}"
ICO_DIS="${DIM2}○${NC}"
ICO_OK="${OK}✓${NC}"
ICO_ERR="${ERR}✗${NC}"
ICO_WARN="${WARN_C}!${NC}"
BOX_TL="╭" BOX_TR="╮" BOX_BL="╰" BOX_BR="╯"
BOX_H="─" BOX_V="│"
# ─── Box-drawing helpers ─────────────────────────────────────────────
box_top() {
_w="${1:-54}"
_line=""; _i=0; while [ "$_i" -lt "$_w" ]; do _line="${_line}${BOX_H}"; _i=$((_i+1)); done
echo -e "${DIM}${BOX_TL}${_line}${BOX_TR}${NC}"
}
box_bot() {
_w="${1:-54}"
_line=""; _i=0; while [ "$_i" -lt "$_w" ]; do _line="${_line}${BOX_H}"; _i=$((_i+1)); done
echo -e "${DIM}${BOX_BL}${_line}${BOX_BR}${NC}"
}
box_sep() {
_w="${1:-54}"
_line=""; _i=0; while [ "$_i" -lt "$_w" ]; do _line="${_line}${BOX_H}"; _i=$((_i+1)); done
echo -e "${DIM}├${_line}┤${NC}"
}
box_line() {
echo -e "${DIM}${BOX_V}${NC} $1"
}
# ─── Auto-sizing box buffer ──────────────────────────────────────────
_BOX_BUF=""
_BOX_BUF_SEP="$(printf '\037')"
box_buf_reset() { _BOX_BUF=""; }
box_buf_line() { _BOX_BUF="${_BOX_BUF}${1}${_BOX_BUF_SEP}"; }
box_buf_sep() { _BOX_BUF="${_BOX_BUF}__BOXSEP__${_BOX_BUF_SEP}"; }
_visible_bytes() {
_vb="$(printf '%b' "$1" 2>/dev/null | sed 's/\x1b\[[0-9;]*[mGKHJ]//g')"
echo "${#_vb}"
}
box_buf_flush() {
_bf_min="${1:-44}"; _bf_max="${2:-100}"
_bf_w="$_bf_min"
_bf_rest="$_BOX_BUF"
while [ -n "$_bf_rest" ]; do
_bf_line="${_bf_rest%%${_BOX_BUF_SEP}*}"
case "$_bf_rest" in
*"${_BOX_BUF_SEP}"*) _bf_rest="${_bf_rest#*${_BOX_BUF_SEP}}" ;;
*) _bf_rest="" ;;
esac
[ -z "$_bf_line" ] && continue
[ "$_bf_line" = "__BOXSEP__" ] && continue
_bf_len="$(_visible_bytes "$_bf_line")"
_bf_len=$((_bf_len + 2))
[ "$_bf_len" -gt "$_bf_w" ] && _bf_w="$_bf_len"
done
[ "$_bf_w" -gt "$_bf_max" ] && _bf_w="$_bf_max"
box_top "$_bf_w"
_bf_rest="$_BOX_BUF"
while [ -n "$_bf_rest" ]; do
_bf_line="${_bf_rest%%${_BOX_BUF_SEP}*}"
case "$_bf_rest" in
*"${_BOX_BUF_SEP}"*) _bf_rest="${_bf_rest#*${_BOX_BUF_SEP}}" ;;
*) _bf_rest="" ;;
esac
if [ "$_bf_line" = "__BOXSEP__" ]; then
box_sep "$_bf_w"
else
box_line "$_bf_line"
fi
done
box_bot "$_bf_w"
box_buf_reset
return 0
}
# ─── Breadcrumbs ─────────────────────────────────────────────────────
_CRUMBS=""
crumb_set() { _CRUMBS="$*"; }
crumb_push() { [ -n "$_CRUMBS" ] && _CRUMBS="${_CRUMBS} > $1" || _CRUMBS="$1"; }
crumb_pop() { _CRUMBS="$(echo "$_CRUMBS" | sed 's/ > [^>]*$//')"; }
crumb_show() {
[ -z "$_CRUMBS" ] && return
echo -e "${DIM2}${_CRUMBS}${NC}"
echo ""
}
# ─── Spinner ─────────────────────────────────────────────────────────
_SPIN_PID=""
_spin_frames='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
spinner_start() {
_msg="${1:-Working...}"
(
_idx=0
while true; do
_ch="$(printf '%s' "$_spin_frames" | cut -c$((_idx % 10 + 1)))"
printf '\r %b %b' "${V}${_ch}${NC}" "${A}${_msg}${NC}" >&2
_idx=$((_idx + 1))
sleep 0.1 2>/dev/null || sleep 1
done
) &
_SPIN_PID=$!
}
spinner_stop() {
[ -n "$_SPIN_PID" ] && kill "$_SPIN_PID" 2>/dev/null; wait "$_SPIN_PID" 2>/dev/null || true
_SPIN_PID=""
# Clear the spinner line. `\033[2K` erases the entire line on capable
# terminals; the trailing space-pad is a fallback for minimal TERMs
# (some busybox-over-ssh clients ignore CSI sequences).
printf '\r\033[2K\r \r' >&2
}
# ─── SIGINT handling ─────────────────────────────────────────────────
_SIGINT=0
on_error() {
_SIGINT=1
echo ""
}
trap on_error INT
_CANCELLED=0
trap_cancel() {
_CANCELLED=0
trap '_CANCELLED=1; trap on_error INT' INT
}
trap_restore() {
trap on_error INT
}
is_cancelled() { [ "$_CANCELLED" -eq 1 ]; }
sigint_caught() {
[ "$_SIGINT" -eq 1 ] || return 1
_SIGINT=0
return 0
}
# ─── Common helpers ──────────────────────────────────────────────────
log() { printf '%s\n' "$*"; }
warn() { echo -e " ${ERR}${ICO_WARN} warning:${NC} $*" >&2; }
die() { echo -e " ${ERR}${ICO_ERR} error:${NC} $*" >&2; exit 1; }
cancelled() { echo -e " ${DIM2}Cancelled${NC}"; }
PAUSE() {
echo -ne "\n ${DIM2}Press Enter...${NC}"
read dummy || true
_SIGINT=0
}
section() {
_stitle="$1"; _slen=${#_stitle}; _spad=$((34 - _slen))
[ "$_spad" -lt 1 ] && _spad=1
_sline=""; _si=0; while [ "$_si" -lt "$_spad" ]; do _sline="${_sline}─"; _si=$((_si+1)); done
echo -e "\n ${DIM2}──${NC} ${V}${_stitle}${NC} ${DIM2}${_sline}${NC}\n"
}
have_cmd() { command -v "$1" >/dev/null 2>&1; }
# log_event MSG... — append a timestamped line to CFG_LOG_PATH. Never fails
# (log file not yet available, permissions, etc.). Used for every operational
# event so `v › View logs` reflects history — not just --cron output.
log_event() {
[ -z "${CFG_LOG_PATH:-}" ] && return 0
mkdir -p "$(dirname "$CFG_LOG_PATH")" 2>/dev/null || true
_le_ts="$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null || date)"
printf '[%s] %s\n' "$_le_ts" "$*" >> "$CFG_LOG_PATH" 2>/dev/null || true
}
# ─── Input helpers ───────────────────────────────────────────────────
prompt() {
_var="$1"; _q="$2"; _def="${3:-}"
if [ -n "$_def" ]; then
printf " %s [%b%s%b]: " "$_q" "$DIM2" "$_def" "$NC"
else
printf " %s: " "$_q"
fi
read -r _ans || true
is_cancelled && { eval "$_var="; return 1; }
_ans="$(printf '%s' "${_ans:-}" | tr -d '\001-\037\177')"
[ -z "${_ans:-}" ] && _ans="$_def"
eval "$_var=\$_ans"
}
confirm() {
_q="$1"; _def="${2:-y}"
if [ "$_def" = "y" ]; then
echo -ne " ${_q} [${OK}Y${NC}/${DIM2}n${NC}] "
else
echo -ne " ${_q} [${DIM2}y${NC}/${ERR}N${NC}] "
fi
read -r _ans || true
_ans="$(printf '%s' "${_ans:-}" | tr -d '\001-\037\177')"
case "${_ans:-}" in
1|y|Y|yes) return 0 ;;
2|n|N|no) return 1 ;;
"")
[ "$_def" = "y" ] && return 0 || return 1 ;;
*)
[ "$_def" = "y" ] && return 0 || return 1 ;;
esac
}
# read_choice VAR — single menu choice, ASCII alnum + '+' only.
read_choice() {
read -r _rc_raw || true
# Ctrl+C during read: discard any partial input and return empty so the
# caller's "" branch triggers go-back. Peek at _SIGINT without consuming
# it (sigint_caught would reset it) so show_menu's double-tap exit check
# still fires when we eventually unwind back to the main menu.
if [ "${_SIGINT:-0}" -eq 1 ]; then
eval "$1=''"
return
fi
if [ -z "${_rc_raw:-}" ]; then
eval "$1=''"
return
fi
_rc_clean="$(printf '%s' "$_rc_raw" | LC_ALL=C tr -cd 'A-Za-z0-9+' 2>/dev/null || true)"
[ -z "$_rc_clean" ] && _rc_clean="?"
eval "$1=\$_rc_clean"
}
# ─── Network helpers ─────────────────────────────────────────────────
check_dns() {
nslookup google.com >/dev/null 2>&1
}
check_internet() {
ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && return 0
ping -c1 -W2 8.8.8.8 >/dev/null 2>&1 && return 0
have_cmd curl && curl -so /dev/null --connect-timeout 3 \
http://connectivitycheck.gstatic.com/generate_204 2>/dev/null && return 0
return 1
}
# wget_retry URL DEST [retries]
wget_retry() {
_wr_url="$1"; _wr_dest="$2"; _wr_max="${3:-$DOWNLOAD_RETRIES}"
_wr_attempt=0
while [ "$_wr_attempt" -lt "$_wr_max" ]; do
if wget -qO "$_wr_dest" "$_wr_url" 2>/dev/null; then
[ -s "$_wr_dest" ] && return 0
fi
rm -f "$_wr_dest"
_wr_attempt=$((_wr_attempt + 1))
done
return 1
}
# ─── Subscription & group helpers ────────────────────────────────────
# sub_count — number of `config subscription` sections
sub_count() {
iterate_sub_names | awk 'NF' | wc -l | tr -d ' '
}
# group_count — number of `config group` sections
group_count() {
iterate_group_names | awk 'NF' | wc -l | tr -d ' '
}
# iterate_sub_names — print UCI names of all subscription sections, one per line
iterate_sub_names() {
uci -q show mole 2>/dev/null \
| awk -F'[.=]' '/^mole\.[^.@]+=subscription$/ {print $2}'
}
# iterate_group_names — print UCI names of all group sections, one per line
iterate_group_names() {
uci -q show mole 2>/dev/null \
| awk -F'[.=]' '/^mole\.[^.@]+=group$/ {print $2}'
}
# _uci_get SECTION KEY [DEFAULT] — read mole.SECTION.KEY with fallback
_uci_get() {
_v="$(uci -q get "mole.$1.$2" 2>/dev/null || true)"
if [ -n "$_v" ]; then printf '%s' "$_v"; else printf '%s' "${3:-}"; fi
}
sub_get() { _uci_get "$@"; }
group_get() { _uci_get "$@"; }
# next_cron_run SCHEDULE — best-effort human hint (stub until cron screen lands)
next_cron_run() {
_cs="$1"
[ -z "$_cs" ] && { echo "-"; return; }
printf '%s' "$_cs"
}
# podkop_present — is podkop package installed (for status box)
podkop_present() {
[ -f /etc/config/podkop ] || [ -x /etc/init.d/podkop ]
}
# ─── Podkop integration ──────────────────────────────────────────────
#
# Ownership model (liminal-style): each podkop section we manage gets a
# marker option `podkop.<name>._mole_section='<tag>'`; a mirror record lives
# under `mole.<tag>=podkop_section` with source_group list + target_list.
#
# Flush semantics: we compute sha256 over the sorted-unique planned URI list
# and the sorted-unique list currently in `podkop.<name>.<target_list>`. We
# only `uci delete + add_list + commit + podkop reload` when those hashes
# differ — reordering the same set triggers no reload.
# Protocols podkop actually accepts in urltest/selector links. vmess:// and
# tuic:// are silently dropped at flush time (podkop's validator rejects them).
PODKOP_ACCEPTED='ss://|vless://|trojan://|socks4://|socks4a://|socks5://|hysteria2://|hy2://'
# Enumerate all podkop section names (type `section`, not `settings`).
podkop_enumerate_sections() {
[ -f /etc/config/podkop ] || return 0
uci -q show podkop 2>/dev/null \
| awk -F'[.=]' '/^podkop\.[^.@]+=section$/ {print $2}'
}
# podkop_section_owner NAME — print the mole tag that owns this section,
# or empty if unmanaged. Marker lives at podkop.<name>._mole_section.
podkop_section_owner() {
uci -q get "podkop.$1._mole_section" 2>/dev/null || true
}
# mole_managed_sections — print our tag list (UCI names of `podkop_section`
# records). These are the sections we actively manage.
mole_managed_sections() {
uci -q show mole 2>/dev/null \
| awk -F'[.=]' '/^mole\.[^.@]+=podkop_section$/ {print $2}'
}
# ps_get TAG KEY [DEFAULT] — read mole.TAG.KEY with fallback
ps_get() { _uci_get "$@"; }
# ps_sources TAG — space-separated list of group_ids feeding this section
ps_sources() {
uci -q get "mole.$1.source_group" 2>/dev/null || true
}
# canonical_hash — strip #fragment, strip reality `sid=…` query param,
# sort -u, sha256sum, print first 16 hex chars.
#
# Fragment stripping: display names change often on the server side; we
# don't want that to trigger a flush.
#
# sid stripping: Reality panels rotate the short_id on every subscription
# fetch. Treating those as meaningful diffs would (a) spam the UI with
# "⚠ flush needed" on every refresh and (b) trigger a podkop restart every
# time cron runs — which drops the active connection for several seconds.
# Servers typically keep previously-issued sids on their whitelist, so a
# stale sid on the client usually still authenticates. This is an explicit
# trade-off: if a server operator rotates their entire whitelist, mole
# won't notice until the next refresh changes something else — the user
# would need to flush manually from the Podkop section view.
canonical_hash() {
sed -e 's/#.*//' -e 's/[?&]sid=[^&#]*//g' 2>/dev/null \
| sort -u 2>/dev/null \
| { sha256sum 2>/dev/null || md5sum 2>/dev/null || cksum; } \
| awk '{print substr($1,1,16)}'
}
# gather_planned_uris TAG — collect URIs from all source groups' subs,
# applying per-sub exclusions. Output: sorted unique list, one URI per line.
#
# Perf-critical: called on every Podkop Sections render and on every flush.
# Previously called parse_uri_hostport + 3 cuts + sha256sum per URI — that's
# ~5 subshells per URI × N URIs × M subs, which hit several seconds for
# real-world pool sizes. Inlined with POSIX parameter expansion: zero
# subshells per URI on the hot path (no exclusions), one sha256sum per URI
# only when link-exclusions are active.
gather_planned_uris() {
_gpu_tag="$1"
_gpu_tmp="${CFG_CACHE_DIR}/planned.${_gpu_tag}.$$"
: > "$_gpu_tmp"
_gpu_sources="$(ps_sources "$_gpu_tag")"
for _gpu_g in $_gpu_sources; do
group_exists "$_gpu_g" || continue
for _gpu_s in $(subs_in_group "$_gpu_g"); do
_gpu_en="$(sub_get "$_gpu_s" enabled 1)"
[ "$_gpu_en" = "0" ] && continue
_gpu_pool="$(sub_pool_file "$_gpu_s")"
[ -f "$_gpu_pool" ] && [ -s "$_gpu_pool" ] || continue
_gpu_excl_p="$(compute_effective_excludes "$_gpu_s")"
_gpu_excl_l="$(sub_link_excludes "$_gpu_s")"
while IFS= read -r _gpu_uri; do
[ -z "$_gpu_uri" ] && continue
# Extract proto via parameter expansion (no subshell)
_gpu_proto="${_gpu_uri%%://*}"
# Drop unsupported schemes + proto-excludes in one case match
case "$_gpu_proto" in
ss|vless|trojan|socks4|socks4a|socks5|hysteria2|hy2) ;;
*) continue ;;
esac
if [ -n "$_gpu_excl_p" ]; then
case " $_gpu_excl_p " in *" $_gpu_proto "*) continue ;; esac
fi
# Link-exclude path: compute link_id (URI minus fragment+query)
# and check against the stored exclusion list.
if [ -n "$_gpu_excl_l" ]; then
_gpu_nofrag="${_gpu_uri%%#*}"
_gpu_lid="$(printf '%s' "${_gpu_nofrag%%\?*}" | { sha256sum 2>/dev/null || md5sum 2>/dev/null || cksum; } | awk '{print substr($1,1,12)}')"
case " $_gpu_excl_l " in *" $_gpu_lid "*) continue ;; esac
fi
printf '%s\n' "$_gpu_uri" >> "$_gpu_tmp"
done < "$_gpu_pool"
done
done
sort -u < "$_gpu_tmp"
rm -f "$_gpu_tmp"
}
# ps_link_list TAG — returns the UCI list name matching this section's proxy mode.
ps_link_list() {
case "$(ps_get "$1" proxy_mode "urltest")" in
selector) printf 'selector_proxy_links' ;;
*) printf 'urltest_proxy_links' ;;
esac
}
# podkop_current_uris NAME TARGET_LIST — print URIs currently in
# podkop.<name>.<target_list>, one per line.
podkop_current_uris() {
_pcu_n="$1"; _pcu_l="$2"
[ -f /etc/config/podkop ] || return 0
# `uci get` joins list entries with spaces; re-split via tr. URIs don't
# contain raw spaces (they'd be URL-encoded), so this is safe.
_pcu_raw="$(uci -q get "podkop.${_pcu_n}.${_pcu_l}" 2>/dev/null || true)"
printf '%s' "$_pcu_raw" | tr ' ' '\n' | awk 'NF'
}
# podkop_needs_flush TAG — 0 if planned_hash differs from podkop_current_hash.
# Mode-aware: reads from the list type matching the section's proxy_mode.
podkop_needs_flush() {
_pnf_tag="$1"
_pnf_name="$(ps_get "$_pnf_tag" podkop_name "$_pnf_tag")"
_pnf_list="$(ps_link_list "$_pnf_tag")"
_pnf_planned="$(gather_planned_uris "$_pnf_tag" | canonical_hash)"
_pnf_current="$(podkop_current_uris "$_pnf_name" "$_pnf_list" | canonical_hash)"
[ "$_pnf_planned" != "$_pnf_current" ]
}
# podkop_flush TAG — push planned URIs to podkop's proxy list.
# Mode-aware: writes to urltest_proxy_links or selector_proxy_links based on
# the section's stored proxy_mode. Ensures connection_type=proxy.
# Returns 0 on flushed (URI set changed), 1 on no-op (already in sync).
podkop_flush() {
_pf_tag="$1"
_pf_name="$(ps_get "$_pf_tag" podkop_name "$_pf_tag")"
_pf_mode="$(ps_get "$_pf_tag" proxy_mode "urltest")"
case "$_pf_mode" in urltest|selector) ;; *) _pf_mode="urltest" ;; esac
_pf_link_list="${_pf_mode}_proxy_links"
_pf_planned_file="${CFG_CACHE_DIR}/flush.${_pf_tag}.$$"
gather_planned_uris "$_pf_tag" > "$_pf_planned_file"
_pf_planned_hash="$(canonical_hash < "$_pf_planned_file")"
_pf_current_hash="$(podkop_current_uris "$_pf_name" "$_pf_link_list" | canonical_hash)"
_pf_count="$(awk 'NF' "$_pf_planned_file" | wc -l | tr -d ' ')"
if [ "$_pf_planned_hash" = "$_pf_current_hash" ]; then
rm -f "$_pf_planned_file"
uci set "mole.${_pf_tag}.last_flushed_hash=${_pf_planned_hash}"
uci set "mole.${_pf_tag}.last_flush_count=${_pf_count}"
uci commit mole
log_event "flush ${_pf_tag} noop ${_pf_count} links"
return 1
fi
# Always clear both lists so there's exactly one canonical pool.
uci -q delete "podkop.${_pf_name}.selector_proxy_links" 2>/dev/null || true
uci -q delete "podkop.${_pf_name}.urltest_proxy_links" 2>/dev/null || true
while IFS= read -r _pf_u; do
[ -z "$_pf_u" ] && continue
uci add_list "podkop.${_pf_name}.${_pf_link_list}=${_pf_u}"
done < "$_pf_planned_file"
uci set "podkop.${_pf_name}.connection_type=proxy"
uci set "podkop.${_pf_name}.proxy_config_type=${_pf_mode}"
uci set "podkop.${_pf_name}._mole_section=${_pf_tag}"
uci commit podkop
uci set "mole.${_pf_tag}.last_flushed_hash=${_pf_planned_hash}"
uci set "mole.${_pf_tag}.last_flush_count=${_pf_count}"
uci set "mole.${_pf_tag}.last_flush_ts=$(date +%s 2>/dev/null || echo 0)"
uci commit mole
rm -f "$_pf_planned_file"
# After flush, podkop's tag ordering has shifted — invalidate any cached
# /proxies JSON so the next section-view render pulls fresh history.
invalidate_latency_cache
log_event "flush ${_pf_tag} ok ${_pf_count} links (hash ${_pf_planned_hash})"
return 0
}
# podkop_restart — restart podkop service (liminal-style svc_restart).
# Podkop's init script runs `stop_main; start_main` on restart anyway, and
# reload is effectively the same call without the dnsmasq touch. Using
# restart directly matches what liminal does (`svc_restart podkop`).
podkop_restart() {
[ -x /etc/init.d/podkop ] || return 0
log_event "podkop restart"
/etc/init.d/podkop restart >/dev/null 2>&1 || true
}
# flush_all_auto [silent=0] — flush every managed section whose URI set
# changed. One podkop reload at the end for all of them.
flush_all_auto() {
_faa_silent="${1:-0}"
_faa_changed=0
_faa_any=0
for _faa_tag in $(mole_managed_sections); do
_faa_any=1
if podkop_flush "$_faa_tag"; then
_faa_changed=$((_faa_changed + 1))
if [ "$_faa_silent" = "0" ]; then
_faa_n="$(ps_get "$_faa_tag" last_flush_count 0)"
echo -e " ${ICO_OK} ${OK}Flushed${NC} ${W}$(ps_get "$_faa_tag" podkop_name "$_faa_tag")${NC} ${DIM2}(${_faa_n} links)${NC}"
fi
fi
done
if [ "$_faa_any" = "0" ]; then
[ "$_faa_silent" = "0" ] && echo -e " ${DIM2}No managed podkop sections${NC}"
return 0
fi
if [ "$_faa_changed" -gt 0 ]; then
[ "$_faa_silent" = "0" ] && printf " %bRestarting podkop%b ... " "$W" "$NC"
podkop_restart
[ "$_faa_silent" = "0" ] && echo -e "${ICO_OK}"
else
[ "$_faa_silent" = "0" ] && echo -e " ${DIM2}In sync — no restart needed${NC}"
fi
}
# mole_any_dirty — 0 if any managed section needs a flush (used for the
# dirty indicator on the main menu status box).
mole_any_dirty() {
for _sad_tag in $(mole_managed_sections); do
podkop_needs_flush "$_sad_tag" && return 0
done
return 1
}
# ─── Clash API latency (via podkop shell helper) ─────────────────────
#
# Single shared cache of podkop's `/proxies` JSON — sing-box's own URLTest
# engine automatically re-probes every urltest_check_interval (3m default)
# and updates `history[0].delay`, so we just need to read it. Cache with a
# short TTL to avoid hammering on rapid re-renders.
LATENCY_CACHE_TTL=5
latency_cache_file() {
printf '%s/latency.cache' "$CFG_CACHE_DIR"
}
# fetch_proxies_json — print /proxies JSON. Uses short-TTL cache. Empty on
# failure (no podkop, not running, API not reachable).
fetch_proxies_json() {
_fpj_cache="$(latency_cache_file)"
if [ -f "$_fpj_cache" ]; then
_fpj_age=$(( $(date +%s 2>/dev/null || echo 0) - $(stat -c %Y "$_fpj_cache" 2>/dev/null || echo 0) ))
if [ "$_fpj_age" -ge 0 ] && [ "$_fpj_age" -lt "$LATENCY_CACHE_TTL" ]; then
cat "$_fpj_cache" 2>/dev/null
return 0
fi
fi
[ -x /usr/bin/podkop ] || return 1
_fpj_json="$(/usr/bin/podkop clash_api get_proxies 2>/dev/null)"
[ -z "$_fpj_json" ] && return 1
mkdir -p "$(dirname "$_fpj_cache")" 2>/dev/null || true
printf '%s' "$_fpj_json" > "$_fpj_cache"
printf '%s' "$_fpj_json"
}
# invalidate_latency_cache — force next fetch to hit podkop. Call after flush
# because URI ordering (and thus tag assignment) may have shifted.
invalidate_latency_cache() {
rm -f "$(latency_cache_file)" 2>/dev/null || true
}
# trigger_latency_test TAG — force a fresh probe for the whole URLTest group.
# Updates sing-box's internal history; our next fetch_proxies_json picks it up.
trigger_latency_test() {
_tlt_tag="$1"
_tlt_name="$(ps_get "$_tlt_tag" podkop_name "$_tlt_tag")"
[ -x /usr/bin/podkop ] || return 1
have_cmd jq || return 1
/usr/bin/podkop clash_api get_group_latency "${_tlt_name}-urltest-out" 10000 >/dev/null 2>&1
invalidate_latency_cache
log_event "latency test ${_tlt_tag}"
}
# build_uri_ms_map TAG — build a TSV of URI → ms for the section. Planned
# URIs (sorted) → tag index N → lookup via `/proxies` response.
# Writes to stdout: "<uri>\t<ms>" per line. ms may be empty for un-probed.
build_uri_ms_map() {
_bum_tag="$1"
_bum_name="$(ps_get "$_bum_tag" podkop_name "$_bum_tag")"
_bum_json="$(fetch_proxies_json)"
[ -z "$_bum_json" ] && return 1
have_cmd jq || return 1
_bum_planned_file="${CFG_CACHE_DIR}/bum_planned.${_bum_tag}.$$"
gather_planned_uris "$_bum_tag" > "$_bum_planned_file"
# Extract tag → ms from /proxies, filtering to this section's members
_bum_lat_file="${CFG_CACHE_DIR}/bum_lat.${_bum_tag}.$$"
printf '%s' "$_bum_json" | jq -r --arg n "$_bum_name" '
.proxies // {}
| to_entries[]
| select(
(.key | startswith($n + "-"))
and (.key | endswith("-out"))
and (.key != ($n + "-urltest-out"))
)
| "\(.key)\t\(.value.history[0].delay // "")"
' 2>/dev/null > "$_bum_lat_file"
# Join: for each planned URI at position N, find tag "<name>-N-out" and
# emit "uri\tms". One awk pass over both files.
awk -v prefix="${_bum_name}-" -v suffix="-out" -v FS='\t' '
FNR==NR {
# First file: planned URIs (sorted). NR = index.
uris[FNR] = $0
next
}
{
# Second file: tag\tms. Extract N from tag.
tag = $1; ms = $2
# Strip prefix + suffix → should be pure integer
n = tag
sub("^" prefix, "", n)
sub(suffix "$", "", n)
if (n ~ /^[0-9]+$/ && uris[n]) {
print uris[n] "\t" ms
}
}
' "$_bum_planned_file" "$_bum_lat_file"
rm -f "$_bum_planned_file" "$_bum_lat_file"
}
# get_active_uri TAG — print the URI currently selected by sing-box's urltest
# outbound (the winning proxy). Uses cached /proxies JSON. Empty on failure.
get_active_uri() {
_gau_tag="$1"
_gau_name="$(ps_get "$_gau_tag" podkop_name "$_gau_tag")"
_gau_json="$(fetch_proxies_json)"
[ -z "$_gau_json" ] && return 0
have_cmd jq || return 0
_gau_active_tag="$(printf '%s' "$_gau_json" | jq -r \
--arg key "${_gau_name}-urltest-out" \
'.proxies[$key].now // ""' 2>/dev/null)"
[ -z "$_gau_active_tag" ] || [ "$_gau_active_tag" = "null" ] && return 0
# Extract N from "{name}-N-out"
_gau_idx="${_gau_active_tag#${_gau_name}-}"
_gau_idx="${_gau_idx%-out}"
case "$_gau_idx" in ''|*[!0-9]*) return 0 ;; esac
gather_planned_uris "$_gau_tag" | awk -v n="$_gau_idx" 'NR==n {print; exit}'
}
# ─── Adopt / unadopt / create podkop sections ────────────────────────
# adopt_podkop_section PODKOP_NAME — create mole tag record + set marker.
# Forces proxy_config_type=urltest on the podkop side. If the section was a
# selector, any URIs in selector_proxy_links are migrated to
# urltest_proxy_links so the pool isn't lost.
adopt_podkop_section() {
_aps_n="$1"
uci -q get "podkop.${_aps_n}" >/dev/null 2>&1 || return 1
_aps_tag="$(slugify "$_aps_n")"
[ -z "$_aps_tag" ] && _aps_tag="$_aps_n"
_aps_sfx=2
while uci -q get "mole.${_aps_tag}" >/dev/null 2>&1; do
_aps_tag="$(slugify "$_aps_n")_${_aps_sfx}"
_aps_sfx=$((_aps_sfx + 1))
done
# Preserve the existing proxy_config_type (urltest or selector) instead
# of forcing urltest — let users keep their manually configured mode.
_aps_cur_type="$(uci -q get "podkop.${_aps_n}.proxy_config_type" 2>/dev/null || echo "urltest")"
case "$_aps_cur_type" in urltest|selector) ;; *) _aps_cur_type="urltest" ;; esac
uci set "podkop.${_aps_n}.connection_type=proxy"
uci set "podkop.${_aps_n}.proxy_config_type=${_aps_cur_type}"
uci set "podkop.${_aps_n}._mole_section=${_aps_tag}"
uci commit podkop
uci set "mole.${_aps_tag}=podkop_section"
uci set "mole.${_aps_tag}.podkop_name=${_aps_n}"
uci set "mole.${_aps_tag}.proxy_mode=${_aps_cur_type}"
uci set "mole.${_aps_tag}.last_flushed_hash="
uci set "mole.${_aps_tag}.last_flush_count=0"
uci set "mole.${_aps_tag}.last_flush_ts=0"
uci commit mole
log_event "adopt ${_aps_n} as ${_aps_tag}"
echo "$_aps_tag"
}
# unadopt_podkop_section TAG — drop our record + strip marker (podkop section
# stays intact with whatever URIs it has right now)
unadopt_podkop_section() {
_ups_tag="$1"
_ups_n="$(ps_get "$_ups_tag" podkop_name "$_ups_tag")"
uci -q delete "podkop.${_ups_n}._mole_section" 2>/dev/null || true
uci commit podkop
uci -q delete "mole.${_ups_tag}" 2>/dev/null || true
uci commit mole
log_event "unadopt ${_ups_tag} (${_ups_n})"
}
# ─── Formatting helpers ──────────────────────────────────────────────
# slugify STR — "Liberty VPN" → "liberty_vpn"
slugify() {
printf '%s' "$1" \
| LC_ALL=C tr -c 'a-zA-Z0-9' '_' \
| tr 'A-Z' 'a-z' \
| sed 's/__*/_/g; s/^_//; s/_$//'
}
# sanitize_uci_val VALUE — strip chars that corrupt UCI config file syntax.
# UCI wraps option values in single quotes; an embedded single quote truncates
# the value at parse time and can corrupt the entire config section.
sanitize_uci_val() {
printf '%s' "$1" | tr -d "'\"\n\r\\"
}
# strip_display_emoji STR — drop 4-byte UTF-8 sequences (emojis, flags,
# pictographs) for display-only cleanup and trim whitespace. Cyrillic /
# Latin (2-byte UTF-8) is preserved. We build the regex with printf so
# BusyBox sed doesn't need \xNN escape support.
strip_display_emoji() {
_sde_pat="$(printf '[\360-\367][\200-\277][\200-\277][\200-\277]')"
printf '%s' "$1" \
| sed "s/${_sde_pat}//g" \
| sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}
# url_to_sub_id URL — deterministic UCI name (sub_XXXXXXXX) from URL hash
url_to_sub_id() {
_h=""
if have_cmd sha256sum; then
_h="$(printf '%s' "$1" | sha256sum 2>/dev/null | awk '{print substr($1,1,8)}')"
elif have_cmd md5sum; then
_h="$(printf '%s' "$1" | md5sum 2>/dev/null | awk '{print substr($1,1,8)}')"
fi
[ -z "$_h" ] && _h="$(printf '%s' "$1" | cksum | awk '{printf "%08x", $1}')"
echo "sub_${_h}"
}
# url_display URL [maxlen] — host + truncated path
url_display() {
_ud_url="$1"; _ud_max="${2:-48}"
_ud_short="$(printf '%s' "$_ud_url" | sed 's|^https\?://||; s|^www\.||')"
_ud_len=${#_ud_short}
if [ "$_ud_len" -gt "$_ud_max" ]; then
_ud_short="$(printf '%s' "$_ud_short" | cut -c1-$((_ud_max - 3)))..."
fi
printf '%s' "$_ud_short"
}
# fmt_bytes BYTES — human-readable
fmt_bytes() {
_fb="${1:-0}"
case "$_fb" in ''|*[!0-9]*) _fb=0 ;; esac
if [ "$_fb" -ge 1099511627776 ]; then
awk -v b="$_fb" 'BEGIN{printf "%.1f TB", b/1099511627776}'
elif [ "$_fb" -ge 1073741824 ]; then
awk -v b="$_fb" 'BEGIN{printf "%.1f GB", b/1073741824}'
elif [ "$_fb" -ge 1048576 ]; then
awk -v b="$_fb" 'BEGIN{printf "%.1f MB", b/1048576}'
elif [ "$_fb" -ge 1024 ]; then
awk -v b="$_fb" 'BEGIN{printf "%.1f KB", b/1024}'
else
printf '%s B' "$_fb"
fi
}
# fmt_traffic UP DN TOTAL — "1.2 GB / 5.0 GB" | "0.0 GB / ∞" | ""
fmt_traffic() {
_ft_up="${1:-0}"; _ft_dn="${2:-0}"; _ft_tot="${3:-0}"
case "$_ft_up" in ''|*[!0-9]*) _ft_up=0 ;; esac
case "$_ft_dn" in ''|*[!0-9]*) _ft_dn=0 ;; esac
case "$_ft_tot" in ''|*[!0-9]*) _ft_tot=0 ;; esac
_ft_used="$(awk -v u="$_ft_up" -v d="$_ft_dn" 'BEGIN{print u+d}')"
case "$_ft_used" in ''|*[!0-9]*) _ft_used=0 ;; esac
if [ "$_ft_tot" != "0" ]; then
printf '%s / %s' "$(fmt_bytes "$_ft_used")" "$(fmt_bytes "$_ft_tot")"
else
printf '%s / \xe2\x88\x9e' "$(awk -v b="$_ft_used" 'BEGIN{printf "%.1f GB", b/1073741824}')"
fi
}
# fmt_days_until UNIX_TS — "18d" / "3h" / "expired" / "-"
fmt_days_until() {
_du_ts="${1:-0}"
case "$_du_ts" in ''|*[!0-9]*) _du_ts=0 ;; esac
[ "$_du_ts" -le 0 ] && { printf '-'; return; }
_du_now="$(date +%s 2>/dev/null || echo 0)"
_du_diff=$((_du_ts - _du_now))
if [ "$_du_diff" -le 0 ]; then
printf 'expired'; return
fi
_du_d=$((_du_diff / 86400))
if [ "$_du_d" -ge 1 ]; then
printf '%sd' "$_du_d"
else
printf '%sh' $((_du_diff / 3600))
fi
}
# fmt_age_since UNIX_TS — "12m ago" / "-"
fmt_age_since() {
_as_ts="${1:-0}"
case "$_as_ts" in ''|*[!0-9]*) _as_ts=0 ;; esac
[ "$_as_ts" -le 0 ] && { printf '-'; return; }
_as_now="$(date +%s 2>/dev/null || echo 0)"
_as_diff=$((_as_now - _as_ts))
[ "$_as_diff" -lt 0 ] && _as_diff=0
if [ "$_as_diff" -lt 60 ]; then
printf '%ss ago' "$_as_diff"
elif [ "$_as_diff" -lt 3600 ]; then