1
0

install.sh 57 KB

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