1
0

install.sh 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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. cur_dir=$(pwd)
  8. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  9. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  10. # check root
  11. [[ $EUID -ne 0 ]] && echo -e "${red}Fatal error: ${plain} Please run this script with root privilege \n " && exit 1
  12. # Check OS and set release variable
  13. if [[ -f /etc/os-release ]]; then
  14. source /etc/os-release
  15. release=$ID
  16. elif [[ -f /usr/lib/os-release ]]; then
  17. source /usr/lib/os-release
  18. release=$ID
  19. else
  20. echo "Failed to check the system OS, please contact the author!" >&2
  21. exit 1
  22. fi
  23. echo "The OS release is: $release"
  24. arch() {
  25. case "$(uname -m)" in
  26. x86_64 | x64 | amd64) echo 'amd64' ;;
  27. i*86 | x86) echo '386' ;;
  28. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  29. armv7* | armv7 | arm) echo 'armv7' ;;
  30. armv6* | armv6) echo 'armv6' ;;
  31. armv5* | armv5) echo 'armv5' ;;
  32. s390x) echo 's390x' ;;
  33. *) echo -e "${green}Unsupported CPU architecture! ${plain}" && rm -f install.sh && exit 1 ;;
  34. esac
  35. }
  36. echo "Arch: $(arch)"
  37. # Non-interactive mode: triggered explicitly via XUI_NONINTERACTIVE=1, or
  38. # implicitly when stdin is not a TTY (e.g. `curl ... | bash`, cloud-init).
  39. # In this mode every prompt below is replaced by an env var or a sane default.
  40. if [[ "${XUI_NONINTERACTIVE:-0}" == "1" ]] || [[ ! -t 0 ]]; then
  41. NONINTERACTIVE=1
  42. else
  43. NONINTERACTIVE=0
  44. fi
  45. export NONINTERACTIVE
  46. # Simple helpers
  47. is_ipv4() {
  48. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  49. }
  50. is_ipv6() {
  51. [[ "$1" =~ : ]] && return 0 || return 1
  52. }
  53. is_ip() {
  54. is_ipv4 "$1" || is_ipv6 "$1"
  55. }
  56. is_domain() {
  57. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  58. }
  59. # acme.sh's standalone server binds IPv4 by default; --listen-v6 makes it
  60. # v6-only, which breaks HTTP-01 validation when the domain's A record points
  61. # at this host's IPv4 (#4994). Only force IPv6 when the host has no global
  62. # IPv4 address at all.
  63. acme_listen_flag() {
  64. if ip -4 addr show scope global 2> /dev/null | grep -q "inet "; then
  65. echo ""
  66. else
  67. echo "--listen-v6"
  68. fi
  69. }
  70. # Port helpers
  71. is_port_in_use() {
  72. local port="$1"
  73. if command -v ss > /dev/null 2>&1; then
  74. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  75. return
  76. fi
  77. if command -v netstat > /dev/null 2>&1; then
  78. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  79. return
  80. fi
  81. if command -v lsof > /dev/null 2>&1; then
  82. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  83. fi
  84. return 1
  85. }
  86. install_base() {
  87. case "${release}" in
  88. ubuntu | debian | armbian)
  89. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  90. ;;
  91. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  92. dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  93. ;;
  94. centos)
  95. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  96. yum makecache -y && yum install -y cronie curl tar tzdata socat ca-certificates openssl
  97. else
  98. dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
  99. fi
  100. ;;
  101. arch | manjaro | parch)
  102. pacman -Sy --noconfirm cronie curl tar tzdata socat ca-certificates openssl
  103. ;;
  104. opensuse-tumbleweed | opensuse-leap)
  105. zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
  106. ;;
  107. alpine)
  108. apk update && apk add dcron curl tar tzdata socat ca-certificates openssl
  109. ;;
  110. *)
  111. apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
  112. ;;
  113. esac
  114. }
  115. gen_random_string() {
  116. local length="$1"
  117. openssl rand -base64 $((length * 2)) \
  118. | tr -dc 'a-zA-Z0-9' \
  119. | head -c "$length"
  120. }
  121. # prompt_or_default VARNAME "prompt text" "default" [ENV_NAME]
  122. # Interactive: read into VARNAME. Non-interactive: VARNAME = ${ENV_NAME:-default}.
  123. # ENV_NAME defaults to VARNAME when omitted. Keeps every interactive prompt
  124. # string byte-for-byte identical to the original `read -rp`.
  125. prompt_or_default() {
  126. local __var="$1" __prompt="$2" __default="$3" __env="${4:-$1}"
  127. if [[ "$NONINTERACTIVE" == "1" ]]; then
  128. printf -v "$__var" '%s' "${!__env:-$__default}"
  129. else
  130. # shellcheck disable=SC2229
  131. read -rp "$__prompt" "$__var"
  132. fi
  133. }
  134. # write_install_result <user> <pass> <port> <webpath> <scheme> <host> <token> <dbtype>
  135. # Persists a parseable, root-only credentials file consumed by cloud-init/MOTD.
  136. # Values are written with printf '%q' so a pinned password/username containing
  137. # spaces, quotes, $(...) or backticks is shell-escaped and the file stays safely
  138. # source-able (consumers do '. install-result.env'). For the alphanumeric random
  139. # values gen_random_string emits, %q is a no-op. This is a DIFFERENT file from the
  140. # Postgres env file (/etc/default/x-ui).
  141. write_install_result() {
  142. local u="$1" p="$2" port="$3" wbp="$4" scheme="$5" host="$6" token="$7" dbtype="$8"
  143. local result_file="/etc/x-ui/install-result.env"
  144. local url_host="${host:-SERVER_IP_UNKNOWN}"
  145. install -d -m 755 /etc/x-ui 2> /dev/null
  146. local prev_umask
  147. prev_umask=$(umask)
  148. umask 077
  149. if ! {
  150. printf 'XUI_USERNAME=%q\n' "$u"
  151. printf 'XUI_PASSWORD=%q\n' "$p"
  152. printf 'XUI_PANEL_PORT=%q\n' "$port"
  153. printf 'XUI_WEB_BASE_PATH=%q\n' "$wbp"
  154. printf 'XUI_ACCESS_URL=%q\n' "${scheme}://${url_host}:${port}/${wbp}"
  155. printf 'XUI_API_TOKEN=%q\n' "$token"
  156. printf 'XUI_DB_TYPE=%q\n' "$dbtype"
  157. } > "$result_file"; then
  158. umask "$prev_umask"
  159. echo -e "${yellow}Warning: failed to write ${result_file}.${plain}" >&2
  160. return 1
  161. fi
  162. umask "$prev_umask"
  163. chmod 600 "$result_file" 2> /dev/null
  164. chown root:root "$result_file" 2> /dev/null || true
  165. echo -e "${green}Install result written to ${result_file} (mode 600).${plain}"
  166. }
  167. # RHEL-family initdb writes pg_hba.conf host rules with ident auth, which
  168. # compares the OS username against the Postgres role and always rejects the
  169. # randomly generated panel role over TCP (#5806). Prepend password-auth rules
  170. # scoped to the panel database; first match wins, and md5 also accepts
  171. # scram-sha-256-stored verifiers, so this works on every supported distro.
  172. pg_ensure_hba_password_auth() {
  173. local pg_db="$1"
  174. local hba_file
  175. hba_file=$(sudo -u postgres psql -tAc 'SHOW hba_file' 2> /dev/null | tr -d '[:space:]')
  176. [[ -n "${hba_file}" && -f "${hba_file}" ]] || return 0
  177. grep -Eq "^host[[:space:]]+${pg_db}[[:space:]]" "${hba_file}" && return 0
  178. local tmp
  179. tmp=$(mktemp) || return 1
  180. {
  181. echo "# Added by 3x-ui: allow password logins for the panel database."
  182. echo "host ${pg_db} all 127.0.0.1/32 md5"
  183. echo "host ${pg_db} all ::1/128 md5"
  184. cat "${hba_file}"
  185. } > "${tmp}" || {
  186. rm -f "${tmp}"
  187. return 1
  188. }
  189. cat "${tmp}" > "${hba_file}" || {
  190. rm -f "${tmp}"
  191. return 1
  192. }
  193. rm -f "${tmp}"
  194. sudo -u postgres psql -tAc 'SELECT pg_reload_conf()' > /dev/null 2>&1 || true
  195. }
  196. install_postgres_local() {
  197. local pg_user pg_pass
  198. pg_pass=$(gen_random_string 24)
  199. local pg_db="xui"
  200. local pg_host="127.0.0.1"
  201. local pg_port="5432"
  202. case "${release}" in
  203. ubuntu | debian | armbian)
  204. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  205. ;;
  206. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  207. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  208. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  209. ;;
  210. centos)
  211. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  212. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  213. else
  214. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  215. fi
  216. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  217. ;;
  218. arch | manjaro | parch)
  219. pacman -Sy --noconfirm postgresql >&2 || return 1
  220. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  221. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  222. fi
  223. ;;
  224. opensuse-tumbleweed | opensuse-leap)
  225. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  226. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  227. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  228. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  229. fi
  230. ;;
  231. alpine)
  232. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  233. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  234. /etc/init.d/postgresql setup >&2 || return 1
  235. fi
  236. rc-update add postgresql default >&2 2> /dev/null || true
  237. rc-service postgresql start >&2 || return 1
  238. ;;
  239. *)
  240. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  241. return 1
  242. ;;
  243. esac
  244. if [[ "${release}" != "alpine" ]]; then
  245. systemctl enable --now postgresql >&2 || return 1
  246. fi
  247. # Wait briefly for the server to accept connections.
  248. local i
  249. for i in 1 2 3 4 5; do
  250. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  251. sleep 1
  252. done
  253. local existing_owner=""
  254. existing_owner=$(sudo -u postgres psql -tAc \
  255. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  256. | tr -d '[:space:]')
  257. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  258. pg_user="${existing_owner}"
  259. else
  260. pg_user=$(gen_random_string 8)
  261. fi
  262. # Idempotent role/db creation. Identifiers are double-quoted because a
  263. # random username may start with a digit, which Postgres rejects unquoted.
  264. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  265. | grep -q 1 \
  266. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  267. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  268. | grep -q 1 \
  269. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  270. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  271. pg_ensure_hba_password_auth "${pg_db}" \
  272. || echo -e "${yellow}Warning: could not update pg_hba.conf; PostgreSQL may reject the panel's TCP login (ident auth).${plain}" >&2
  273. local pg_pass_enc
  274. 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')
  275. if [[ -n "${PG_CRED_FILE:-}" ]]; then
  276. local prev_umask
  277. prev_umask=$(umask)
  278. umask 077
  279. if ! cat > "${PG_CRED_FILE}" << EOF; then
  280. PG_USER=${pg_user}
  281. PG_PASS=${pg_pass}
  282. PG_HOST=${pg_host}
  283. PG_PORT=${pg_port}
  284. PG_DB=${pg_db}
  285. EOF
  286. umask "${prev_umask}"
  287. echo -e "${red}Failed to write PostgreSQL credentials to ${PG_CRED_FILE}${plain}" >&2
  288. return 1
  289. fi
  290. umask "${prev_umask}"
  291. fi
  292. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  293. return 0
  294. }
  295. ensure_pg_client() {
  296. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  297. return 0
  298. fi
  299. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore) for in-panel backup...${plain}" >&2
  300. case "${release}" in
  301. ubuntu | debian | armbian)
  302. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  303. ;;
  304. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  305. dnf install -y -q postgresql >&2 || return 1
  306. ;;
  307. centos)
  308. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  309. yum install -y postgresql >&2 || return 1
  310. else
  311. dnf install -y -q postgresql >&2 || return 1
  312. fi
  313. ;;
  314. arch | manjaro | parch)
  315. pacman -Sy --noconfirm postgresql >&2 || return 1
  316. ;;
  317. opensuse-tumbleweed | opensuse-leap)
  318. zypper -q install -y postgresql >&2 || return 1
  319. ;;
  320. alpine)
  321. apk add --no-cache postgresql-client >&2 || return 1
  322. ;;
  323. *)
  324. return 1
  325. ;;
  326. esac
  327. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  328. }
  329. install_acme() {
  330. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  331. cd ~ || return 1
  332. curl -s https://get.acme.sh | sh > /dev/null 2>&1
  333. if [ $? -ne 0 ]; then
  334. echo -e "${red}Failed to install acme.sh${plain}"
  335. return 1
  336. else
  337. echo -e "${green}acme.sh installed successfully${plain}"
  338. fi
  339. return 0
  340. }
  341. setup_ssl_certificate() {
  342. local domain="$1"
  343. local server_ip="$2"
  344. local existing_port="$3"
  345. local existing_webBasePath="$4"
  346. echo -e "${green}Setting up SSL certificate...${plain}"
  347. # Check if acme.sh is installed
  348. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  349. install_acme
  350. if [ $? -ne 0 ]; then
  351. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  352. return 1
  353. fi
  354. fi
  355. # Create certificate directory
  356. local certPath="/root/cert/${domain}"
  357. mkdir -p "$certPath"
  358. # Issue certificate
  359. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  360. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  361. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  362. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport 80 --force
  363. if [ $? -ne 0 ]; then
  364. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  365. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  366. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc 2> /dev/null
  367. rm -rf "$certPath" 2> /dev/null
  368. return 1
  369. fi
  370. # Install certificate
  371. ~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  372. --key-file /root/cert/${domain}/privkey.pem \
  373. --fullchain-file /root/cert/${domain}/fullchain.pem \
  374. --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
  375. if [ $? -ne 0 ]; then
  376. echo -e "${yellow}Failed to install certificate${plain}"
  377. return 1
  378. fi
  379. # Enable auto-renew
  380. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  381. # Secure permissions: private key readable only by owner
  382. chmod 600 $certPath/privkey.pem 2> /dev/null
  383. chmod 644 $certPath/fullchain.pem 2> /dev/null
  384. # Set certificate for panel
  385. local webCertFile="/root/cert/${domain}/fullchain.pem"
  386. local webKeyFile="/root/cert/${domain}/privkey.pem"
  387. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  388. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" > /dev/null 2>&1
  389. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  390. return 0
  391. else
  392. echo -e "${yellow}Certificate files not found${plain}"
  393. return 1
  394. fi
  395. }
  396. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  397. # Requires acme.sh and port 80 open for HTTP-01 challenge
  398. setup_ip_certificate() {
  399. local ipv4="$1"
  400. local ipv6="$2" # optional
  401. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  402. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  403. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  404. # Check for acme.sh
  405. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  406. install_acme
  407. if [ $? -ne 0 ]; then
  408. echo -e "${red}Failed to install acme.sh${plain}"
  409. return 1
  410. fi
  411. fi
  412. # Validate IP address
  413. if [[ -z "$ipv4" ]]; then
  414. echo -e "${red}IPv4 address is required${plain}"
  415. return 1
  416. fi
  417. if ! is_ipv4 "$ipv4"; then
  418. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  419. return 1
  420. fi
  421. # Create certificate directory
  422. local certDir="/root/cert/ip"
  423. mkdir -p "$certDir"
  424. # Build domain arguments
  425. local domain_args="-d ${ipv4}"
  426. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  427. domain_args="${domain_args} -d ${ipv6}"
  428. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  429. fi
  430. # Set reload command for auto-renewal (add || true so it doesn't fail during first install)
  431. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  432. # Choose port for HTTP-01 listener (default 80, prompt override)
  433. local WebPort=""
  434. prompt_or_default WebPort "Port to use for ACME HTTP-01 listener (default 80): " "80" XUI_ACME_HTTP_PORT
  435. WebPort="${WebPort:-80}"
  436. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  437. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  438. WebPort=80
  439. fi
  440. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  441. if [[ "${WebPort}" -ne 80 ]]; then
  442. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  443. fi
  444. # Ensure chosen port is available
  445. while true; do
  446. if is_port_in_use "${WebPort}"; then
  447. echo -e "${yellow}Port ${WebPort} is in use.${plain}"
  448. local alt_port=""
  449. if [[ "$NONINTERACTIVE" == "1" ]]; then
  450. echo -e "${red}Port ${WebPort} is busy; cannot proceed in non-interactive mode.${plain}"
  451. return 1
  452. fi
  453. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  454. alt_port="${alt_port// /}"
  455. if [[ -z "${alt_port}" ]]; then
  456. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  457. return 1
  458. fi
  459. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  460. echo -e "${red}Invalid port provided.${plain}"
  461. return 1
  462. fi
  463. WebPort="${alt_port}"
  464. continue
  465. else
  466. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  467. break
  468. fi
  469. done
  470. # Issue certificate with shortlived profile
  471. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  472. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  473. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  474. ~/.acme.sh/acme.sh --issue \
  475. ${domain_args} \
  476. --standalone \
  477. --server letsencrypt \
  478. --certificate-profile shortlived \
  479. --days 6 \
  480. --httpport ${WebPort} \
  481. --force
  482. if [ $? -ne 0 ]; then
  483. echo -e "${red}Failed to issue IP certificate${plain}"
  484. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  485. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  486. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  487. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  488. rm -rf ${certDir} 2> /dev/null
  489. return 1
  490. fi
  491. echo -e "${green}Certificate issued successfully, installing...${plain}"
  492. # Install certificate
  493. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  494. # but the cert files are still installed. We check for files instead of exit code.
  495. ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
  496. --key-file "${certDir}/privkey.pem" \
  497. --fullchain-file "${certDir}/fullchain.pem" \
  498. --reloadcmd "${reloadCmd}" 2>&1 || true
  499. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  500. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  501. echo -e "${red}Certificate files not found after installation${plain}"
  502. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  503. rm -rf ~/.acme.sh/${ipv4} ~/.acme.sh/${ipv4}_ecc 2> /dev/null
  504. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} ~/.acme.sh/${ipv6}_ecc 2> /dev/null
  505. rm -rf ${certDir} 2> /dev/null
  506. return 1
  507. fi
  508. echo -e "${green}Certificate files installed successfully${plain}"
  509. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  510. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  511. # Secure permissions: private key readable only by owner
  512. chmod 600 ${certDir}/privkey.pem 2> /dev/null
  513. chmod 644 ${certDir}/fullchain.pem 2> /dev/null
  514. # Configure panel to use the certificate
  515. echo -e "${green}Setting certificate paths for the panel...${plain}"
  516. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  517. if [ $? -ne 0 ]; then
  518. echo -e "${yellow}Warning: Could not set certificate paths automatically${plain}"
  519. echo -e "${yellow}Certificate files are at:${plain}"
  520. echo -e " Cert: ${certDir}/fullchain.pem"
  521. echo -e " Key: ${certDir}/privkey.pem"
  522. else
  523. echo -e "${green}Certificate paths configured successfully${plain}"
  524. fi
  525. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  526. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  527. echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}"
  528. return 0
  529. }
  530. # Comprehensive manual SSL certificate issuance via acme.sh
  531. ssl_cert_issue() {
  532. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  533. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  534. # check for acme.sh first
  535. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  536. echo "acme.sh could not be found. Installing now..."
  537. cd ~ || return 1
  538. curl -s https://get.acme.sh | sh
  539. if [ $? -ne 0 ]; then
  540. echo -e "${red}Failed to install acme.sh${plain}"
  541. return 1
  542. else
  543. echo -e "${green}acme.sh installed successfully${plain}"
  544. fi
  545. fi
  546. # get the domain here, and we need to verify it
  547. local domain=""
  548. if [[ "$NONINTERACTIVE" == "1" ]]; then
  549. domain="${XUI_DOMAIN// /}"
  550. if [[ -z "$domain" ]] || ! is_domain "$domain"; then
  551. echo -e "${red}XUI_SSL_MODE=domain requires a valid XUI_DOMAIN (got: '${XUI_DOMAIN:-}').${plain}"
  552. return 1
  553. fi
  554. else
  555. while true; do
  556. read -rp "Please enter your domain name: " domain
  557. domain="${domain// /}" # Trim whitespace
  558. if [[ -z "$domain" ]]; then
  559. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  560. continue
  561. fi
  562. if ! is_domain "$domain"; then
  563. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  564. continue
  565. fi
  566. break
  567. done
  568. fi
  569. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  570. SSL_ISSUED_DOMAIN="${domain}"
  571. # detect existing certificate and reuse it only if its files are actually
  572. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  573. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  574. # with no usable cert files, which must not be reused (it produces a 0-byte
  575. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  576. local cert_exists=0
  577. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  578. local acmeCertDir=""
  579. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  580. acmeCertDir=~/.acme.sh/${domain}_ecc
  581. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  582. acmeCertDir=~/.acme.sh/${domain}
  583. fi
  584. if [[ -n "${acmeCertDir}" ]]; then
  585. cert_exists=1
  586. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  587. echo -e "${yellow}Existing certificate found for ${domain}, will reuse it.${plain}"
  588. [[ -n "${certInfo}" ]] && echo "$certInfo"
  589. else
  590. echo -e "${yellow}Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing.${plain}"
  591. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  592. fi
  593. fi
  594. if [[ ${cert_exists} -eq 0 ]]; then
  595. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  596. fi
  597. # create a directory for the certificate
  598. certPath="/root/cert/${domain}"
  599. if [ ! -d "$certPath" ]; then
  600. mkdir -p "$certPath"
  601. else
  602. rm -rf "$certPath"
  603. mkdir -p "$certPath"
  604. fi
  605. # get the port number for the standalone server
  606. local WebPort=80
  607. prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT
  608. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  609. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  610. WebPort=80
  611. fi
  612. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  613. # Stop panel temporarily
  614. echo -e "${yellow}Stopping panel temporarily...${plain}"
  615. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  616. if [[ ${cert_exists} -eq 0 ]]; then
  617. # issue the certificate
  618. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  619. [[ -n "${XUI_ACME_EMAIL:-}" ]] && ~/.acme.sh/acme.sh --register-account -m "${XUI_ACME_EMAIL}" > /dev/null 2>&1
  620. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  621. if [ $? -ne 0 ]; then
  622. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  623. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  624. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  625. return 1
  626. else
  627. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  628. fi
  629. else
  630. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  631. fi
  632. # Setup reload command
  633. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  634. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  635. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  636. if [[ "$NONINTERACTIVE" == "1" ]]; then
  637. setReloadcmd="n"
  638. else
  639. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  640. fi
  641. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  642. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  643. echo -e "${green}\t2.${plain} Input your own command"
  644. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  645. read -rp "Choose an option: " choice
  646. case "$choice" in
  647. 1)
  648. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  649. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  650. ;;
  651. 2)
  652. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  653. read -rp "Please enter your custom reloadcmd: " reloadCmd
  654. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  655. ;;
  656. *)
  657. echo -e "${green}Keeping default reloadcmd${plain}"
  658. ;;
  659. esac
  660. fi
  661. # install the certificate
  662. local installOutput=""
  663. installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  664. --key-file /root/cert/${domain}/privkey.pem \
  665. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  666. local installRc=$?
  667. echo "${installOutput}"
  668. local installWroteFiles=0
  669. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  670. installWroteFiles=1
  671. fi
  672. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  673. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  674. else
  675. echo -e "${red}Installing certificate failed, exiting.${plain}"
  676. if [[ ${cert_exists} -eq 0 ]]; then
  677. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  678. fi
  679. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  680. return 1
  681. fi
  682. # enable auto-renew
  683. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  684. if [ $? -ne 0 ]; then
  685. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  686. ls -lah /root/cert/${domain}/
  687. # Secure permissions: private key readable only by owner
  688. chmod 600 $certPath/privkey.pem 2> /dev/null
  689. chmod 644 $certPath/fullchain.pem 2> /dev/null
  690. else
  691. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  692. ls -lah /root/cert/${domain}/
  693. # Secure permissions: private key readable only by owner
  694. chmod 600 $certPath/privkey.pem 2> /dev/null
  695. chmod 644 $certPath/fullchain.pem 2> /dev/null
  696. fi
  697. # start panel
  698. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  699. # Prompt user to set panel paths after successful certificate installation
  700. if [[ "$NONINTERACTIVE" == "1" ]]; then
  701. setPanel="y"
  702. else
  703. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  704. fi
  705. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  706. local webCertFile="/root/cert/${domain}/fullchain.pem"
  707. local webKeyFile="/root/cert/${domain}/privkey.pem"
  708. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  709. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  710. echo -e "${green}Certificate paths set for the panel${plain}"
  711. echo -e "${green}Certificate File: $webCertFile${plain}"
  712. echo -e "${green}Private Key File: $webKeyFile${plain}"
  713. echo ""
  714. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  715. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  716. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  717. else
  718. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  719. fi
  720. else
  721. echo -e "${yellow}Skipping panel path setting.${plain}"
  722. fi
  723. return 0
  724. }
  725. # Reusable interactive SSL setup (domain or IP)
  726. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  727. prompt_and_setup_ssl() {
  728. local panel_port="$1"
  729. local web_base_path="$2"
  730. local server_ip="$3"
  731. local ssl_choice=""
  732. SSL_SCHEME="https"
  733. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  734. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  735. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  736. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  737. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  738. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  739. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  740. if [[ "$NONINTERACTIVE" == "1" ]]; then
  741. case "${XUI_SSL_MODE:-none}" in
  742. domain) ssl_choice="1" ;;
  743. ip) ssl_choice="2" ;;
  744. none | "") ssl_choice="4" ;;
  745. *)
  746. echo -e "${yellow}Unknown XUI_SSL_MODE='${XUI_SSL_MODE}', defaulting to none (HTTP).${plain}"
  747. ssl_choice="4"
  748. ;;
  749. esac
  750. else
  751. read -rp "Choose an option (default 2 for IP): " ssl_choice
  752. ssl_choice="${ssl_choice// /}" # Trim whitespace
  753. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  754. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  755. ssl_choice="2"
  756. fi
  757. fi
  758. case "$ssl_choice" in
  759. 1)
  760. # User chose Let's Encrypt domain option
  761. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  762. if ssl_cert_issue; then
  763. local cert_domain="${SSL_ISSUED_DOMAIN}"
  764. if [[ -z "${cert_domain}" ]]; then
  765. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  766. fi
  767. if [[ -n "${cert_domain}" ]]; then
  768. SSL_HOST="${cert_domain}"
  769. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  770. else
  771. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  772. SSL_HOST="${server_ip}"
  773. fi
  774. else
  775. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  776. SSL_HOST="${server_ip}"
  777. fi
  778. ;;
  779. 2)
  780. # User chose Let's Encrypt IP certificate option
  781. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  782. # Ask for optional IPv6
  783. local ipv6_addr=""
  784. prompt_or_default ipv6_addr "Do you have an IPv6 address to include? (leave empty to skip): " "" XUI_SSL_IPV6
  785. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  786. # Stop panel if running (port 80 needed)
  787. if [[ $release == "alpine" ]]; then
  788. rc-service x-ui stop > /dev/null 2>&1
  789. else
  790. systemctl stop x-ui > /dev/null 2>&1
  791. fi
  792. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  793. if [ $? -eq 0 ]; then
  794. SSL_HOST="${server_ip}"
  795. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  796. else
  797. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  798. SSL_HOST="${server_ip}"
  799. fi
  800. ;;
  801. 3)
  802. # User chose Custom Paths (User Provided) option
  803. echo -e "${green}Using custom existing certificate...${plain}"
  804. local custom_cert=""
  805. local custom_key=""
  806. local custom_domain=""
  807. # 3.1 Request Domain to compose Panel URL later
  808. read -rp "Please enter domain name certificate issued for: " custom_domain
  809. custom_domain="${custom_domain// /}" # Remove spaces
  810. # 3.2 Loop for Certificate Path
  811. while true; do
  812. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  813. # Strip quotes if present
  814. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  815. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  816. break
  817. elif [[ ! -f "$custom_cert" ]]; then
  818. echo -e "${red}Error: File does not exist! Try again.${plain}"
  819. elif [[ ! -r "$custom_cert" ]]; then
  820. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  821. else
  822. echo -e "${red}Error: File is empty!${plain}"
  823. fi
  824. done
  825. # 3.3 Loop for Private Key Path
  826. while true; do
  827. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  828. # Strip quotes if present
  829. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  830. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  831. break
  832. elif [[ ! -f "$custom_key" ]]; then
  833. echo -e "${red}Error: File does not exist! Try again.${plain}"
  834. elif [[ ! -r "$custom_key" ]]; then
  835. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  836. else
  837. echo -e "${red}Error: File is empty!${plain}"
  838. fi
  839. done
  840. # 3.4 Apply Settings via x-ui binary
  841. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  842. # Set SSL_HOST for composing Panel URL
  843. if [[ -n "$custom_domain" ]]; then
  844. SSL_HOST="$custom_domain"
  845. else
  846. SSL_HOST="${server_ip}"
  847. fi
  848. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  849. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  850. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  851. ;;
  852. 4)
  853. echo ""
  854. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  855. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  856. echo -e "${yellow}Only safe when:${plain}"
  857. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  858. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  859. echo ""
  860. SSL_SCHEME="http"
  861. SSL_HOST="${server_ip}"
  862. local bind_local=""
  863. if [[ "$NONINTERACTIVE" == "1" ]]; then
  864. # Cloud images must stay reachable on their public interface.
  865. bind_local="n"
  866. else
  867. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  868. fi
  869. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  870. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  871. SSL_HOST="127.0.0.1"
  872. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  873. echo ""
  874. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  875. echo -e " Standard SSH command:"
  876. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  877. echo -e " If using an SSH key:"
  878. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  879. echo -e " Then open in your browser:"
  880. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  881. echo ""
  882. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  883. else
  884. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  885. fi
  886. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  887. echo -e "${green}✓ SSL setup skipped.${plain}"
  888. ;;
  889. *)
  890. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  891. SSL_HOST="${server_ip}"
  892. ;;
  893. esac
  894. }
  895. config_after_install() {
  896. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  897. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  898. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  899. # Properly detect empty cert by checking if cert: line exists and has content after it
  900. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  901. local URL_lists=(
  902. "https://api4.ipify.org"
  903. "https://ipv4.icanhazip.com"
  904. "https://v4.api.ipinfo.io/ip"
  905. "https://ipv4.myexternalip.com/raw"
  906. "https://4.ident.me"
  907. "https://check-host.net/ip"
  908. )
  909. local server_ip=""
  910. for ip_address in "${URL_lists[@]}"; do
  911. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  912. local http_code=$(echo "$response" | tail -n1)
  913. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  914. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  915. server_ip="${ip_result}"
  916. break
  917. fi
  918. done
  919. if [[ -z "$server_ip" ]]; then
  920. if [[ "$NONINTERACTIVE" == "1" ]]; then
  921. # Panel binds 0.0.0.0 regardless; the IP is only used to compose the
  922. # displayed access URL. Fall back to XUI_SERVER_IP or leave blank.
  923. server_ip="${XUI_SERVER_IP:-}"
  924. else
  925. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  926. while [[ -z "$server_ip" ]]; do
  927. read -rp "Please enter your server's public IPv4 address: " server_ip
  928. server_ip="${server_ip// /}"
  929. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  930. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  931. server_ip=""
  932. fi
  933. done
  934. fi
  935. fi
  936. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  937. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  938. local config_webBasePath="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
  939. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  940. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  941. local config_port=""
  942. local db_label="SQLite (/etc/x-ui/x-ui.db)"
  943. echo ""
  944. echo -e "${green}═══════════════════════════════════════════${plain}"
  945. echo -e "${green} Database Selection ${plain}"
  946. echo -e "${green}═══════════════════════════════════════════${plain}"
  947. echo -e " 1) SQLite (default — recommended for < 500 clients)"
  948. echo -e " 2) PostgreSQL (recommended for high client counts / many nodes)"
  949. if [[ "$NONINTERACTIVE" == "1" ]]; then
  950. if [[ "${XUI_DB_TYPE:-sqlite}" == "postgres" ]]; then
  951. db_choice="2"
  952. else
  953. db_choice="1"
  954. fi
  955. else
  956. read -rp "Choose [1]: " db_choice
  957. db_choice="${db_choice:-1}"
  958. fi
  959. if [[ "$db_choice" == "2" ]]; then
  960. local xui_env_file
  961. case "${release}" in
  962. ubuntu | debian | armbian)
  963. xui_env_file="/etc/default/x-ui"
  964. ;;
  965. arch | manjaro | parch | alpine)
  966. xui_env_file="/etc/conf.d/x-ui"
  967. ;;
  968. *)
  969. xui_env_file="/etc/sysconfig/x-ui"
  970. ;;
  971. esac
  972. local xui_dsn=""
  973. local pg_mode=""
  974. local pg_local_installed=0
  975. while [[ -z "$xui_dsn" ]]; do
  976. if [[ "$NONINTERACTIVE" == "1" ]]; then
  977. if [[ -n "${XUI_DB_DSN:-}" ]]; then
  978. xui_dsn="${XUI_DB_DSN}"
  979. db_label="PostgreSQL (external)"
  980. break
  981. fi
  982. echo -e "${yellow}Installing PostgreSQL locally (non-interactive)...${plain}"
  983. local pg_cred_file
  984. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  985. if [[ -n "${pg_cred_file}" ]] && xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  986. pg_local_installed=1
  987. if [[ -r "${pg_cred_file}" ]]; then
  988. # shellcheck disable=SC1090
  989. source "${pg_cred_file}"
  990. fi
  991. rm -f "${pg_cred_file}"
  992. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  993. break
  994. fi
  995. rm -f "${pg_cred_file}"
  996. echo -e "${red}PostgreSQL installation failed in non-interactive mode; aborting.${plain}"
  997. echo -e "${yellow}Set XUI_DB_DSN to use an existing server, or XUI_DB_TYPE=sqlite.${plain}"
  998. exit 1
  999. fi
  1000. echo ""
  1001. echo -e " 1) Install PostgreSQL locally and create a dedicated user/db (recommended)"
  1002. echo -e " 2) Use an existing PostgreSQL server (enter DSN)"
  1003. read -rp "Choose [1]: " pg_mode
  1004. pg_mode="${pg_mode:-1}"
  1005. if [[ "$pg_mode" == "2" ]]; then
  1006. while [[ -z "$xui_dsn" ]]; do
  1007. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " xui_dsn
  1008. xui_dsn="${xui_dsn// /}"
  1009. done
  1010. db_label="PostgreSQL (external)"
  1011. else
  1012. echo -e "${yellow}Installing PostgreSQL — this may take a moment...${plain}"
  1013. local pg_cred_file
  1014. pg_cred_file=$(mktemp 2> /dev/null) || pg_cred_file=$(mktemp -t x-ui-pg-creds.XXXXXXXX)
  1015. if [[ -z "${pg_cred_file}" ]]; then
  1016. echo -e "${red}Failed to create temporary credentials file.${plain}"
  1017. xui_dsn=""
  1018. continue
  1019. fi
  1020. if xui_dsn=$(PG_CRED_FILE="${pg_cred_file}" install_postgres_local); then
  1021. pg_local_installed=1
  1022. if [[ -r "${pg_cred_file}" ]]; then
  1023. # shellcheck disable=SC1090
  1024. source "${pg_cred_file}"
  1025. fi
  1026. rm -f "${pg_cred_file}"
  1027. db_label="PostgreSQL (${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB})"
  1028. else
  1029. rm -f "${pg_cred_file}"
  1030. echo ""
  1031. echo -e "${red}PostgreSQL installation failed.${plain}"
  1032. echo -e " 1) Retry local install"
  1033. echo -e " 2) Enter an external DSN instead"
  1034. echo -e " 3) Abort install"
  1035. echo -e " 4) Fall back to SQLite"
  1036. read -rp "Choose [1]: " pg_fail
  1037. pg_fail="${pg_fail:-1}"
  1038. case "$pg_fail" in
  1039. 2) pg_mode="2" ;;
  1040. 3)
  1041. echo -e "${red}Install aborted.${plain}"
  1042. exit 1
  1043. ;;
  1044. 4)
  1045. db_choice="1"
  1046. xui_dsn=""
  1047. break
  1048. ;;
  1049. *) xui_dsn="" ;;
  1050. esac
  1051. fi
  1052. fi
  1053. done
  1054. if [[ -n "$xui_dsn" ]]; then
  1055. install -d -m 755 "$(dirname "$xui_env_file")"
  1056. umask 077
  1057. cat > "$xui_env_file" << EOF
  1058. XUI_DB_TYPE=postgres
  1059. XUI_DB_DSN=${xui_dsn}
  1060. EOF
  1061. chmod 600 "$xui_env_file"
  1062. umask 022
  1063. export XUI_DB_TYPE=postgres
  1064. export XUI_DB_DSN="${xui_dsn}"
  1065. 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}"
  1066. fi
  1067. fi
  1068. if [[ "$NONINTERACTIVE" == "1" ]]; then
  1069. if [[ -n "${XUI_PANEL_PORT:-}" ]]; then
  1070. config_port="${XUI_PANEL_PORT}"
  1071. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1072. else
  1073. config_port=$(shuf -i 1024-62000 -n 1)
  1074. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1075. fi
  1076. else
  1077. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  1078. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  1079. read -rp "Please set up the panel port: " config_port
  1080. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  1081. else
  1082. config_port=$(shuf -i 1024-62000 -n 1)
  1083. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  1084. fi
  1085. fi
  1086. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  1087. echo ""
  1088. echo -e "${green}═══════════════════════════════════════════${plain}"
  1089. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1090. echo -e "${green}═══════════════════════════════════════════${plain}"
  1091. echo -e "${yellow}SSL is strongly recommended. Skip only if a reverse proxy${plain}"
  1092. echo -e "${yellow}or SSH tunnel handles TLS for you.${plain}"
  1093. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1094. echo ""
  1095. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  1096. # Retrieve the API token for display
  1097. local config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1098. # Display final credentials and access information
  1099. echo ""
  1100. echo -e "${green}═══════════════════════════════════════════${plain}"
  1101. echo -e "${green} Panel Installation Complete! ${plain}"
  1102. echo -e "${green}═══════════════════════════════════════════${plain}"
  1103. echo -e "${green}Username: ${config_username}${plain}"
  1104. echo -e "${green}Password: ${config_password}${plain}"
  1105. echo -e "${green}Port: ${config_port}${plain}"
  1106. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  1107. echo -e "${green}Database: ${db_label}${plain}"
  1108. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  1109. echo -e "${green}API Token: ${config_apiToken}${plain}"
  1110. echo -e "${green}═══════════════════════════════════════════${plain}"
  1111. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  1112. if [[ "$SSL_SCHEME" == "https" ]]; then
  1113. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  1114. else
  1115. echo -e "${yellow}⚠ SSL Certificate: Skipped — panel is HTTP-only. Use a reverse proxy or SSH tunnel.${plain}"
  1116. fi
  1117. if [[ "$db_choice" == "2" ]]; then
  1118. echo ""
  1119. echo -e "${green}PostgreSQL backup & restore is built into the panel:${plain}"
  1120. echo -e " ${blue}${SSL_SCHEME}://${SSL_HOST}:${config_port}/${config_webBasePath}${plain} → Backup & Restore"
  1121. echo -e "${yellow} Back Up downloads a pg_dump .dump file; Restore reloads it via pg_restore.${plain}"
  1122. fi
  1123. if [[ "$db_choice" == "2" && "$pg_local_installed" == "1" ]]; then
  1124. echo ""
  1125. echo -e "${green}═══════════════════════════════════════════${plain}"
  1126. echo -e "${green} PostgreSQL Credentials ${plain}"
  1127. echo -e "${green}═══════════════════════════════════════════${plain}"
  1128. echo -e "${green}DB Name: ${PG_DB}${plain}"
  1129. echo -e "${green}Username: ${PG_USER}${plain}"
  1130. echo -e "${green}Password: ${PG_PASS}${plain}"
  1131. echo -e "${green}Host: ${PG_HOST}${plain}"
  1132. echo -e "${green}Port: ${PG_PORT}${plain}"
  1133. echo -e "${green}DSN: ${xui_dsn}${plain}"
  1134. echo -e "${green}Env file: ${xui_env_file}${plain}"
  1135. echo -e "${green}-------------------------------------------${plain}"
  1136. echo -e "${green}Connect from this server:${plain}"
  1137. echo -e " ${blue}sudo -u postgres psql -d ${PG_DB}${plain} (as the postgres superuser)"
  1138. echo -e " ${blue}PGPASSWORD='${PG_PASS}' psql -h ${PG_HOST} -p ${PG_PORT} -U ${PG_USER} -d ${PG_DB}${plain}"
  1139. echo -e "${green}═══════════════════════════════════════════${plain}"
  1140. echo -e "${yellow}⚠ The panel reads these credentials from ${xui_env_file}.${plain}"
  1141. echo -e "${yellow}⚠ Save the password — it is not stored anywhere else in plain text.${plain}"
  1142. unset PG_USER PG_PASS PG_HOST PG_PORT PG_DB
  1143. fi
  1144. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1145. : "${SSL_SCHEME:=https}"
  1146. : "${SSL_HOST:=${server_ip}}"
  1147. local db_type_out="sqlite"
  1148. [[ "$db_choice" == "2" ]] && db_type_out="postgres"
  1149. write_install_result "${config_username}" "${config_password}" "${config_port}" \
  1150. "${config_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${db_type_out}"
  1151. else
  1152. local config_webBasePath=$(gen_random_string 18)
  1153. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  1154. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  1155. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  1156. # If the panel is already installed but no certificate is configured, prompt for SSL now
  1157. if [[ -z "${existing_cert}" ]]; then
  1158. echo ""
  1159. echo -e "${green}═══════════════════════════════════════════${plain}"
  1160. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1161. echo -e "${green}═══════════════════════════════════════════${plain}"
  1162. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1163. echo ""
  1164. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  1165. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  1166. else
  1167. # If a cert already exists, just show the access URL
  1168. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  1169. fi
  1170. fi
  1171. else
  1172. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  1173. local config_username="${XUI_USERNAME:-$(gen_random_string 10)}"
  1174. local config_password="${XUI_PASSWORD:-$(gen_random_string 10)}"
  1175. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  1176. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  1177. echo -e "Generated new random login credentials:"
  1178. echo -e "###############################################"
  1179. echo -e "${green}Username: ${config_username}${plain}"
  1180. echo -e "${green}Password: ${config_password}${plain}"
  1181. echo -e "###############################################"
  1182. # Persist a machine-parseable credentials file for cloud-init / MOTD.
  1183. local config_apiToken
  1184. config_apiToken=$(${xui_folder}/x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}')
  1185. : "${SSL_SCHEME:=https}"
  1186. : "${SSL_HOST:=${server_ip}}"
  1187. write_install_result "${config_username}" "${config_password}" "${existing_port}" \
  1188. "${existing_webBasePath}" "${SSL_SCHEME}" "${SSL_HOST}" "${config_apiToken}" "${XUI_DB_TYPE:-sqlite}"
  1189. else
  1190. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  1191. fi
  1192. # Existing install: if no cert configured, prompt user for SSL setup
  1193. # Properly detect empty cert by checking if cert: line exists and has content after it
  1194. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1195. if [[ -z "$existing_cert" ]]; then
  1196. echo ""
  1197. echo -e "${green}═══════════════════════════════════════════${plain}"
  1198. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  1199. echo -e "${green}═══════════════════════════════════════════${plain}"
  1200. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  1201. echo ""
  1202. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  1203. echo -e "${green}Access URL: ${SSL_SCHEME}://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  1204. else
  1205. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  1206. fi
  1207. fi
  1208. ${xui_folder}/x-ui migrate
  1209. }
  1210. # setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
  1211. # by invoking the freshly installed x-ui CLI. IP Limit is load-bearing on
  1212. # fail2ban (without it the panel disables the limitIp field and zeroes existing
  1213. # limits), so a fresh install should make it work out of the box, just like the
  1214. # Docker image already does. Non-fatal by design: a fail2ban failure must never
  1215. # abort the panel install.
  1216. setup_fail2ban() {
  1217. if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
  1218. echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
  1219. return 0
  1220. fi
  1221. if [[ ! -x /usr/bin/x-ui ]]; then
  1222. echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
  1223. return 0
  1224. fi
  1225. echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
  1226. if /usr/bin/x-ui setup-fail2ban; then
  1227. echo -e "${green}Fail2ban setup complete.${plain}"
  1228. else
  1229. 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}"
  1230. fi
  1231. return 0
  1232. }
  1233. # Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
  1234. # atomic mv, so a failed cp/curl or an interrupted mv never leaves a
  1235. # truncated unit file at the live path -- systemd would then fail to parse
  1236. # it on the next daemon-reload/start. Same pattern already used for
  1237. # /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
  1238. # file already extracted from the release tarball) vs curl (GitHub fallback).
  1239. _install_xui_service_unit() {
  1240. local source="$1"
  1241. local source_is_url="$2"
  1242. local dest="${xui_service}/x-ui.service"
  1243. local temp_file="${dest}.tmp.$$"
  1244. rm -f "$temp_file"
  1245. if [[ "$source_is_url" == "true" ]]; then
  1246. curl -fLRo "$temp_file" "$source" > /dev/null 2>&1
  1247. else
  1248. cp -f "$source" "$temp_file" > /dev/null 2>&1
  1249. fi
  1250. if [[ $? -ne 0 ]]; then
  1251. rm -f "$temp_file"
  1252. return 1
  1253. fi
  1254. if [[ ! -s "$temp_file" ]]; then
  1255. rm -f "$temp_file"
  1256. return 1
  1257. fi
  1258. mv -f "$temp_file" "$dest"
  1259. if [[ $? -ne 0 ]]; then
  1260. rm -f "$temp_file"
  1261. return 1
  1262. fi
  1263. return 0
  1264. }
  1265. install_x-ui() {
  1266. cd ${xui_folder%/x-ui}/
  1267. # Download resources
  1268. if [ $# == 0 ]; then
  1269. tag_version=$(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/')
  1270. if [[ ! -n "$tag_version" ]]; then
  1271. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  1272. exit 1
  1273. fi
  1274. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  1275. curl -fLR --retry 5 --retry-delay 3 --connect-timeout 15 --max-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
  1276. if [[ $? -ne 0 ]]; then
  1277. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  1278. exit 1
  1279. fi
  1280. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1281. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1282. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1283. exit 1
  1284. fi
  1285. else
  1286. tag_version=$1
  1287. # The rolling dev channel ships under a fixed, non-semver tag that is
  1288. # force-moved to the latest main commit on every push. Accept `dev` as a
  1289. # convenient alias and skip the numeric floor check for it.
  1290. if [[ "$tag_version" == "dev" || "$tag_version" == "dev-latest" ]]; then
  1291. tag_version="dev-latest"
  1292. echo -e "${yellow}Installing the rolling dev build (tag: dev-latest). This is a per-commit pre-release, not a stable version.${plain}"
  1293. else
  1294. tag_version_numeric=${tag_version#v}
  1295. min_version="2.3.5"
  1296. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  1297. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  1298. exit 1
  1299. fi
  1300. fi
  1301. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  1302. echo -e "Beginning to install x-ui ${tag_version}"
  1303. curl -fLR --retry 5 --retry-delay 3 --connect-timeout 15 --max-time 300 -o ${xui_folder}-linux-$(arch).tar.gz ${url}
  1304. if [[ $? -ne 0 ]]; then
  1305. echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}"
  1306. exit 1
  1307. fi
  1308. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1309. rm ${xui_folder}-linux-$(arch).tar.gz -f
  1310. echo -e "${red}Downloaded x-ui release archive is empty${plain}"
  1311. exit 1
  1312. fi
  1313. fi
  1314. local xui_script_temp="/usr/bin/x-ui-temp.$$"
  1315. rm -f "${xui_script_temp}"
  1316. curl -fLRo "${xui_script_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  1317. if [[ $? -ne 0 ]]; then
  1318. rm -f "${xui_script_temp}"
  1319. echo -e "${red}Failed to download x-ui.sh${plain}"
  1320. exit 1
  1321. fi
  1322. if [[ ! -s "${xui_script_temp}" ]]; then
  1323. rm -f "${xui_script_temp}"
  1324. echo -e "${red}Downloaded x-ui.sh is empty${plain}"
  1325. exit 1
  1326. fi
  1327. # Stop x-ui service and remove old resources
  1328. if [[ -e ${xui_folder}/ ]]; then
  1329. if [[ $release == "alpine" ]]; then
  1330. rc-service x-ui stop
  1331. else
  1332. systemctl stop x-ui
  1333. fi
  1334. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  1335. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  1336. # an inbound port with an outdated secret, silently breaking new clients.
  1337. # The freshly installed panel respawns a clean mtg per inbound on start.
  1338. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  1339. rm ${xui_folder}/ -rf
  1340. fi
  1341. # Extract resources and set permissions
  1342. tar zxvf x-ui-linux-$(arch).tar.gz
  1343. if [[ $? -ne 0 ]]; then
  1344. rm x-ui-linux-$(arch).tar.gz -f
  1345. rm -f "${xui_script_temp}"
  1346. 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}"
  1347. exit 1
  1348. fi
  1349. rm x-ui-linux-$(arch).tar.gz -f
  1350. cd x-ui
  1351. if [[ $? -ne 0 || ! -s x-ui ]]; then
  1352. rm -f "${xui_script_temp}"
  1353. 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}"
  1354. exit 1
  1355. fi
  1356. chmod +x x-ui
  1357. chmod +x x-ui.sh
  1358. # Check the system's architecture and rename the file accordingly
  1359. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  1360. mv bin/xray-linux-$(arch) bin/xray-linux-arm
  1361. chmod +x bin/xray-linux-arm
  1362. if [[ -f bin/mtg-linux-$(arch) ]]; then
  1363. mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
  1364. chmod +x bin/mtg-linux-arm
  1365. fi
  1366. fi
  1367. chmod +x x-ui bin/xray-linux-$(arch)
  1368. if [[ -f bin/mtg-linux-arm ]]; then
  1369. chmod +x bin/mtg-linux-arm
  1370. elif [[ -f bin/mtg-linux-$(arch) ]]; then
  1371. chmod +x bin/mtg-linux-$(arch)
  1372. fi
  1373. # Update x-ui cli and se set permission
  1374. mv -f "${xui_script_temp}" /usr/bin/x-ui
  1375. if [[ $? -ne 0 ]]; then
  1376. rm -f "${xui_script_temp}"
  1377. echo -e "${red}Failed to install x-ui.sh${plain}"
  1378. exit 1
  1379. fi
  1380. chmod +x /usr/bin/x-ui
  1381. mkdir -p /var/log/x-ui
  1382. config_after_install
  1383. # Etckeeper compatibility
  1384. if [ -d "/etc/.git" ]; then
  1385. if [ -f "/etc/.gitignore" ]; then
  1386. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  1387. echo "" >> "/etc/.gitignore"
  1388. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  1389. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  1390. fi
  1391. else
  1392. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  1393. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  1394. fi
  1395. fi
  1396. if [[ $release == "alpine" ]]; then
  1397. xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
  1398. rm -f "${xui_rc_temp}"
  1399. curl -fLRo "${xui_rc_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
  1400. if [[ $? -ne 0 ]]; then
  1401. rm -f "${xui_rc_temp}"
  1402. echo -e "${red}Failed to download x-ui.rc${plain}"
  1403. exit 1
  1404. fi
  1405. if [[ ! -s "${xui_rc_temp}" ]]; then
  1406. rm -f "${xui_rc_temp}"
  1407. echo -e "${red}Downloaded x-ui.rc is empty${plain}"
  1408. exit 1
  1409. fi
  1410. mv -f "${xui_rc_temp}" /etc/init.d/x-ui
  1411. if [[ $? -ne 0 ]]; then
  1412. rm -f "${xui_rc_temp}"
  1413. echo -e "${red}Failed to install x-ui.rc${plain}"
  1414. exit 1
  1415. fi
  1416. chmod +x /etc/init.d/x-ui
  1417. rc-update add x-ui
  1418. rc-service x-ui start
  1419. else
  1420. # Install systemd service file
  1421. service_installed=false
  1422. if [ -f "x-ui.service" ]; then
  1423. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  1424. if _install_xui_service_unit "x-ui.service" "false"; then
  1425. service_installed=true
  1426. fi
  1427. fi
  1428. if [ "$service_installed" = false ]; then
  1429. case "${release}" in
  1430. ubuntu | debian | armbian)
  1431. if [ -f "x-ui.service.debian" ]; then
  1432. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  1433. if _install_xui_service_unit "x-ui.service.debian" "false"; then
  1434. service_installed=true
  1435. fi
  1436. fi
  1437. ;;
  1438. arch | manjaro | parch)
  1439. if [ -f "x-ui.service.arch" ]; then
  1440. echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
  1441. if _install_xui_service_unit "x-ui.service.arch" "false"; then
  1442. service_installed=true
  1443. fi
  1444. fi
  1445. ;;
  1446. *)
  1447. if [ -f "x-ui.service.rhel" ]; then
  1448. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  1449. if _install_xui_service_unit "x-ui.service.rhel" "false"; then
  1450. service_installed=true
  1451. fi
  1452. fi
  1453. ;;
  1454. esac
  1455. fi
  1456. # If service file not found in tar.gz, download from GitHub
  1457. if [ "$service_installed" = false ]; then
  1458. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1459. case "${release}" in
  1460. ubuntu | debian | armbian)
  1461. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian"
  1462. ;;
  1463. arch | manjaro | parch)
  1464. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch"
  1465. ;;
  1466. *)
  1467. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel"
  1468. ;;
  1469. esac
  1470. if ! _install_xui_service_unit "$service_unit_url" "true"; then
  1471. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  1472. exit 1
  1473. fi
  1474. service_installed=true
  1475. fi
  1476. if [ "$service_installed" = true ]; then
  1477. echo -e "${green}Setting up systemd unit...${plain}"
  1478. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1479. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1480. systemctl daemon-reload
  1481. systemctl enable x-ui
  1482. systemctl start x-ui
  1483. else
  1484. echo -e "${red}Failed to install x-ui.service file${plain}"
  1485. exit 1
  1486. fi
  1487. fi
  1488. # IP Limit relies on fail2ban; install + configure it now so the feature
  1489. # works out of the box (no-op when XUI_ENABLE_FAIL2BAN=false). Never fatal.
  1490. setup_fail2ban
  1491. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  1492. echo -e ""
  1493. echo -e "┌───────────────────────────────────────────────────────┐
  1494. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1495. │ │
  1496. │ ${blue}x-ui${plain} - Admin Management Script │
  1497. │ ${blue}x-ui start${plain} - Start │
  1498. │ ${blue}x-ui stop${plain} - Stop │
  1499. │ ${blue}x-ui restart${plain} - Restart │
  1500. │ ${blue}x-ui status${plain} - Current Status │
  1501. │ ${blue}x-ui settings${plain} - Current Settings │
  1502. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1503. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1504. │ ${blue}x-ui log${plain} - Check logs │
  1505. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1506. │ ${blue}x-ui update${plain} - Update │
  1507. │ ${blue}x-ui legacy${plain} - Legacy version │
  1508. │ ${blue}x-ui install${plain} - Install │
  1509. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1510. └───────────────────────────────────────────────────────┘"
  1511. }
  1512. echo -e "${green}Running...${plain}"
  1513. install_base
  1514. install_x-ui $1