Repository navigation
Expand file tree
/
Copy pathx-ui-latest.sh
More file actions
4616 lines (4393 loc) · 289 KB
/
Copy pathx-ui-latest.sh
File metadata and controls
4616 lines (4393 loc) · 289 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/bash
# 3x-ui Auto Nginx - based on x-ui-pro-refactor by mozaroc (github.com/mozaroc/3x-ui-pro), which derives from x-ui-pro by GFW4Fun (github.com/GFW4Fun/x-ui-pro)
# Copyright (C) 2026 xPROMSx contributors
# Material added by xPROMSx contributors is licensed GPL-3.0-only; inherited material keeps its authors' rights (see THIRD_PARTY_NOTICES.md).
# Additional attribution terms (GPL-3.0 section 7) apply to material added by xPROMSx contributors: see docs/NOTICE.md
# ─── Output helpers ──────────────────────────────────────────────────────────
# Per invocation only: CLI and sourced helpers always start in English.
UI_LANG=en
UI_INTERACTIVE=0
UI_COMPLETION_FD=
ui_text() {
local format=$1
[[ ${UI_LANG:-en} != ru ]] || format=$2
shift 2
# Formats are literal UI text; domains, URLs and credentials are arguments.
# shellcheck disable=SC2059
printf "$format" "$@"
}
msg_ok() { if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then printf '\e[1;32m%s\e[0m\n' "$1"; else printf '%s\n' "$1"; fi; }
msg_err() { if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then printf '\e[1;31m%s\e[0m\n' "$1"; else printf '%s\n' "$1"; fi; }
msg_inf() { if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then printf '\e[1;36m%s\e[0m\n' "$1"; else printf '%s\n' "$1"; fi; }
msg_warn() { if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then printf '\e[1;33m%s\e[0m\n' "$1"; else printf '%s\n' "$1"; fi; }
# 38;5;208 is orange: explanatory text of refusals and warnings (ui_note, ui_wrap).
ui_note() {
if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then
printf '\e[38;5;208m'; ui_text "$@"; printf '\e[0m'
else ui_text "$@"; fi
}
# ui_wrap ANSI-CODE TEXT: text inside a frame wraps by words to the frame width (60 characters, UTF-8 under
# any LC_ALL; a longer word such as a path stays whole) and every line is coloured separately.
ui_wrap() {
local line
while IFS= read -r line; do
if [[ -n "$line" && -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then printf '\e[%sm%s\e[0m\n' "$1" "$line"
else printf '%s\n' "$line"; fi
done < <(printf '%s' "$2" | python3 -I -c 'import sys, textwrap
out = []
for line in sys.stdin.buffer.read().decode("utf-8", "replace").rstrip("\n").split("\n"):
body = line.lstrip(" "); indent = line[:len(line) - len(body)]
out.append(textwrap.fill(body, 60, initial_indent=indent, subsequent_indent=indent, break_long_words=False, break_on_hyphens=False))
sys.stdout.buffer.write(("\n".join(out) + "\n").encode())' 2>/dev/null || printf '%s\n' "$2")
}
ui_rule() {
printf '%s\n' '------------------------------------------------------------'
}
ui_frame() {
printf '%s\n' '============================================================'
}
# Refusal: red [FAIL] between frames, then the orange explanation (one language, chosen by the caller).
ui_refuse() {
printf '\n'; ui_frame; msg_err ' [FAIL]'; ui_frame
ui_wrap '38;5;208' "$1"; ui_frame
}
ui_title() {
printf '\n%s\n' '============================================================'
msg_inf " $1"
if [[ ${2:-0} == 1 ]]; then ui_back ' © xPROMSx · github.com/xPROMSx/3x-ui-auto-nginx'; fi
printf '%s\n\n' '============================================================'
}
ui_section() {
printf '\n'; msg_inf " $1"; ui_rule
}
ui_header() {
ui_title ' 3X-UI AUTO NGINX' "${2:-0}"
msg_inf " $1"; ui_rule
}
ui_prompt() {
ui_rule; ui_text ' Select an option: ' ' Выберите пункт: '
}
ui_back() {
if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then
printf '\e[2m%s\e[0m\n' "$1"
else printf '%s\n' "$1"; fi
}
ui_values() {
if [[ -t 1 && ${TERM:-dumb} != dumb && ! ${NO_COLOR+x} ]]; then
printf '\e[1;36m'; ui_text "$@"; printf '\e[0m'
else ui_text "$@"; fi
}
ui_complete() {
# Private acknowledgement to manager_menu, separate from live stdout/stderr.
# Cancellation still returns 0; no public operation exit codes are repurposed.
if [[ ${UI_COMPLETION_FD:-} == 3 ]]; then printf 'completed\n' >&3; fi
return 0
}
ui_size() {
local bytes=$1 divisor=1 unit=B
if (( bytes >= 1073741824 )); then divisor=1073741824 unit=GiB
elif (( bytes >= 1048576 )); then divisor=1048576 unit=MiB
elif (( bytes >= 1024 )); then divisor=1024 unit=KiB; fi
if (( divisor == 1 )); then printf '%d B' "$bytes"
else printf '%d.%d %s' "$((bytes/divisor))" "$((bytes%divisor*10/divisor))" "$unit"; fi
}
ui_archive() {
local archive=$1 bytes
bytes=$(stat -c %s -- "$archive") || return 1
ui_text ' File: ' ' Файл: '; printf '%q\n' "${archive##*/}"
ui_text ' Size: %s\n' ' Размер: %s\n' "$(ui_size "$bytes")"
ui_text ' Directory: ' ' Каталог: '; printf '%q\n' "${archive%/*}"
}
select_language() {
local answer
while true; do
ui_header 'SELECT LANGUAGE / ВЫБЕРИТЕ ЯЗЫК' 1
printf '\n 1. English\n 2. Русский\n'
ui_back ' 3. Exit / Выход'
printf '\n'; ui_rule; printf ' Select / Выбор: '
IFS= read -r answer || return 1
case "$answer" in
1) UI_LANG=en; UI_INTERACTIVE=1; return 0 ;;
2) UI_LANG=ru; UI_INTERACTIVE=1; return 0 ;;
3) return 1 ;;
*) printf 'Invalid selection / Неверный выбор.\n' ;;
esac
done
}
# The first interactive question must precede even source-ref validation.
# Importing the library and every CLI invocation keep their original startup.
if [[ ${BASH_SOURCE[0]:-} == "$0" && $# == 0 && -t 0 && -t 1 ]]; then
select_language || exit 0
fi
# ─── Pre-flight checks ───────────────────────────────────────────────────────
check_os() {
local os_id='' os_version='' key value
while IFS='=' read -r key value || [[ -n "$key" ]]; do
case "$value" in \"*\"|\'*\') value=${value:1:-1} ;; esac
case "$key" in ID) os_id=$value ;; VERSION_ID) os_version=$value ;; esac
done < /etc/os-release
case "${os_id}" in
ubuntu)
[[ "$os_version" == "24.04" || "$os_version" == "26.04" ]] && return 0
;;
debian)
[[ "$os_version" == "13" ]] && return 0
;;
esac
msg_err "$(ui_text 'Unsupported OS: %s %s' 'Неподдерживаемая ОС: %s %s' "$os_id" "$os_version")"
ui_text '\nThis script supports:\n Ubuntu 24.04 / 26.04\n Debian 13\n' '\nПоддерживаемые ОС:\n Ubuntu 24.04 / 26.04\n Debian 13\n'
ui_text '\nPlease reinstall your server with one of the supported OS versions and try again.\n' '\nУстановите на сервер одну из поддерживаемых версий ОС и повторите запуск.\n'
exit 1
}
check_cpu() {
local cpuinfo="${1:-/proc/cpuinfo}" arch feature_field cpu_model cpu_flags
CPU_SUPPORT_LEVEL="info"
CPU_SUPPORT_TEXT=$(ui_text 'Compatible (acceleration not assessed)' 'Совместим (ускорение не проверялось)')
arch=$(uname -m 2>/dev/null) || return 0
case "$arch" in
x86_64|i386|i486|i586|i686) feature_field="flags" ;;
aarch64|arm64) feature_field="Features" ;;
*) return 0 ;;
esac
cpu_model=$(grep -m1 -E '^[[:space:]]*model name[[:space:]]*:' "$cpuinfo" 2>/dev/null) || cpu_model=""
cpu_flags=$(grep -m1 -E "^[[:space:]]*${feature_field}[[:space:]]*:" "$cpuinfo" 2>/dev/null) || return 0
cpu_flags="${cpu_flags#*:}"
[[ -n "${cpu_flags//[[:space:]]/}" ]] || return 0
if [[ " $cpu_flags " =~ [[:space:]]aes[[:space:]] ]]; then
CPU_SUPPORT_LEVEL="ok"
CPU_SUPPORT_TEXT=$(ui_text 'Compatible (hardware AES available)' 'Совместим (аппаратный AES доступен)')
else
CPU_SUPPORT_LEVEL="warn"
CPU_SUPPORT_TEXT=$(ui_text 'Compatible — hardware AES unavailable' 'Совместим — аппаратный AES недоступен')
msg_warn "$(ui_text 'Hardware AES unavailable. Xray can run, but cryptographic performance may be lower.' 'Аппаратный AES недоступен. Xray может работать, но скорость шифрования может быть ниже.')"
if [[ "${cpu_model,,}" == *qemu* ]]; then
msg_warn "$(ui_text 'Generic QEMU/KVM CPU detected: host-passthrough / AES exposure is recommended when available.' 'Обнаружен стандартный CPU QEMU/KVM: при возможности включите host-passthrough / доступ к AES.')"
fi
msg_warn "$(ui_text 'Continuing installation.' 'Установка продолжается.')"
fi
}
# ─── Constants ───────────────────────────────────────────────────────────────
XUIDB="/etc/x-ui/x-ui.db"
PROJECT_REF="${XUI_AUTO_REF:-main}"
configure_project_source() {
if [[ "$PROJECT_REF" != main && ! "$PROJECT_REF" =~ ^[a-fA-F0-9]{40}$ &&
! "$PROJECT_REF" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
msg_err 'Invalid XUI_AUTO_REF: use main, an exact 40-hex commit SHA, or a stable vMAJOR.MINOR.PATCH tag.'
return 1
fi
GITHUB_RAW="https://raw.githubusercontent.com/xPROMSx/3x-ui-auto-nginx/${PROJECT_REF}"
}
# Validation is local only; source/import performs no operation.
configure_project_source || return 1 2>/dev/null || exit 1
PROJECT_SOURCE_SHA=
LEGACY_CERTBOT_CRON='@monthly certbot renew --non-interactive --pre-hook "systemctl stop nginx" --post-hook "systemctl start nginx" > /dev/null 2>&1'
# ─── Default argument values ─────────────────────────────────────────────────
domain=""
reality_domain=""
INSTALL="y"
AUTODOMAIN="n"
CFALLOW="n"
PANEL_VERSION=""
INSTALL_AGH=n
INSTALL_SECURITY=n
DNS_PREPARED=n
DNS_FINALIZED=n
DNS_ROLLBACK_ATTEMPTED=n
DNS_ROLLBACK_RESULT=not_requested
INSTALL_VISION=n
INSTALL_WARP_RU=n
CREATE_CLIENT=n
vision_domain=''
# ─── Stop & clean previous install (called from main, after domain validation) ─
clean_previous_install() {
# A confirmed full rebuild removes only the exact previously owned route.
# Preserve an unknown or independently modified optional snippet.
local cdn_route=/etc/nginx/snippets/x-ui-auto-optional/xhttp-cdn.conf
if [[ -e $cdn_route || -L $cdn_route ]]; then
[[ -f $cdn_route && ! -L $cdn_route && $(stat -c '%u:%a:%h' "$cdn_route") == 0:600:1 &&
-n ${XHTTP_CDN_PREVIOUS_SHA:-} && $(sha256sum "$cdn_route" | cut -d ' ' -f1) == "$XHTTP_CDN_PREVIOUS_SHA" ]] || {
msg_err 'XHTTP CDN route ownership changed; rebuild stopped before cleanup.'; return 1;
}
rm -f "$cdn_route" || return 1
fi
systemctl stop x-ui 2>/dev/null || true
if [[ "${VISION_PREVIOUS_HOOK:-}" == owned ]]; then
rm -f /etc/letsencrypt/renewal-hooks/deploy/3x-ui-auto-nginx-vision
fi
rm -rf /etc/systemd/system/x-ui.service || return 1
rm -rf /usr/local/x-ui || return 1
rm -rf /etc/x-ui || return 1
# Cover-site state lived in /etc/x-ui (removed above); preflight_cover_sites already
# confirmed these exact directories as owned, so remove them for a fresh publish.
rm -rf /var/www/html/cover-panel /var/www/html/cover-reality /var/www/html/cover-vision || return 1
rm -rf /etc/nginx/sites-enabled/* || return 1
rm -rf /etc/nginx/sites-available/* || return 1
rm -rf /etc/nginx/stream-enabled/* || return 1
}
# ─── Port / path generators ──────────────────────────────────────────────────
get_port() {
echo $(( ((RANDOM<<15)|RANDOM) % 49152 + 10000 ))
}
gen_random_string() {
local length="$1"
head -c 4096 /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c "$length"
echo
}
# Matches the panel's host group_id format (16 lowercase alphanumerics)
gen_group_id() {
head -c 4096 /dev/urandom | tr -dc 'a-z0-9' | head -c 16
echo
}
# 0 = free, 3 = occupied, other = probe failure. After release dependencies.
check_free() {
python3 - "$1" <<'PYPORT'
import errno, socket, sys
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
probe.bind(('127.0.0.1', int(sys.argv[1])))
except OSError as error:
sys.exit(3 if error.errno == errno.EADDRINUSE else 2)
PYPORT
}
ALLOCATED_TCP_PORTS=()
make_port() {
# Assign in the caller shell: command substitution would discard reservations.
local destination candidate used attempt status
for destination in "$@"; do
candidate=$(get_port)
for ((attempt=0; attempt<128; attempt++, candidate=(candidate>=59151?10000:candidate+1))); do
for used in "${ALLOCATED_TCP_PORTS[@]}"; do
[[ "$used" != "$candidate" ]] || break
done
[[ "${used:-}" != "$candidate" ]] || continue
status=0
check_free "$candidate" || status=$?
if (( status == 0 )); then
printf -v "$destination" '%s' "$candidate"
ALLOCATED_TCP_PORTS+=("$candidate")
break
fi
(( status == 3 )) || { msg_err 'Internal TCP port probe failed.'; return 1; }
done
(( attempt < 128 )) || { msg_err 'No free distinct internal TCP port found.'; return 1; }
done
}
# ─── Generate paths (ports follow mandatory release dependencies in main) ───
initialize_installation() {
sub_path=$(gen_random_string 10)
json_path=$(gen_random_string 10)
panel_path=$(gen_random_string 16)
ws_path=$(gen_random_string 10)
trojan_path=$(gen_random_string 10)
xhttp_path=$(gen_random_string 16)
config_username=$(gen_random_string 10)
config_password=$(gen_random_string 20)
diag_path="/net-$(gen_random_string 16)/"
diag_token=$(gen_random_string 16)
}
parse_installation_args() {
while [ "$#" -gt 0 ]; do
case "$1" in -install|-subdomain|-reality_domain|-ONLY_CF_IP_ALLOW|-version)
(( $# >= 2 )) || { msg_err "Missing argument: $1"; return 2; } ;; esac
case "$1" in
-install) INSTALL="$2"; shift 2 ;;
-subdomain) domain="$2"; shift 2 ;;
-reality_domain) reality_domain="$2"; shift 2 ;;
-ONLY_CF_IP_ALLOW) CFALLOW="$2"; shift 2 ;;
-version)
PANEL_VERSION="${2:-}"
[[ -n "$PANEL_VERSION" ]] || { msg_err "-version requires a stable release tag."; exit 1; }
shift 2 ;;
-uninstall) msg_err "The -uninstall option has been removed."; return 2 ;;
*) shift 1 ;;
esac
done
}
# Only stable release versions at or above the supported security baseline.
_validate_panel_version() {
local version="${1#v}"
if [[ ! "$version" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] ||
[[ "$(printf '%s\n' 3.8.0 "$version" | sort -V | head -n1)" != "3.8.0" ]]; then
msg_err "Unsupported 3X-UI version: $1. Use a stable release >= v3.8.0."
return 1
fi
}
# ─── Detect package manager ───────────────────────────────────────────────────
# ─────────────────────────────────────────────────────────────────────────────
# EXISTING INSTALLATION
# ─────────────────────────────────────────────────────────────────────────────
detect_existing_installation() {
EXISTING_INSTALL_CATEGORIES=()
if [[ -e /etc/x-ui || -e /usr/local/x-ui || -e /usr/bin/x-ui ||
-e /etc/systemd/system/x-ui.service || -e /lib/systemd/system/x-ui.service ]] ||
systemctl is-active --quiet x-ui 2>/dev/null || systemctl is-enabled --quiet x-ui 2>/dev/null; then
EXISTING_INSTALL_CATEGORIES+=("3X-UI installation")
fi
if [[ -e /usr/local/lib/3x-ui-pro || -e /usr/local/bin/x-ui-backup ||
-e /etc/systemd/system/mtr-backend.service ]] ||
systemctl is-active --quiet mtr-backend 2>/dev/null || systemctl is-enabled --quiet mtr-backend 2>/dev/null; then
EXISTING_INSTALL_CATEGORIES+=("Project runtime / diagnostics")
fi
if [[ -d /etc/nginx ]] || compgen -G '/etc/nginx/sites-enabled/*' >/dev/null ||
compgen -G '/etc/nginx/sites-available/*' >/dev/null || compgen -G '/etc/nginx/stream-enabled/*' >/dev/null ||
compgen -G '/etc/nginx/snippets/*' >/dev/null ||
[[ "$(dpkg-query -W -f='${Status}' nginx-common 2>/dev/null)" == 'install ok installed' ]]; then
EXISTING_INSTALL_CATEGORIES+=("nginx configuration / package")
fi
if [[ -d /root/cert ]] || compgen -G '/etc/letsencrypt/live/*' >/dev/null; then
EXISTING_INSTALL_CATEGORIES+=("TLS certificates")
fi
if command -v crontab >/dev/null && LC_ALL=C crontab -l 2>/dev/null | grep -Fxq -- "$LEGACY_CERTBOT_CRON"; then
EXISTING_INSTALL_CATEGORIES+=("Legacy project certificate renewal")
fi
if [[ -e /opt/AdGuardHome || -e /etc/systemd/system/AdGuardHome.service ||
-e /etc/nginx/snippets/adguard.conf || -e /etc/nginx/snippets/x-ui-auto-optional/adguard.conf ]] ||
systemctl is-active --quiet AdGuardHome 2>/dev/null || systemctl is-enabled --quiet AdGuardHome 2>/dev/null; then
EXISTING_INSTALL_CATEGORIES+=("AdGuard Home")
fi
return 0
}
confirm_destructive_reinstall() {
local answer category
detect_existing_installation
(( ${#EXISTING_INSTALL_CATEGORIES[@]} )) || return 0
msg_warn '============================================================'
msg_warn "$(ui_text ' Existing installation detected' ' Обнаружена существующая установка')"
msg_warn '============================================================'
for category in "${EXISTING_INSTALL_CATEGORIES[@]}"; do msg_warn " [!] $category"; done
ui_text '\nContinuing will run a full OS dist-upgrade (services may restart),\nremove data in project-managed installation paths and replace nginx configuration.\nUse a clean dedicated VPS; this is a full rebuild, not an update.\nThe OS upgrade cannot be rolled back. Copy a backup off-host first.\n\n' '\nПродолжение запустит полный dist-upgrade ОС (службы могут перезапуститься),\nудалит данные в управляемых проектом каталогах и заменит конфигурацию nginx.\nИспользуйте чистый выделенный VPS: это полная переустановка, а не обновление.\nОбновление ОС нельзя откатить. Сначала скопируйте Backup за пределы VPS.\n\n'
ui_text 'Type YES to remove the existing deployment and continue: ' 'Чтобы удалить существующую установку и продолжить, введите YES: '
if ! IFS= read -r answer || [[ "$answer" != YES ]]; then
msg_err "$(ui_text 'Cancelled. Existing deployment was not changed.' 'Отменено. Существующая установка не изменена.')"
return 1
fi
}
remove_legacy_certbot_cron() {
command -v crontab >/dev/null || return 0
local directory
directory=$(mktemp -d) || return 1
if ! LC_ALL=C crontab -l > "$directory/current" 2> "$directory/error"; then
if grep -qi 'no crontab for' "$directory/error"; then rm -rf "$directory"; return 0; fi
rm -rf "$directory"; return 1
fi
if grep -Fxq -- "$LEGACY_CERTBOT_CRON" "$directory/current"; then
awk -v legacy="$LEGACY_CERTBOT_CRON" '$0 != legacy' "$directory/current" > "$directory/new" || { rm -rf "$directory"; return 1; }
crontab - < "$directory/new" && crontab -l > "$directory/verified" &&
cmp -s "$directory/new" "$directory/verified" || { rm -rf "$directory"; return 1; }
fi
rm -rf "$directory"
}
cleanup_adguard() {
# Only the upstream-generated project unit is owned here; never run an old binary.
if systemctl cat AdGuardHome >/dev/null 2>&1 || systemctl is-active --quiet AdGuardHome 2>/dev/null; then
local fragment
fragment=$(systemctl show -p FragmentPath --value AdGuardHome) || return 1
[[ "$fragment" == /etc/systemd/system/AdGuardHome.service ]] || return 1
systemctl stop AdGuardHome && systemctl disable AdGuardHome || return 1
systemctl is-active --quiet AdGuardHome && return 1
rm -f /etc/systemd/system/AdGuardHome.service || return 1
systemctl daemon-reload || return 1
fi
rm -rf /opt/AdGuardHome || return 1
rm -f /etc/nginx/snippets/adguard.conf /etc/nginx/snippets/x-ui-auto-optional/adguard.conf || return 1
rm -f /usr/local/lib/3x-ui-pro/managed-adguard.sh
}
# ─────────────────────────────────────────────────────────────────────────────
# GET SERVER IP
# ─────────────────────────────────────────────────────────────────────────────
IP4_REGEX="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
IP6_REGEX="([a-f0-9:]+:+)+[a-f0-9]+"
get_server_ip() {
IP4=$(ip route get 8.8.8.8 2>&1 | grep -Po -- 'src \K\S*')
IP6=$(ip route get 2620:fe::fe 2>&1 | grep -Po -- 'src \K\S*')
[[ $IP4 =~ $IP4_REGEX ]] || IP4=$(curl -4 -fsS --connect-timeout 5 --max-time 10 https://ipv4.icanhazip.com | tr -d '[:space:]')
[[ $IP6 =~ $IP6_REGEX ]] || IP6=$(curl -6 -fsS --connect-timeout 5 --max-time 10 https://ipv6.icanhazip.com 2>/dev/null | tr -d '[:space:]')
[[ $IP4 =~ $IP4_REGEX ]] || IP4=""
[[ $IP6 =~ $IP6_REGEX ]] || IP6=""
}
# ─────────────────────────────────────────────────────────────────────────────
# DOMAIN VALIDATION
# ─────────────────────────────────────────────────────────────────────────────
valid_hostname() {
local LC_ALL=C label
local -a labels
(( ${#1} > 0 && ${#1} <= 253 )) &&
[[ "$1" =~ ^[a-zA-Z0-9.-]+$ && "$1" == *.* && "$1" != *. ]] || return 1
IFS=. read -r -a labels <<< "$1"
for label in "${labels[@]}"; do
[[ "$label" =~ ^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$ ]] || return 1
done
}
validate_domains() {
local LC_ALL=C
while true; do
[[ -n "$domain" ]] && break
ui_text 'Enter the domain for your 3X-UI panel: ' 'Введите домен панели 3X-UI: '
IFS= read -r domain || { msg_err "$(ui_text 'Panel domain is required.' 'Необходимо указать домен панели.')"; return 1; }
done
valid_hostname "$domain" || { msg_err "$(ui_text 'Invalid panel hostname: use ASCII DNS labels (punycode supported), without URL, whitespace or terminal dot.' 'Некорректный домен панели: используйте DNS-имя в ASCII (punycode поддерживается), без URL, пробелов и точки в конце.')"; return 1; }
domain=${domain,,}
SubDomain=$(echo "$domain" | sed 's/^[^ ]* \|\..*//g')
MainDomain=$(echo "$domain" | sed 's/.*\.\([^.]*\..*\)$/\1/')
[[ "${SubDomain}.${MainDomain}" != "${domain}" ]] && MainDomain=${domain}
while true; do
[[ -n "$reality_domain" ]] && break
ui_text 'Enter the domain for VLESS REALITY: ' 'Введите домен VLESS REALITY: '
IFS= read -r reality_domain || { msg_err "$(ui_text 'REALITY domain is required.' 'Необходимо указать домен REALITY.')"; return 1; }
done
valid_hostname "$reality_domain" || { msg_err "$(ui_text 'Invalid REALITY hostname: use ASCII DNS labels (punycode supported), without URL, whitespace or terminal dot.' 'Некорректный домен REALITY: используйте DNS-имя в ASCII (punycode поддерживается), без URL, пробелов и точки в конце.')"; return 1; }
reality_domain=${reality_domain,,}
RealitySubDomain=$(echo "$reality_domain" | sed 's/^[^ ]* \|\..*//g')
RealityMainDomain=$(echo "$reality_domain" | sed 's/.*\.\([^.]*\..*\)$/\1/')
[[ "${RealitySubDomain}.${RealityMainDomain}" != "${reality_domain}" ]] && RealityMainDomain=${reality_domain}
if [[ "$domain" == "$reality_domain" ]]; then
msg_err "$(ui_text 'Panel domain and REALITY domain must be different! Got: %s' 'Домены панели и REALITY должны различаться! Указано: %s' "$domain")"
exit 1
fi
}
# ─────────────────────────────────────────────────────────────────────────────
# INSTALL PACKAGES
# ─────────────────────────────────────────────────────────────────────────────
apt_system() {
local output attempt rc deadline=$((SECONDS + 300))
local -a statuses
output=$(mktemp) || return 1
for attempt in {1..30}; do
if DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l UCF_FORCE_CONFFOLD=1 \
apt-get -o DPkg::Lock::Timeout=300 -o Dpkg::Options::=--force-confdef \
-o Dpkg::Options::=--force-confold -o Acquire::Retries=3 \
-o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \
"$@" 2>&1 | tee "$output"; then
statuses=("${PIPESTATUS[@]}")
else
statuses=("${PIPESTATUS[@]}")
fi
rc=${statuses[0]}
(( statuses[1] == 0 )) || { rm -f "$output"; return 1; }
if (( rc == 0 )); then rm -f "$output"; return 0; fi
# apt update's lists lock does not use DPkg::Lock::Timeout.
if ! grep -Eq 'Could not get lock|Unable to acquire.*lock' "$output"; then break; fi
(( SECONDS < deadline )) || break
sleep 10
done
rm -f "$output"; return "$rc"
}
setup_swap() {
[[ "${INSTALL_SECURITY:-n}" == y ]] || return 0
SWAP_RESULT=skipped
SWAP_REASON='required tools unavailable'
local tool active fs available fstab_tmp='' identity
for tool in swapon swapoff findmnt df awk fallocate chmod mkswap stat cp mv mktemp grep rm; do
command -v "$tool" >/dev/null || return 0
done
SWAP_REASON='cannot inspect active swap'
active=$(swapon --show=NAME --noheadings --raw) || return 0
if [[ -n "$active" ]]; then SWAP_RESULT=existing; return 0; fi
SWAP_REASON='/swapfile already exists'
[[ ! -e /swapfile && ! -L /swapfile ]] || return 0
SWAP_REASON='unsupported filesystem'
fs=$(findmnt -n -o FSTYPE --target /) || return 0
[[ "$fs" == ext4 || "$fs" == xfs ]] || return 0
SWAP_REASON='less than 4 GiB free'
available=$(df -Pk / | awk 'END {print $4}') || return 0
[[ "$available" =~ ^[0-9]+$ ]] && (( available >= 4194304 )) || return 0
SWAP_REASON='fstab unavailable or already references /swapfile'
[[ -f /etc/fstab && ! -L /etc/fstab ]] || return 0
awk '$1 == "/swapfile" {found=1} END {exit found}' /etc/fstab || return 0
SWAP_REASON='cannot create private swap file'
(set -o noclobber; umask 077; : > /swapfile) 2>/dev/null || return 0
identity=$(stat -c '%d:%i' /swapfile) || { rm -f /swapfile; return 0; }
# Only this invocation's file is owned; never remove pre-existing swap.
while :; do
SWAP_REASON='allocation failed'
fallocate -l 1G /swapfile && chmod 600 /swapfile || break
SWAP_REASON='mkswap failed'
mkswap /swapfile || break
SWAP_REASON='activation failed'
swapon /swapfile || break
active=$(swapon --show=NAME --noheadings --raw) || break
grep -Fxq /swapfile <<< "$active" || break
SWAP_REASON='fstab update failed'
# Stage the append privately: a failed write must not leave a partial entry.
fstab_tmp=$(mktemp /etc/.3x-ui-fstab.XXXXXX) || break
cp -p /etc/fstab "$fstab_tmp" || break
printf '\n/swapfile none swap sw 0 0\n' >> "$fstab_tmp" || break
mv -f "$fstab_tmp" /etc/fstab || break
SWAP_RESULT=created
return 0
done
[[ -z "$fstab_tmp" ]] || rm -f "$fstab_tmp"
if active=$(swapon --show=NAME --noheadings --raw); then
if grep -Fxq /swapfile <<< "$active"; then
swapoff /swapfile || { SWAP_REASON+='; swap cleanup failed'; return 0; }
fi
if [[ ! -L /swapfile && "$(stat -c '%d:%i' /swapfile)" == "$identity" ]]; then
rm -f /swapfile || SWAP_REASON+='; file cleanup failed'
fi
else
SWAP_REASON+='; activation unknown, file retained'
fi
return 0
}
ensure_sshd_runtime_dir() {
local directory=/run/sshd config=/usr/lib/tmpfiles.d/openssh-server.conf
[[ ! -L "$directory" && ( ! -e "$directory" || -d "$directory" ) ]] || {
msg_err 'Unsafe OpenSSH runtime path: /run/sshd must be a real directory, not a symlink or file.'; return 1;
}
if [[ -f "$config" ]]; then
systemd-tmpfiles --create --prefix="$directory" "$config" || {
msg_err 'Could not prepare OpenSSH runtime directory through systemd-tmpfiles.'; return 1;
}
fi
[[ ! -L "$directory" && ( ! -e "$directory" || -d "$directory" ) ]] || {
msg_err 'Unsafe OpenSSH runtime path after tmpfiles: /run/sshd.'; return 1;
}
if [[ ! -d "$directory" || "$(stat -c '%u:%g:%a' -- "$directory")" != 0:0:755 ]]; then
install -d -o root -g root -m 0755 -- "$directory" || {
msg_err 'Could not restore OpenSSH runtime directory ownership/permissions.'; return 1;
}
fi
[[ ! -L "$directory" && -d "$directory" && "$(stat -c '%u:%g:%a' -- "$directory")" == 0:0:755 ]] || {
msg_err 'OpenSSH runtime directory verification failed: expected root:root mode 0755.'; return 1;
}
}
check_systemd_manager() {
local version
if ! version=$(systemctl --system show --property=Version --value) || [[ -z "$version" ]]; then
msg_err 'systemd manager is unavailable after package operations; cannot safely continue configuration.'; return 1
fi
}
preflight_base_os() {
local audit binary
for binary in apt-get apt-config dpkg systemctl timedatectl getent /usr/sbin/sshd; do
command -v "$binary" >/dev/null || { msg_err "Base OS tool unavailable: $binary"; return 1; }
done
audit=$(dpkg --audit) || return 1
[[ -z "$audit" ]] || { msg_err 'Incomplete dpkg state; repair it before installation.'; return 1; }
ensure_sshd_runtime_dir || return 1
/usr/sbin/sshd -t || { msg_err 'OpenSSH configuration validation failed before OS preparation.'; return 1; }
if systemctl is-active --quiet ssh.socket; then
BASE_SSH_UNIT=ssh.socket
elif systemctl is-active --quiet ssh.service; then
BASE_SSH_UNIT=ssh.service
else
msg_err 'No active SSH service/socket; refusing OS preparation.'; return 1;
fi
getent ahosts debian.org >/dev/null || { msg_err 'Initial libc DNS resolution failed.'; return 1; }
}
verify_base_os() {
local binary
check_systemd_manager || return 1
ensure_sshd_runtime_dir || return 1
/usr/sbin/sshd -t || { msg_err 'OpenSSH configuration validation failed after OS preparation.'; return 1; }
systemctl is-active --quiet "$BASE_SSH_UNIT" || {
msg_err "Original SSH activation unit is not active after OS preparation: $BASE_SSH_UNIT."; return 1;
}
for binary in curl wget jq python3 openssl ip ss ufw; do
command -v "$binary" >/dev/null || return 1
done
getent ahosts debian.org >/dev/null
}
prepare_base_os() {
msg_warn "$(ui_text 'Preparing OS: full dist-upgrade; package changes cannot be rolled back.' 'Подготовка ОС: полный dist-upgrade; изменения пакетов нельзя откатить.')"
apt_system -o APT::Update::Error-Mode=any update || { msg_err "$(ui_text 'APT list refresh failed (exit %s). Package changes are not rolled back.' 'Не удалось обновить списки APT (exit %s). Изменения пакетов не откатываются.' "$?")"; return 1; }
# Show the full upgrade plan before applying it with normal APT safeguards.
apt_system -s -y dist-upgrade || { msg_err "$(ui_text 'Full upgrade simulation failed (exit %s). No deployment cleanup was performed.' 'Проверка полного обновления завершилась ошибкой (exit %s). Данные установки не удалялись.' "$?")"; return 1; }
apt_system -y dist-upgrade || { msg_err "$(ui_text 'Full OS upgrade failed (exit %s). Package changes are not rolled back.' 'Полное обновление ОС завершилось ошибкой (exit %s). Изменения пакетов не откатываются.' "$?")"; return 1; }
apt_system -y --no-install-recommends install curl wget jq python3 openssl \
ca-certificates procps iproute2 ufw tar gzip || { msg_err "$(ui_text 'System dependency installation failed (exit %s). Package changes are not rolled back.' 'Установка системных зависимостей завершилась ошибкой (exit %s). Изменения пакетов не откатываются.' "$?")"; return 1; }
verify_base_os || return 1
BASE_OS_RESULT=configured
}
prepare_system_dns() {
[[ "${INSTALL_SECURITY:-n}" == y ]] || return 0
local output status
DNS_PREPARED=y
if ! output=$(python3 "$PANEL_STAGE/managed-security.py" --prepare-dns "$PANEL_STAGE/dns-checkpoint"); then
status=$(printf '%s' "$output" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])') || status=failed_unverified
printf '%s' "$output" | python3 -c 'import json,sys; [print("[!] DNS preparation: "+w,file=sys.stderr) for w in json.load(sys.stdin)["warnings"]]'
if [[ "$status" == failed_rolled_back ]]; then
DNS_PREPARED=n
DOT_RESULT=failed_rolled_back
msg_warn "$(ui_text 'DoT unavailable; original DNS restored. Continuing core, Fail2ban and APT installation. Inspect the DNS failure above.' 'DoT недоступен; исходные настройки DNS восстановлены. Установка основного стека, Fail2ban и APT продолжается. Проверьте ошибку DNS выше.')"
verify_base_os
return $?
fi
DOT_RESULT=failed_unverified
return 1
fi
DOT_RESULT=configured
printf '%s' "$output" | python3 -c 'import json,sys; [print("[!] "+w) for w in json.load(sys.stdin)["warnings"]]'
verify_base_os
}
rollback_system_dns() {
local output
DNS_ROLLBACK_ATTEMPTED=y
DNS_ROLLBACK_RESULT=failed_unverified
output=$(python3 "$PANEL_STAGE/managed-security.py" --rollback-dns "$PANEL_STAGE/dns-checkpoint")
DNS_ROLLBACK_RESULT=$(printf '%s' "$output" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])') || return 1
printf '%s' "$output" | python3 -c 'import json,sys; [print("[!] "+w,file=sys.stderr) for w in json.load(sys.stdin)["warnings"]]'
if [[ "$DNS_ROLLBACK_RESULT" == failed_rolled_back ]]; then DNS_PREPARED=n; return 0; fi
return 1
}
finish_initial_reboot() {
[[ -e /var/run/reboot-required ]] || return 0
if (( $1 != 0 )); then
msg_warn "$(ui_text 'Reboot required, but installation failed. Inspect the failure before rebooting manually: sudo reboot' 'Нужна перезагрузка, но установка завершилась ошибкой. Разберитесь с ошибкой перед ручной перезагрузкой: sudo reboot')"
else
msg_warn "$(ui_text 'Initial upgrade requires a manual reboot: sudo reboot. Post-reboot acceptance is pending.' 'После первоначального обновления нужна ручная перезагрузка: sudo reboot. Проверка после перезагрузки ещё не выполнена.')"
fi
}
install_packages() {
if [[ ${INSTALL} == *"y"* ]]; then
local version
version=$(grep -oP '(?<=VERSION_ID=")[0-9]+' /etc/os-release)
[[ "$version" == "20" || "$version" == "22" ]] && echo "System: Ubuntu $version"
apt_system -o APT::Update::Error-Mode=any update || { msg_err "$(ui_text 'APT list refresh failed (exit %s). Package changes are not rolled back.' 'Не удалось обновить списки APT (exit %s). Изменения пакетов не откатываются.' "$?")"; return 1; }
apt_system -y install curl wget jq bash sudo nginx-full certbot sqlite3 ufw netcat-openbsd mtr-tiny python3 python3-configobj python3-cryptography libcap2-bin openssl procps iproute2 tar gzip tzdata ca-certificates || return 1
if ! ipv6_available; then
rm -f /etc/nginx/sites-enabled/default || return 1
fi
systemctl daemon-reload && systemctl enable --now nginx || return 1
fi
apt_system -y --no-install-recommends install ca-certificates || return 1
local binary
for binary in openssl sysctl ip ss tar gzip curl wget jq bash sudo nginx certbot sqlite3 ufw nc mtr python3 setcap; do
command -v "$binary" >/dev/null || { msg_err "Required binary is missing: $binary"; return 1; }
done
python3 -c 'import configobj, cryptography' || { msg_err 'Required Python modules are unavailable: configobj, cryptography.'; return 1; }
}
# ─────────────────────────────────────────────────────────────────────────────
# SSL CERTIFICATES
# ─────────────────────────────────────────────────────────────────────────────
prepare_acme_webroot() {
install -d -o root -g root -m 0755 /var/www/acme /var/www/acme/.well-known /var/www/acme/.well-known/acme-challenge
}
ipv6_available() {
python3 - <<'PYIPV6'
import socket, sys
try:
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM): pass
except OSError:
sys.exit(1)
PYIPV6
}
setup_acme_http() {
local ipv6_listen=''
if ipv6_available; then ipv6_listen='listen [::]:80;'; fi
prepare_acme_webroot || return 1
mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled || return 1
cat > /etc/nginx/sites-available/80.conf <<EOF
# 253-byte DNS key plus 64-bit hash entry/sentinel; nginx aligns to cache lines.
server_names_hash_bucket_size 272;
server {
listen 80;
${ipv6_listen}
server_name ${domain} ${reality_domain};
server_tokens off;
if (\$host !~* ^(${domain//./\\.}|${reality_domain//./\\.})\$) { return 404; }
location ^~ /.well-known/acme-challenge/ {
root /var/www/acme;
default_type text/plain;
try_files \$uri =404;
}
location / { return 301 https://\$host\$request_uri; }
}
EOF
[[ $? == 0 ]] || return 1
rm -f /etc/nginx/sites-enabled/default || return 1
ln -sf /etc/nginx/sites-available/80.conf /etc/nginx/sites-enabled/80.conf || return 1
nginx -t && systemctl enable --now nginx && systemctl reload nginx && systemctl is-active --quiet nginx
}
get_ssl_certs() {
if [[ ${AUTODOMAIN} == *"y"* ]]; then
local resolve_ok=true
for d in "$domain" "$reality_domain"; do
local a
a=$(getent ahostsv4 "$d" 2>/dev/null | awk 'NR==1{print $1}')
if [[ "$a" != "$IP4" ]]; then
msg_err "$(ui_text 'Auto-domain %s does not resolve to %s. Fix DNS and retry.' 'Домен %s не разрешается в %s. Исправьте DNS и повторите попытку.' "$d" "$IP4")"
resolve_ok=false
fi
done
[[ $resolve_ok == false ]] && return 1
fi
# Rebuild only our hook after runtime configuration; preserve all lineages.
rm -f /etc/letsencrypt/renewal-hooks/deploy/3x-ui-auto-nginx || return 1
local d
for d in "$domain" "$reality_domain"; do
if [[ -e "/etc/letsencrypt/live/$d" || -e "/etc/letsencrypt/renewal/$d.conf" ]]; then
[[ -d "/etc/letsencrypt/live/$d" && -f "/etc/letsencrypt/renewal/$d.conf" ]] || {
msg_err "$(ui_text 'Incomplete certificate lineage: %s. Resolve it before rebuilding.' 'Неполные данные сертификата (lineage): %s. Исправьте их перед переустановкой.' "$d")"; return 1;
}
check_certificate_identity "$d" || return 1
if ! check_webroot_lineage "$d" 2>/dev/null; then
certbot reconfigure --cert-name "$d" --webroot --webroot-path /var/www/acme \
--pre-hook '' --post-hook '' --non-interactive || return 1
fi
elif compgen -G "/etc/letsencrypt/live/$d-*" >/dev/null || compgen -G "/etc/letsencrypt/renewal/$d-*.conf" >/dev/null; then
msg_err "$(ui_text 'Ambiguous certificate lineage for %s. Resolve it before rebuilding.' 'Неоднозначный сертификат (lineage) для %s. Исправьте это перед переустановкой.' "$d")"; return 1
else
certbot certonly --webroot --webroot-path /var/www/acme --cert-name "$d" -d "$d" \
--non-interactive --agree-tos --register-unsafely-without-email || return 1
fi
check_webroot_lineage "$d" || return 1
done
mkdir -p "/root/cert/${domain}" || return 1
chmod 755 /root/cert "/root/cert/${domain}" || return 1
ln -sf "/etc/letsencrypt/live/${domain}/fullchain.pem" "/root/cert/${domain}/fullchain.pem" || return 1
ln -sf "/etc/letsencrypt/live/${domain}/privkey.pem" "/root/cert/${domain}/privkey.pem"
}
# ─────────────────────────────────────────────────────────────────────────────
# CONFIGURE NGINX
# ─────────────────────────────────────────────────────────────────────────────
configure_nginx() {
install -d -o root -g root -m 0755 /etc/nginx/snippets/x-ui-auto-optional || return 1
install -d -o root -g root -m 0755 /etc/nginx/stream-sni.d /etc/nginx/stream-upstreams.d || return 1
mkdir -p /etc/nginx/stream-enabled /etc/nginx/snippets || return 1
# nginx >= 1.25.1 deprecates "listen ... http2" in favor of "http2 on;";
# older versions (Ubuntu 24.04) don't know the new directive
local ngx_ver http2_listen="" http2_on="" ipv6_listen=''
if ipv6_available; then ipv6_listen='listen [::]:443;'; fi
ngx_ver=$(nginx -v 2>&1 | grep -oP '[0-9]+\.[0-9]+\.[0-9]+' || echo 0)
if [[ "$(printf '%s\n' 1.25.1 "$ngx_ver" | sort -V | head -1)" == "1.25.1" ]]; then
http2_on="http2 on;"
else
http2_listen=" http2"
fi
# SNI-based stream: reality → 8443, domain → 7443
cat > /etc/nginx/stream-enabled/stream.conf <<EOF
# 253-byte DNS key plus 64-bit hash entry/sentinel; nginx aligns to cache lines.
map_hash_bucket_size 272;
map \$ssl_preread_server_name \$sni_name {
hostnames;
${reality_domain} xray;
${domain} www;
include /etc/nginx/stream-sni.d/*.conf;
default xray;
}
upstream xray {
server 127.0.0.1:8443 max_fails=0;
server 127.0.0.1:9443 backup;
}
upstream www { server 127.0.0.1:7443; }
include /etc/nginx/stream-upstreams.d/*.conf;
server {
proxy_protocol on;
set_real_ip_from unix:;
listen 443;
${ipv6_listen}
proxy_pass \$sni_name;
ssl_preread on;
}
EOF
[[ $? -eq 0 ]] || return 1
grep -xqFR "stream { include /etc/nginx/stream-enabled/*.conf; }" /etc/nginx/* \
|| echo "stream { include /etc/nginx/stream-enabled/*.conf; }" >> /etc/nginx/nginx.conf
grep -xqFR "load_module modules/ngx_stream_module.so;" /etc/nginx/* \
|| sed -i '1s/^/load_module \/usr\/lib\/nginx\/modules\/ngx_stream_module.so; /' /etc/nginx/nginx.conf
grep -xqFR "worker_rlimit_nofile 16384;" /etc/nginx/* \
|| echo "worker_rlimit_nofile 16384;" >> /etc/nginx/nginx.conf
sed -i "/worker_connections/c\worker_connections 4096;" /etc/nginx/nginx.conf
# Shared proxy locations for xray inbounds (included by both vhosts)
cat > /etc/nginx/snippets/includes.conf <<EOF
#Subscription — prefix location covers all sub-paths (assets, JS, etc.)
# Local error_page overrides inherited cover-page redirects; backend 5xx retain their status.
location /${sub_path}/ {
access_log off;
error_log /dev/null crit;
error_page 404 =404 @subscription_error;
if (\$hack = 1) { return 404; }
proxy_redirect off;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass https://127.0.0.1:${sub_port};
}
location = /${sub_path} {
access_log off;
error_log /dev/null crit;
error_page 404 =404 @subscription_error;
if (\$hack = 1) { return 404; }
proxy_redirect off;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass https://127.0.0.1:${sub_port};
}
# Regex takes priority over prefix: catches subscription IDs (one-level deep)
# and routes Clash/Mihomo clients to dynamic clash.yaml generator
location ~ ^/${sub_path}/(?<clash_sub_id>[^/]+)$ {
access_log off;
error_log /dev/null crit;
error_page 404 =404 @subscription_error;
if (\$hack = 1) { return 404; }
if (\$serve_clash_yaml = 1) { rewrite ^ /__clash_api?sub_id=\$clash_sub_id last; }
proxy_redirect off;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass https://127.0.0.1:${sub_port};
}
#Subscription (json)
location /${json_path} {
access_log off;
error_log /dev/null crit;
error_page 404 =404 @subscription_error;
if (\$hack = 1) { return 404; }
proxy_redirect off;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass https://127.0.0.1:${sub_port};
}
location /${json_path}/ {
access_log off;
error_log /dev/null crit;
error_page 404 =404 @subscription_error;
if (\$hack = 1) { return 404; }
proxy_redirect off;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass https://127.0.0.1:${sub_port};
}
location @subscription_error {
access_log off;
error_log /dev/null crit;
return 404;
}
#XHTTP
location ^~ /${xhttp_path}/ {
client_max_body_size 0;
client_body_timeout 1h;
grpc_read_timeout 1h;
grpc_send_timeout 1h;
grpc_set_header Connection "";
grpc_set_header Host \$host;
grpc_set_header X-Real-IP \$remote_addr;
grpc_set_header X-Forwarded-For \$remote_addr;
grpc_pass unix:/dev/shm/uds2023.sock;
}
# Installer-managed WS: exact path, fixed backend port
location = /${ws_port}/${ws_path} {
if (\$hack = 1) { return 404; }
client_max_body_size 0;
client_body_timeout 1d;
proxy_read_timeout 1d;
proxy_http_version 1.1;
proxy_buffering off;
proxy_request_buffering off;
proxy_socket_keepalive on;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:${ws_port};
}
# Xray custom gRPC serviceName is the full method path (no /Tun suffix)
location = /${trojan_port}/${trojan_path} {
if (\$hack = 1) { return 404; }
client_max_body_size 0;
client_body_timeout 1d;
grpc_read_timeout 1d;
grpc_socket_keepalive on;
grpc_set_header Host \$host;
grpc_pass grpc://127.0.0.1:${trojan_port};
}
location / { error_page 404 /404.html; try_files \$uri \$uri/ =404; }
EOF
[[ $? -eq 0 ]] || return 1
# HTTP-level maps. The clash maps are consumed by the shared includes.conf
# snippet, which is included by BOTH vhosts, so they live in their own
# always-loaded file — never inside a single vhost, or the other vhost's
# include would reference an undefined var ("unknown ... variable").
cat > /etc/nginx/sites-available/00-maps.conf <<EOF
# Detect Clash/Mihomo clients by User-Agent
map \$http_user_agent \$is_clash_ua {
~*(clash|clashx|clashn|mihomo|stash|surfboard) 1;
default 0;
}
# Serve clash.yaml only when: Clash UA AND no ?provider=1 query param
# (proxy-provider refresh requests add ?provider=1 and must get the real sub)
map "\$is_clash_ua:\$arg_provider:\$http_user_agent:\$http_x_hwid" \$serve_clash_yaml {
# XKeen UI HTTP providers advertise this version-independent UA pair + HWID.
"~*^1::ClashMeta/[0-9][0-9A-Za-z.+_-]*;[ ]*mihomo/[0-9][0-9A-Za-z.+_-]*:.+\$" 0;
~^1:: 1;
default 0;
}
EOF
[[ $? -eq 0 ]] || return 1
# Main domain vhost (TLS termination at 7443, proxy_protocol)
install -o root -g root -m 0600 /dev/null "/etc/nginx/sites-available/${domain}" || return 1
cat > "/etc/nginx/sites-available/${domain}" <<EOF
# Rate limiting zones (http context)
limit_req_zone \$binary_remote_addr zone=diag_api:10m rate=6r/m;
limit_req_zone \$binary_remote_addr zone=diag_page:10m rate=30r/m;
limit_conn_zone \$binary_remote_addr zone=per_ip:10m;
# Diagnostics access: cookie issued by the SSO bridge after panel login
# Exact regex avoids a 40-byte hash entry on CPUs with 32-byte map buckets.