install.sh 53 KB

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