1
0

install.sh 60 KB

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