update.sh 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  8. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  9. # Don't edit this config
  10. b_source="${BASH_SOURCE[0]}"
  11. while [ -h "$b_source" ]; do
  12. b_dir="$(cd -P "$(dirname "$b_source")" > /dev/null 2>&1 && pwd || pwd -P)"
  13. b_source="$(readlink "$b_source")"
  14. [[ $b_source != /* ]] && b_source="$b_dir/$b_source"
  15. done
  16. cur_dir="$(cd -P "$(dirname "$b_source")" > /dev/null 2>&1 && pwd || pwd -P)"
  17. script_name=$(basename "$0")
  18. # Check command exist function
  19. _command_exists() {
  20. type "$1" &> /dev/null
  21. }
  22. # Fail, log and exit script function
  23. _fail() {
  24. local msg=${1}
  25. echo -e "${red}${msg}${plain}"
  26. exit 2
  27. }
  28. # Records this run's outcome for the panel's web updater to poll, since it
  29. # launches this script detached and has no other way to learn whether it
  30. # finished. Written to a fixed path outside XUI_MAIN_FOLDER so it survives
  31. # the update regardless of what happens to that folder. The EXIT trap below
  32. # covers every exit path in this file, including the bare `exit 1`/`exit 2`
  33. # calls that don't go through _fail.
  34. xui_update_run_id="${XUI_UPDATE_RUN_ID:-0}"
  35. [[ "${xui_update_run_id}" =~ ^[0-9]+$ ]] || xui_update_run_id="0"
  36. xui_update_status_file="${XUI_UPDATE_STATUS_FILE:-/etc/x-ui/update-status.json}"
  37. _write_update_status() {
  38. local state="$1"
  39. local exit_code="$2"
  40. local status_dir
  41. status_dir="$(dirname "${xui_update_status_file}")"
  42. mkdir -p "${status_dir}" > /dev/null 2>&1
  43. local tmp_file="${xui_update_status_file}.tmp.$$"
  44. printf '{"runId":"%s","state":"%s","exitCode":%s,"finishedAt":%s}\n' \
  45. "${xui_update_run_id}" "${state}" "${exit_code}" "$(date +%s)" > "${tmp_file}" 2> /dev/null
  46. mv -f "${tmp_file}" "${xui_update_status_file}" > /dev/null 2>&1
  47. }
  48. _report_update_exit() {
  49. local code=$?
  50. if [[ "${code}" -eq 0 ]]; then
  51. _write_update_status "success" "0"
  52. else
  53. _write_update_status "failed" "${code}"
  54. fi
  55. }
  56. trap _report_update_exit EXIT
  57. trap 'exit 143' TERM
  58. trap 'exit 130' INT
  59. # check root
  60. [[ $EUID -ne 0 ]] && _fail "FATAL ERROR: Please run this script with root privilege."
  61. if _command_exists curl; then
  62. curl_bin=$(which curl)
  63. else
  64. _fail "ERROR: Command 'curl' not found."
  65. fi
  66. # Check OS and set release variable
  67. if [[ -f /etc/os-release ]]; then
  68. source /etc/os-release
  69. release=$ID
  70. elif [[ -f /usr/lib/os-release ]]; then
  71. source /usr/lib/os-release
  72. release=$ID
  73. else
  74. _fail "Failed to check the system OS, please contact the author!"
  75. fi
  76. echo "The OS release is: $release"
  77. arch() {
  78. case "$(uname -m)" in
  79. x86_64 | x64 | amd64) echo 'amd64' ;;
  80. i*86 | x86) echo '386' ;;
  81. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  82. armv7* | armv7 | arm) echo 'armv7' ;;
  83. armv6* | armv6) echo 'armv6' ;;
  84. armv5* | armv5) echo 'armv5' ;;
  85. s390x) echo 's390x' ;;
  86. *) echo -e "${red}Unsupported CPU architecture!${plain}" && rm -f "${cur_dir}/${script_name}" > /dev/null 2>&1 && exit 2 ;;
  87. esac
  88. }
  89. echo "Arch: $(arch)"
  90. # Simple helpers
  91. is_ipv4() {
  92. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  93. }
  94. is_ipv6() {
  95. [[ "$1" =~ : ]] && return 0 || return 1
  96. }
  97. is_ip() {
  98. is_ipv4 "$1" || is_ipv6 "$1"
  99. }
  100. is_domain() {
  101. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  102. }
  103. # acme.sh's standalone server binds IPv4 by default; --listen-v6 makes it
  104. # v6-only, which breaks HTTP-01 validation when the domain's A record points
  105. # at this host's IPv4 (#4994). Only force IPv6 when the host has no global
  106. # IPv4 address at all.
  107. acme_listen_flag() {
  108. if ip -4 addr show scope global 2> /dev/null | grep -q "inet "; then
  109. echo ""
  110. else
  111. echo "--listen-v6"
  112. fi
  113. }
  114. # Port helpers
  115. is_port_in_use() {
  116. local port="$1"
  117. if command -v ss > /dev/null 2>&1; then
  118. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  119. return
  120. fi
  121. if command -v netstat > /dev/null 2>&1; then
  122. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  123. return
  124. fi
  125. if command -v lsof > /dev/null 2>&1; then
  126. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  127. fi
  128. return 1
  129. }
  130. gen_random_string() {
  131. local length="$1"
  132. openssl rand -base64 $((length * 2)) \
  133. | tr -dc 'a-zA-Z0-9' \
  134. | head -c "$length"
  135. }
  136. xui_env_file_path() {
  137. case "${release}" in
  138. ubuntu | debian | armbian)
  139. echo "/etc/default/x-ui"
  140. ;;
  141. arch | manjaro | parch | alpine)
  142. echo "/etc/conf.d/x-ui"
  143. ;;
  144. *)
  145. echo "/etc/sysconfig/x-ui"
  146. ;;
  147. esac
  148. }
  149. load_xui_env() {
  150. local env_file
  151. env_file="$(xui_env_file_path)"
  152. if [[ -r "$env_file" ]]; then
  153. set -a
  154. # shellcheck disable=SC1090
  155. source "$env_file"
  156. set +a
  157. fi
  158. }
  159. install_base() {
  160. echo -e "${green}Updating and install dependency packages...${plain}"
  161. case "${release}" in
  162. ubuntu | debian | armbian)
  163. apt-get update > /dev/null 2>&1 && apt-get install -y -q cron curl tar tzdata socat openssl > /dev/null 2>&1
  164. ;;
  165. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  166. dnf makecache -y > /dev/null 2>&1 && dnf install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
  167. ;;
  168. centos)
  169. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  170. yum -y update > /dev/null 2>&1 && yum install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
  171. else
  172. dnf makecache -y > /dev/null 2>&1 && dnf install -y -q cronie curl tar tzdata socat openssl > /dev/null 2>&1
  173. fi
  174. ;;
  175. arch | manjaro | parch)
  176. pacman -Syu > /dev/null 2>&1 && pacman -Syu --noconfirm cronie curl tar tzdata socat openssl > /dev/null 2>&1
  177. ;;
  178. opensuse-tumbleweed | opensuse-leap)
  179. zypper refresh > /dev/null 2>&1 && zypper -q install -y cron curl tar timezone socat openssl > /dev/null 2>&1
  180. ;;
  181. alpine)
  182. apk update > /dev/null 2>&1 && apk add dcron curl tar tzdata socat openssl > /dev/null 2>&1
  183. ;;
  184. *)
  185. apt-get update > /dev/null 2>&1 && apt install -y -q cron curl tar tzdata socat openssl > /dev/null 2>&1
  186. ;;
  187. esac
  188. }
  189. install_acme() {
  190. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  191. cd ~ || return 1
  192. curl -s https://get.acme.sh | sh > /dev/null 2>&1
  193. if [ $? -ne 0 ]; then
  194. echo -e "${red}Failed to install acme.sh${plain}"
  195. return 1
  196. else
  197. echo -e "${green}acme.sh installed successfully${plain}"
  198. fi
  199. return 0
  200. }
  201. setup_ssl_certificate() {
  202. local domain="$1"
  203. local server_ip="$2"
  204. local existing_port="$3"
  205. local existing_webBasePath="$4"
  206. echo -e "${green}Setting up SSL certificate...${plain}"
  207. # Check if acme.sh is installed
  208. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  209. install_acme
  210. if [ $? -ne 0 ]; then
  211. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  212. return 1
  213. fi
  214. fi
  215. # Create certificate directory
  216. local certPath="/root/cert/${domain}"
  217. mkdir -p "$certPath"
  218. # Issue certificate
  219. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  220. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  221. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  222. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport 80 --force
  223. if [ $? -ne 0 ]; then
  224. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  225. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  226. rm -rf ~/.acme.sh/${domain} 2> /dev/null
  227. rm -rf "$certPath" 2> /dev/null
  228. return 1
  229. fi
  230. # Install certificate
  231. ~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  232. --key-file /root/cert/${domain}/privkey.pem \
  233. --fullchain-file /root/cert/${domain}/fullchain.pem \
  234. --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
  235. if [ $? -ne 0 ]; then
  236. echo -e "${yellow}Failed to install certificate${plain}"
  237. return 1
  238. fi
  239. # Enable auto-renew
  240. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  241. chmod 600 $certPath/privkey.pem 2> /dev/null
  242. chmod 644 $certPath/fullchain.pem 2> /dev/null
  243. # Set certificate for panel
  244. local webCertFile="/root/cert/${domain}/fullchain.pem"
  245. local webKeyFile="/root/cert/${domain}/privkey.pem"
  246. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  247. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" > /dev/null 2>&1
  248. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  249. return 0
  250. else
  251. echo -e "${yellow}Certificate files not found${plain}"
  252. return 1
  253. fi
  254. }
  255. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  256. # Requires acme.sh and port 80 open for HTTP-01 challenge
  257. setup_ip_certificate() {
  258. local ipv4="$1"
  259. local ipv6="$2" # optional
  260. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  261. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  262. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  263. # Check for acme.sh
  264. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  265. install_acme
  266. if [ $? -ne 0 ]; then
  267. echo -e "${red}Failed to install acme.sh${plain}"
  268. return 1
  269. fi
  270. fi
  271. # Validate IP address
  272. if [[ -z "$ipv4" ]]; then
  273. echo -e "${red}IPv4 address is required${plain}"
  274. return 1
  275. fi
  276. if ! is_ipv4 "$ipv4"; then
  277. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  278. return 1
  279. fi
  280. # Create certificate directory
  281. local certDir="/root/cert/ip"
  282. mkdir -p "$certDir"
  283. # Build domain arguments
  284. local domain_args="-d ${ipv4}"
  285. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  286. domain_args="${domain_args} -d ${ipv6}"
  287. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  288. fi
  289. # Set reload command for auto-renewal (add || true so it doesn't fail if service stopped)
  290. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  291. # Choose port for HTTP-01 listener (default 80, prompt override)
  292. local WebPort=""
  293. read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
  294. WebPort="${WebPort:-80}"
  295. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  296. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  297. WebPort=80
  298. fi
  299. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  300. if [[ "${WebPort}" -ne 80 ]]; then
  301. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  302. fi
  303. # Ensure chosen port is available
  304. while true; do
  305. if is_port_in_use "${WebPort}"; then
  306. echo -e "${yellow}Port ${WebPort} is currently in use.${plain}"
  307. local alt_port=""
  308. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  309. alt_port="${alt_port// /}"
  310. if [[ -z "${alt_port}" ]]; then
  311. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  312. return 1
  313. fi
  314. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  315. echo -e "${red}Invalid port provided.${plain}"
  316. return 1
  317. fi
  318. WebPort="${alt_port}"
  319. continue
  320. else
  321. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  322. break
  323. fi
  324. done
  325. # Issue certificate with shortlived profile
  326. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  327. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>&1
  328. ~/.acme.sh/acme.sh --issue \
  329. ${domain_args} \
  330. --standalone \
  331. --server letsencrypt \
  332. --certificate-profile shortlived \
  333. --days 6 \
  334. --httpport ${WebPort} \
  335. --force
  336. if [ $? -ne 0 ]; then
  337. echo -e "${red}Failed to issue IP certificate${plain}"
  338. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  339. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  340. rm -rf ~/.acme.sh/${ipv4} 2> /dev/null
  341. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2> /dev/null
  342. rm -rf ${certDir} 2> /dev/null
  343. return 1
  344. fi
  345. echo -e "${green}Certificate issued successfully, installing...${plain}"
  346. # Install certificate
  347. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  348. # but the cert files are still installed. We check for files instead of exit code.
  349. ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
  350. --key-file "${certDir}/privkey.pem" \
  351. --fullchain-file "${certDir}/fullchain.pem" \
  352. --reloadcmd "${reloadCmd}" 2>&1 || true
  353. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  354. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  355. echo -e "${red}Certificate files not found after installation${plain}"
  356. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  357. rm -rf ~/.acme.sh/${ipv4} 2> /dev/null
  358. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2> /dev/null
  359. rm -rf ${certDir} 2> /dev/null
  360. return 1
  361. fi
  362. echo -e "${green}Certificate files installed successfully${plain}"
  363. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  364. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  365. chmod 600 ${certDir}/privkey.pem 2> /dev/null
  366. chmod 644 ${certDir}/fullchain.pem 2> /dev/null
  367. # Configure panel to use the certificate
  368. echo -e "${green}Setting certificate paths for the panel...${plain}"
  369. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  370. if [ $? -ne 0 ]; then
  371. echo -e "${yellow}Warning: Could not set certificate paths automatically.${plain}"
  372. echo -e "${yellow}You may need to set them manually in the panel settings.${plain}"
  373. echo -e "${yellow}Cert path: ${certDir}/fullchain.pem${plain}"
  374. echo -e "${yellow}Key path: ${certDir}/privkey.pem${plain}"
  375. else
  376. echo -e "${green}Certificate paths set successfully!${plain}"
  377. fi
  378. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  379. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  380. echo -e "${yellow}Panel will automatically restart after each renewal.${plain}"
  381. return 0
  382. }
  383. # Comprehensive manual SSL certificate issuance via acme.sh
  384. ssl_cert_issue() {
  385. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  386. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  387. # check for acme.sh first
  388. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  389. echo "acme.sh could not be found. Installing now..."
  390. cd ~ || return 1
  391. curl -s https://get.acme.sh | sh
  392. if [ $? -ne 0 ]; then
  393. echo -e "${red}Failed to install acme.sh${plain}"
  394. return 1
  395. else
  396. echo -e "${green}acme.sh installed successfully${plain}"
  397. fi
  398. fi
  399. # get the domain here, and we need to verify it
  400. local domain=""
  401. while true; do
  402. read -rp "Please enter your domain name: " domain
  403. domain="${domain// /}" # Trim whitespace
  404. if [[ -z "$domain" ]]; then
  405. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  406. continue
  407. fi
  408. if ! is_domain "$domain"; then
  409. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  410. continue
  411. fi
  412. break
  413. done
  414. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  415. SSL_ISSUED_DOMAIN="${domain}"
  416. # detect existing certificate and reuse it if present
  417. local cert_exists=0
  418. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  419. cert_exists=1
  420. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  421. echo -e "${yellow}Existing certificate found for ${domain}, will reuse it.${plain}"
  422. [[ -n "${certInfo}" ]] && echo "$certInfo"
  423. else
  424. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  425. fi
  426. # create a directory for the certificate
  427. certPath="/root/cert/${domain}"
  428. if [ ! -d "$certPath" ]; then
  429. mkdir -p "$certPath"
  430. else
  431. rm -rf "$certPath"
  432. mkdir -p "$certPath"
  433. fi
  434. # get the port number for the standalone server
  435. local WebPort=80
  436. read -rp "Please choose which port to use (default is 80): " WebPort
  437. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  438. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  439. WebPort=80
  440. fi
  441. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  442. # Stop panel temporarily
  443. echo -e "${yellow}Stopping panel temporarily...${plain}"
  444. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  445. if [[ ${cert_exists} -eq 0 ]]; then
  446. # issue the certificate
  447. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  448. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  449. if [ $? -ne 0 ]; then
  450. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  451. rm -rf ~/.acme.sh/${domain}
  452. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  453. return 1
  454. else
  455. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  456. fi
  457. else
  458. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  459. fi
  460. # Setup reload command
  461. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  462. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  463. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  464. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  465. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  466. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  467. echo -e "${green}\t2.${plain} Input your own command"
  468. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  469. read -rp "Choose an option: " choice
  470. case "$choice" in
  471. 1)
  472. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  473. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  474. ;;
  475. 2)
  476. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  477. read -rp "Please enter your custom reloadcmd: " reloadCmd
  478. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  479. ;;
  480. *)
  481. echo -e "${green}Keeping default reloadcmd${plain}"
  482. ;;
  483. esac
  484. fi
  485. # install the certificate
  486. local installOutput=""
  487. installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  488. --key-file /root/cert/${domain}/privkey.pem \
  489. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  490. local installRc=$?
  491. echo "${installOutput}"
  492. local installWroteFiles=0
  493. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  494. installWroteFiles=1
  495. fi
  496. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  497. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  498. else
  499. echo -e "${red}Installing certificate failed, exiting.${plain}"
  500. if [[ ${cert_exists} -eq 0 ]]; then
  501. rm -rf ~/.acme.sh/${domain}
  502. fi
  503. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  504. return 1
  505. fi
  506. # enable auto-renew
  507. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  508. if [ $? -ne 0 ]; then
  509. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  510. ls -lah /root/cert/${domain}/
  511. chmod 600 $certPath/privkey.pem
  512. chmod 644 $certPath/fullchain.pem
  513. else
  514. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  515. ls -lah /root/cert/${domain}/
  516. chmod 600 $certPath/privkey.pem
  517. chmod 644 $certPath/fullchain.pem
  518. fi
  519. # Restart panel
  520. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  521. # Prompt user to set panel paths after successful certificate installation
  522. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  523. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  524. local webCertFile="/root/cert/${domain}/fullchain.pem"
  525. local webKeyFile="/root/cert/${domain}/privkey.pem"
  526. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  527. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  528. echo -e "${green}Certificate paths set for the panel${plain}"
  529. echo -e "${green}Certificate File: $webCertFile${plain}"
  530. echo -e "${green}Private Key File: $webKeyFile${plain}"
  531. echo ""
  532. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  533. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  534. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  535. else
  536. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  537. fi
  538. else
  539. echo -e "${yellow}Skipping panel path setting.${plain}"
  540. fi
  541. return 0
  542. }
  543. # Unified interactive SSL setup (domain or IP)
  544. # Sets global `SSL_HOST` to the chosen domain/IP
  545. prompt_and_setup_ssl() {
  546. local panel_port="$1"
  547. local web_base_path="$2" # expected without leading slash
  548. local server_ip="$3"
  549. local ssl_choice=""
  550. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  551. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  552. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  553. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  554. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  555. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  556. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  557. read -rp "Choose an option (default 2 for IP): " ssl_choice
  558. ssl_choice="${ssl_choice// /}" # Trim whitespace
  559. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  560. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  561. ssl_choice="2"
  562. fi
  563. case "$ssl_choice" in
  564. 1)
  565. # User chose Let's Encrypt domain option
  566. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  567. if ssl_cert_issue; then
  568. local cert_domain="${SSL_ISSUED_DOMAIN}"
  569. if [[ -z "${cert_domain}" ]]; then
  570. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  571. fi
  572. if [[ -n "${cert_domain}" ]]; then
  573. SSL_HOST="${cert_domain}"
  574. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  575. else
  576. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  577. SSL_HOST="${server_ip}"
  578. fi
  579. else
  580. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  581. SSL_HOST="${server_ip}"
  582. fi
  583. ;;
  584. 2)
  585. # User chose Let's Encrypt IP certificate option
  586. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  587. # Ask for optional IPv6
  588. local ipv6_addr=""
  589. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  590. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  591. # Stop panel if running (port 80 needed)
  592. if [[ $release == "alpine" ]]; then
  593. rc-service x-ui stop > /dev/null 2>&1
  594. else
  595. systemctl stop x-ui > /dev/null 2>&1
  596. fi
  597. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  598. if [ $? -eq 0 ]; then
  599. SSL_HOST="${server_ip}"
  600. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  601. else
  602. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  603. SSL_HOST="${server_ip}"
  604. fi
  605. # Restart panel after SSL is configured (restart applies new cert settings)
  606. if [[ $release == "alpine" ]]; then
  607. rc-service x-ui restart > /dev/null 2>&1
  608. else
  609. systemctl restart x-ui > /dev/null 2>&1
  610. fi
  611. ;;
  612. 3)
  613. # User chose Custom Paths (User Provided) option
  614. echo -e "${green}Using custom existing certificate...${plain}"
  615. local custom_cert=""
  616. local custom_key=""
  617. local custom_domain=""
  618. # 3.1 Request Domain to compose Panel URL later
  619. read -rp "Please enter domain name certificate issued for: " custom_domain
  620. custom_domain="${custom_domain// /}" # Remove spaces
  621. # 3.2 Loop for Certificate Path
  622. while true; do
  623. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  624. # Strip quotes if present
  625. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  626. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  627. break
  628. elif [[ ! -f "$custom_cert" ]]; then
  629. echo -e "${red}Error: File does not exist! Try again.${plain}"
  630. elif [[ ! -r "$custom_cert" ]]; then
  631. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  632. else
  633. echo -e "${red}Error: File is empty!${plain}"
  634. fi
  635. done
  636. # 3.3 Loop for Private Key Path
  637. while true; do
  638. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  639. # Strip quotes if present
  640. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  641. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  642. break
  643. elif [[ ! -f "$custom_key" ]]; then
  644. echo -e "${red}Error: File does not exist! Try again.${plain}"
  645. elif [[ ! -r "$custom_key" ]]; then
  646. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  647. else
  648. echo -e "${red}Error: File is empty!${plain}"
  649. fi
  650. done
  651. # 3.4 Apply Settings via x-ui binary
  652. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  653. # Set SSL_HOST for composing Panel URL
  654. if [[ -n "$custom_domain" ]]; then
  655. SSL_HOST="$custom_domain"
  656. else
  657. SSL_HOST="${server_ip}"
  658. fi
  659. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  660. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  661. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  662. ;;
  663. 4)
  664. echo ""
  665. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  666. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  667. echo -e "${yellow}Only safe when:${plain}"
  668. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  669. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  670. echo ""
  671. SSL_SCHEME="http"
  672. SSL_HOST="${server_ip}"
  673. local bind_local=""
  674. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  675. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  676. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  677. SSL_HOST="127.0.0.1"
  678. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  679. echo ""
  680. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  681. echo -e " Standard SSH command:"
  682. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  683. echo -e " If using an SSH key:"
  684. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  685. echo -e " Then open in your browser:"
  686. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  687. echo ""
  688. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  689. else
  690. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  691. fi
  692. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  693. echo -e "${green}✓ SSL setup skipped.${plain}"
  694. ;;
  695. *)
  696. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  697. SSL_HOST="${server_ip}"
  698. ;;
  699. esac
  700. }
  701. config_after_update() {
  702. local panel_needs_restart=0
  703. echo -e "${yellow}x-ui settings:${plain}"
  704. ${xui_folder}/x-ui setting -show true
  705. ${xui_folder}/x-ui migrate
  706. # Properly detect empty cert by checking if cert: line exists and has content after it
  707. local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2> /dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  708. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  709. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  710. # Get server IP
  711. local URL_lists=(
  712. "https://api4.ipify.org"
  713. "https://ipv4.icanhazip.com"
  714. "https://v4.api.ipinfo.io/ip"
  715. "https://ipv4.myexternalip.com/raw"
  716. "https://4.ident.me"
  717. "https://check-host.net/ip"
  718. )
  719. local server_ip=""
  720. for ip_address in "${URL_lists[@]}"; do
  721. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  722. local http_code=$(echo "$response" | tail -n1)
  723. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  724. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  725. server_ip="${ip_result}"
  726. break
  727. fi
  728. done
  729. if [[ -z "$server_ip" ]]; then
  730. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  731. while [[ -z "$server_ip" ]]; do
  732. read -rp "Please enter your server's public IPv4 address: " server_ip
  733. server_ip="${server_ip// /}"
  734. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  735. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  736. server_ip=""
  737. fi
  738. done
  739. fi
  740. # Handle missing/short webBasePath
  741. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  742. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  743. local config_webBasePath=$(gen_random_string 18)
  744. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  745. existing_webBasePath="${config_webBasePath}"
  746. panel_needs_restart=1
  747. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  748. fi
  749. # Check and prompt for SSL if missing
  750. if [[ -z "$existing_cert" ]]; then
  751. echo ""
  752. echo -e "${red}═══════════════════════════════════════════${plain}"
  753. echo -e "${red} ⚠ NO SSL CERTIFICATE DETECTED ⚠ ${plain}"
  754. echo -e "${red}═══════════════════════════════════════════${plain}"
  755. echo -e "${yellow}For security, SSL certificate is MANDATORY for all panels.${plain}"
  756. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  757. echo ""
  758. # Prompt and setup SSL (domain or IP)
  759. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  760. echo ""
  761. echo -e "${green}═══════════════════════════════════════════${plain}"
  762. echo -e "${green} Panel Access Information ${plain}"
  763. echo -e "${green}═══════════════════════════════════════════${plain}"
  764. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  765. echo -e "${green}═══════════════════════════════════════════${plain}"
  766. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  767. else
  768. echo -e "${green}SSL certificate is already configured${plain}"
  769. # Show access URL with existing certificate
  770. local cert_domain=$(basename "$(dirname "$existing_cert")")
  771. echo ""
  772. echo -e "${green}═══════════════════════════════════════════${plain}"
  773. echo -e "${green} Panel Access Information ${plain}"
  774. echo -e "${green}═══════════════════════════════════════════${plain}"
  775. echo -e "${green}Access URL: https://${cert_domain}:${existing_port}/${existing_webBasePath}${plain}"
  776. echo -e "${green}═══════════════════════════════════════════${plain}"
  777. fi
  778. if [[ "$panel_needs_restart" -eq 1 ]]; then
  779. echo -e "${yellow}Restarting panel to apply the new web base path...${plain}"
  780. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  781. fi
  782. }
  783. # setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
  784. # by invoking the freshly downloaded x-ui CLI. IP Limit is load-bearing on
  785. # fail2ban (without it the panel disables the limitIp field and zeroes existing
  786. # limits), so updating an older install should make it work without a manual
  787. # trip through the IP Limit menu. Non-fatal: a fail2ban failure must never abort
  788. # the update. XUI_ENABLE_FAIL2BAN is honored (load_xui_env exports it from the
  789. # persisted env file, so a deliberate opt-out survives updates).
  790. setup_fail2ban() {
  791. if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
  792. echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
  793. return 0
  794. fi
  795. if [[ ! -x /usr/bin/x-ui ]]; then
  796. echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
  797. return 0
  798. fi
  799. echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
  800. if /usr/bin/x-ui setup-fail2ban; then
  801. echo -e "${green}Fail2ban setup complete.${plain}"
  802. else
  803. echo -e "${yellow}Fail2ban setup did not finish; IP Limit stays disabled until you run 'x-ui' and open the IP Limit menu. Continuing.${plain}"
  804. fi
  805. return 0
  806. }
  807. # Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
  808. # atomic mv, so a failed cp/curl or an interrupted mv never leaves a
  809. # truncated unit file at the live path -- systemd would then fail to parse
  810. # it on the next daemon-reload/start. Same pattern already used for
  811. # /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
  812. # file already extracted from the release tarball) vs curl (GitHub fallback).
  813. _install_xui_service_unit() {
  814. local source="$1"
  815. local source_is_url="$2"
  816. local dest="${xui_service}/x-ui.service"
  817. local temp_file="${dest}.tmp.$$"
  818. rm -f "$temp_file"
  819. if [[ "$source_is_url" == "true" ]]; then
  820. ${curl_bin} -fLRo "$temp_file" "$source" > /dev/null 2>&1
  821. else
  822. cp -f "$source" "$temp_file" > /dev/null 2>&1
  823. fi
  824. if [[ $? -ne 0 ]]; then
  825. rm -f "$temp_file"
  826. return 1
  827. fi
  828. if [[ ! -s "$temp_file" ]]; then
  829. rm -f "$temp_file"
  830. return 1
  831. fi
  832. mv -f "$temp_file" "$dest"
  833. if [[ $? -ne 0 ]]; then
  834. rm -f "$temp_file"
  835. return 1
  836. fi
  837. return 0
  838. }
  839. update_x-ui() {
  840. cd ${xui_folder%/x-ui}/
  841. load_xui_env
  842. if [ -f "${xui_folder}/x-ui" ]; then
  843. current_xui_version=$(${xui_folder}/x-ui -v)
  844. echo -e "${green}Current x-ui version: ${current_xui_version}${plain}"
  845. else
  846. _fail "ERROR: Current x-ui version: unknown"
  847. fi
  848. echo -e "${green}Downloading new x-ui version...${plain}"
  849. # XUI_UPDATE_TAG lets the panel target a specific release tag (e.g. the
  850. # rolling dev-latest pre-release). Empty keeps the default latest-stable flow.
  851. if [[ -n "${XUI_UPDATE_TAG}" ]]; then
  852. tag_version="${XUI_UPDATE_TAG}"
  853. echo -e "${green}Using update tag: ${tag_version}${plain}"
  854. else
  855. tag_version=$(${curl_bin} -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" 2> /dev/null | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  856. if [[ ! -n "$tag_version" ]]; then
  857. _fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
  858. fi
  859. fi
  860. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  861. ${curl_bin} -fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz 2> /dev/null
  862. if [[ $? -ne 0 ]]; then
  863. _fail "ERROR: Failed to download x-ui, please be sure that your server can access GitHub"
  864. fi
  865. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  866. rm ${xui_folder}-linux-$(arch).tar.gz -f > /dev/null 2>&1
  867. _fail "ERROR: Downloaded x-ui release archive is empty, please be sure that your server can access GitHub"
  868. fi
  869. if [[ -e ${xui_folder}/ ]]; then
  870. echo -e "${green}Stopping x-ui...${plain}"
  871. if [[ $release == "alpine" ]]; then
  872. if [ -f "/etc/init.d/x-ui" ]; then
  873. rc-service x-ui stop > /dev/null 2>&1
  874. rc-update del x-ui > /dev/null 2>&1
  875. echo -e "${green}Removing old service unit version...${plain}"
  876. rm -f /etc/init.d/x-ui > /dev/null 2>&1
  877. else
  878. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  879. _fail "ERROR: x-ui service unit not installed."
  880. fi
  881. else
  882. if [ -f "${xui_service}/x-ui.service" ]; then
  883. systemctl stop x-ui > /dev/null 2>&1
  884. systemctl disable x-ui > /dev/null 2>&1
  885. echo -e "${green}Removing old systemd unit version...${plain}"
  886. rm ${xui_service}/x-ui.service -f > /dev/null 2>&1
  887. systemctl daemon-reload > /dev/null 2>&1
  888. else
  889. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  890. _fail "ERROR: x-ui systemd unit not installed."
  891. fi
  892. fi
  893. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  894. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  895. # an inbound port with an outdated secret, silently breaking new clients.
  896. # The new panel respawns a clean mtg per inbound on next start.
  897. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  898. echo -e "${green}Removing old x-ui version...${plain}"
  899. rm ${xui_folder} -f > /dev/null 2>&1
  900. rm ${xui_folder}/x-ui.service -f > /dev/null 2>&1
  901. rm ${xui_folder}/x-ui.service.debian -f > /dev/null 2>&1
  902. rm ${xui_folder}/x-ui.service.arch -f > /dev/null 2>&1
  903. rm ${xui_folder}/x-ui.service.rhel -f > /dev/null 2>&1
  904. rm ${xui_folder}/x-ui -f > /dev/null 2>&1
  905. rm ${xui_folder}/x-ui.sh -f > /dev/null 2>&1
  906. echo -e "${green}Removing old xray version...${plain}"
  907. rm ${xui_folder}/bin/xray-linux-amd64 -f > /dev/null 2>&1
  908. echo -e "${green}Removing old README and LICENSE file...${plain}"
  909. rm ${xui_folder}/bin/README.md -f > /dev/null 2>&1
  910. rm ${xui_folder}/bin/LICENSE -f > /dev/null 2>&1
  911. else
  912. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  913. _fail "ERROR: x-ui not installed."
  914. fi
  915. echo -e "${green}Installing new x-ui version...${plain}"
  916. tar zxvf x-ui-linux-$(arch).tar.gz > /dev/null 2>&1
  917. if [[ $? -ne 0 ]]; then
  918. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  919. _fail "ERROR: Failed to extract the x-ui release archive -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the update again"
  920. fi
  921. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  922. cd x-ui > /dev/null 2>&1
  923. if [[ $? -ne 0 || ! -s x-ui ]]; then
  924. _fail "ERROR: Extracted x-ui archive is missing the x-ui binary -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the update again"
  925. fi
  926. chmod +x x-ui > /dev/null 2>&1
  927. # Check the system's architecture and rename the file accordingly
  928. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  929. mv bin/xray-linux-$(arch) bin/xray-linux-arm > /dev/null 2>&1
  930. chmod +x bin/xray-linux-arm > /dev/null 2>&1
  931. fi
  932. chmod +x x-ui bin/xray-linux-$(arch) > /dev/null 2>&1
  933. echo -e "${green}Downloading and installing x-ui.sh script...${plain}"
  934. local xui_script_temp="/usr/bin/x-ui-temp.$$"
  935. rm -f "${xui_script_temp}"
  936. ${curl_bin} -fLRo "${xui_script_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh > /dev/null 2>&1
  937. if [[ $? -ne 0 ]]; then
  938. rm -f "${xui_script_temp}"
  939. _fail "ERROR: Failed to download x-ui.sh script, please be sure that your server can access GitHub"
  940. fi
  941. if [[ ! -s "${xui_script_temp}" ]]; then
  942. rm -f "${xui_script_temp}"
  943. _fail "ERROR: Downloaded x-ui.sh script is empty, please be sure that your server can access GitHub"
  944. fi
  945. mv -f "${xui_script_temp}" /usr/bin/x-ui
  946. if [[ $? -ne 0 ]]; then
  947. rm -f "${xui_script_temp}"
  948. _fail "ERROR: Failed to install x-ui.sh script"
  949. fi
  950. chmod +x ${xui_folder}/x-ui.sh > /dev/null 2>&1
  951. chmod +x /usr/bin/x-ui > /dev/null 2>&1
  952. mkdir -p /var/log/x-ui > /dev/null 2>&1
  953. echo -e "${green}Changing owner...${plain}"
  954. chown -R root:root ${xui_folder} > /dev/null 2>&1
  955. if [ -f "${xui_folder}/bin/config.json" ]; then
  956. echo -e "${green}Changing on config file permissions...${plain}"
  957. chmod 640 ${xui_folder}/bin/config.json > /dev/null 2>&1
  958. fi
  959. if [[ $release == "alpine" ]]; then
  960. echo -e "${green}Downloading and installing startup unit x-ui.rc...${plain}"
  961. xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
  962. rm -f "${xui_rc_temp}"
  963. ${curl_bin} -fLRo "${xui_rc_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc > /dev/null 2>&1
  964. if [[ $? -ne 0 ]]; then
  965. rm -f "${xui_rc_temp}"
  966. _fail "ERROR: Failed to download startup unit x-ui.rc, please be sure that your server can access GitHub"
  967. fi
  968. if [[ ! -s "${xui_rc_temp}" ]]; then
  969. rm -f "${xui_rc_temp}"
  970. _fail "ERROR: Downloaded startup unit x-ui.rc is empty, please be sure that your server can access GitHub"
  971. fi
  972. mv -f "${xui_rc_temp}" /etc/init.d/x-ui
  973. if [[ $? -ne 0 ]]; then
  974. rm -f "${xui_rc_temp}"
  975. _fail "ERROR: Failed to install startup unit x-ui.rc"
  976. fi
  977. chmod +x /etc/init.d/x-ui > /dev/null 2>&1
  978. chown root:root /etc/init.d/x-ui > /dev/null 2>&1
  979. rc-update add x-ui > /dev/null 2>&1
  980. rc-service x-ui start > /dev/null 2>&1
  981. else
  982. if [ -f "x-ui.service" ]; then
  983. echo -e "${green}Installing systemd unit...${plain}"
  984. if ! _install_xui_service_unit "x-ui.service" "false"; then
  985. echo -e "${red}Failed to copy x-ui.service${plain}"
  986. exit 1
  987. fi
  988. else
  989. service_installed=false
  990. case "${release}" in
  991. ubuntu | debian | armbian)
  992. if [ -f "x-ui.service.debian" ]; then
  993. echo -e "${green}Installing debian-like systemd unit...${plain}"
  994. if _install_xui_service_unit "x-ui.service.debian" "false"; then
  995. service_installed=true
  996. fi
  997. fi
  998. ;;
  999. arch | manjaro | parch)
  1000. if [ -f "x-ui.service.arch" ]; then
  1001. echo -e "${green}Installing arch-like systemd unit...${plain}"
  1002. if _install_xui_service_unit "x-ui.service.arch" "false"; then
  1003. service_installed=true
  1004. fi
  1005. fi
  1006. ;;
  1007. *)
  1008. if [ -f "x-ui.service.rhel" ]; then
  1009. echo -e "${green}Installing rhel-like systemd unit...${plain}"
  1010. if _install_xui_service_unit "x-ui.service.rhel" "false"; then
  1011. service_installed=true
  1012. fi
  1013. fi
  1014. ;;
  1015. esac
  1016. # If service file not found in tar.gz, download from GitHub
  1017. if [ "$service_installed" = false ]; then
  1018. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1019. case "${release}" in
  1020. ubuntu | debian | armbian)
  1021. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian"
  1022. ;;
  1023. arch | manjaro | parch)
  1024. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch"
  1025. ;;
  1026. *)
  1027. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel"
  1028. ;;
  1029. esac
  1030. if ! _install_xui_service_unit "$service_unit_url" "true"; then
  1031. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  1032. exit 1
  1033. fi
  1034. fi
  1035. fi
  1036. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1037. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1038. systemctl daemon-reload > /dev/null 2>&1
  1039. systemctl enable x-ui > /dev/null 2>&1
  1040. systemctl start x-ui > /dev/null 2>&1
  1041. fi
  1042. config_after_update
  1043. # IP Limit relies on fail2ban; install + configure it now so the feature
  1044. # works out of the box on update too (no-op when XUI_ENABLE_FAIL2BAN=false).
  1045. # Never fatal.
  1046. setup_fail2ban
  1047. echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
  1048. echo -e ""
  1049. echo -e "┌───────────────────────────────────────────────────────┐
  1050. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1051. │ │
  1052. │ ${blue}x-ui${plain} - Admin Management Script │
  1053. │ ${blue}x-ui start${plain} - Start │
  1054. │ ${blue}x-ui stop${plain} - Stop │
  1055. │ ${blue}x-ui restart${plain} - Restart │
  1056. │ ${blue}x-ui status${plain} - Current Status │
  1057. │ ${blue}x-ui settings${plain} - Current Settings │
  1058. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1059. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1060. │ ${blue}x-ui log${plain} - Check logs │
  1061. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1062. │ ${blue}x-ui update${plain} - Update │
  1063. │ ${blue}x-ui legacy${plain} - Legacy version │
  1064. │ ${blue}x-ui install${plain} - Install │
  1065. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1066. └───────────────────────────────────────────────────────┘"
  1067. }
  1068. echo -e "${green}Running...${plain}"
  1069. install_base
  1070. update_x-ui $1