1
0

install.sh 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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. install_postgres_local() {
  196. local pg_user pg_pass
  197. pg_pass=$(gen_random_string 24)
  198. local pg_db="xui"
  199. local pg_host="127.0.0.1"
  200. local pg_port="5432"
  201. case "${release}" in
  202. ubuntu | debian | armbian)
  203. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  204. ;;
  205. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  206. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  207. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  208. ;;
  209. centos)
  210. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  211. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  212. else
  213. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  214. fi
  215. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  216. ;;
  217. arch | manjaro | parch)
  218. pacman -Sy --noconfirm postgresql >&2 || return 1
  219. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  220. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  221. fi
  222. ;;
  223. opensuse-tumbleweed | opensuse-leap)
  224. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  225. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  226. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  227. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  228. fi
  229. ;;
  230. alpine)
  231. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  232. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  233. /etc/init.d/postgresql setup >&2 || return 1
  234. fi
  235. rc-update add postgresql default >&2 2> /dev/null || true
  236. rc-service postgresql start >&2 || return 1
  237. ;;
  238. *)
  239. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  240. return 1
  241. ;;
  242. esac
  243. if [[ "${release}" != "alpine" ]]; then
  244. systemctl enable --now postgresql >&2 || return 1
  245. fi
  246. # Wait briefly for the server to accept connections.
  247. local i
  248. for i in 1 2 3 4 5; do
  249. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  250. sleep 1
  251. done
  252. local existing_owner=""
  253. existing_owner=$(sudo -u postgres psql -tAc \
  254. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  255. | tr -d '[:space:]')
  256. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  257. pg_user="${existing_owner}"
  258. else
  259. pg_user=$(gen_random_string 8)
  260. fi
  261. # Idempotent role/db creation. Identifiers are double-quoted because a
  262. # random username may start with a digit, which Postgres rejects unquoted.
  263. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  264. | grep -q 1 \
  265. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  266. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  267. | grep -q 1 \
  268. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  269. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  270. pg_ensure_hba_password_auth "${pg_db}" \
  271. || echo -e "${yellow}Warning: could not update pg_hba.conf; PostgreSQL may reject the panel's TCP login (ident auth).${plain}" >&2
  272. local pg_pass_enc
  273. 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')
  274. if [[ -n "${PG_CRED_FILE:-}" ]]; then
  275. local prev_umask
  276. prev_umask=$(umask)
  277. umask 077
  278. if ! cat > "${PG_CRED_FILE}" << EOF; then
  279. PG_USER=${pg_user}
  280. PG_PASS=${pg_pass}
  281. PG_HOST=${pg_host}
  282. PG_PORT=${pg_port}
  283. PG_DB=${pg_db}
  284. EOF
  285. umask "${prev_umask}"
  286. echo -e "${red}Failed to write PostgreSQL credentials to ${PG_CRED_FILE}${plain}" >&2
  287. return 1
  288. fi
  289. umask "${prev_umask}"
  290. fi
  291. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  292. return 0
  293. }
  294. ensure_pg_client() {
  295. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  296. return 0
  297. fi
  298. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore) for in-panel backup...${plain}" >&2
  299. case "${release}" in
  300. ubuntu | debian | armbian)
  301. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  302. ;;
  303. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  304. dnf install -y -q postgresql >&2 || return 1
  305. ;;
  306. centos)
  307. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  308. yum install -y postgresql >&2 || return 1
  309. else
  310. dnf install -y -q postgresql >&2 || return 1
  311. fi
  312. ;;
  313. arch | manjaro | parch)
  314. pacman -Sy --noconfirm postgresql >&2 || return 1
  315. ;;
  316. opensuse-tumbleweed | opensuse-leap)
  317. zypper -q install -y postgresql >&2 || return 1
  318. ;;
  319. alpine)
  320. apk add --no-cache postgresql-client >&2 || return 1
  321. ;;
  322. *)
  323. return 1
  324. ;;
  325. esac
  326. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  327. }
  328. install_acme() {
  329. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  330. cd ~ || return 1
  331. curl -s https://get.acme.sh | sh > /dev/null 2>&1
  332. if [ $? -ne 0 ]; then
  333. echo -e "${red}Failed to install acme.sh${plain}"
  334. return 1
  335. else
  336. echo -e "${green}acme.sh installed successfully${plain}"
  337. fi
  338. return 0
  339. }
  340. install_tuic_server() {
  341. local target_arch=""
  342. case "$(arch)" in
  343. amd64|x86_64) target_arch="x86_64-unknown-linux-musl" ;;
  344. arm64|aarch64) target_arch="aarch64-unknown-linux-musl" ;;
  345. armv7|armv7l) target_arch="armv7-unknown-linux-musleabihf" ;;
  346. 386|i386|i686) target_arch="i686-unknown-linux-musl" ;;
  347. armv6|armv6l|armv5|armv5l|s390x)
  348. echo -e "${yellow}tuic-server does not provide prebuilt binaries for $(arch); TUIC inbounds will be unavailable on this machine${plain}"
  349. return 0
  350. ;;
  351. *) return 0 ;;
  352. esac
  353. local tuic_url="https://github.com/EAimTY/tuic/releases/download/tuic-server-1.0.0/tuic-server-1.0.0-${target_arch}"
  354. echo -e "${green}Installing tuic-server (${target_arch})...${plain}"
  355. mkdir -p "${xui_folder}/bin"
  356. if curl -fLR --connect-timeout 15 --retry 3 -o "${xui_folder}/bin/tuic-server" "${tuic_url}" && [[ -s "${xui_folder}/bin/tuic-server" ]]; then
  357. chmod +x "${xui_folder}/bin/tuic-server"
  358. echo -e "${green}tuic-server installed successfully${plain}"
  359. else
  360. rm -f "${xui_folder}/bin/tuic-server"
  361. echo -e "${yellow}Failed to download tuic-server (optional), skipping${plain}"
  362. fi
  363. }
  364. setup_ssl_certificate() {
  365. local domain="$1"
  366. local server_ip="$2"
  367. local existing_port="$3"
  368. local existing_webBasePath="$4"
  369. echo -e "${green}Setting up SSL certificate...${plain}"
  370. # Check if acme.sh is installed
  371. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  372. install_acme
  373. if [ $? -ne 0 ]; then
  374. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  375. return 1
  376. fi
  377. fi
  378. # Create certificate directory
  379. local certPath="/root/cert/${domain}"
  380. mkdir -p "$certPath"
  381. # Issue certificate
  382. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  383. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  384. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  385. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport 80 --force
  386. if [ $? -ne 0 ]; then
  387. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  388. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  389. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc 2> /dev/null
  390. rm -rf "$certPath" 2> /dev/null
  391. return 1
  392. fi
  393. # Install certificate
  394. ~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  395. --key-file /root/cert/${domain}/privkey.pem \
  396. --fullchain-file /root/cert/${domain}/fullchain.pem \
  397. --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
  398. if [ $? -ne 0 ]; then
  399. echo -e "${yellow}Failed to install certificate${plain}"
  400. return 1
  401. fi
  402. # Enable auto-renew
  403. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  404. # Secure permissions: private key readable only by owner
  405. chmod 600 $certPath/privkey.pem 2> /dev/null
  406. chmod 644 $certPath/fullchain.pem 2> /dev/null
  407. # Set certificate for panel
  408. local webCertFile="/root/cert/${domain}/fullchain.pem"
  409. local webKeyFile="/root/cert/${domain}/privkey.pem"
  410. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  411. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" > /dev/null 2>&1
  412. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  413. return 0
  414. else
  415. echo -e "${yellow}Certificate files not found${plain}"
  416. return 1
  417. fi
  418. }
  419. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  420. # Requires acme.sh and port 80 open for HTTP-01 challenge
  421. setup_ip_certificate() {
  422. local ipv4="$1"
  423. local ipv6="$2" # optional
  424. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  425. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  426. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  427. # Check for acme.sh
  428. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  429. install_acme
  430. if [ $? -ne 0 ]; then
  431. echo -e "${red}Failed to install acme.sh${plain}"
  432. return 1
  433. fi
  434. fi
  435. # Validate IP address
  436. if [[ -z "$ipv4" ]]; then
  437. echo -e "${red}IPv4 address is required${plain}"
  438. return 1
  439. fi
  440. if ! is_ipv4 "$ipv4"; then
  441. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  442. return 1
  443. fi
  444. # Create certificate directory
  445. local certDir="/root/cert/ip"
  446. mkdir -p "$certDir"
  447. # Build domain arguments
  448. local domain_args="-d ${ipv4}"
  449. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  450. domain_args="${domain_args} -d ${ipv6}"
  451. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  452. fi
  453. # Set reload command for auto-renewal (add || true so it doesn't fail during first install)
  454. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  455. # Choose port for HTTP-01 listener (default 80, prompt override)
  456. local WebPort=""
  457. prompt_or_default WebPort "Port to use for ACME HTTP-01 listener (default 80): " "80" XUI_ACME_HTTP_PORT
  458. WebPort="${WebPort:-80}"
  459. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  460. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  461. WebPort=80
  462. fi
  463. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  464. if [[ "${WebPort}" -ne 80 ]]; then
  465. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  466. fi
  467. # Ensure chosen port is available
  468. while true; do
  469. if is_port_in_use "${WebPort}"; then
  470. echo -e "${yellow}Port ${WebPort} is in use.${plain}"
  471. local alt_port=""
  472. if [[ "$NONINTERACTIVE" == "1" ]]; then
  473. echo -e "${red}Port ${WebPort} is busy; cannot proceed in non-interactive mode.${plain}"
  474. return 1
  475. fi
  476. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  477. alt_port="${alt_port// /}"
  478. if [[ -z "${alt_port}" ]]; then
  479. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  480. return 1
  481. fi
  482. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  483. echo -e "${red}Invalid port provided.${plain}"
  484. return 1
  485. fi
  486. WebPort="${alt_port}"
  487. continue
  488. else
  489. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  490. break
  491. fi
  492. done
  493. # Issue certificate with shortlived profile
  494. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  495. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  496. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  497. ~/.acme.sh/acme.sh --issue \
  498. ${domain_args} \
  499. --standalone \
  500. --server letsencrypt \
  501. --certificate-profile shortlived \
  502. --days 6 \
  503. --httpport ${WebPort} \
  504. --force
  505. if [ $? -ne 0 ]; then
  506. echo -e "${red}Failed to issue IP certificate${plain}"
  507. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  508. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  509. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  510. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  511. rm -rf ${certDir} 2> /dev/null
  512. return 1
  513. fi
  514. echo -e "${green}Certificate issued successfully, installing...${plain}"
  515. # Install certificate
  516. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  517. # but the cert files are still installed. We check for files instead of exit code.
  518. ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
  519. --key-file "${certDir}/privkey.pem" \
  520. --fullchain-file "${certDir}/fullchain.pem" \
  521. --reloadcmd "${reloadCmd}" 2>&1 || true
  522. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  523. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  524. echo -e "${red}Certificate files not found after installation${plain}"
  525. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  526. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  527. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  528. rm -rf ${certDir} 2> /dev/null
  529. return 1
  530. fi
  531. echo -e "${green}Certificate files installed successfully${plain}"
  532. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  533. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  534. # Secure permissions: private key readable only by owner
  535. chmod 600 ${certDir}/privkey.pem 2> /dev/null
  536. chmod 644 ${certDir}/fullchain.pem 2> /dev/null
  537. # Configure panel to use the certificate
  538. echo -e "${green}Setting certificate paths for the panel...${plain}"
  539. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  540. if [ $? -ne 0 ]; then
  541. echo -e "${yellow}Warning: Could not set certificate paths automatically${plain}"
  542. echo -e "${yellow}Certificate files are at:${plain}"
  543. echo -e " Cert: ${certDir}/fullchain.pem"
  544. echo -e " Key: ${certDir}/privkey.pem"
  545. else
  546. echo -e "${green}Certificate paths configured successfully${plain}"
  547. fi
  548. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  549. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  550. echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}"
  551. return 0
  552. }
  553. # Comprehensive manual SSL certificate issuance via acme.sh
  554. ssl_cert_issue() {
  555. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  556. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  557. # check for acme.sh first
  558. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  559. echo "acme.sh could not be found. Installing now..."
  560. cd ~ || return 1
  561. curl -s https://get.acme.sh | sh
  562. if [ $? -ne 0 ]; then
  563. echo -e "${red}Failed to install acme.sh${plain}"
  564. return 1
  565. else
  566. echo -e "${green}acme.sh installed successfully${plain}"
  567. fi
  568. fi
  569. # get the domain here, and we need to verify it
  570. local domain=""
  571. if [[ "$NONINTERACTIVE" == "1" ]]; then
  572. domain="${XUI_DOMAIN// /}"
  573. if [[ -z "$domain" ]] || ! is_domain "$domain"; then
  574. echo -e "${red}XUI_SSL_MODE=domain requires a valid XUI_DOMAIN (got: '${XUI_DOMAIN:-}').${plain}"
  575. return 1
  576. fi
  577. else
  578. while true; do
  579. read -rp "Please enter your domain name: " domain
  580. domain="${domain// /}" # Trim whitespace
  581. if [[ -z "$domain" ]]; then
  582. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  583. continue
  584. fi
  585. if ! is_domain "$domain"; then
  586. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  587. continue
  588. fi
  589. break
  590. done
  591. fi
  592. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  593. SSL_ISSUED_DOMAIN="${domain}"
  594. # detect existing certificate and reuse it only if its files are actually
  595. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  596. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  597. # with no usable cert files, which must not be reused (it produces a 0-byte
  598. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  599. local cert_exists=0
  600. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  601. local acmeCertDir=""
  602. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  603. acmeCertDir=~/.acme.sh/${domain}_ecc
  604. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  605. acmeCertDir=~/.acme.sh/${domain}
  606. fi
  607. if [[ -n "${acmeCertDir}" ]]; then
  608. cert_exists=1
  609. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  610. echo -e "${yellow}Existing certificate found for ${domain}, will reuse it.${plain}"
  611. [[ -n "${certInfo}" ]] && echo "$certInfo"
  612. else
  613. echo -e "${yellow}Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing.${plain}"
  614. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  615. fi
  616. fi
  617. if [[ ${cert_exists} -eq 0 ]]; then
  618. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  619. fi
  620. # create a directory for the certificate
  621. certPath="/root/cert/${domain}"
  622. if [ ! -d "$certPath" ]; then
  623. mkdir -p "$certPath"
  624. else
  625. rm -rf "$certPath"
  626. mkdir -p "$certPath"
  627. fi
  628. # get the port number for the standalone server
  629. local WebPort=80
  630. prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT
  631. if [[ -z ${WebPort} ]]; then
  632. WebPort=80
  633. elif [[ ! ${WebPort} =~ ^[1-9][0-9]*$ || ${WebPort} -gt 65535 ]]; then
  634. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  635. WebPort=80
  636. fi
  637. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  638. # Stop panel temporarily
  639. echo -e "${yellow}Stopping panel temporarily...${plain}"
  640. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  641. if [[ ${cert_exists} -eq 0 ]]; then
  642. # issue the certificate
  643. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  644. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  645. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  646. if [ $? -ne 0 ]; then
  647. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  648. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  649. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  650. return 1
  651. else
  652. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  653. fi
  654. else
  655. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  656. fi
  657. # Setup reload command
  658. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  659. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  660. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  661. if [[ "$NONINTERACTIVE" == "1" ]]; then
  662. setReloadcmd="n"
  663. else
  664. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  665. fi
  666. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  667. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  668. echo -e "${green}\t2.${plain} Input your own command"
  669. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  670. read -rp "Choose an option: " choice
  671. case "$choice" in
  672. 1)
  673. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  674. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  675. ;;
  676. 2)
  677. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  678. read -rp "Please enter your custom reloadcmd: " reloadCmd
  679. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  680. ;;
  681. *)
  682. echo -e "${green}Keeping default reloadcmd${plain}"
  683. ;;
  684. esac
  685. fi
  686. # install the certificate
  687. local installOutput=""
  688. installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  689. --key-file /root/cert/${domain}/privkey.pem \
  690. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  691. local installRc=$?
  692. echo "${installOutput}"
  693. local installWroteFiles=0
  694. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  695. installWroteFiles=1
  696. fi
  697. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  698. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  699. else
  700. echo -e "${red}Installing certificate failed, exiting.${plain}"
  701. if [[ ${cert_exists} -eq 0 ]]; then
  702. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  703. fi
  704. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  705. return 1
  706. fi
  707. # enable auto-renew
  708. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  709. if [ $? -ne 0 ]; then
  710. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  711. ls -lah /root/cert/${domain}/
  712. # Secure permissions: private key readable only by owner
  713. chmod 600 $certPath/privkey.pem 2> /dev/null
  714. chmod 644 $certPath/fullchain.pem 2> /dev/null
  715. else
  716. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  717. ls -lah /root/cert/${domain}/
  718. # Secure permissions: private key readable only by owner
  719. chmod 600 $certPath/privkey.pem 2> /dev/null
  720. chmod 644 $certPath/fullchain.pem 2> /dev/null
  721. fi
  722. # start panel
  723. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  724. # Prompt user to set panel paths after successful certificate installation
  725. if [[ "$NONINTERACTIVE" == "1" ]]; then
  726. setPanel="y"
  727. else
  728. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  729. fi
  730. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  731. local webCertFile="/root/cert/${domain}/fullchain.pem"
  732. local webKeyFile="/root/cert/${domain}/privkey.pem"
  733. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  734. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  735. echo -e "${green}Certificate paths set for the panel${plain}"
  736. echo -e "${green}Certificate File: $webCertFile${plain}"
  737. echo -e "${green}Private Key File: $webKeyFile${plain}"
  738. echo ""
  739. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  740. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  741. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  742. else
  743. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  744. fi
  745. else
  746. echo -e "${yellow}Skipping panel path setting.${plain}"
  747. fi
  748. return 0
  749. }
  750. # Reusable interactive SSL setup (domain or IP)
  751. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  752. prompt_and_setup_ssl() {
  753. local panel_port="$1"
  754. local web_base_path="$2"
  755. local server_ip="$3"
  756. local ssl_choice=""
  757. SSL_SCHEME="https"
  758. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  759. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  760. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  761. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  762. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  763. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  764. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  765. if [[ "$NONINTERACTIVE" == "1" ]]; then
  766. case "${XUI_SSL_MODE:-none}" in
  767. domain) ssl_choice="1" ;;
  768. ip) ssl_choice="2" ;;
  769. none | "") ssl_choice="4" ;;
  770. *)
  771. echo -e "${yellow}Unknown XUI_SSL_MODE='${XUI_SSL_MODE}', defaulting to none (HTTP).${plain}"
  772. ssl_choice="4"
  773. ;;
  774. esac
  775. else
  776. read -rp "Choose an option (default 2 for IP): " ssl_choice
  777. ssl_choice="${ssl_choice// /}" # Trim whitespace
  778. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  779. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  780. ssl_choice="2"
  781. fi
  782. fi
  783. case "$ssl_choice" in
  784. 1)
  785. # User chose Let's Encrypt domain option
  786. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  787. if ssl_cert_issue; then
  788. local cert_domain="${SSL_ISSUED_DOMAIN}"
  789. if [[ -z "${cert_domain}" ]]; then
  790. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  791. fi
  792. if [[ -n "${cert_domain}" ]]; then
  793. SSL_HOST="${cert_domain}"
  794. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  795. else
  796. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  797. SSL_HOST="${server_ip}"
  798. fi
  799. else
  800. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  801. SSL_HOST="${server_ip}"
  802. fi
  803. ;;
  804. 2)
  805. # User chose Let's Encrypt IP certificate option
  806. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  807. # Confirm the auto-detected IP before issuing for it: with asymmetric
  808. # routing / multi-WAN the echo services can return a transit address.
  809. if [[ "$NONINTERACTIVE" != "1" ]]; then
  810. local ip_confirm=""
  811. read -rp "Is ${server_ip} the correct incoming public IPv4 address for this server? [Default y]: " ip_confirm
  812. if [[ -n "$ip_confirm" && "$ip_confirm" != "y" && "$ip_confirm" != "Y" ]]; then
  813. server_ip=""
  814. while [[ -z "$server_ip" ]]; do
  815. read -rp "Please enter your server's public IPv4 address: " server_ip
  816. server_ip="${server_ip// /}"
  817. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  818. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  819. server_ip=""
  820. fi
  821. done
  822. fi
  823. fi
  824. # Ask for optional IPv6
  825. local ipv6_addr=""
  826. prompt_or_default ipv6_addr "Do you have an IPv6 address to include? (leave empty to skip): " "" XUI_SSL_IPV6
  827. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  828. # Stop panel if running (port 80 needed)
  829. if [[ $release == "alpine" ]]; then
  830. rc-service x-ui stop > /dev/null 2>&1
  831. else
  832. systemctl stop x-ui > /dev/null 2>&1
  833. fi
  834. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  835. if [ $? -eq 0 ]; then
  836. SSL_HOST="${server_ip}"
  837. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  838. else
  839. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  840. SSL_HOST="${server_ip}"
  841. fi
  842. ;;
  843. 3)
  844. # User chose Custom Paths (User Provided) option
  845. echo -e "${green}Using custom existing certificate...${plain}"
  846. local custom_cert=""
  847. local custom_key=""
  848. local custom_domain=""
  849. # 3.1 Request Domain to compose Panel URL later
  850. read -rp "Please enter domain name certificate issued for: " custom_domain
  851. custom_domain="${custom_domain// /}" # Remove spaces
  852. # 3.2 Loop for Certificate Path
  853. while true; do
  854. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  855. # Strip quotes if present
  856. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  857. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  858. break
  859. elif [[ ! -f "$custom_cert" ]]; then
  860. echo -e "${red}Error: File does not exist! Try again.${plain}"
  861. elif [[ ! -r "$custom_cert" ]]; then
  862. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  863. else
  864. echo -e "${red}Error: File is empty!${plain}"
  865. fi
  866. done
  867. # 3.3 Loop for Private Key Path
  868. while true; do
  869. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  870. # Strip quotes if present
  871. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  872. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  873. break
  874. elif [[ ! -f "$custom_key" ]]; then
  875. echo -e "${red}Error: File does not exist! Try again.${plain}"
  876. elif [[ ! -r "$custom_key" ]]; then
  877. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  878. else
  879. echo -e "${red}Error: File is empty!${plain}"
  880. fi
  881. done
  882. # 3.4 Apply Settings via x-ui binary
  883. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  884. # Set SSL_HOST for composing Panel URL
  885. if [[ -n "$custom_domain" ]]; then
  886. SSL_HOST="$custom_domain"
  887. else
  888. SSL_HOST="${server_ip}"
  889. fi
  890. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  891. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  892. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  893. ;;
  894. 4)
  895. echo ""
  896. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  897. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  898. echo -e "${yellow}Only safe when:${plain}"
  899. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  900. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  901. echo ""
  902. SSL_SCHEME="http"
  903. SSL_HOST="${server_ip}"
  904. local bind_local=""
  905. if [[ "$NONINTERACTIVE" == "1" ]]; then
  906. # Cloud images must stay reachable on their public interface.
  907. bind_local="n"
  908. else
  909. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  910. fi
  911. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  912. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  913. SSL_HOST="127.0.0.1"
  914. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  915. echo ""
  916. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  917. echo -e " Standard SSH command:"
  918. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  919. echo -e " If using an SSH key:"
  920. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  921. echo -e " Then open in your browser:"
  922. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  923. echo ""
  924. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  925. else
  926. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  927. fi
  928. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  929. echo -e "${green}✓ SSL setup skipped.${plain}"
  930. ;;
  931. *)
  932. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  933. SSL_HOST="${server_ip}"
  934. ;;
  935. esac
  936. }
  937. config_after_install() {
  938. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  939. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  940. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  941. # Properly detect empty cert by checking if cert: line exists and has content after it
  942. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  943. local URL_lists=(
  944. "https://api4.ipify.org"
  945. "https://ipv4.icanhazip.com"
  946. "https://v4.api.ipinfo.io/ip"
  947. "https://ipv4.myexternalip.com/raw"
  948. "https://4.ident.me"
  949. "https://check-host.net/ip"
  950. )
  951. local server_ip=""
  952. for ip_address in "${URL_lists[@]}"; do
  953. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  954. local http_code=$(echo "$response" | tail -n1)
  955. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  956. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  957. server_ip="${ip_result}"
  958. break
  959. fi
  960. done
  961. if [[ -z "$server_ip" ]]; then
  962. if [[ "$NONINTERACTIVE" == "1" ]]; then
  963. # Panel binds 0.0.0.0 regardless; the IP is only used to compose the
  964. # displayed access URL. Fall back to XUI_SERVER_IP or leave blank.
  965. server_ip="${XUI_SERVER_IP:-}"
  966. else
  967. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  968. while [[ -z "$server_ip" ]]; do
  969. read -rp "Please enter your server's public IPv4 address: " server_ip
  970. server_ip="${server_ip// /}"
  971. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  972. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  973. server_ip=""
  974. fi
  975. done
  976. fi
  977. fi
  978. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  979. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  980. local config_webBasePath="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
  981. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  982. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  983. local config_port=""
  984. local db_label="SQLite (/etc/x-ui/x-ui.db)"
  985. echo ""
  986. echo -e "${green}═══════════════════════════════════════════${plain}"
  987. echo -e "${green} Database Selection ${plain}"
  988. echo -e "${green}═══════════════════════════════════════════${plain}"
  989. echo -e " 1) SQLite (default — recommended for < 500 clients)"
  990. echo -e " 2) PostgreSQL (recommended for high client counts / many nodes)"
  991. if [[ "$NONINTERACTIVE" == "1" ]]; then
  992. if [[ "${XUI_DB_TYPE:-sqlite}" == "postgres" ]]; then
  993. db_choice="2"
  994. else
  995. db_choice="1"
  996. fi
  997. else
  998. read -rp "Choose [1]: " db_choice
  999. db_choice="${db_choice:-1}"
  1000. fi
  1001. if [[ "$db_choice" == "2" ]]; then
  1002. local xui_env_file
  1003. case "${release}" in
  1004. ubuntu | debian | armbian)
  1005. xui_env_file="/etc/default/x-ui"
  1006. ;;
  1007. arch | manjaro | parch | alpine)
  1008. xui_env_file="/etc/conf.d/x-ui"
  1009. ;;
  1010. *)
  1011. xui_env_file="/etc/sysconfig/x-ui"
  1012. ;;
  1013. esac
  1014. local xui_dsn=""
  1015. local pg_mode=""
  1016. local pg_local_installed=0
  1017. while [[ -z "$xui_dsn" ]]; do
  1018. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1019. if [[ -n "${XUI_DB_DSN:-}" ]]; then
  1020. xui_dsn="${XUI_DB_DSN}"
  1021. db_label="PostgreSQL (external)"
  1022. break
  1023. fi
  1024. echo -e "${yellow}Installing PostgreSQL locally (non-interactive)...${plain}"
  1025. local pg_cred_file
  1026. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  1027. if [[ -n "${pg_cred_file}" ]] && xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  1028. pg_local_installed=1
  1029. if [[ -r "${pg_cred_file}" ]]; then
  1030. # shellcheck disable=SC1090
  1031. source "${pg_cred_file}"
  1032. fi
  1033. rm -f "${pg_cred_file}"
  1034. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  1035. break
  1036. fi
  1037. rm -f "${pg_cred_file}"
  1038. echo -e "${red}PostgreSQL installation failed in non-interactive mode; aborting.${plain}"
  1039. echo -e "${yellow}Set XUI_DB_DSN to use an existing server, or XUI_DB_TYPE=sqlite.${plain}"
  1040. exit 1
  1041. fi
  1042. echo ""
  1043. echo -e " 1) Install PostgreSQL locally and create a dedicated user/db (recommended)"
  1044. echo -e " 2) Use an existing PostgreSQL server (enter DSN)"
  1045. read -rp "Choose [1]: " pg_mode
  1046. pg_mode="${pg_mode:-1}"
  1047. if [[ "$pg_mode" == "2" ]]; then
  1048. while [[ -z "$xui_dsn" ]]; do
  1049. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " xui_dsn
  1050. xui_dsn="${xui_dsn// /}"
  1051. done
  1052. db_label="PostgreSQL (external)"
  1053. else
  1054. echo -e "${yellow}Installing PostgreSQL — this may take a moment...${plain}"
  1055. local pg_cred_file
  1056. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  1057. if [[ -z "${pg_cred_file}" ]]; then
  1058. echo -e "${red}Failed to create temporary credentials file.${plain}"
  1059. xui_dsn=""
  1060. continue
  1061. fi
  1062. if xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  1063. pg_local_installed=1
  1064. if [[ -r "${pg_cred_file}" ]]; then
  1065. # shellcheck disable=SC1090
  1066. source "${pg_cred_file}"
  1067. fi
  1068. rm -f "${pg_cred_file}"
  1069. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  1070. else
  1071. rm -f "${pg_cred_file}"
  1072. echo ""
  1073. echo -e "${red}PostgreSQL installation failed.${plain}"
  1074. echo -e " 1) Retry local install"
  1075. echo -e " 2) Enter an external DSN instead"
  1076. echo -e " 3) Abort install"
  1077. echo -e " 4) Fall back to SQLite"
  1078. read -rp "Choose [1]: " pg_fail
  1079. pg_fail="${pg_fail:-1}"
  1080. case "$pg_fail" in
  1081. 2) pg_mode="2" ;;
  1082. 3)
  1083. echo -e "${red}Install aborted.${plain}"
  1084. exit 1
  1085. ;;
  1086. 4)
  1087. db_choice="1"
  1088. xui_dsn=""
  1089. break
  1090. ;;
  1091. *) xui_dsn="" ;;
  1092. esac
  1093. fi
  1094. fi
  1095. done
  1096. if [[ -n "$xui_dsn" ]]; then
  1097. install -d -m 755 "$(dirname "$xui_env_file")"
  1098. umask 077
  1099. cat > "$xui_env_file" << EOF
  1100. XUI_DB_TYPE=postgres
  1101. XUI_DB_DSN=${xui_dsn}
  1102. EOF
  1103. chmod 600 "$xui_env_file"
  1104. umask 022
  1105. export XUI_DB_TYPE=postgres
  1106. export XUI_DB_DSN="${xui_dsn}"
  1107. 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}"
  1108. fi
  1109. fi
  1110. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1111. if [[ -n "${XUI_PANEL_PORT:-}" ]]; then
  1112. config_port="${XUI_PANEL_PORT}"
  1113. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1114. else
  1115. config_port=$(shuf -i 1024-62000 -n 1)
  1116. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1117. fi
  1118. else
  1119. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  1120. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  1121. read -rp "Please set up the panel port: " config_port
  1122. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1123. else
  1124. config_port=$(shuf -i 1024-62000 -n 1)
  1125. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1126. fi
  1127. fi
  1128. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  1129. echo ""
  1130. echo -e "${green}═══════════════════════════════════════════${plain}"
  1131. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1132. echo -e "${green}═══════════════════════════════════════════${plain}"
  1133. echo -e "${yellow}SSL is strongly recommended. Skip only if a reverse proxy${plain}"
  1134. echo -e "${yellow}or SSH tunnel handles TLS for you.${plain}"
  1135. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1136. echo ""
  1137. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  1138. # Retrieve the API token for display
  1139. local config_apiToken=$(${xui_folder}/x-ui setting -getApiToken | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1140. # Display final credentials and access information
  1141. echo ""
  1142. echo -e "${green}═══════════════════════════════════════════${plain}"
  1143. echo -e "${green} Panel Installation Complete! ${plain}"
  1144. echo -e "${green}═══════════════════════════════════════════${plain}"
  1145. echo -e "${green}Username: ${config_username}${plain}"
  1146. echo -e "${green}Password: ${config_password}${plain}"
  1147. echo -e "${green}Port: ${config_port}${plain}"
  1148. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  1149. echo -e "${green}Database: ${db_label}${plain}"
  1150. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  1151. echo -e "${green}API Token: ${config_apiToken}${plain}"
  1152. echo -e "${green}═══════════════════════════════════════════${plain}"
  1153. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  1154. if [[ "$SSL_SCHEME" == "https" ]]; then
  1155. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  1156. else
  1157. echo -e "${yellow}⚠ SSL Certificate: Skipped — panel is HTTP-only. Use a reverse proxy or SSH tunnel.${plain}"
  1158. fi
  1159. if [[ "$db_choice" == "2" ]]; then
  1160. echo ""
  1161. echo -e "${green}PostgreSQL backup & restore is built into the panel:${plain}"
  1162. echo -e " ${blue}${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain} → Backup & Restore"
  1163. echo -e "${yellow} Back Up downloads a pg_dump .dump file; Restore reloads it via pg_restore.${plain}"
  1164. fi
  1165. if [[ "$db_choice" == "2" && "$pg_local_installed" == "1" ]]; then
  1166. echo ""
  1167. echo -e "${green}═══════════════════════════════════════════${plain}"
  1168. echo -e "${green} PostgreSQL Credentials ${plain}"
  1169. echo -e "${green}═══════════════════════════════════════════${plain}"
  1170. echo -e "${green}DB Name: ${PG_DB}${plain}"
  1171. echo -e "${green}Username: ${PG_USER}${plain}"
  1172. echo -e "${green}Password: ${PG_PASS}${plain}"
  1173. echo -e "${green}Host: ${PG_HOST}${plain}"
  1174. echo -e "${green}Port: ${PG_PORT}${plain}"
  1175. echo -e "${green}DSN: ${xui_dsn}${plain}"
  1176. echo -e "${green}Env file: ${xui_env_file}${plain}"
  1177. echo -e "${green}-------------------------------------------${plain}"
  1178. echo -e "${green}Connect from this server:${plain}"
  1179. echo -e " ${blue}sudo -u postgres psql -d ${PG_DB}${plain} (as the postgres superuser)"
  1180. echo -e " ${blue}PGPASSWORD='${PG_PASS}' psql -h ${PG_HOST} -p ${PG_PORT} -U ${PG_USER} -d ${PG_DB}${plain}"
  1181. echo -e "${green}═══════════════════════════════════════════${plain}"
  1182. echo -e "${yellow}⚠ The panel reads these credentials from ${xui_env_file}.${plain}"
  1183. echo -e "${yellow}⚠ Save the password — it is not stored anywhere else in plain text.${plain}"
  1184. unset PG_USER PG_PASS PG_HOST PG_PORT PG_DB
  1185. fi
  1186. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1187. : "${SSL_SCHEME:=https}"
  1188. : "${SSL_HOST:=${server_ip}}"
  1189. local db_type_out="sqlite"
  1190. [[ "$db_choice" == "2" ]] && db_type_out="postgres"
  1191. write_install_result "${config_username}" "${config_password}" "${config_port}" \
  1192. "${config_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${db_type_out}"
  1193. else
  1194. local config_webBasePath=$(gen_random_string 18)
  1195. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  1196. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  1197. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  1198. # If the panel is already installed but no certificate is configured, prompt for SSL now
  1199. if [[ -z "${existing_cert}" ]]; then
  1200. echo ""
  1201. echo -e "${green}═══════════════════════════════════════════${plain}"
  1202. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1203. echo -e "${green}═══════════════════════════════════════════${plain}"
  1204. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1205. echo ""
  1206. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  1207. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  1208. else
  1209. # If a cert already exists, just show the access URL
  1210. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  1211. fi
  1212. fi
  1213. else
  1214. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  1215. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  1216. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  1217. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  1218. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  1219. echo -e "Generated new random login credentials:"
  1220. echo -e "###############################################"
  1221. echo -e "${green}Username: ${config_username}${plain}"
  1222. echo -e "${green}Password: ${config_password}${plain}"
  1223. echo -e "###############################################"
  1224. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1225. local config_apiToken
  1226. config_apiToken=$(${xui_folder}/x-ui setting -getApiToken | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1227. : "${SSL_SCHEME:=https}"
  1228. : "${SSL_HOST:=${server_ip}}"
  1229. write_install_result "${config_username}" "${config_password}" "${existing_port}" \
  1230. "${existing_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${XUI_DB_TYPE:-sqlite}"
  1231. else
  1232. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  1233. fi
  1234. # Existing install: if no cert configured, prompt user for SSL setup
  1235. # Properly detect empty cert by checking if cert: line exists and has content after it
  1236. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1237. if [[ -z "$existing_cert" ]]; then
  1238. echo ""
  1239. echo -e "${green}═══════════════════════════════════════════${plain}"
  1240. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1241. echo -e "${green}═══════════════════════════════════════════${plain}"
  1242. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1243. echo ""
  1244. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  1245. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  1246. else
  1247. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  1248. fi
  1249. fi
  1250. ${xui_folder}/x-ui migrate
  1251. }
  1252. # setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
  1253. # by invoking the freshly installed x-ui CLI. IP Limit is load-bearing on
  1254. # fail2ban (without it the panel disables the limitIp field and zeroes existing
  1255. # limits), so a fresh install should make it work out of the box, just like the
  1256. # Docker image already does. Non-fatal by design: a fail2ban failure must never
  1257. # abort the panel install.
  1258. setup_fail2ban() {
  1259. if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
  1260. echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
  1261. return 0
  1262. fi
  1263. if [[ ! -x /usr/bin/x-ui ]]; then
  1264. echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
  1265. return 0
  1266. fi
  1267. # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
  1268. # usage banner, which would read as success here.
  1269. if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
  1270. echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
  1271. return 0
  1272. fi
  1273. echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
  1274. if /usr/bin/x-ui setup-fail2ban; then
  1275. echo -e "${green}Fail2ban setup complete.${plain}"
  1276. else
  1277. 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}"
  1278. fi
  1279. return 0
  1280. }
  1281. # Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
  1282. # atomic mv, so a failed cp/curl or an interrupted mv never leaves a
  1283. # truncated unit file at the live path -- systemd would then fail to parse
  1284. # it on the next daemon-reload/start. Same pattern already used for
  1285. # /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
  1286. # file already extracted from the release tarball) vs curl (GitHub fallback).
  1287. _install_xui_service_unit() {
  1288. local source="$1"
  1289. local source_is_url="$2"
  1290. local dest="${xui_service}/x-ui.service"
  1291. local temp_file="${dest}.tmp.$$"
  1292. rm -f "$temp_file"
  1293. if [[ "$source_is_url" == "true" ]]; then
  1294. curl -fLRo "$temp_file" "$source" > /dev/null 2>&1
  1295. else
  1296. cp -f "$source" "$temp_file" > /dev/null 2>&1
  1297. fi
  1298. if [[ $? -ne 0 ]]; then
  1299. rm -f "$temp_file"
  1300. return 1
  1301. fi
  1302. if [[ ! -s "$temp_file" ]]; then
  1303. rm -f "$temp_file"
  1304. return 1
  1305. fi
  1306. mv -f "$temp_file" "$dest"
  1307. if [[ $? -ne 0 ]]; then
  1308. rm -f "$temp_file"
  1309. return 1
  1310. fi
  1311. return 0
  1312. }
  1313. # resolve_latest_tag prints the latest stable release tag. It prefers the web
  1314. # releases/latest redirect, which is not subject to the unauthenticated API's
  1315. # 60 req/h-per-IP limit that trips shared CI/CGNAT addresses (the install then
  1316. # fails with "Failed to fetch x-ui version"), and falls back to the API.
  1317. resolve_latest_tag() {
  1318. local url tag
  1319. 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)
  1320. tag=${url##*/tag/}
  1321. if [[ "$tag" != "$url" && -n "$tag" && "$tag" != "latest" ]]; then
  1322. echo "$tag"
  1323. return 0
  1324. fi
  1325. 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/'
  1326. }
  1327. # Releases publish <asset>.sha256 next to each archive. A mismatch or a failed
  1328. # sidecar download aborts the install; only a 404 (releases predating the
  1329. # sidecar) is tolerated with a warning.
  1330. verify_release_checksum() {
  1331. local url="$1" file="$2" sums="$2.sha256" code expected actual
  1332. rm -f "${sums}"
  1333. code=$(curl -sL --retry 3 --retry-delay 3 --connect-timeout 15 --max-time 60 -o "${sums}" -w '%{http_code}' "${url}.sha256")
  1334. if [[ "${code}" == "404" ]]; then
  1335. rm -f "${sums}"
  1336. echo -e "${yellow}No checksum published for this release, skipping verification${plain}"
  1337. return 0
  1338. fi
  1339. if [[ "${code}" != "200" ]]; then
  1340. rm -f "${sums}" "${file}"
  1341. echo -e "${red}Failed to download the checksum for $(basename "${file}") (HTTP ${code})${plain}"
  1342. exit 1
  1343. fi
  1344. expected=$(awk 'NR == 1 {print $1}' "${sums}")
  1345. actual=$(sha256sum "${file}" | awk '{print $1}')
  1346. rm -f "${sums}"
  1347. if [[ ! "${expected}" =~ ^[0-9a-f]{64}$ || "${expected}" != "${actual}" ]]; then
  1348. rm -f "${file}"
  1349. echo -e "${red}Checksum mismatch for $(basename "${file}"): expected ${expected:-<none>}, got ${actual}${plain}"
  1350. exit 1
  1351. fi
  1352. echo -e "${green}Checksum verified: ${actual}${plain}"
  1353. }
  1354. # Older tags predate some of these files (x-ui.rc arrived in v2.8.4). Serving
  1355. # main's copy against an old binary is the mismatch this pinning exists to
  1356. # prevent, so probe before anything is stopped or removed and refuse the tag.
  1357. require_repo_files() {
  1358. local ref="$1" name status
  1359. shift
  1360. [[ "${ref}" == "main" ]] && return 0
  1361. for name in "$@"; do
  1362. status=$(curl -sIL --retry 3 --connect-timeout 15 -o /dev/null -w '%{http_code}' "https://raw.githubusercontent.com/MHSanaei/3x-ui/${ref}/${name}")
  1363. if [[ "${status}" != "200" ]]; then
  1364. echo -e "${red}${name} is not available for ${ref} (HTTP ${status})${plain}"
  1365. echo -e "${red}Install a release that ships it, or 'dev' for the rolling build. Your existing installation has not been touched.${plain}"
  1366. exit 1
  1367. fi
  1368. done
  1369. }
  1370. install_x-ui() {
  1371. cd ${xui_folder%/x-ui}/
  1372. # Download resources
  1373. if [ $# == 0 ]; then
  1374. tag_version=$(resolve_latest_tag)
  1375. if [[ ! -n "$tag_version" ]]; then
  1376. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  1377. exit 1
  1378. fi
  1379. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  1380. 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
  1381. if [[ $? -ne 0 ]]; then
  1382. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  1383. exit 1
  1384. fi
  1385. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1386. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1387. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1388. exit 1
  1389. fi
  1390. 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"
  1391. else
  1392. tag_version=$1
  1393. # The rolling dev channel ships under a fixed, non-semver tag that is
  1394. # force-moved to the latest main commit on every push. Accept `dev` as a
  1395. # convenient alias and skip the numeric floor check for it.
  1396. if [[ "$tag_version" == "dev" || "$tag_version" == "dev-latest" ]]; then
  1397. tag_version="dev-latest"
  1398. echo -e "${yellow}Installing the rolling dev build (tag: dev-latest). This is a per-commit pre-release, not a stable version.${plain}"
  1399. else
  1400. tag_version_numeric=${tag_version#v}
  1401. min_version="2.3.5"
  1402. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  1403. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  1404. exit 1
  1405. fi
  1406. fi
  1407. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  1408. echo -e "Beginning to install x-ui ${tag_version}"
  1409. curl -fLR --retry 5 --retry-delay 3 --connect-timeout 15 --speed-limit 1 --speed-time 300 -o ${xui_folder}-linux-$(arch).tar.gz ${url}
  1410. if [[ $? -ne 0 ]]; then
  1411. echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}"
  1412. exit 1
  1413. fi
  1414. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1415. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1416. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1417. exit 1
  1418. fi
  1419. verify_release_checksum "${url}" "${xui_folder}-linux-$(arch).tar.gz"
  1420. fi
  1421. # x-ui.sh, x-ui.rc and the unit files must come from the same release as
  1422. # the binary; only the rolling dev build tracks main.
  1423. local script_ref="${tag_version}"
  1424. if [[ "${tag_version}" == "dev-latest" ]]; then
  1425. script_ref="main"
  1426. fi
  1427. # The unit files are only fetched when the release tarball lacks them, so
  1428. # they are checked at that point instead of here.
  1429. local required_files=("x-ui.sh")
  1430. [[ $release == "alpine" ]] && required_files+=("x-ui.rc")
  1431. require_repo_files "${script_ref}" "${required_files[@]}"
  1432. local xui_script_temp="/usr/bin/x-ui-temp.$$"
  1433. rm -f "${xui_script_temp}"
  1434. curl -fLRo "${xui_script_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.sh"
  1435. if [[ $? -ne 0 ]]; then
  1436. rm -f "${xui_script_temp}"
  1437. echo -e "${red}Failed to download x-ui.sh${plain}"
  1438. exit 1
  1439. fi
  1440. if [[ ! -s "${xui_script_temp}" ]]; then
  1441. rm -f "${xui_script_temp}"
  1442. echo -e "${red}Downloaded x-ui.sh is empty${plain}"
  1443. exit 1
  1444. fi
  1445. # Stop x-ui service and remove old resources
  1446. local custom_bin_backup=""
  1447. if [[ -e ${xui_folder}/ ]]; then
  1448. if [[ $release == "alpine" ]]; then
  1449. rc-service x-ui stop
  1450. else
  1451. systemctl stop x-ui
  1452. fi
  1453. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  1454. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  1455. # an inbound port with an outdated secret, silently breaking new clients.
  1456. # The freshly installed panel respawns a clean mtg per inbound on start.
  1457. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  1458. pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true
  1459. # bin/ is about to be wiped wholesale by the tar extraction below. The
  1460. # release only ships known assets (xray/mtg binaries, the bundled
  1461. # geoip*/geosite*.dat sets) -- anything else in bin/ was placed there
  1462. # by the admin (e.g. a hand-added custom geoip/geosite file referenced
  1463. # from a routing rule via "ext:<file>:<code>") and would otherwise be
  1464. # silently deleted on every update, breaking Xray at next start with
  1465. # "failed to open <file>: no such file or directory" for any routing
  1466. # rule that references it. Moved aside rather than copied: a rename
  1467. # on the same filesystem is atomic (no truncated file if disk space
  1468. # runs out mid-copy, unlike `cp`) and keeps the snapshot under
  1469. # /usr/local rather than a separate, possibly small/tmpfs $TMPDIR.
  1470. if [[ -d "${xui_folder}/bin" ]]; then
  1471. custom_bin_backup="${xui_folder%/x-ui}/x-ui-bin-backup.$$"
  1472. rm -rf "${custom_bin_backup}"
  1473. if ! mv "${xui_folder}/bin" "${custom_bin_backup}"; then
  1474. custom_bin_backup=""
  1475. echo -e "${yellow}Could not back up bin/ -- custom files there will not be preserved across this update${plain}"
  1476. fi
  1477. fi
  1478. # Sole cleanup path for the backup from here on -- covers both the
  1479. # two `exit 1`s below (extraction/binary-missing failures) and an
  1480. # interrupted update (Ctrl-C, signal) before the restore runs.
  1481. # Cleared once the restore below finishes normally.
  1482. trap '[[ -n "${custom_bin_backup}" ]] && rm -rf "${custom_bin_backup}"' EXIT INT TERM
  1483. rm ${xui_folder}/ -rf
  1484. fi
  1485. # Extract resources and set permissions
  1486. tar zxvf x-ui-linux-$(arch).tar.gz
  1487. if [[ $? -ne 0 ]]; then
  1488. rm x-ui-linux-$(arch).tar.gz -f
  1489. rm -f "${xui_script_temp}"
  1490. 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}"
  1491. exit 1
  1492. fi
  1493. rm x-ui-linux-$(arch).tar.gz -f
  1494. cd x-ui
  1495. if [[ $? -ne 0 || ! -s x-ui ]]; then
  1496. rm -f "${xui_script_temp}"
  1497. 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}"
  1498. exit 1
  1499. fi
  1500. chmod +x x-ui
  1501. chmod +x x-ui.sh
  1502. # Check the system's architecture and rename the file accordingly.
  1503. # The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
  1504. # so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
  1505. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  1506. mv bin/xray-linux-$(arch) bin/xray-linux-arm32
  1507. chmod +x bin/xray-linux-arm32
  1508. if [[ -f bin/mtg-linux-$(arch) ]]; then
  1509. mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
  1510. chmod +x bin/mtg-linux-arm
  1511. fi
  1512. fi
  1513. chmod +x x-ui bin/xray-linux-$(arch)
  1514. if [[ -f bin/mtg-linux-arm ]]; then
  1515. chmod +x bin/mtg-linux-arm
  1516. elif [[ -f bin/mtg-linux-$(arch) ]]; then
  1517. chmod +x bin/mtg-linux-$(arch)
  1518. fi
  1519. if [[ -f bin/tuic-server ]]; then
  1520. chmod +x bin/tuic-server
  1521. else
  1522. install_tuic_server
  1523. fi
  1524. # Restore anything from the old bin/ that the fresh release doesn't ship
  1525. # (custom geoip/geosite files, or anything else an admin hand-placed
  1526. # there) -- never overwrites a same-named file the new release provides,
  1527. # so bundled assets (geoip.dat, geoip_RU.dat, ...) still get the fresh
  1528. # per-release copy. Runs after the arch-rename above so xray-linux-arm32/
  1529. # mtg-linux-arm already exist under their final names there and aren't
  1530. # mistaken for custom files needing a restore. Skips paths the panel
  1531. # itself regenerates at runtime (config.json, mtproto/*.toml -- see
  1532. # internal/xray/process.go, internal/mtproto/manager.go): those aren't
  1533. # admin-placed, and restoring a stale one only resurrects dead state (an
  1534. # orphaned mtg config for a since-deleted inbound) or the wrong
  1535. # directory permissions.
  1536. if [[ -n "${custom_bin_backup}" ]]; then
  1537. local restored_custom_bin=()
  1538. while IFS= read -r -d '' f; do
  1539. local rel="${f#"${custom_bin_backup}"/}"
  1540. case "${rel}" in
  1541. config.json | mtproto | mtproto/* | tuic | tuic/*) continue ;;
  1542. esac
  1543. if [[ ! -e "bin/${rel}" ]]; then
  1544. mkdir -p "bin/$(dirname "${rel}")"
  1545. cp -a "${f}" "bin/${rel}"
  1546. restored_custom_bin+=("${rel}")
  1547. fi
  1548. done < <(find "${custom_bin_backup}" \( -type f -o -type l \) -print0)
  1549. rm -rf "${custom_bin_backup}"
  1550. custom_bin_backup=""
  1551. if [[ ${#restored_custom_bin[@]} -gt 0 ]]; then
  1552. echo -e "${green}Restored custom file(s) in bin/ not shipped by this release: ${restored_custom_bin[*]}${plain}"
  1553. fi
  1554. fi
  1555. trap - EXIT INT TERM
  1556. # Update x-ui cli and se set permission
  1557. mv -f "${xui_script_temp}" /usr/bin/x-ui
  1558. if [[ $? -ne 0 ]]; then
  1559. rm -f "${xui_script_temp}"
  1560. echo -e "${red}Failed to install x-ui.sh${plain}"
  1561. exit 1
  1562. fi
  1563. chmod +x /usr/bin/x-ui
  1564. mkdir -p /var/log/x-ui
  1565. config_after_install
  1566. # Etckeeper compatibility
  1567. if [ -d "/etc/.git" ]; then
  1568. if [ -f "/etc/.gitignore" ]; then
  1569. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  1570. echo "" >> "/etc/.gitignore"
  1571. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  1572. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  1573. fi
  1574. else
  1575. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  1576. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  1577. fi
  1578. fi
  1579. if [[ $release == "alpine" ]]; then
  1580. xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
  1581. rm -f "${xui_rc_temp}"
  1582. curl -fLRo "${xui_rc_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.rc"
  1583. if [[ $? -ne 0 ]]; then
  1584. rm -f "${xui_rc_temp}"
  1585. echo -e "${red}Failed to download x-ui.rc${plain}"
  1586. exit 1
  1587. fi
  1588. if [[ ! -s "${xui_rc_temp}" ]]; then
  1589. rm -f "${xui_rc_temp}"
  1590. echo -e "${red}Downloaded x-ui.rc is empty${plain}"
  1591. exit 1
  1592. fi
  1593. mv -f "${xui_rc_temp}" /etc/init.d/x-ui
  1594. if [[ $? -ne 0 ]]; then
  1595. rm -f "${xui_rc_temp}"
  1596. echo -e "${red}Failed to install x-ui.rc${plain}"
  1597. exit 1
  1598. fi
  1599. chmod +x /etc/init.d/x-ui
  1600. rc-update add x-ui
  1601. rc-service x-ui start
  1602. else
  1603. # Install systemd service file
  1604. service_installed=false
  1605. if [ -f "x-ui.service" ]; then
  1606. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  1607. if _install_xui_service_unit "x-ui.service" "false"; then
  1608. service_installed=true
  1609. fi
  1610. fi
  1611. if [ "$service_installed" = false ]; then
  1612. case "${release}" in
  1613. ubuntu | debian | armbian)
  1614. if [ -f "x-ui.service.debian" ]; then
  1615. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  1616. if _install_xui_service_unit "x-ui.service.debian" "false"; then
  1617. service_installed=true
  1618. fi
  1619. fi
  1620. ;;
  1621. arch | manjaro | parch)
  1622. if [ -f "x-ui.service.arch" ]; then
  1623. echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
  1624. if _install_xui_service_unit "x-ui.service.arch" "false"; then
  1625. service_installed=true
  1626. fi
  1627. fi
  1628. ;;
  1629. *)
  1630. if [ -f "x-ui.service.rhel" ]; then
  1631. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  1632. if _install_xui_service_unit "x-ui.service.rhel" "false"; then
  1633. service_installed=true
  1634. fi
  1635. fi
  1636. ;;
  1637. esac
  1638. fi
  1639. # If service file not found in tar.gz, download from GitHub
  1640. if [ "$service_installed" = false ]; then
  1641. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1642. case "${release}" in
  1643. ubuntu | debian | armbian)
  1644. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.debian"
  1645. ;;
  1646. arch | manjaro | parch)
  1647. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.arch"
  1648. ;;
  1649. *)
  1650. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.rhel"
  1651. ;;
  1652. esac
  1653. if ! _install_xui_service_unit "$service_unit_url" "true"; then
  1654. echo -e "${red}Failed to install x-ui.service from GitHub (${script_ref}) -- the release tarball did not ship one either${plain}"
  1655. exit 1
  1656. fi
  1657. service_installed=true
  1658. fi
  1659. if [ "$service_installed" = true ]; then
  1660. echo -e "${green}Setting up systemd unit...${plain}"
  1661. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1662. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1663. systemctl daemon-reload
  1664. systemctl enable x-ui
  1665. systemctl start x-ui
  1666. else
  1667. echo -e "${red}Failed to install x-ui.service file${plain}"
  1668. exit 1
  1669. fi
  1670. fi
  1671. # IP Limit relies on fail2ban; install + configure it now so the feature
  1672. # works out of the box (no-op when XUI_ENABLE_FAIL2BAN=false). Never fatal.
  1673. setup_fail2ban
  1674. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  1675. echo -e ""
  1676. echo -e "┌───────────────────────────────────────────────────────┐
  1677. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1678. │ │
  1679. │ ${blue}x-ui${plain} - Admin Management Script │
  1680. │ ${blue}x-ui start${plain} - Start │
  1681. │ ${blue}x-ui stop${plain} - Stop │
  1682. │ ${blue}x-ui restart${plain} - Restart │
  1683. │ ${blue}x-ui status${plain} - Current Status │
  1684. │ ${blue}x-ui settings${plain} - Current Settings │
  1685. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1686. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1687. │ ${blue}x-ui log${plain} - Check logs │
  1688. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1689. │ ${blue}x-ui update${plain} - Update │
  1690. │ ${blue}x-ui legacy${plain} - Legacy version │
  1691. │ ${blue}x-ui install${plain} - Install │
  1692. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1693. └───────────────────────────────────────────────────────┘"
  1694. }
  1695. echo -e "${green}Running...${plain}"
  1696. install_base
  1697. install_x-ui $1