install.sh 56 KB

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