install.sh 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054
  1. #!/bin/bash
  2. red='\033[0;31m'
  3. green='\033[0;32m'
  4. blue='\033[0;34m'
  5. yellow='\033[0;33m'
  6. plain='\033[0m'
  7. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  8. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  9. # check root
  10. [[ $EUID -ne 0 ]] && echo -e "${red}Fatal error: ${plain} Please run this script with root privilege \n " && exit 1
  11. # Check OS and set release variable
  12. if [[ -f /etc/os-release ]]; then
  13. source /etc/os-release
  14. release=$ID
  15. elif [[ -f /usr/lib/os-release ]]; then
  16. source /usr/lib/os-release
  17. release=$ID
  18. else
  19. echo "Failed to check the system OS, please contact the author!" >&2
  20. exit 1
  21. fi
  22. echo "The OS release is: $release"
  23. arch() {
  24. case "$(uname -m)" in
  25. x86_64 | x64 | amd64) echo 'amd64' ;;
  26. i*86 | x86) echo '386' ;;
  27. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  28. armv7* | armv7 | arm) echo 'armv7' ;;
  29. armv6* | armv6) echo 'armv6' ;;
  30. armv5* | armv5) echo 'armv5' ;;
  31. s390x) echo 's390x' ;;
  32. *) echo -e "${green}Unsupported CPU architecture! ${plain}" && rm -f "$(realpath "$0")" && exit 1 ;;
  33. esac
  34. }
  35. echo "Arch: $(arch)"
  36. # Non-interactive mode: triggered explicitly via XUI_NONINTERACTIVE=1, or
  37. # implicitly when stdin is not a TTY (e.g. `curl ... | bash`, cloud-init).
  38. # In this mode every prompt below is replaced by an env var or a sane default.
  39. if [[ "${XUI_NONINTERACTIVE:-0}" == "1" ]] || [[ ! -t 0 ]]; then
  40. NONINTERACTIVE=1
  41. else
  42. NONINTERACTIVE=0
  43. fi
  44. export NONINTERACTIVE
  45. # Simple helpers
  46. is_ipv4() {
  47. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  48. }
  49. is_ipv6() {
  50. [[ "$1" =~ : ]] && return 0 || return 1
  51. }
  52. is_ip() {
  53. is_ipv4 "$1" || is_ipv6 "$1"
  54. }
  55. is_domain() {
  56. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  57. }
  58. # acme.sh's standalone server binds IPv4 by default; --listen-v6 makes it
  59. # v6-only, which breaks HTTP-01 validation when the domain's A record points
  60. # at this host's IPv4 (#4994). Only force IPv6 when the host has no global
  61. # IPv4 address at all.
  62. acme_listen_flag() {
  63. if ip -4 addr show scope global 2> /dev/null | grep -q "inet "; then
  64. echo ""
  65. else
  66. echo "--listen-v6"
  67. fi
  68. }
  69. # Port helpers
  70. is_port_in_use() {
  71. local port="$1"
  72. if command -v ss > /dev/null 2>&1; then
  73. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  74. return
  75. fi
  76. if command -v netstat > /dev/null 2>&1; then
  77. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  78. return
  79. fi
  80. if command -v lsof > /dev/null 2>&1; then
  81. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  82. fi
  83. return 1
  84. }
  85. install_base() {
  86. case "${release}" in
  87. ubuntu | debian | armbian)
  88. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  89. ;;
  90. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  91. dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  92. ;;
  93. centos)
  94. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  95. yum makecache -y && yum install -y cronie curl tar tzdata socat ca-certificates openssl
  96. else
  97. dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  98. fi
  99. ;;
  100. arch | manjaro | parch)
  101. pacman -Sy --noconfirm cronie curl tar tzdata socat ca-certificates openssl
  102. ;;
  103. opensuse-tumbleweed | opensuse-leap)
  104. zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
  105. ;;
  106. alpine)
  107. apk update && apk add dcron curl tar tzdata socat ca-certificates openssl
  108. ;;
  109. *)
  110. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  111. ;;
  112. esac
  113. }
  114. gen_random_string() {
  115. local length="$1"
  116. openssl rand -base64 $((length * 2)) \
  117. | tr -dc 'a-zA-Z0-9' \
  118. | head -c "$length"
  119. }
  120. # prompt_or_default VARNAME "prompt text" "default" [ENV_NAME]
  121. # Interactive: read into VARNAME. Non-interactive: VARNAME = ${ENV_NAME:-default}.
  122. # ENV_NAME defaults to VARNAME when omitted. Keeps every interactive prompt
  123. # string byte-for-byte identical to the original `read -rp`.
  124. prompt_or_default() {
  125. local __var="$1" __prompt="$2" __default="$3" __env="${4:-$1}"
  126. if [[ "$NONINTERACTIVE" == "1" ]]; then
  127. printf -v "$__var" '%s' "${!__env:-$__default}"
  128. else
  129. # shellcheck disable=SC2229
  130. read -rp "$__prompt" "$__var"
  131. fi
  132. }
  133. # write_install_result <user> <pass> <port> <webpath> <scheme> <host> <token> <dbtype>
  134. # Persists a parseable, root-only credentials file consumed by cloud-init/MOTD.
  135. # Values are written with printf '%q' so a pinned password/username containing
  136. # spaces, quotes, $(...) or backticks is shell-escaped and the file stays safely
  137. # source-able (consumers do '. install-result.env'). For the alphanumeric random
  138. # values gen_random_string emits, %q is a no-op. This is a DIFFERENT file from the
  139. # Postgres env file (/etc/default/x-ui).
  140. write_install_result() {
  141. local u="$1" p="$2" port="$3" wbp="$4" scheme="$5" host="$6" token="$7" dbtype="$8"
  142. local result_file="/etc/x-ui/install-result.env"
  143. local url_host="${host:-SERVER_IP_UNKNOWN}"
  144. install -d -m 700 /etc/x-ui 2> /dev/null
  145. local prev_umask
  146. prev_umask=$(umask)
  147. umask 077
  148. if ! {
  149. printf 'XUI_USERNAME=%q\n' "$u"
  150. printf 'XUI_PASSWORD=%q\n' "$p"
  151. printf 'XUI_PANEL_PORT=%q\n' "$port"
  152. printf 'XUI_WEB_BASE_PATH=%q\n' "$wbp"
  153. printf 'XUI_ACCESS_URL=%q\n' "${scheme}://${url_host}:${port}/${wbp}"
  154. printf 'XUI_API_TOKEN=%q\n' "$token"
  155. printf 'XUI_DB_TYPE=%q\n' "$dbtype"
  156. } > "$result_file"; then
  157. umask "$prev_umask"
  158. echo -e "${yellow}Warning: failed to write ${result_file}.${plain}" >&2
  159. return 1
  160. fi
  161. umask "$prev_umask"
  162. chmod 600 "$result_file" 2> /dev/null
  163. chown root:root "$result_file" 2> /dev/null || true
  164. echo -e "${green}Install result written to ${result_file} (mode 600).${plain}"
  165. }
  166. # RHEL-family initdb writes pg_hba.conf host rules with ident auth, which
  167. # compares the OS username against the Postgres role and always rejects the
  168. # randomly generated panel role over TCP (#5806). Prepend password-auth rules
  169. # scoped to the panel database; first match wins, and md5 also accepts
  170. # scram-sha-256-stored verifiers, so this works on every supported distro.
  171. pg_ensure_hba_password_auth() {
  172. local pg_db="$1"
  173. local hba_file
  174. hba_file=$(sudo -u postgres psql -tAc 'SHOW hba_file' 2> /dev/null | tr -d '[:space:]')
  175. [[ -n "${hba_file}" && -f "${hba_file}" ]] || return 0
  176. grep -Eq "^host[[:space:]]+${pg_db}[[:space:]]" "${hba_file}" && return 0
  177. local tmp
  178. tmp=$(mktemp) || return 1
  179. {
  180. echo "# Added by 3x-ui: allow password logins for the panel database."
  181. echo "host ${pg_db} all 127.0.0.1/32 md5"
  182. echo "host ${pg_db} all ::1/128 md5"
  183. cat "${hba_file}"
  184. } > "${tmp}" || {
  185. rm -f "${tmp}"
  186. return 1
  187. }
  188. cat "${tmp}" > "${hba_file}" || {
  189. rm -f "${tmp}"
  190. return 1
  191. }
  192. rm -f "${tmp}"
  193. sudo -u postgres psql -tAc 'SELECT pg_reload_conf()' > /dev/null 2>&1 || true
  194. }
  195. # New installs get this PostgreSQL major from the official PGDG repository; distros or
  196. # CPU architectures PGDG does not build for fall back to the distribution's own package.
  197. PG_TARGET_MAJOR=18
  198. pg_has_debian_cluster() {
  199. command -v pg_lsclusters > /dev/null 2>&1 && [[ -n "$(pg_lsclusters -h 2> /dev/null)" ]]
  200. }
  201. # Installs postgresql-${PG_TARGET_MAJOR} from apt.postgresql.org. On failure it removes the
  202. # repository it added, so an unsupported release cannot break later `apt-get update` runs.
  203. pg_apt_install_pgdg_server() {
  204. local list added_lists=()
  205. for list in /etc/apt/sources.list.d/pgdg.list /etc/apt/sources.list.d/pgdg.sources; do
  206. [[ -e "${list}" ]] || added_lists+=("${list}")
  207. done
  208. if apt-get install -y -q postgresql-common ca-certificates gnupg >&2 \
  209. && /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >&2 \
  210. && apt-get install -y -q "postgresql-${PG_TARGET_MAJOR}" >&2; then
  211. return 0
  212. fi
  213. for list in "${added_lists[@]}"; do
  214. rm -f "${list}"
  215. done
  216. apt-get update >&2 || true
  217. echo -e "${yellow}PostgreSQL ${PG_TARGET_MAJOR} is not available for this system; installing the distribution's PostgreSQL instead.${plain}" >&2
  218. return 1
  219. }
  220. # Installs postgresql${PG_TARGET_MAJOR}-server from the PGDG yum repository (EL 8+ only); on
  221. # failure it undoes the repository and module changes it made. The caller runs initdb.
  222. pg_el_install_pgdg_server() {
  223. local elver
  224. elver=$(rpm -E %rhel 2> /dev/null)
  225. [[ "${elver}" =~ ^[0-9]+$ && "${elver}" -ge 8 ]] && command -v dnf > /dev/null 2>&1 || return 1
  226. [[ -f /var/lib/pgsql/data/PG_VERSION ]] && return 1
  227. local added_repo=false
  228. if ! rpm -q pgdg-redhat-repo > /dev/null 2>&1; then
  229. if dnf install -y -q "https://download.postgresql.org/pub/repos/yum/reporpms/EL-${elver}-$(uname -m)/pgdg-redhat-repo-latest.noarch.rpm" >&2; then
  230. added_repo=true
  231. dnf -qy module disable postgresql > /dev/null 2>&1 || true
  232. fi
  233. fi
  234. if rpm -q pgdg-redhat-repo > /dev/null 2>&1 \
  235. && dnf install -y -q "postgresql${PG_TARGET_MAJOR}-server" "postgresql${PG_TARGET_MAJOR}-contrib" >&2; then
  236. return 0
  237. fi
  238. if [[ "${added_repo}" == "true" ]]; then
  239. dnf -qy module reset postgresql > /dev/null 2>&1 || true
  240. dnf remove -y -q pgdg-redhat-repo >&2 || true
  241. fi
  242. echo -e "${yellow}PostgreSQL ${PG_TARGET_MAJOR} is not available for this system; installing the distribution's PostgreSQL instead.${plain}" >&2
  243. return 1
  244. }
  245. install_postgres_local() {
  246. local pg_user pg_pass
  247. pg_pass=$(gen_random_string 24)
  248. local pg_db="xui"
  249. local pg_host="127.0.0.1"
  250. local pg_port="5432"
  251. local pg_service="postgresql"
  252. case "${release}" in
  253. ubuntu | debian | armbian)
  254. apt-get update >&2 || return 1
  255. if pg_has_debian_cluster || ! pg_apt_install_pgdg_server; then
  256. apt-get install -y -q postgresql >&2 || return 1
  257. fi
  258. ;;
  259. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol | centos)
  260. if [[ "${release}" != "fedora" && "${release}" != "amzn" ]] && pg_el_install_pgdg_server; then
  261. pg_service="postgresql-${PG_TARGET_MAJOR}"
  262. [[ -f "/var/lib/pgsql/${PG_TARGET_MAJOR}/data/PG_VERSION" ]] \
  263. || "/usr/pgsql-${PG_TARGET_MAJOR}/bin/postgresql-${PG_TARGET_MAJOR}-setup" initdb >&2 || return 1
  264. else
  265. if [[ "${release}" == "centos" && "${VERSION_ID}" =~ ^7 ]]; then
  266. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  267. else
  268. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  269. fi
  270. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  271. fi
  272. ;;
  273. arch | manjaro | parch)
  274. pacman -Sy --noconfirm postgresql >&2 || return 1
  275. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  276. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  277. fi
  278. ;;
  279. opensuse-tumbleweed | opensuse-leap)
  280. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  281. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  282. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  283. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  284. fi
  285. ;;
  286. alpine)
  287. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  288. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  289. /etc/init.d/postgresql setup >&2 || return 1
  290. fi
  291. rc-update add postgresql default >&2 2> /dev/null || true
  292. rc-service postgresql start >&2 || return 1
  293. ;;
  294. *)
  295. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  296. return 1
  297. ;;
  298. esac
  299. if [[ "${release}" != "alpine" ]]; then
  300. systemctl enable --now "${pg_service}" >&2 || return 1
  301. fi
  302. # Wait briefly for the server to accept connections.
  303. local i
  304. for i in 1 2 3 4 5; do
  305. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  306. sleep 1
  307. done
  308. local existing_owner=""
  309. existing_owner=$(sudo -u postgres psql -tAc \
  310. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  311. | tr -d '[:space:]')
  312. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  313. pg_user="${existing_owner}"
  314. else
  315. pg_user=$(gen_random_string 8)
  316. fi
  317. # Idempotent role/db creation. Identifiers are double-quoted because a
  318. # random username may start with a digit, which Postgres rejects unquoted.
  319. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  320. | grep -q 1 \
  321. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  322. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  323. | grep -q 1 \
  324. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  325. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  326. pg_ensure_hba_password_auth "${pg_db}" \
  327. || echo -e "${yellow}Warning: could not update pg_hba.conf; PostgreSQL may reject the panel's TCP login (ident auth).${plain}" >&2
  328. local pg_pass_enc
  329. pg_pass_enc=$(printf '%s' "${pg_pass}" | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g')
  330. if [[ -n "${PG_CRED_FILE:-}" ]]; then
  331. local prev_umask
  332. prev_umask=$(umask)
  333. umask 077
  334. if ! cat > "${PG_CRED_FILE}" << EOF; then
  335. PG_USER=${pg_user}
  336. PG_PASS=${pg_pass}
  337. PG_HOST=${pg_host}
  338. PG_PORT=${pg_port}
  339. PG_DB=${pg_db}
  340. EOF
  341. umask "${prev_umask}"
  342. echo -e "${red}Failed to write PostgreSQL credentials to ${PG_CRED_FILE}${plain}" >&2
  343. return 1
  344. fi
  345. umask "${prev_umask}"
  346. fi
  347. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  348. return 0
  349. }
  350. ensure_pg_client() {
  351. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  352. return 0
  353. fi
  354. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore) for in-panel backup...${plain}" >&2
  355. case "${release}" in
  356. ubuntu | debian | armbian)
  357. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  358. ;;
  359. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  360. dnf install -y -q postgresql >&2 || return 1
  361. ;;
  362. centos)
  363. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  364. yum install -y postgresql >&2 || return 1
  365. else
  366. dnf install -y -q postgresql >&2 || return 1
  367. fi
  368. ;;
  369. arch | manjaro | parch)
  370. pacman -Sy --noconfirm postgresql >&2 || return 1
  371. ;;
  372. opensuse-tumbleweed | opensuse-leap)
  373. zypper -q install -y postgresql >&2 || return 1
  374. ;;
  375. alpine)
  376. apk add --no-cache postgresql-client >&2 || return 1
  377. ;;
  378. *)
  379. return 1
  380. ;;
  381. esac
  382. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  383. }
  384. install_acme() {
  385. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  386. cd ~ || return 1
  387. curl -s https://get.acme.sh | sh > /dev/null 2>&1
  388. if [ $? -ne 0 ]; then
  389. echo -e "${red}Failed to install acme.sh${plain}"
  390. return 1
  391. else
  392. echo -e "${green}acme.sh installed successfully${plain}"
  393. fi
  394. return 0
  395. }
  396. setup_ssl_certificate() {
  397. local domain="$1"
  398. local server_ip="$2"
  399. local existing_port="$3"
  400. local existing_webBasePath="$4"
  401. echo -e "${green}Setting up SSL certificate...${plain}"
  402. # Check if acme.sh is installed
  403. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  404. install_acme
  405. if [ $? -ne 0 ]; then
  406. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  407. return 1
  408. fi
  409. fi
  410. # Create certificate directory
  411. local certPath="/root/cert/${domain}"
  412. mkdir -p "$certPath"
  413. # Issue certificate
  414. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  415. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  416. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  417. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport 80 --force
  418. if [ $? -ne 0 ]; then
  419. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  420. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  421. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc 2> /dev/null
  422. rm -rf "$certPath" 2> /dev/null
  423. return 1
  424. fi
  425. # Install certificate
  426. ~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  427. --key-file /root/cert/${domain}/privkey.pem \
  428. --fullchain-file /root/cert/${domain}/fullchain.pem \
  429. --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
  430. if [ $? -ne 0 ]; then
  431. echo -e "${yellow}Failed to install certificate${plain}"
  432. return 1
  433. fi
  434. # Enable auto-renew
  435. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  436. # Secure permissions: private key readable only by owner
  437. chmod 600 $certPath/privkey.pem 2> /dev/null
  438. chmod 644 $certPath/fullchain.pem 2> /dev/null
  439. # Set certificate for panel
  440. local webCertFile="/root/cert/${domain}/fullchain.pem"
  441. local webKeyFile="/root/cert/${domain}/privkey.pem"
  442. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  443. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" > /dev/null 2>&1
  444. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  445. return 0
  446. else
  447. echo -e "${yellow}Certificate files not found${plain}"
  448. return 1
  449. fi
  450. }
  451. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  452. # Requires acme.sh and port 80 open for HTTP-01 challenge
  453. setup_ip_certificate() {
  454. local ipv4="$1"
  455. local ipv6="$2" # optional
  456. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  457. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  458. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  459. # Check for acme.sh
  460. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  461. install_acme
  462. if [ $? -ne 0 ]; then
  463. echo -e "${red}Failed to install acme.sh${plain}"
  464. return 1
  465. fi
  466. fi
  467. # Validate IP address
  468. if [[ -z "$ipv4" ]]; then
  469. echo -e "${red}IPv4 address is required${plain}"
  470. return 1
  471. fi
  472. if ! is_ipv4 "$ipv4"; then
  473. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  474. return 1
  475. fi
  476. # Create certificate directory
  477. local certDir="/root/cert/ip"
  478. mkdir -p "$certDir"
  479. # Build domain arguments
  480. local domain_args="-d ${ipv4}"
  481. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  482. domain_args="${domain_args} -d ${ipv6}"
  483. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  484. fi
  485. # Set reload command for auto-renewal (add || true so it doesn't fail during first install)
  486. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  487. # Choose port for HTTP-01 listener (default 80, prompt override)
  488. local WebPort=""
  489. prompt_or_default WebPort "Port to use for ACME HTTP-01 listener (default 80): " "80" XUI_ACME_HTTP_PORT
  490. WebPort="${WebPort:-80}"
  491. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  492. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  493. WebPort=80
  494. fi
  495. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  496. if [[ "${WebPort}" -ne 80 ]]; then
  497. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  498. fi
  499. # Ensure chosen port is available
  500. while true; do
  501. if is_port_in_use "${WebPort}"; then
  502. echo -e "${yellow}Port ${WebPort} is in use.${plain}"
  503. local alt_port=""
  504. if [[ "$NONINTERACTIVE" == "1" ]]; then
  505. echo -e "${red}Port ${WebPort} is busy; cannot proceed in non-interactive mode.${plain}"
  506. return 1
  507. fi
  508. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  509. alt_port="${alt_port// /}"
  510. if [[ -z "${alt_port}" ]]; then
  511. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  512. return 1
  513. fi
  514. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  515. echo -e "${red}Invalid port provided.${plain}"
  516. return 1
  517. fi
  518. WebPort="${alt_port}"
  519. continue
  520. else
  521. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  522. break
  523. fi
  524. done
  525. # Issue certificate with shortlived profile
  526. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  527. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  528. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  529. ~/.acme.sh/acme.sh --issue \
  530. ${domain_args} \
  531. --standalone \
  532. --server letsencrypt \
  533. --certificate-profile shortlived \
  534. --days 6 \
  535. --httpport ${WebPort} \
  536. --force
  537. if [ $? -ne 0 ]; then
  538. echo -e "${red}Failed to issue IP certificate${plain}"
  539. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  540. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  541. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  542. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  543. rm -rf ${certDir} 2> /dev/null
  544. return 1
  545. fi
  546. echo -e "${green}Certificate issued successfully, installing...${plain}"
  547. # Install certificate
  548. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  549. # but the cert files are still installed. We check for files instead of exit code.
  550. ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
  551. --key-file "${certDir}/privkey.pem" \
  552. --fullchain-file "${certDir}/fullchain.pem" \
  553. --reloadcmd "${reloadCmd}" 2>&1 || true
  554. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  555. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  556. echo -e "${red}Certificate files not found after installation${plain}"
  557. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  558. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  559. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  560. rm -rf ${certDir} 2> /dev/null
  561. return 1
  562. fi
  563. echo -e "${green}Certificate files installed successfully${plain}"
  564. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  565. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  566. # Secure permissions: private key readable only by owner
  567. chmod 600 ${certDir}/privkey.pem 2> /dev/null
  568. chmod 644 ${certDir}/fullchain.pem 2> /dev/null
  569. # Configure panel to use the certificate
  570. echo -e "${green}Setting certificate paths for the panel...${plain}"
  571. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  572. if [ $? -ne 0 ]; then
  573. echo -e "${yellow}Warning: Could not set certificate paths automatically${plain}"
  574. echo -e "${yellow}Certificate files are at:${plain}"
  575. echo -e " Cert: ${certDir}/fullchain.pem"
  576. echo -e " Key: ${certDir}/privkey.pem"
  577. else
  578. echo -e "${green}Certificate paths configured successfully${plain}"
  579. fi
  580. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  581. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  582. echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}"
  583. return 0
  584. }
  585. # Comprehensive manual SSL certificate issuance via acme.sh
  586. ssl_cert_issue() {
  587. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  588. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  589. # check for acme.sh first
  590. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  591. echo "acme.sh could not be found. Installing now..."
  592. cd ~ || return 1
  593. curl -s https://get.acme.sh | sh
  594. if [ $? -ne 0 ]; then
  595. echo -e "${red}Failed to install acme.sh${plain}"
  596. return 1
  597. else
  598. echo -e "${green}acme.sh installed successfully${plain}"
  599. fi
  600. fi
  601. # get the domain here, and we need to verify it
  602. local domain=""
  603. if [[ "$NONINTERACTIVE" == "1" ]]; then
  604. domain="${XUI_DOMAIN// /}"
  605. if [[ -z "$domain" ]] || ! is_domain "$domain"; then
  606. echo -e "${red}XUI_SSL_MODE=domain requires a valid XUI_DOMAIN (got: '${XUI_DOMAIN:-}').${plain}"
  607. return 1
  608. fi
  609. else
  610. while true; do
  611. read -rp "Please enter your domain name: " domain
  612. domain="${domain// /}" # Trim whitespace
  613. if [[ -z "$domain" ]]; then
  614. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  615. continue
  616. fi
  617. if ! is_domain "$domain"; then
  618. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  619. continue
  620. fi
  621. break
  622. done
  623. fi
  624. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  625. SSL_ISSUED_DOMAIN="${domain}"
  626. # detect existing certificate and reuse it only if its files are actually
  627. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  628. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  629. # with no usable cert files, which must not be reused (it produces a 0-byte
  630. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  631. local cert_exists=0
  632. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  633. local acmeCertDir=""
  634. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  635. acmeCertDir=~/.acme.sh/${domain}_ecc
  636. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  637. acmeCertDir=~/.acme.sh/${domain}
  638. fi
  639. if [[ -n "${acmeCertDir}" ]]; then
  640. cert_exists=1
  641. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  642. echo -e "${yellow}Existing certificate found for ${domain}, will reuse it.${plain}"
  643. [[ -n "${certInfo}" ]] && echo "$certInfo"
  644. else
  645. echo -e "${yellow}Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing.${plain}"
  646. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  647. fi
  648. fi
  649. if [[ ${cert_exists} -eq 0 ]]; then
  650. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  651. fi
  652. # create a directory for the certificate
  653. certPath="/root/cert/${domain}"
  654. if [ ! -d "$certPath" ]; then
  655. mkdir -p "$certPath"
  656. else
  657. rm -rf "$certPath"
  658. mkdir -p "$certPath"
  659. fi
  660. # get the port number for the standalone server
  661. local WebPort=80
  662. prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT
  663. if [[ -z ${WebPort} ]]; then
  664. WebPort=80
  665. elif [[ ! ${WebPort} =~ ^[1-9][0-9]*$ || ${WebPort} -gt 65535 ]]; then
  666. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  667. WebPort=80
  668. fi
  669. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  670. # Stop panel temporarily
  671. echo -e "${yellow}Stopping panel temporarily...${plain}"
  672. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  673. if [[ ${cert_exists} -eq 0 ]]; then
  674. # issue the certificate
  675. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  676. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  677. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  678. if [ $? -ne 0 ]; then
  679. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  680. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  681. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  682. return 1
  683. else
  684. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  685. fi
  686. else
  687. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  688. fi
  689. # Setup reload command
  690. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  691. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  692. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  693. if [[ "$NONINTERACTIVE" == "1" ]]; then
  694. setReloadcmd="n"
  695. else
  696. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  697. fi
  698. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  699. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  700. echo -e "${green}\t2.${plain} Input your own command"
  701. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  702. read -rp "Choose an option: " choice
  703. case "$choice" in
  704. 1)
  705. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  706. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  707. ;;
  708. 2)
  709. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  710. read -rp "Please enter your custom reloadcmd: " reloadCmd
  711. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  712. ;;
  713. *)
  714. echo -e "${green}Keeping default reloadcmd${plain}"
  715. ;;
  716. esac
  717. fi
  718. # install the certificate
  719. local installOutput=""
  720. installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  721. --key-file /root/cert/${domain}/privkey.pem \
  722. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  723. local installRc=$?
  724. echo "${installOutput}"
  725. local installWroteFiles=0
  726. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  727. installWroteFiles=1
  728. fi
  729. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  730. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  731. else
  732. echo -e "${red}Installing certificate failed, exiting.${plain}"
  733. if [[ ${cert_exists} -eq 0 ]]; then
  734. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  735. fi
  736. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  737. return 1
  738. fi
  739. # enable auto-renew
  740. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  741. if [ $? -ne 0 ]; then
  742. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  743. ls -lah /root/cert/${domain}/
  744. # Secure permissions: private key readable only by owner
  745. chmod 600 $certPath/privkey.pem 2> /dev/null
  746. chmod 644 $certPath/fullchain.pem 2> /dev/null
  747. else
  748. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  749. ls -lah /root/cert/${domain}/
  750. # Secure permissions: private key readable only by owner
  751. chmod 600 $certPath/privkey.pem 2> /dev/null
  752. chmod 644 $certPath/fullchain.pem 2> /dev/null
  753. fi
  754. # start panel
  755. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  756. # Prompt user to set panel paths after successful certificate installation
  757. if [[ "$NONINTERACTIVE" == "1" ]]; then
  758. setPanel="y"
  759. else
  760. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  761. fi
  762. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  763. local webCertFile="/root/cert/${domain}/fullchain.pem"
  764. local webKeyFile="/root/cert/${domain}/privkey.pem"
  765. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  766. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  767. echo -e "${green}Certificate paths set for the panel${plain}"
  768. echo -e "${green}Certificate File: $webCertFile${plain}"
  769. echo -e "${green}Private Key File: $webKeyFile${plain}"
  770. echo ""
  771. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  772. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  773. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  774. else
  775. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  776. fi
  777. else
  778. echo -e "${yellow}Skipping panel path setting.${plain}"
  779. fi
  780. return 0
  781. }
  782. # Reusable interactive SSL setup (domain or IP)
  783. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  784. prompt_and_setup_ssl() {
  785. local panel_port="$1"
  786. local web_base_path="$2"
  787. local server_ip="$3"
  788. local ssl_choice=""
  789. SSL_SCHEME="https"
  790. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  791. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  792. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  793. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  794. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  795. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  796. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  797. if [[ "$NONINTERACTIVE" == "1" ]]; then
  798. case "${XUI_SSL_MODE:-none}" in
  799. domain) ssl_choice="1" ;;
  800. ip) ssl_choice="2" ;;
  801. none | "") ssl_choice="4" ;;
  802. *)
  803. echo -e "${yellow}Unknown XUI_SSL_MODE='${XUI_SSL_MODE}', defaulting to none (HTTP).${plain}"
  804. ssl_choice="4"
  805. ;;
  806. esac
  807. else
  808. read -rp "Choose an option (default 2 for IP): " ssl_choice
  809. ssl_choice="${ssl_choice// /}" # Trim whitespace
  810. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  811. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  812. ssl_choice="2"
  813. fi
  814. fi
  815. case "$ssl_choice" in
  816. 1)
  817. # User chose Let's Encrypt domain option
  818. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  819. if ssl_cert_issue; then
  820. local cert_domain="${SSL_ISSUED_DOMAIN}"
  821. if [[ -z "${cert_domain}" ]]; then
  822. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  823. fi
  824. if [[ -n "${cert_domain}" ]]; then
  825. SSL_HOST="${cert_domain}"
  826. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  827. else
  828. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  829. SSL_HOST="${server_ip}"
  830. fi
  831. else
  832. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  833. SSL_HOST="${server_ip}"
  834. fi
  835. ;;
  836. 2)
  837. # User chose Let's Encrypt IP certificate option
  838. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  839. # Confirm the auto-detected IP before issuing for it: with asymmetric
  840. # routing / multi-WAN the echo services can return a transit address.
  841. if [[ "$NONINTERACTIVE" != "1" ]]; then
  842. local ip_confirm=""
  843. read -rp "Is ${server_ip} the correct incoming public IPv4 address for this server? [Default y]: " ip_confirm
  844. if [[ -n "$ip_confirm" && "$ip_confirm" != "y" && "$ip_confirm" != "Y" ]]; then
  845. server_ip=""
  846. while [[ -z "$server_ip" ]]; do
  847. read -rp "Please enter your server's public IPv4 address: " server_ip
  848. server_ip="${server_ip// /}"
  849. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  850. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  851. server_ip=""
  852. fi
  853. done
  854. fi
  855. fi
  856. # Ask for optional IPv6
  857. local ipv6_addr=""
  858. prompt_or_default ipv6_addr "Do you have an IPv6 address to include? (leave empty to skip): " "" XUI_SSL_IPV6
  859. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  860. # Stop panel if running (port 80 needed)
  861. if [[ $release == "alpine" ]]; then
  862. rc-service x-ui stop > /dev/null 2>&1
  863. else
  864. systemctl stop x-ui > /dev/null 2>&1
  865. fi
  866. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  867. if [ $? -eq 0 ]; then
  868. SSL_HOST="${server_ip}"
  869. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  870. else
  871. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  872. SSL_HOST="${server_ip}"
  873. fi
  874. ;;
  875. 3)
  876. # User chose Custom Paths (User Provided) option
  877. echo -e "${green}Using custom existing certificate...${plain}"
  878. local custom_cert=""
  879. local custom_key=""
  880. local custom_domain=""
  881. # 3.1 Request Domain to compose Panel URL later
  882. read -rp "Please enter domain name certificate issued for: " custom_domain
  883. custom_domain="${custom_domain// /}" # Remove spaces
  884. # 3.2 Loop for Certificate Path
  885. while true; do
  886. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  887. # Strip quotes if present
  888. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  889. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  890. break
  891. elif [[ ! -f "$custom_cert" ]]; then
  892. echo -e "${red}Error: File does not exist! Try again.${plain}"
  893. elif [[ ! -r "$custom_cert" ]]; then
  894. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  895. else
  896. echo -e "${red}Error: File is empty!${plain}"
  897. fi
  898. done
  899. # 3.3 Loop for Private Key Path
  900. while true; do
  901. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  902. # Strip quotes if present
  903. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  904. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  905. break
  906. elif [[ ! -f "$custom_key" ]]; then
  907. echo -e "${red}Error: File does not exist! Try again.${plain}"
  908. elif [[ ! -r "$custom_key" ]]; then
  909. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  910. else
  911. echo -e "${red}Error: File is empty!${plain}"
  912. fi
  913. done
  914. # 3.4 Apply Settings via x-ui binary
  915. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  916. # Set SSL_HOST for composing Panel URL
  917. if [[ -n "$custom_domain" ]]; then
  918. SSL_HOST="$custom_domain"
  919. else
  920. SSL_HOST="${server_ip}"
  921. fi
  922. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  923. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  924. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  925. ;;
  926. 4)
  927. echo ""
  928. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  929. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  930. echo -e "${yellow}Only safe when:${plain}"
  931. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  932. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  933. echo ""
  934. SSL_SCHEME="http"
  935. SSL_HOST="${server_ip}"
  936. local bind_local=""
  937. if [[ "$NONINTERACTIVE" == "1" ]]; then
  938. # Cloud images must stay reachable on their public interface.
  939. bind_local="n"
  940. else
  941. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  942. fi
  943. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  944. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  945. SSL_HOST="127.0.0.1"
  946. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  947. echo ""
  948. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  949. echo -e " Standard SSH command:"
  950. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  951. echo -e " If using an SSH key:"
  952. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  953. echo -e " Then open in your browser:"
  954. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  955. echo ""
  956. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  957. else
  958. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  959. fi
  960. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  961. echo -e "${green}✓ SSL setup skipped.${plain}"
  962. ;;
  963. *)
  964. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  965. SSL_HOST="${server_ip}"
  966. ;;
  967. esac
  968. }
  969. config_after_install() {
  970. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  971. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  972. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  973. # Properly detect empty cert by checking if cert: line exists and has content after it
  974. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  975. local URL_lists=(
  976. "https://api4.ipify.org"
  977. "https://ipv4.icanhazip.com"
  978. "https://v4.api.ipinfo.io/ip"
  979. "https://ipv4.myexternalip.com/raw"
  980. "https://4.ident.me"
  981. "https://check-host.net/ip"
  982. )
  983. local server_ip=""
  984. for ip_address in "${URL_lists[@]}"; do
  985. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  986. local http_code=$(echo "$response" | tail -n1)
  987. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  988. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  989. server_ip="${ip_result}"
  990. break
  991. fi
  992. done
  993. if [[ -z "$server_ip" ]]; then
  994. if [[ "$NONINTERACTIVE" == "1" ]]; then
  995. # Panel binds 0.0.0.0 regardless; the IP is only used to compose the
  996. # displayed access URL. Fall back to XUI_SERVER_IP or leave blank.
  997. server_ip="${XUI_SERVER_IP:-}"
  998. else
  999. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  1000. while [[ -z "$server_ip" ]]; do
  1001. read -rp "Please enter your server's public IPv4 address: " server_ip
  1002. server_ip="${server_ip// /}"
  1003. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1004. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  1005. server_ip=""
  1006. fi
  1007. done
  1008. fi
  1009. fi
  1010. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  1011. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  1012. local config_webBasePath="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
  1013. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  1014. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  1015. local config_port=""
  1016. local db_label="SQLite (/etc/x-ui/x-ui.db)"
  1017. echo ""
  1018. echo -e "${green}═══════════════════════════════════════════${plain}"
  1019. echo -e "${green} Database Selection ${plain}"
  1020. echo -e "${green}═══════════════════════════════════════════${plain}"
  1021. echo -e " 1) SQLite (default — recommended for < 500 clients)"
  1022. echo -e " 2) PostgreSQL (recommended for high client counts / many nodes)"
  1023. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1024. if [[ "${XUI_DB_TYPE:-sqlite}" == "postgres" ]]; then
  1025. db_choice="2"
  1026. else
  1027. db_choice="1"
  1028. fi
  1029. else
  1030. read -rp "Choose [1]: " db_choice
  1031. db_choice="${db_choice:-1}"
  1032. fi
  1033. if [[ "$db_choice" == "2" ]]; then
  1034. local xui_env_file
  1035. case "${release}" in
  1036. ubuntu | debian | armbian)
  1037. xui_env_file="/etc/default/x-ui"
  1038. ;;
  1039. arch | manjaro | parch | alpine)
  1040. xui_env_file="/etc/conf.d/x-ui"
  1041. ;;
  1042. *)
  1043. xui_env_file="/etc/sysconfig/x-ui"
  1044. ;;
  1045. esac
  1046. local xui_dsn=""
  1047. local pg_mode=""
  1048. local pg_local_installed=0
  1049. while [[ -z "$xui_dsn" ]]; do
  1050. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1051. if [[ -n "${XUI_DB_DSN:-}" ]]; then
  1052. xui_dsn="${XUI_DB_DSN}"
  1053. db_label="PostgreSQL (external)"
  1054. break
  1055. fi
  1056. echo -e "${yellow}Installing PostgreSQL locally (non-interactive)...${plain}"
  1057. local pg_cred_file
  1058. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  1059. if [[ -n "${pg_cred_file}" ]] && xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  1060. pg_local_installed=1
  1061. if [[ -r "${pg_cred_file}" ]]; then
  1062. # shellcheck disable=SC1090
  1063. source "${pg_cred_file}"
  1064. fi
  1065. rm -f "${pg_cred_file}"
  1066. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  1067. break
  1068. fi
  1069. rm -f "${pg_cred_file}"
  1070. echo -e "${red}PostgreSQL installation failed in non-interactive mode; aborting.${plain}"
  1071. echo -e "${yellow}Set XUI_DB_DSN to use an existing server, or XUI_DB_TYPE=sqlite.${plain}"
  1072. exit 1
  1073. fi
  1074. echo ""
  1075. echo -e " 1) Install PostgreSQL locally and create a dedicated user/db (recommended)"
  1076. echo -e " 2) Use an existing PostgreSQL server (enter DSN)"
  1077. read -rp "Choose [1]: " pg_mode
  1078. pg_mode="${pg_mode:-1}"
  1079. if [[ "$pg_mode" == "2" ]]; then
  1080. while [[ -z "$xui_dsn" ]]; do
  1081. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " xui_dsn
  1082. xui_dsn="${xui_dsn// /}"
  1083. done
  1084. db_label="PostgreSQL (external)"
  1085. else
  1086. echo -e "${yellow}Installing PostgreSQL — this may take a moment...${plain}"
  1087. local pg_cred_file
  1088. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  1089. if [[ -z "${pg_cred_file}" ]]; then
  1090. echo -e "${red}Failed to create temporary credentials file.${plain}"
  1091. xui_dsn=""
  1092. continue
  1093. fi
  1094. if xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  1095. pg_local_installed=1
  1096. if [[ -r "${pg_cred_file}" ]]; then
  1097. # shellcheck disable=SC1090
  1098. source "${pg_cred_file}"
  1099. fi
  1100. rm -f "${pg_cred_file}"
  1101. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  1102. else
  1103. rm -f "${pg_cred_file}"
  1104. echo ""
  1105. echo -e "${red}PostgreSQL installation failed.${plain}"
  1106. echo -e " 1) Retry local install"
  1107. echo -e " 2) Enter an external DSN instead"
  1108. echo -e " 3) Abort install"
  1109. echo -e " 4) Fall back to SQLite"
  1110. read -rp "Choose [1]: " pg_fail
  1111. pg_fail="${pg_fail:-1}"
  1112. case "$pg_fail" in
  1113. 2) pg_mode="2" ;;
  1114. 3)
  1115. echo -e "${red}Install aborted.${plain}"
  1116. exit 1
  1117. ;;
  1118. 4)
  1119. db_choice="1"
  1120. xui_dsn=""
  1121. break
  1122. ;;
  1123. *) xui_dsn="" ;;
  1124. esac
  1125. fi
  1126. fi
  1127. done
  1128. if [[ -n "$xui_dsn" ]]; then
  1129. install -d -m 755 "$(dirname "$xui_env_file")"
  1130. umask 077
  1131. cat > "$xui_env_file" << EOF
  1132. XUI_DB_TYPE=postgres
  1133. XUI_DB_DSN=${xui_dsn}
  1134. EOF
  1135. chmod 600 "$xui_env_file"
  1136. umask 022
  1137. export XUI_DB_TYPE=postgres
  1138. export XUI_DB_DSN="${xui_dsn}"
  1139. ensure_pg_client || echo -e "${yellow}⚠ Could not install pg_dump/pg_restore. In-panel database backup/restore will be unavailable until you install the postgresql-client package.${plain}"
  1140. fi
  1141. fi
  1142. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1143. if [[ -n "${XUI_PANEL_PORT:-}" ]]; then
  1144. config_port="${XUI_PANEL_PORT}"
  1145. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1146. else
  1147. config_port=$(shuf -i 1024-62000 -n 1)
  1148. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1149. fi
  1150. else
  1151. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  1152. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  1153. read -rp "Please set up the panel port: " config_port
  1154. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1155. else
  1156. config_port=$(shuf -i 1024-62000 -n 1)
  1157. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1158. fi
  1159. fi
  1160. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  1161. echo ""
  1162. echo -e "${green}═══════════════════════════════════════════${plain}"
  1163. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1164. echo -e "${green}═══════════════════════════════════════════${plain}"
  1165. echo -e "${yellow}SSL is strongly recommended. Skip only if a reverse proxy${plain}"
  1166. echo -e "${yellow}or SSH tunnel handles TLS for you.${plain}"
  1167. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1168. echo ""
  1169. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  1170. # Retrieve the API token for display
  1171. local config_apiToken=$(${xui_folder}/x-ui setting -getApiToken | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1172. # Display final credentials and access information
  1173. echo ""
  1174. echo -e "${green}═══════════════════════════════════════════${plain}"
  1175. echo -e "${green} Panel Installation Complete! ${plain}"
  1176. echo -e "${green}═══════════════════════════════════════════${plain}"
  1177. echo -e "${green}Username: ${config_username}${plain}"
  1178. echo -e "${green}Password: ${config_password}${plain}"
  1179. echo -e "${green}Port: ${config_port}${plain}"
  1180. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  1181. echo -e "${green}Database: ${db_label}${plain}"
  1182. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  1183. echo -e "${green}API Token: ${config_apiToken}${plain}"
  1184. echo -e "${green}═══════════════════════════════════════════${plain}"
  1185. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  1186. if [[ "$SSL_SCHEME" == "https" ]]; then
  1187. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  1188. else
  1189. echo -e "${yellow}⚠ SSL Certificate: Skipped — panel is HTTP-only. Use a reverse proxy or SSH tunnel.${plain}"
  1190. fi
  1191. if [[ "$db_choice" == "2" ]]; then
  1192. echo ""
  1193. echo -e "${green}PostgreSQL backup & restore is built into the panel:${plain}"
  1194. echo -e " ${blue}${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain} → Backup & Restore"
  1195. echo -e "${yellow} Back Up downloads a pg_dump .dump file; Restore reloads it via pg_restore.${plain}"
  1196. fi
  1197. if [[ "$db_choice" == "2" && "$pg_local_installed" == "1" ]]; then
  1198. echo ""
  1199. echo -e "${green}═══════════════════════════════════════════${plain}"
  1200. echo -e "${green} PostgreSQL Credentials ${plain}"
  1201. echo -e "${green}═══════════════════════════════════════════${plain}"
  1202. echo -e "${green}DB Name: ${PG_DB}${plain}"
  1203. echo -e "${green}Username: ${PG_USER}${plain}"
  1204. echo -e "${green}Password: ${PG_PASS}${plain}"
  1205. echo -e "${green}Host: ${PG_HOST}${plain}"
  1206. echo -e "${green}Port: ${PG_PORT}${plain}"
  1207. echo -e "${green}DSN: ${xui_dsn}${plain}"
  1208. echo -e "${green}Env file: ${xui_env_file}${plain}"
  1209. echo -e "${green}-------------------------------------------${plain}"
  1210. echo -e "${green}Connect from this server:${plain}"
  1211. echo -e " ${blue}sudo -u postgres psql -d ${PG_DB}${plain} (as the postgres superuser)"
  1212. echo -e " ${blue}PGPASSWORD='${PG_PASS}' psql -h ${PG_HOST} -p ${PG_PORT} -U ${PG_USER} -d ${PG_DB}${plain}"
  1213. echo -e "${green}═══════════════════════════════════════════${plain}"
  1214. echo -e "${yellow}⚠ The panel reads these credentials from ${xui_env_file}.${plain}"
  1215. echo -e "${yellow}⚠ Save the password — it is not stored anywhere else in plain text.${plain}"
  1216. unset PG_USER PG_PASS PG_HOST PG_PORT PG_DB
  1217. fi
  1218. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1219. : "${SSL_SCHEME:=https}"
  1220. : "${SSL_HOST:=${server_ip}}"
  1221. local db_type_out="sqlite"
  1222. [[ "$db_choice" == "2" ]] && db_type_out="postgres"
  1223. write_install_result "${config_username}" "${config_password}" "${config_port}" \
  1224. "${config_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${db_type_out}"
  1225. else
  1226. local config_webBasePath=$(gen_random_string 18)
  1227. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  1228. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  1229. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  1230. # If the panel is already installed but no certificate is configured, prompt for SSL now
  1231. if [[ -z "${existing_cert}" ]]; then
  1232. echo ""
  1233. echo -e "${green}═══════════════════════════════════════════${plain}"
  1234. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1235. echo -e "${green}═══════════════════════════════════════════${plain}"
  1236. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1237. echo ""
  1238. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  1239. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  1240. else
  1241. # If a cert already exists, just show the access URL
  1242. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  1243. fi
  1244. fi
  1245. else
  1246. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  1247. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  1248. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  1249. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  1250. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  1251. echo -e "Generated new random login credentials:"
  1252. echo -e "###############################################"
  1253. echo -e "${green}Username: ${config_username}${plain}"
  1254. echo -e "${green}Password: ${config_password}${plain}"
  1255. echo -e "###############################################"
  1256. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1257. local config_apiToken
  1258. config_apiToken=$(${xui_folder}/x-ui setting -getApiToken | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1259. : "${SSL_SCHEME:=https}"
  1260. : "${SSL_HOST:=${server_ip}}"
  1261. write_install_result "${config_username}" "${config_password}" "${existing_port}" \
  1262. "${existing_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${XUI_DB_TYPE:-sqlite}"
  1263. else
  1264. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  1265. fi
  1266. # Existing install: if no cert configured, prompt user for SSL setup
  1267. # Properly detect empty cert by checking if cert: line exists and has content after it
  1268. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1269. if [[ -z "$existing_cert" ]]; then
  1270. echo ""
  1271. echo -e "${green}═══════════════════════════════════════════${plain}"
  1272. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1273. echo -e "${green}═══════════════════════════════════════════${plain}"
  1274. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1275. echo ""
  1276. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  1277. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  1278. else
  1279. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  1280. fi
  1281. fi
  1282. ${xui_folder}/x-ui migrate
  1283. }
  1284. # setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
  1285. # by invoking the freshly installed x-ui CLI. IP Limit is load-bearing on
  1286. # fail2ban (without it the panel disables the limitIp field and zeroes existing
  1287. # limits), so a fresh install should make it work out of the box, just like the
  1288. # Docker image already does. Non-fatal by design: a fail2ban failure must never
  1289. # abort the panel install.
  1290. setup_fail2ban() {
  1291. if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
  1292. echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
  1293. return 0
  1294. fi
  1295. if [[ ! -x /usr/bin/x-ui ]]; then
  1296. echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
  1297. return 0
  1298. fi
  1299. # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
  1300. # usage banner, which would read as success here.
  1301. if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
  1302. echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
  1303. return 0
  1304. fi
  1305. echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
  1306. if /usr/bin/x-ui setup-fail2ban; then
  1307. echo -e "${green}Fail2ban setup complete.${plain}"
  1308. else
  1309. echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}"
  1310. fi
  1311. return 0
  1312. }
  1313. # Major version of the local systemd, 0 when it cannot be determined. The
  1314. # SystemCallFilter=@system-service group only exists from systemd 239 on (other
  1315. # @-named groups exist since 231); on older versions an unknown group is not
  1316. # ignored safely, the filter stays in force and leaves a whitelist the panel
  1317. # cannot run under.
  1318. _xui_systemd_major_version() {
  1319. local version=""
  1320. if command -v systemctl > /dev/null 2>&1; then
  1321. version="$(systemctl --version 2>/dev/null | awk 'NR == 1 {print $2}')"
  1322. fi
  1323. if [[ ! "$version" =~ ^[0-9]+$ ]]; then
  1324. echo 0
  1325. return 0
  1326. fi
  1327. echo "$version"
  1328. }
  1329. # The shipped units list hardening that older systemd does not know: the
  1330. # directive is logged and ignored at load time rather than rejected, so the
  1331. # panel still starts, only without that protection. Each entry is the systemd
  1332. # release that introduced the directive (systemd.exec(5)); everything else in
  1333. # the unit predates the oldest systemd install.sh supports (CentOS 7 has 219).
  1334. # SystemCallFilter= is listed because the drop-in only writes it from 239 on.
  1335. _xui_warn_unsupported_hardening() {
  1336. local version entry missing=""
  1337. version="$(_xui_systemd_major_version)"
  1338. [[ "$version" -gt 0 ]] || return 0
  1339. for entry in RestrictRealtime:231 ReadWritePaths:231 ProtectKernelTunables:232 \
  1340. ProtectKernelModules:232 RestrictNamespaces:233 LockPersonality:235 \
  1341. SystemCallFilter:239 ProtectHostname:242 RestrictSUIDSGID:242 \
  1342. ProtectKernelLogs:244 ProtectClock:245; do
  1343. if [[ "$version" -lt "${entry##*:}" ]]; then
  1344. missing="${missing:+$missing, }${entry%%:*} (${entry##*:})"
  1345. fi
  1346. done
  1347. [[ -n "$missing" ]] || return 0
  1348. echo -e "${yellow}Note: systemd ${version} ignores part of the hardening in x-ui.service; the panel still starts.${plain}"
  1349. echo " Not applied, needs a newer systemd: ${missing}."
  1350. if [[ "$version" -lt 231 ]]; then
  1351. echo " The panel's folders stay writable through ReadWriteDirectories=, the alias this script installs."
  1352. fi
  1353. echo " The rest of the hardening is in force. Upgrade systemd to apply the above."
  1354. return 0
  1355. }
  1356. # ProtectSystem=full makes /usr, /boot, /efi and /etc read-only. ProtectSystem=
  1357. # strict would make the whole hierarchy read-only (only the kernel API
  1358. # filesystems stay as they are), and that would break the panel's own use of
  1359. # /tmp. The panel's stores are configurable (XUI_DB_FOLDER, XUI_LOG_FOLDER,
  1360. # XUI_BIN_FOLDER), and XUI_MAIN_FOLDER is the folder install.sh/update.sh place
  1361. # the files in -- the unit's WorkingDirectory on a stock install, and what a
  1362. # relative XUI_BIN_FOLDER is resolved against. So a hard-coded list in the unit
  1363. # either misses a relocated store -- the panel then cannot write its own SQLite
  1364. # database and sits in a Restart=on-failure loop -- or forces the operator to
  1365. # edit a file that every install/update overwrites from the release tarball.
  1366. # install.sh and update.sh therefore regenerate the drop-in from the folders
  1367. # actually in use, and the unit's own ReadWritePaths only carry the
  1368. # plain-install defaults. A relocated store means re-running install or update:
  1369. # the drop-in is only written here.
  1370. _xui_service_write_paths_dropin() {
  1371. # $1 is the env file to resolve the XUI_* folders from; callers pass nothing
  1372. # and get the OS-specific path the unit itself uses.
  1373. local env_file="${1:-}"
  1374. local dropin_dir dropin temp_file
  1375. local db_folder log_folder bin_folder main_folder
  1376. local path line="" whitespace_paths="" seen_paths="" escaped_path
  1377. if [[ -z "$env_file" ]]; then
  1378. case "${release}" in
  1379. ubuntu | debian | armbian)
  1380. env_file="/etc/default/x-ui"
  1381. ;;
  1382. arch | manjaro | parch | alpine)
  1383. env_file="/etc/conf.d/x-ui"
  1384. ;;
  1385. *)
  1386. env_file="/etc/sysconfig/x-ui"
  1387. ;;
  1388. esac
  1389. fi
  1390. if [[ -r "$env_file" ]]; then
  1391. set -a
  1392. # shellcheck disable=SC1090
  1393. source "$env_file"
  1394. set +a
  1395. fi
  1396. # XUI_* wins over the script's own default: the unit hands that same env
  1397. # file to the panel through EnvironmentFile=, so these are the folders it
  1398. # will actually use.
  1399. main_folder="${XUI_MAIN_FOLDER:-${xui_folder}}"
  1400. db_folder="${XUI_DB_FOLDER:-/etc/x-ui}"
  1401. log_folder="${XUI_LOG_FOLDER:-/var/log/x-ui}"
  1402. # An empty XUI_BIN_FOLDER resolves to "bin" relative to the panel's working
  1403. # directory, which the unit sets to the main folder.
  1404. bin_folder="${XUI_BIN_FOLDER:-bin}"
  1405. if [[ "$bin_folder" != /* ]]; then
  1406. bin_folder="${main_folder%/}/${bin_folder#./}"
  1407. fi
  1408. for path in "$db_folder" "$log_folder" "$bin_folder" "$main_folder"; do
  1409. [[ "$path" == /* ]] || continue
  1410. # ReadWritePaths= is a whitespace-separated list, and a folder whose
  1411. # name contains whitespace cannot be written into it without relying on
  1412. # quoting. A wrong entry makes systemd reject the whole drop-in and the
  1413. # panel would not start, so leave such a folder out and say so instead.
  1414. if [[ "$path" != "${path//[[:space:]]/}" ]]; then
  1415. whitespace_paths="${whitespace_paths:+$whitespace_paths }$path"
  1416. continue
  1417. fi
  1418. case " $seen_paths " in
  1419. *" $path "*) continue ;;
  1420. esac
  1421. seen_paths="${seen_paths}${seen_paths:+ }$path"
  1422. # systemd expands %-specifiers in unit files, so a folder name carrying
  1423. # a literal % has to be written as %%, or the entry stops naming the
  1424. # folder systemd is meant to keep writable.
  1425. escaped_path="${path//%/%%}"
  1426. line="${line} -${escaped_path}"
  1427. done
  1428. if [[ -n "$whitespace_paths" ]]; then
  1429. echo "Warning: these folders contain whitespace and were left out of" >&2
  1430. echo " 10-xui-sandbox.conf: $whitespace_paths" >&2
  1431. echo " The panel cannot write to them under the unit's sandbox." >&2
  1432. fi
  1433. line="${line# }"
  1434. [[ -n "$line" ]] || return 1
  1435. dropin_dir="${xui_service}/x-ui.service.d"
  1436. dropin="${dropin_dir}/10-xui-sandbox.conf"
  1437. temp_file="${dropin}.tmp.$$"
  1438. mkdir -p "$dropin_dir" || return 1
  1439. cat > "$temp_file" << EOF
  1440. # Regenerated by install.sh/update.sh on every install and update: edits here
  1441. # are lost, and the list only reflects the XUI_* variables read from
  1442. # ${env_file} at that moment. Re-run install/update after moving a store.
  1443. # It lists the folders the panel writes to. Put local additions in their own
  1444. # drop-in, for example 20-x-ui-local.conf, which nothing here touches.
  1445. [Service]
  1446. ReadWritePaths=${line}
  1447. ReadWriteDirectories=${line}
  1448. EOF
  1449. if [[ "$(_xui_systemd_major_version)" -ge 239 ]]; then
  1450. cat >> "$temp_file" << 'EOF'
  1451. # @system-service needs systemd >= 239; on older versions the unknown group
  1452. # would leave the panel with a filter it cannot start under (x-ui.service.*).
  1453. SystemCallFilter=@system-service
  1454. SystemCallErrorNumber=EPERM
  1455. EOF
  1456. fi
  1457. if [[ ! -s "$temp_file" ]]; then
  1458. rm -f "$temp_file"
  1459. return 1
  1460. fi
  1461. chmod 644 "$temp_file"
  1462. mv -f "$temp_file" "$dropin" || { rm -f "$temp_file"; return 1; }
  1463. if command -v systemctl > /dev/null 2>&1; then
  1464. systemctl daemon-reload > /dev/null 2>&1 || true
  1465. fi
  1466. return 0
  1467. }
  1468. # Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
  1469. # atomic mv, so a failed cp/curl or an interrupted mv never leaves a
  1470. # truncated unit file at the live path -- systemd would then fail to parse
  1471. # it on the next daemon-reload/start. Same pattern already used for
  1472. # /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
  1473. # file already extracted from the release tarball) vs curl (GitHub fallback).
  1474. _install_xui_service_unit() {
  1475. local source="$1"
  1476. local source_is_url="$2"
  1477. local dest="${xui_service}/x-ui.service"
  1478. local temp_file="${dest}.tmp.$$"
  1479. rm -f "$temp_file"
  1480. if [[ "$source_is_url" == "true" ]]; then
  1481. curl -fLRo "$temp_file" "$source" > /dev/null 2>&1
  1482. else
  1483. cp -f "$source" "$temp_file" > /dev/null 2>&1
  1484. fi
  1485. if [[ $? -ne 0 ]]; then
  1486. rm -f "$temp_file"
  1487. return 1
  1488. fi
  1489. if [[ ! -s "$temp_file" ]]; then
  1490. rm -f "$temp_file"
  1491. return 1
  1492. fi
  1493. mv -f "$temp_file" "$dest"
  1494. if [[ $? -ne 0 ]]; then
  1495. rm -f "$temp_file"
  1496. return 1
  1497. fi
  1498. if ! _xui_service_write_paths_dropin; then
  1499. echo -e "${yellow}Warning: could not refresh ${xui_service}/x-ui.service.d/10-xui-sandbox.conf.${plain}"
  1500. echo -e "${yellow}If XUI_DB_FOLDER or XUI_LOG_FOLDER points outside /etc/x-ui and /var/log/x-ui, the panel may not be able to write to it under ProtectSystem=full.${plain}"
  1501. fi
  1502. _xui_warn_unsupported_hardening
  1503. return 0
  1504. }
  1505. # resolve_latest_tag prints the latest stable release tag. It prefers the web
  1506. # releases/latest redirect, which is not subject to the unauthenticated API's
  1507. # 60 req/h-per-IP limit that trips shared CI/CGNAT addresses (the install then
  1508. # fails with "Failed to fetch x-ui version"), and falls back to the API.
  1509. resolve_latest_tag() {
  1510. local url tag
  1511. url=$(curl -sSLI -o /dev/null -w '%{url_effective}' --retry 5 --retry-delay 3 --connect-timeout 15 --max-time 60 "https://github.com/MHSanaei/3x-ui/releases/latest" 2>/dev/null)
  1512. tag=${url##*/tag/}
  1513. if [[ "$tag" != "$url" && -n "$tag" && "$tag" != "latest" ]]; then
  1514. echo "$tag"
  1515. return 0
  1516. fi
  1517. curl -Ls --retry 5 --retry-delay 3 --connect-timeout 15 --max-time 60 "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/'
  1518. }
  1519. # Releases publish <asset>.sha256 next to each archive. A mismatch or a failed
  1520. # sidecar download aborts the install; only a 404 (releases predating the
  1521. # sidecar) is tolerated with a warning.
  1522. verify_release_checksum() {
  1523. local url="$1" file="$2" sums="$2.sha256" code expected actual
  1524. rm -f "${sums}"
  1525. code=$(curl -sL --retry 3 --retry-delay 3 --connect-timeout 15 --max-time 60 -o "${sums}" -w '%{http_code}' "${url}.sha256")
  1526. if [[ "${code}" == "404" ]]; then
  1527. rm -f "${sums}"
  1528. echo -e "${yellow}No checksum published for this release, skipping verification${plain}"
  1529. return 0
  1530. fi
  1531. if [[ "${code}" != "200" ]]; then
  1532. rm -f "${sums}" "${file}"
  1533. echo -e "${red}Failed to download the checksum for $(basename "${file}") (HTTP ${code})${plain}"
  1534. exit 1
  1535. fi
  1536. expected=$(awk 'NR == 1 {print $1}' "${sums}")
  1537. actual=$(sha256sum "${file}" | awk '{print $1}')
  1538. rm -f "${sums}"
  1539. if [[ ! "${expected}" =~ ^[0-9a-f]{64}$ || "${expected}" != "${actual}" ]]; then
  1540. rm -f "${file}"
  1541. echo -e "${red}Checksum mismatch for $(basename "${file}"): expected ${expected:-<none>}, got ${actual}${plain}"
  1542. exit 1
  1543. fi
  1544. echo -e "${green}Checksum verified: ${actual}${plain}"
  1545. }
  1546. # Older tags predate some of these files (x-ui.rc arrived in v2.8.4). Serving
  1547. # main's copy against an old binary is the mismatch this pinning exists to
  1548. # prevent, so probe before anything is stopped or removed and refuse the tag.
  1549. require_repo_files() {
  1550. local ref="$1" name status
  1551. shift
  1552. [[ "${ref}" == "main" ]] && return 0
  1553. for name in "$@"; do
  1554. status=$(curl -sIL --retry 3 --connect-timeout 15 -o /dev/null -w '%{http_code}' "https://raw.githubusercontent.com/MHSanaei/3x-ui/${ref}/${name}")
  1555. if [[ "${status}" != "200" ]]; then
  1556. echo -e "${red}${name} is not available for ${ref} (HTTP ${status})${plain}"
  1557. echo -e "${red}Install a release that ships it, or 'dev' for the rolling build. Your existing installation has not been touched.${plain}"
  1558. exit 1
  1559. fi
  1560. done
  1561. }
  1562. install_x-ui() {
  1563. cd ${xui_folder%/x-ui}/
  1564. # Download resources
  1565. if [ $# == 0 ]; then
  1566. tag_version=$(resolve_latest_tag)
  1567. if [[ ! -n "$tag_version" ]]; then
  1568. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  1569. exit 1
  1570. fi
  1571. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  1572. curl -fLR --retry 5 --retry-delay 3 --connect-timeout 15 --speed-limit 1 --speed-time 300 -o ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz
  1573. if [[ $? -ne 0 ]]; then
  1574. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  1575. exit 1
  1576. fi
  1577. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1578. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1579. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1580. exit 1
  1581. fi
  1582. verify_release_checksum "https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz" "${xui_folder}-linux-$(arch).tar.gz"
  1583. else
  1584. tag_version=$1
  1585. # The rolling dev channel ships under a fixed, non-semver tag that is
  1586. # force-moved to the latest main commit on every push. Accept `dev` as a
  1587. # convenient alias and skip the numeric floor check for it.
  1588. if [[ "$tag_version" == "dev" || "$tag_version" == "dev-latest" ]]; then
  1589. tag_version="dev-latest"
  1590. echo -e "${yellow}Installing the rolling dev build (tag: dev-latest). This is a per-commit pre-release, not a stable version.${plain}"
  1591. else
  1592. tag_version_numeric=${tag_version#v}
  1593. min_version="2.3.5"
  1594. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  1595. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  1596. exit 1
  1597. fi
  1598. fi
  1599. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  1600. echo -e "Beginning to install x-ui ${tag_version}"
  1601. curl -fLR --retry 5 --retry-delay 3 --connect-timeout 15 --speed-limit 1 --speed-time 300 -o ${xui_folder}-linux-$(arch).tar.gz ${url}
  1602. if [[ $? -ne 0 ]]; then
  1603. echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}"
  1604. exit 1
  1605. fi
  1606. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1607. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1608. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1609. exit 1
  1610. fi
  1611. verify_release_checksum "${url}" "${xui_folder}-linux-$(arch).tar.gz"
  1612. fi
  1613. # x-ui.sh, x-ui.rc and the unit files must come from the same release as
  1614. # the binary; only the rolling dev build tracks main.
  1615. local script_ref="${tag_version}"
  1616. if [[ "${tag_version}" == "dev-latest" ]]; then
  1617. script_ref="main"
  1618. fi
  1619. # The unit files are only fetched when the release tarball lacks them, so
  1620. # they are checked at that point instead of here.
  1621. local required_files=("x-ui.sh")
  1622. [[ $release == "alpine" ]] && required_files+=("x-ui.rc")
  1623. require_repo_files "${script_ref}" "${required_files[@]}"
  1624. local xui_script_temp="/usr/bin/x-ui-temp.$$"
  1625. rm -f "${xui_script_temp}"
  1626. curl -fLRo "${xui_script_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.sh"
  1627. if [[ $? -ne 0 ]]; then
  1628. rm -f "${xui_script_temp}"
  1629. echo -e "${red}Failed to download x-ui.sh${plain}"
  1630. exit 1
  1631. fi
  1632. if [[ ! -s "${xui_script_temp}" ]]; then
  1633. rm -f "${xui_script_temp}"
  1634. echo -e "${red}Downloaded x-ui.sh is empty${plain}"
  1635. exit 1
  1636. fi
  1637. # Stop x-ui service and remove old resources
  1638. local custom_bin_backup=""
  1639. if [[ -e ${xui_folder}/ ]]; then
  1640. if [[ $release == "alpine" ]]; then
  1641. rc-service x-ui stop
  1642. else
  1643. systemctl stop x-ui
  1644. fi
  1645. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  1646. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  1647. # an inbound port with an outdated secret, silently breaking new clients.
  1648. # The freshly installed panel respawns a clean mtg per inbound on start.
  1649. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  1650. pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true
  1651. # bin/ is about to be wiped wholesale by the tar extraction below. The
  1652. # release only ships known assets (xray/mtg binaries, the bundled
  1653. # geoip*/geosite*.dat sets) -- anything else in bin/ was placed there
  1654. # by the admin (e.g. a hand-added custom geoip/geosite file referenced
  1655. # from a routing rule via "ext:<file>:<code>") and would otherwise be
  1656. # silently deleted on every update, breaking Xray at next start with
  1657. # "failed to open <file>: no such file or directory" for any routing
  1658. # rule that references it. Moved aside rather than copied: a rename
  1659. # on the same filesystem is atomic (no truncated file if disk space
  1660. # runs out mid-copy, unlike `cp`) and keeps the snapshot under
  1661. # /usr/local rather than a separate, possibly small/tmpfs $TMPDIR.
  1662. if [[ -d "${xui_folder}/bin" ]]; then
  1663. custom_bin_backup="${xui_folder%/x-ui}/x-ui-bin-backup.$$"
  1664. rm -rf "${custom_bin_backup}"
  1665. if ! mv "${xui_folder}/bin" "${custom_bin_backup}"; then
  1666. custom_bin_backup=""
  1667. echo -e "${yellow}Could not back up bin/ -- custom files there will not be preserved across this update${plain}"
  1668. fi
  1669. fi
  1670. # Sole cleanup path for the backup from here on -- covers both the
  1671. # two `exit 1`s below (extraction/binary-missing failures) and an
  1672. # interrupted update (Ctrl-C, signal) before the restore runs.
  1673. # Cleared once the restore below finishes normally.
  1674. trap '[[ -n "${custom_bin_backup}" ]] && rm -rf "${custom_bin_backup}"' EXIT INT TERM
  1675. rm ${xui_folder}/ -rf
  1676. fi
  1677. # Extract resources and set permissions
  1678. tar zxvf x-ui-linux-$(arch).tar.gz
  1679. if [[ $? -ne 0 ]]; then
  1680. rm x-ui-linux-$(arch).tar.gz -f
  1681. rm -f "${xui_script_temp}"
  1682. echo -e "${red}Failed to extract the x-ui release archive -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
  1683. exit 1
  1684. fi
  1685. rm x-ui-linux-$(arch).tar.gz -f
  1686. cd x-ui
  1687. if [[ $? -ne 0 || ! -s x-ui ]]; then
  1688. rm -f "${xui_script_temp}"
  1689. echo -e "${red}Extracted x-ui archive is missing the x-ui binary -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
  1690. exit 1
  1691. fi
  1692. chmod +x x-ui
  1693. chmod +x x-ui.sh
  1694. # Check the system's architecture and rename the file accordingly.
  1695. # The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
  1696. # so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
  1697. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  1698. mv bin/xray-linux-$(arch) bin/xray-linux-arm32
  1699. chmod +x bin/xray-linux-arm32
  1700. if [[ -f bin/mtg-linux-$(arch) ]]; then
  1701. mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
  1702. chmod +x bin/mtg-linux-arm
  1703. fi
  1704. fi
  1705. chmod +x x-ui bin/xray-linux-$(arch)
  1706. if [[ -f bin/mtg-linux-arm ]]; then
  1707. chmod +x bin/mtg-linux-arm
  1708. elif [[ -f bin/mtg-linux-$(arch) ]]; then
  1709. chmod +x bin/mtg-linux-$(arch)
  1710. fi
  1711. # Restore anything from the old bin/ that the fresh release doesn't ship
  1712. # (custom geoip/geosite files, or anything else an admin hand-placed
  1713. # there) -- never overwrites a same-named file the new release provides,
  1714. # so bundled assets (geoip.dat, geoip_RU.dat, ...) still get the fresh
  1715. # per-release copy. Runs after the arch-rename above so xray-linux-arm32/
  1716. # mtg-linux-arm already exist under their final names there and aren't
  1717. # mistaken for custom files needing a restore. Skips paths the panel
  1718. # itself regenerates at runtime (config.json, mtproto/*.toml -- see
  1719. # internal/xray/process.go, internal/mtproto/manager.go): those aren't
  1720. # admin-placed, and restoring a stale one only resurrects dead state (an
  1721. # orphaned mtg config for a since-deleted inbound) or the wrong
  1722. # directory permissions.
  1723. if [[ -n "${custom_bin_backup}" ]]; then
  1724. local restored_custom_bin=()
  1725. while IFS= read -r -d '' f; do
  1726. local rel="${f#"${custom_bin_backup}"/}"
  1727. case "${rel}" in
  1728. config.json | mtproto | mtproto/* | tuic | tuic/* | tuic-server | tuic-server-*) continue ;;
  1729. esac
  1730. if [[ ! -e "bin/${rel}" ]]; then
  1731. mkdir -p "bin/$(dirname "${rel}")"
  1732. cp -a "${f}" "bin/${rel}"
  1733. restored_custom_bin+=("${rel}")
  1734. fi
  1735. done < <(find "${custom_bin_backup}" \( -type f -o -type l \) -print0)
  1736. rm -rf "${custom_bin_backup}"
  1737. custom_bin_backup=""
  1738. if [[ ${#restored_custom_bin[@]} -gt 0 ]]; then
  1739. echo -e "${green}Restored custom file(s) in bin/ not shipped by this release: ${restored_custom_bin[*]}${plain}"
  1740. fi
  1741. fi
  1742. trap - EXIT INT TERM
  1743. rm -f bin/tuic-server bin/tuic-server-* > /dev/null 2>&1 || true
  1744. rm -rf bin/tuic > /dev/null 2>&1 || true
  1745. # Update x-ui cli and se set permission
  1746. mv -f "${xui_script_temp}" /usr/bin/x-ui
  1747. if [[ $? -ne 0 ]]; then
  1748. rm -f "${xui_script_temp}"
  1749. echo -e "${red}Failed to install x-ui.sh${plain}"
  1750. exit 1
  1751. fi
  1752. chmod +x /usr/bin/x-ui
  1753. mkdir -p /var/log/x-ui
  1754. config_after_install
  1755. # Etckeeper compatibility
  1756. if [ -d "/etc/.git" ]; then
  1757. if [ -f "/etc/.gitignore" ]; then
  1758. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  1759. echo "" >> "/etc/.gitignore"
  1760. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  1761. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  1762. fi
  1763. else
  1764. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  1765. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  1766. fi
  1767. fi
  1768. if [[ $release == "alpine" ]]; then
  1769. xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
  1770. rm -f "${xui_rc_temp}"
  1771. curl -fLRo "${xui_rc_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.rc"
  1772. if [[ $? -ne 0 ]]; then
  1773. rm -f "${xui_rc_temp}"
  1774. echo -e "${red}Failed to download x-ui.rc${plain}"
  1775. exit 1
  1776. fi
  1777. if [[ ! -s "${xui_rc_temp}" ]]; then
  1778. rm -f "${xui_rc_temp}"
  1779. echo -e "${red}Downloaded x-ui.rc is empty${plain}"
  1780. exit 1
  1781. fi
  1782. mv -f "${xui_rc_temp}" /etc/init.d/x-ui
  1783. if [[ $? -ne 0 ]]; then
  1784. rm -f "${xui_rc_temp}"
  1785. echo -e "${red}Failed to install x-ui.rc${plain}"
  1786. exit 1
  1787. fi
  1788. chmod +x /etc/init.d/x-ui
  1789. rc-update add x-ui
  1790. rc-service x-ui start
  1791. else
  1792. # Install systemd service file
  1793. service_installed=false
  1794. if [ -f "x-ui.service" ]; then
  1795. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  1796. if _install_xui_service_unit "x-ui.service" "false"; then
  1797. service_installed=true
  1798. fi
  1799. fi
  1800. if [ "$service_installed" = false ]; then
  1801. case "${release}" in
  1802. ubuntu | debian | armbian)
  1803. if [ -f "x-ui.service.debian" ]; then
  1804. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  1805. if _install_xui_service_unit "x-ui.service.debian" "false"; then
  1806. service_installed=true
  1807. fi
  1808. fi
  1809. ;;
  1810. arch | manjaro | parch)
  1811. if [ -f "x-ui.service.arch" ]; then
  1812. echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
  1813. if _install_xui_service_unit "x-ui.service.arch" "false"; then
  1814. service_installed=true
  1815. fi
  1816. fi
  1817. ;;
  1818. *)
  1819. if [ -f "x-ui.service.rhel" ]; then
  1820. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  1821. if _install_xui_service_unit "x-ui.service.rhel" "false"; then
  1822. service_installed=true
  1823. fi
  1824. fi
  1825. ;;
  1826. esac
  1827. fi
  1828. # If service file not found in tar.gz, download from GitHub
  1829. if [ "$service_installed" = false ]; then
  1830. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1831. case "${release}" in
  1832. ubuntu | debian | armbian)
  1833. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.debian"
  1834. ;;
  1835. arch | manjaro | parch)
  1836. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.arch"
  1837. ;;
  1838. *)
  1839. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.rhel"
  1840. ;;
  1841. esac
  1842. if ! _install_xui_service_unit "$service_unit_url" "true"; then
  1843. echo -e "${red}Failed to install x-ui.service from GitHub (${script_ref}) -- the release tarball did not ship one either${plain}"
  1844. exit 1
  1845. fi
  1846. service_installed=true
  1847. fi
  1848. if [ "$service_installed" = true ]; then
  1849. echo -e "${green}Setting up systemd unit...${plain}"
  1850. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1851. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1852. systemctl daemon-reload
  1853. systemctl enable x-ui
  1854. systemctl start x-ui
  1855. else
  1856. echo -e "${red}Failed to install x-ui.service file${plain}"
  1857. exit 1
  1858. fi
  1859. fi
  1860. # IP Limit relies on fail2ban; install + configure it now so the feature
  1861. # works out of the box (no-op when XUI_ENABLE_FAIL2BAN=false). Never fatal.
  1862. setup_fail2ban
  1863. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  1864. echo -e ""
  1865. echo -e "┌───────────────────────────────────────────────────────┐
  1866. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1867. │ │
  1868. │ ${blue}x-ui${plain} - Admin Management Script │
  1869. │ ${blue}x-ui start${plain} - Start │
  1870. │ ${blue}x-ui stop${plain} - Stop │
  1871. │ ${blue}x-ui restart${plain} - Restart │
  1872. │ ${blue}x-ui status${plain} - Current Status │
  1873. │ ${blue}x-ui settings${plain} - Current Settings │
  1874. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1875. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1876. │ ${blue}x-ui log${plain} - Check logs │
  1877. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1878. │ ${blue}x-ui update${plain} - Update │
  1879. │ ${blue}x-ui legacy${plain} - Legacy version │
  1880. │ ${blue}x-ui install${plain} - Install │
  1881. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1882. └───────────────────────────────────────────────────────┘"
  1883. }
  1884. echo -e "${green}Running...${plain}"
  1885. install_base
  1886. install_x-ui $1