install.sh 61 KB

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