update.sh 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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 makecache -y > /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 -Sy --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 [[ -z ${WebPort} ]]; then
  438. WebPort=80
  439. elif [[ ! ${WebPort} =~ ^[1-9][0-9]*$ || ${WebPort} -gt 65535 ]]; then
  440. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  441. WebPort=80
  442. fi
  443. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  444. # Stop panel temporarily
  445. echo -e "${yellow}Stopping panel temporarily...${plain}"
  446. systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
  447. if [[ ${cert_exists} -eq 0 ]]; then
  448. # issue the certificate
  449. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  450. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  451. if [ $? -ne 0 ]; then
  452. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  453. rm -rf ~/.acme.sh/${domain}
  454. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  455. return 1
  456. else
  457. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  458. fi
  459. else
  460. echo -e "${green}Using existing certificate, installing certificates...${plain}"
  461. fi
  462. # Setup reload command
  463. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  464. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  465. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  466. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  467. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  468. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  469. echo -e "${green}\t2.${plain} Input your own command"
  470. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  471. read -rp "Choose an option: " choice
  472. case "$choice" in
  473. 1)
  474. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  475. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  476. ;;
  477. 2)
  478. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  479. read -rp "Please enter your custom reloadcmd: " reloadCmd
  480. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  481. ;;
  482. *)
  483. echo -e "${green}Keeping default reloadcmd${plain}"
  484. ;;
  485. esac
  486. fi
  487. # install the certificate
  488. local installOutput=""
  489. installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
  490. --key-file /root/cert/${domain}/privkey.pem \
  491. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  492. local installRc=$?
  493. echo "${installOutput}"
  494. local installWroteFiles=0
  495. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  496. installWroteFiles=1
  497. fi
  498. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  499. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  500. else
  501. echo -e "${red}Installing certificate failed, exiting.${plain}"
  502. if [[ ${cert_exists} -eq 0 ]]; then
  503. rm -rf ~/.acme.sh/${domain}
  504. fi
  505. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  506. return 1
  507. fi
  508. # enable auto-renew
  509. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  510. if [ $? -ne 0 ]; then
  511. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  512. ls -lah /root/cert/${domain}/
  513. chmod 600 $certPath/privkey.pem
  514. chmod 644 $certPath/fullchain.pem
  515. else
  516. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  517. ls -lah /root/cert/${domain}/
  518. chmod 600 $certPath/privkey.pem
  519. chmod 644 $certPath/fullchain.pem
  520. fi
  521. # Restart panel
  522. systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
  523. # Prompt user to set panel paths after successful certificate installation
  524. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  525. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  526. local webCertFile="/root/cert/${domain}/fullchain.pem"
  527. local webKeyFile="/root/cert/${domain}/privkey.pem"
  528. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  529. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  530. echo -e "${green}Certificate paths set for the panel${plain}"
  531. echo -e "${green}Certificate File: $webCertFile${plain}"
  532. echo -e "${green}Private Key File: $webKeyFile${plain}"
  533. echo ""
  534. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  535. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  536. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  537. else
  538. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  539. fi
  540. else
  541. echo -e "${yellow}Skipping panel path setting.${plain}"
  542. fi
  543. return 0
  544. }
  545. # Unified interactive SSL setup (domain or IP)
  546. # Sets global `SSL_HOST` to the chosen domain/IP
  547. prompt_and_setup_ssl() {
  548. local panel_port="$1"
  549. local web_base_path="$2" # expected without leading slash
  550. local server_ip="$3"
  551. local ssl_choice=""
  552. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  553. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  554. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  555. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  556. echo -e "${green}4.${plain} Skip SSL (advanced — behind reverse proxy / SSH tunnel only)"
  557. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  558. echo -e "${blue}Note:${plain} Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel."
  559. read -rp "Choose an option (default 2 for IP): " ssl_choice
  560. ssl_choice="${ssl_choice// /}" # Trim whitespace
  561. # Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
  562. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" && "$ssl_choice" != "4" ]]; then
  563. ssl_choice="2"
  564. fi
  565. case "$ssl_choice" in
  566. 1)
  567. # User chose Let's Encrypt domain option
  568. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  569. if ssl_cert_issue; then
  570. local cert_domain="${SSL_ISSUED_DOMAIN}"
  571. if [[ -z "${cert_domain}" ]]; then
  572. cert_domain=$(~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}')
  573. fi
  574. if [[ -n "${cert_domain}" ]]; then
  575. SSL_HOST="${cert_domain}"
  576. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  577. else
  578. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  579. SSL_HOST="${server_ip}"
  580. fi
  581. else
  582. echo -e "${red}SSL certificate setup failed for domain mode.${plain}"
  583. SSL_HOST="${server_ip}"
  584. fi
  585. ;;
  586. 2)
  587. # User chose Let's Encrypt IP certificate option
  588. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  589. # Confirm the auto-detected IP before issuing for it: with asymmetric
  590. # routing / multi-WAN the echo services can return a transit address.
  591. local ip_confirm=""
  592. read -rp "Is ${server_ip} the correct incoming public IPv4 address for this server? [Default y]: " ip_confirm
  593. if [[ -n "$ip_confirm" && "$ip_confirm" != "y" && "$ip_confirm" != "Y" ]]; then
  594. server_ip=""
  595. while [[ -z "$server_ip" ]]; do
  596. read -rp "Please enter your server's public IPv4 address: " server_ip
  597. server_ip="${server_ip// /}"
  598. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  599. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  600. server_ip=""
  601. fi
  602. done
  603. fi
  604. # Ask for optional IPv6
  605. local ipv6_addr=""
  606. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  607. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  608. # Stop panel if running (port 80 needed)
  609. if [[ $release == "alpine" ]]; then
  610. rc-service x-ui stop > /dev/null 2>&1
  611. else
  612. systemctl stop x-ui > /dev/null 2>&1
  613. fi
  614. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  615. if [ $? -eq 0 ]; then
  616. SSL_HOST="${server_ip}"
  617. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  618. else
  619. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  620. SSL_HOST="${server_ip}"
  621. fi
  622. # Restart panel after SSL is configured (restart applies new cert settings)
  623. if [[ $release == "alpine" ]]; then
  624. rc-service x-ui restart > /dev/null 2>&1
  625. else
  626. systemctl restart x-ui > /dev/null 2>&1
  627. fi
  628. ;;
  629. 3)
  630. # User chose Custom Paths (User Provided) option
  631. echo -e "${green}Using custom existing certificate...${plain}"
  632. local custom_cert=""
  633. local custom_key=""
  634. local custom_domain=""
  635. # 3.1 Request Domain to compose Panel URL later
  636. read -rp "Please enter domain name certificate issued for: " custom_domain
  637. custom_domain="${custom_domain// /}" # Remove spaces
  638. # 3.2 Loop for Certificate Path
  639. while true; do
  640. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  641. # Strip quotes if present
  642. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  643. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  644. break
  645. elif [[ ! -f "$custom_cert" ]]; then
  646. echo -e "${red}Error: File does not exist! Try again.${plain}"
  647. elif [[ ! -r "$custom_cert" ]]; then
  648. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  649. else
  650. echo -e "${red}Error: File is empty!${plain}"
  651. fi
  652. done
  653. # 3.3 Loop for Private Key Path
  654. while true; do
  655. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  656. # Strip quotes if present
  657. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  658. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  659. break
  660. elif [[ ! -f "$custom_key" ]]; then
  661. echo -e "${red}Error: File does not exist! Try again.${plain}"
  662. elif [[ ! -r "$custom_key" ]]; then
  663. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  664. else
  665. echo -e "${red}Error: File is empty!${plain}"
  666. fi
  667. done
  668. # 3.4 Apply Settings via x-ui binary
  669. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" > /dev/null 2>&1
  670. # Set SSL_HOST for composing Panel URL
  671. if [[ -n "$custom_domain" ]]; then
  672. SSL_HOST="$custom_domain"
  673. else
  674. SSL_HOST="${server_ip}"
  675. fi
  676. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  677. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  678. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  679. ;;
  680. 4)
  681. echo ""
  682. echo -e "${red}⚠ Panel will be installed WITHOUT SSL/TLS.${plain}"
  683. echo -e "${yellow}Login credentials and cookies will travel as plain HTTP.${plain}"
  684. echo -e "${yellow}Only safe when:${plain}"
  685. echo -e "${yellow} • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or${plain}"
  686. echo -e "${yellow} • You access the panel exclusively via SSH tunnel${plain}"
  687. echo ""
  688. SSL_SCHEME="http"
  689. SSL_HOST="${server_ip}"
  690. local bind_local=""
  691. read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
  692. if [[ "$bind_local" == "y" || "$bind_local" == "Y" ]]; then
  693. ${xui_folder}/x-ui setting -listenIP "127.0.0.1" > /dev/null 2>&1
  694. SSL_HOST="127.0.0.1"
  695. echo -e "${green}✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet.${plain}"
  696. echo ""
  697. echo -e "${green}SSH Port Forwarding — open the panel from your local machine via:${plain}"
  698. echo -e " Standard SSH command:"
  699. echo -e " ${yellow}ssh -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  700. echo -e " If using an SSH key:"
  701. echo -e " ${yellow}ssh -i <sshkeypath> -L 2222:127.0.0.1:${panel_port} root@${server_ip}${plain}"
  702. echo -e " Then open in your browser:"
  703. echo -e " ${yellow}http://localhost:2222/${web_base_path}${plain}"
  704. echo ""
  705. echo -e "${yellow}Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1:${panel_port} and let it terminate TLS.${plain}"
  706. else
  707. echo -e "${yellow}Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it.${plain}"
  708. fi
  709. systemctl restart x-ui > /dev/null 2>&1 || rc-service x-ui restart > /dev/null 2>&1
  710. echo -e "${green}✓ SSL setup skipped.${plain}"
  711. ;;
  712. *)
  713. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  714. SSL_HOST="${server_ip}"
  715. ;;
  716. esac
  717. }
  718. config_after_update() {
  719. local panel_needs_restart=0
  720. echo -e "${yellow}x-ui settings:${plain}"
  721. ${xui_folder}/x-ui setting -show true
  722. ${xui_folder}/x-ui migrate
  723. # Properly detect empty cert by checking if cert: line exists and has content after it
  724. local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2> /dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  725. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  726. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  727. # Get server IP
  728. local URL_lists=(
  729. "https://api4.ipify.org"
  730. "https://ipv4.icanhazip.com"
  731. "https://v4.api.ipinfo.io/ip"
  732. "https://ipv4.myexternalip.com/raw"
  733. "https://4.ident.me"
  734. "https://check-host.net/ip"
  735. )
  736. local server_ip=""
  737. for ip_address in "${URL_lists[@]}"; do
  738. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  739. local http_code=$(echo "$response" | tail -n1)
  740. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  741. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  742. server_ip="${ip_result}"
  743. break
  744. fi
  745. done
  746. if [[ -z "$server_ip" ]]; then
  747. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  748. while [[ -z "$server_ip" ]]; do
  749. read -rp "Please enter your server's public IPv4 address: " server_ip
  750. server_ip="${server_ip// /}"
  751. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  752. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  753. server_ip=""
  754. fi
  755. done
  756. fi
  757. # Handle missing/short webBasePath
  758. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  759. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  760. local config_webBasePath=$(gen_random_string 18)
  761. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  762. existing_webBasePath="${config_webBasePath}"
  763. panel_needs_restart=1
  764. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  765. fi
  766. # Check and prompt for SSL if missing
  767. if [[ -z "$existing_cert" ]]; then
  768. echo ""
  769. echo -e "${red}═══════════════════════════════════════════${plain}"
  770. echo -e "${red} ⚠ NO SSL CERTIFICATE DETECTED ⚠ ${plain}"
  771. echo -e "${red}═══════════════════════════════════════════${plain}"
  772. echo -e "${yellow}For security, SSL certificate is MANDATORY for all panels.${plain}"
  773. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  774. echo ""
  775. # Prompt and setup SSL (domain or IP)
  776. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  777. echo ""
  778. echo -e "${green}═══════════════════════════════════════════${plain}"
  779. echo -e "${green} Panel Access Information ${plain}"
  780. echo -e "${green}═══════════════════════════════════════════${plain}"
  781. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  782. echo -e "${green}═══════════════════════════════════════════${plain}"
  783. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  784. else
  785. echo -e "${green}SSL certificate is already configured${plain}"
  786. # Show access URL with existing certificate
  787. local cert_domain=$(basename "$(dirname "$existing_cert")")
  788. echo ""
  789. echo -e "${green}═══════════════════════════════════════════${plain}"
  790. echo -e "${green} Panel Access Information ${plain}"
  791. echo -e "${green}═══════════════════════════════════════════${plain}"
  792. echo -e "${green}Access URL: https://${cert_domain}:${existing_port}/${existing_webBasePath}${plain}"
  793. echo -e "${green}═══════════════════════════════════════════${plain}"
  794. fi
  795. if [[ "$panel_needs_restart" -eq 1 ]]; then
  796. echo -e "${yellow}Restarting panel to apply the new web base path...${plain}"
  797. systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
  798. fi
  799. }
  800. # setup_fail2ban auto-installs and configures fail2ban for the IP Limit feature
  801. # by invoking the freshly downloaded x-ui CLI. IP Limit is load-bearing on
  802. # fail2ban (without it the panel disables the limitIp field and zeroes existing
  803. # limits), so updating an older install should make it work without a manual
  804. # trip through the IP Limit menu. Non-fatal: a fail2ban failure must never abort
  805. # the update. XUI_ENABLE_FAIL2BAN is honored (load_xui_env exports it from the
  806. # persisted env file, so a deliberate opt-out survives updates).
  807. setup_fail2ban() {
  808. if [[ -n "${XUI_ENABLE_FAIL2BAN+x}" && "${XUI_ENABLE_FAIL2BAN}" != "true" ]]; then
  809. echo -e "${yellow}XUI_ENABLE_FAIL2BAN=${XUI_ENABLE_FAIL2BAN}, skipping Fail2ban auto-setup.${plain}"
  810. return 0
  811. fi
  812. if [[ ! -x /usr/bin/x-ui ]]; then
  813. echo -e "${yellow}x-ui CLI not found; skipping Fail2ban auto-setup.${plain}"
  814. return 0
  815. fi
  816. # Scripts older than v3.4.0 have no setup-fail2ban and exit 0 from the
  817. # usage banner, which would read as success here.
  818. if ! grep -q '"setup-fail2ban")' /usr/bin/x-ui; then
  819. echo -e "${yellow}This x-ui.sh predates 'x-ui setup-fail2ban'; skipping Fail2ban auto-setup.${plain}"
  820. return 0
  821. fi
  822. echo -e "${green}Setting up Fail2ban for the IP Limit feature...${plain}"
  823. if /usr/bin/x-ui setup-fail2ban; then
  824. echo -e "${green}Fail2ban setup complete.${plain}"
  825. else
  826. 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}"
  827. fi
  828. return 0
  829. }
  830. # The hardened unit makes /usr, /boot, /efi and /etc read-only. The panel's own
  831. # updater is expected to escape that sandbox by running this script through a
  832. # transient systemd-run unit; when systemd-run is unavailable it starts this
  833. # script as a plain child instead, and that child inherits the sandbox and then
  834. # cannot write anything this update needs. Say so once, up front, instead of
  835. # dying partway through with "Failed to download x-ui".
  836. require_writable_update_paths() {
  837. local dir probe
  838. for dir in "${xui_folder%/*}" "/usr/bin"; do
  839. [[ -n "$dir" && -d "$dir" ]] || continue
  840. probe="${dir}/.x-ui-write-test.$$"
  841. # A real write test rather than [[ -w ]]: this runs as root, where a
  842. # permission bit means little and the test only reflects the file mode
  843. # and the mount flags, not an immutable attribute or a full filesystem.
  844. if ! : > "$probe" 2> /dev/null; then
  845. _fail "ERROR: ${dir} is not writable for this process (read-only mount, attribute or full filesystem). The panel's fallback updater cannot run inside the hardened systemd sandbox; update from the panel UI (which uses systemd-run) or run 'x-ui update' in a shell."
  846. fi
  847. rm -f "$probe"
  848. done
  849. }
  850. # Major version of the local systemd, 0 when it cannot be determined. The
  851. # SystemCallFilter=@system-service group only exists from systemd 239 on (other
  852. # @-named groups exist since 231); on older versions an unknown group is not
  853. # ignored safely, the filter stays in force and leaves a whitelist the panel
  854. # cannot run under.
  855. _xui_systemd_major_version() {
  856. local version=""
  857. if command -v systemctl > /dev/null 2>&1; then
  858. version="$(systemctl --version 2>/dev/null | awk 'NR == 1 {print $2}')"
  859. fi
  860. if [[ ! "$version" =~ ^[0-9]+$ ]]; then
  861. echo 0
  862. return 0
  863. fi
  864. echo "$version"
  865. }
  866. # The shipped units list hardening that older systemd does not know: the
  867. # directive is logged and ignored at load time rather than rejected, so the
  868. # panel still starts, only without that protection. Each entry is the systemd
  869. # release that introduced the directive (systemd.exec(5)); everything else in
  870. # the unit predates the oldest systemd install.sh supports (CentOS 7 has 219).
  871. # SystemCallFilter= is listed because the drop-in only writes it from 239 on.
  872. _xui_warn_unsupported_hardening() {
  873. local version entry missing=""
  874. version="$(_xui_systemd_major_version)"
  875. [[ "$version" -gt 0 ]] || return 0
  876. for entry in RestrictRealtime:231 ReadWritePaths:231 ProtectKernelTunables:232 \
  877. ProtectKernelModules:232 RestrictNamespaces:233 LockPersonality:235 \
  878. SystemCallFilter:239 ProtectHostname:242 RestrictSUIDSGID:242 \
  879. ProtectKernelLogs:244 ProtectClock:245; do
  880. if [[ "$version" -lt "${entry##*:}" ]]; then
  881. missing="${missing:+$missing, }${entry%%:*} (${entry##*:})"
  882. fi
  883. done
  884. [[ -n "$missing" ]] || return 0
  885. echo -e "${yellow}Note: systemd ${version} ignores part of the hardening in x-ui.service; the panel still starts.${plain}"
  886. echo " Not applied, needs a newer systemd: ${missing}."
  887. if [[ "$version" -lt 231 ]]; then
  888. echo " The panel's folders stay writable through ReadWriteDirectories=, the alias this script installs."
  889. fi
  890. echo " The rest of the hardening is in force. Upgrade systemd to apply the above."
  891. return 0
  892. }
  893. # ProtectSystem=full makes /usr, /boot, /efi and /etc read-only. ProtectSystem=
  894. # strict would make the whole hierarchy read-only (only the kernel API
  895. # filesystems stay as they are), and that would break the panel's own use of
  896. # /tmp. The panel's stores are configurable (XUI_DB_FOLDER, XUI_LOG_FOLDER,
  897. # XUI_BIN_FOLDER), and XUI_MAIN_FOLDER is the folder install.sh/update.sh place
  898. # the files in -- the unit's WorkingDirectory on a stock install, and what a
  899. # relative XUI_BIN_FOLDER is resolved against. So a hard-coded list in the unit
  900. # either misses a relocated store -- the panel then cannot write its own SQLite
  901. # database and sits in a Restart=on-failure loop -- or forces the operator to
  902. # edit a file that every install/update overwrites from the release tarball.
  903. # install.sh and update.sh therefore regenerate the drop-in from the folders
  904. # actually in use, and the unit's own ReadWritePaths only carry the
  905. # plain-install defaults. A relocated store means re-running install or update:
  906. # the drop-in is only written here.
  907. _xui_service_write_paths_dropin() {
  908. # $1 is the env file to resolve the XUI_* folders from; callers pass nothing
  909. # and get the OS-specific path the unit itself uses.
  910. local env_file="${1:-}"
  911. local dropin_dir dropin temp_file
  912. local db_folder log_folder bin_folder main_folder
  913. local path line="" whitespace_paths="" seen_paths="" escaped_path
  914. if [[ -z "$env_file" ]]; then
  915. env_file="$(xui_env_file_path)"
  916. fi
  917. if [[ -r "$env_file" ]]; then
  918. set -a
  919. # shellcheck disable=SC1090
  920. source "$env_file"
  921. set +a
  922. fi
  923. # XUI_* wins over the script's own default: the unit hands that same env
  924. # file to the panel through EnvironmentFile=, so these are the folders it
  925. # will actually use.
  926. main_folder="${XUI_MAIN_FOLDER:-${xui_folder}}"
  927. db_folder="${XUI_DB_FOLDER:-/etc/x-ui}"
  928. log_folder="${XUI_LOG_FOLDER:-/var/log/x-ui}"
  929. # An empty XUI_BIN_FOLDER resolves to "bin" relative to the panel's working
  930. # directory, which the unit sets to the main folder.
  931. bin_folder="${XUI_BIN_FOLDER:-bin}"
  932. if [[ "$bin_folder" != /* ]]; then
  933. bin_folder="${main_folder%/}/${bin_folder#./}"
  934. fi
  935. for path in "$db_folder" "$log_folder" "$bin_folder" "$main_folder"; do
  936. [[ "$path" == /* ]] || continue
  937. # ReadWritePaths= is a whitespace-separated list, and a folder whose
  938. # name contains whitespace cannot be written into it without relying on
  939. # quoting. A wrong entry makes systemd reject the whole drop-in and the
  940. # panel would not start, so leave such a folder out and say so instead.
  941. if [[ "$path" != "${path//[[:space:]]/}" ]]; then
  942. whitespace_paths="${whitespace_paths:+$whitespace_paths }$path"
  943. continue
  944. fi
  945. case " $seen_paths " in
  946. *" $path "*) continue ;;
  947. esac
  948. seen_paths="${seen_paths}${seen_paths:+ }$path"
  949. # systemd expands %-specifiers in unit files, so a folder name carrying
  950. # a literal % has to be written as %%, or the entry stops naming the
  951. # folder systemd is meant to keep writable.
  952. escaped_path="${path//%/%%}"
  953. line="${line} -${escaped_path}"
  954. done
  955. if [[ -n "$whitespace_paths" ]]; then
  956. echo "Warning: these folders contain whitespace and were left out of" >&2
  957. echo " 10-xui-sandbox.conf: $whitespace_paths" >&2
  958. echo " The panel cannot write to them under the unit's sandbox." >&2
  959. fi
  960. line="${line# }"
  961. [[ -n "$line" ]] || return 1
  962. dropin_dir="${xui_service}/x-ui.service.d"
  963. dropin="${dropin_dir}/10-xui-sandbox.conf"
  964. temp_file="${dropin}.tmp.$$"
  965. mkdir -p "$dropin_dir" || return 1
  966. cat > "$temp_file" << EOF
  967. # Regenerated by install.sh/update.sh on every install and update: edits here
  968. # are lost, and the list only reflects the XUI_* variables read from
  969. # ${env_file} at that moment. Re-run install/update after moving a store.
  970. # It lists the folders the panel writes to. Put local additions in their own
  971. # drop-in, for example 20-x-ui-local.conf, which nothing here touches.
  972. [Service]
  973. ReadWritePaths=${line}
  974. ReadWriteDirectories=${line}
  975. EOF
  976. if [[ "$(_xui_systemd_major_version)" -ge 239 ]]; then
  977. cat >> "$temp_file" << 'EOF'
  978. # @system-service needs systemd >= 239; on older versions the unknown group
  979. # would leave the panel with a filter it cannot start under (x-ui.service.*).
  980. SystemCallFilter=@system-service
  981. SystemCallErrorNumber=EPERM
  982. EOF
  983. fi
  984. if [[ ! -s "$temp_file" ]]; then
  985. rm -f "$temp_file"
  986. return 1
  987. fi
  988. chmod 644 "$temp_file"
  989. mv -f "$temp_file" "$dropin" || { rm -f "$temp_file"; return 1; }
  990. if command -v systemctl > /dev/null 2>&1; then
  991. systemctl daemon-reload > /dev/null 2>&1 || true
  992. fi
  993. return 0
  994. }
  995. # Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
  996. # atomic mv, so a failed cp/curl or an interrupted mv never leaves a
  997. # truncated unit file at the live path -- systemd would then fail to parse
  998. # it on the next daemon-reload/start. Same pattern already used for
  999. # /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
  1000. # file already extracted from the release tarball) vs curl (GitHub fallback).
  1001. _install_xui_service_unit() {
  1002. local source="$1"
  1003. local source_is_url="$2"
  1004. local dest="${xui_service}/x-ui.service"
  1005. local temp_file="${dest}.tmp.$$"
  1006. rm -f "$temp_file"
  1007. if [[ "$source_is_url" == "true" ]]; then
  1008. ${curl_bin} -fLRo "$temp_file" "$source" > /dev/null 2>&1
  1009. else
  1010. cp -f "$source" "$temp_file" > /dev/null 2>&1
  1011. fi
  1012. if [[ $? -ne 0 ]]; then
  1013. rm -f "$temp_file"
  1014. return 1
  1015. fi
  1016. if [[ ! -s "$temp_file" ]]; then
  1017. rm -f "$temp_file"
  1018. return 1
  1019. fi
  1020. mv -f "$temp_file" "$dest"
  1021. if [[ $? -ne 0 ]]; then
  1022. rm -f "$temp_file"
  1023. return 1
  1024. fi
  1025. if ! _xui_service_write_paths_dropin; then
  1026. echo -e "${yellow}Warning: could not refresh ${xui_service}/x-ui.service.d/10-xui-sandbox.conf.${plain}"
  1027. echo -e "${yellow}If XUI_DB_FOLDER or XUI_LOG_FOLDER points outside /etc/x-ui and /var/log/x-ui, the panel may not be able to write to it under ProtectSystem=full.${plain}"
  1028. fi
  1029. _xui_warn_unsupported_hardening
  1030. return 0
  1031. }
  1032. # Older tags predate some of these files (x-ui.rc arrived in v2.8.4). Serving
  1033. # main's copy against an old binary is the mismatch this pinning exists to
  1034. # prevent, so probe before the old install is removed and refuse the tag.
  1035. require_repo_files() {
  1036. local ref="$1" name status
  1037. shift
  1038. [[ "${ref}" == "main" ]] && return 0
  1039. for name in "$@"; do
  1040. status=$(${curl_bin} -sIL --retry 3 --connect-timeout 15 -o /dev/null -w '%{http_code}' "https://raw.githubusercontent.com/MHSanaei/3x-ui/${ref}/${name}")
  1041. if [[ "${status}" != "200" ]]; then
  1042. _fail "ERROR: ${name} is not available for ${ref} (HTTP ${status}). Update to a release that ships it, or to 'dev-latest'. The current installation is untouched."
  1043. fi
  1044. done
  1045. }
  1046. update_x-ui() {
  1047. cd ${xui_folder%/x-ui}/
  1048. load_xui_env
  1049. if [ -f "${xui_folder}/x-ui" ]; then
  1050. current_xui_version=$(${xui_folder}/x-ui -v)
  1051. echo -e "${green}Current x-ui version: ${current_xui_version}${plain}"
  1052. else
  1053. _fail "ERROR: Current x-ui version: unknown"
  1054. fi
  1055. echo -e "${green}Downloading new x-ui version...${plain}"
  1056. # XUI_UPDATE_TAG lets the panel target a specific release tag (e.g. the
  1057. # rolling dev-latest pre-release). Empty keeps the default latest-stable flow.
  1058. if [[ -n "${XUI_UPDATE_TAG}" ]]; then
  1059. tag_version="${XUI_UPDATE_TAG}"
  1060. echo -e "${green}Using update tag: ${tag_version}${plain}"
  1061. else
  1062. 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/')
  1063. if [[ ! -n "$tag_version" ]]; then
  1064. _fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
  1065. fi
  1066. fi
  1067. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  1068. # x-ui.sh, x-ui.rc and the unit files must come from the same release as
  1069. # the binary; only the rolling dev build tracks main.
  1070. script_ref="${tag_version}"
  1071. if [[ "${tag_version}" == "dev-latest" ]]; then
  1072. script_ref="main"
  1073. fi
  1074. # The unit files are only fetched when the release tarball lacks them, so
  1075. # they are checked at that point instead of here.
  1076. local required_files=("x-ui.sh")
  1077. [[ $release == "alpine" ]] && required_files+=("x-ui.rc")
  1078. require_repo_files "${script_ref}" "${required_files[@]}"
  1079. ${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
  1080. if [[ $? -ne 0 ]]; then
  1081. _fail "ERROR: Failed to download x-ui, please be sure that your server can access GitHub"
  1082. fi
  1083. if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
  1084. rm ${xui_folder}-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1085. _fail "ERROR: Downloaded x-ui release archive is empty, please be sure that your server can access GitHub"
  1086. fi
  1087. # Releases publish <asset>.sha256 next to each archive. A mismatch or a
  1088. # failed sidecar download aborts the update; only a 404 (releases
  1089. # predating the sidecar) is tolerated with a warning.
  1090. archive="${xui_folder}-linux-$(arch).tar.gz"
  1091. rm -f "${archive}.sha256"
  1092. sidecar_code=$(${curl_bin} -sL --retry 3 --retry-delay 3 --connect-timeout 15 --max-time 60 -o "${archive}.sha256" -w '%{http_code}' "https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz.sha256" 2> /dev/null)
  1093. if [[ "${sidecar_code}" == "200" ]]; then
  1094. expected_sha256=$(awk 'NR == 1 {print $1}' "${archive}.sha256")
  1095. actual_sha256=$(sha256sum "${archive}" | awk '{print $1}')
  1096. rm -f "${archive}.sha256"
  1097. if [[ ! "${expected_sha256}" =~ ^[0-9a-f]{64}$ || "${expected_sha256}" != "${actual_sha256}" ]]; then
  1098. rm -f "${archive}"
  1099. _fail "ERROR: Checksum mismatch for $(basename "${archive}"): expected ${expected_sha256:-<none>}, got ${actual_sha256}"
  1100. fi
  1101. echo -e "${green}Checksum verified: ${actual_sha256}${plain}"
  1102. elif [[ "${sidecar_code}" == "404" ]]; then
  1103. rm -f "${archive}.sha256"
  1104. echo -e "${yellow}No checksum published for this release, skipping verification${plain}"
  1105. else
  1106. rm -f "${archive}.sha256" "${archive}"
  1107. _fail "ERROR: Failed to download the checksum for x-ui-linux-$(arch).tar.gz (HTTP ${sidecar_code})"
  1108. fi
  1109. if [[ -e ${xui_folder}/ ]]; then
  1110. echo -e "${green}Stopping x-ui...${plain}"
  1111. if [[ $release == "alpine" ]]; then
  1112. if [ -f "/etc/init.d/x-ui" ]; then
  1113. rc-service x-ui stop > /dev/null 2>&1
  1114. rc-update del x-ui > /dev/null 2>&1
  1115. echo -e "${green}Removing old service unit version...${plain}"
  1116. rm -f /etc/init.d/x-ui > /dev/null 2>&1
  1117. else
  1118. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1119. _fail "ERROR: x-ui service unit not installed."
  1120. fi
  1121. else
  1122. if [ -f "${xui_service}/x-ui.service" ]; then
  1123. systemctl stop x-ui > /dev/null 2>&1
  1124. systemctl disable x-ui > /dev/null 2>&1
  1125. echo -e "${green}Removing old systemd unit version...${plain}"
  1126. rm ${xui_service}/x-ui.service -f > /dev/null 2>&1
  1127. systemctl daemon-reload > /dev/null 2>&1
  1128. else
  1129. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1130. _fail "ERROR: x-ui systemd unit not installed."
  1131. fi
  1132. fi
  1133. # Kill any leftover mtg (MTProto) sidecars. x-ui runs them outside its own
  1134. # lifecycle, so on Linux a stale one can survive the stop and keep holding
  1135. # an inbound port with an outdated secret, silently breaking new clients.
  1136. # The new panel respawns a clean mtg per inbound on next start.
  1137. pkill -f 'mtg-linux-[^ ]* run ' > /dev/null 2>&1 || true
  1138. pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true
  1139. echo -e "${green}Removing old x-ui version...${plain}"
  1140. rm ${xui_folder} -f > /dev/null 2>&1
  1141. rm ${xui_folder}/x-ui.service -f > /dev/null 2>&1
  1142. rm ${xui_folder}/x-ui.service.debian -f > /dev/null 2>&1
  1143. rm ${xui_folder}/x-ui.service.arch -f > /dev/null 2>&1
  1144. rm ${xui_folder}/x-ui.service.rhel -f > /dev/null 2>&1
  1145. rm ${xui_folder}/x-ui -f > /dev/null 2>&1
  1146. rm ${xui_folder}/x-ui.sh -f > /dev/null 2>&1
  1147. echo -e "${green}Removing old mtg version...${plain}"
  1148. rm ${xui_folder}/bin/mtg-linux-$(arch) -f > /dev/null 2>&1
  1149. echo -e "${green}Removing old xray version...${plain}"
  1150. rm ${xui_folder}/bin/xray-linux-$(arch) -f > /dev/null 2>&1
  1151. echo -e "${green}Removing old README and LICENSE file...${plain}"
  1152. rm ${xui_folder}/bin/README.md -f > /dev/null 2>&1
  1153. rm ${xui_folder}/bin/LICENSE -f > /dev/null 2>&1
  1154. rm ${xui_folder}/bin/tuic-server -f > /dev/null 2>&1
  1155. rm ${xui_folder}/bin/tuic -rf > /dev/null 2>&1
  1156. else
  1157. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1158. _fail "ERROR: x-ui not installed."
  1159. fi
  1160. echo -e "${green}Installing new x-ui version...${plain}"
  1161. tar zxvf x-ui-linux-$(arch).tar.gz > /dev/null 2>&1
  1162. if [[ $? -ne 0 ]]; then
  1163. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1164. _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"
  1165. fi
  1166. rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
  1167. cd x-ui > /dev/null 2>&1
  1168. if [[ $? -ne 0 || ! -s x-ui ]]; then
  1169. _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"
  1170. fi
  1171. chmod +x x-ui > /dev/null 2>&1
  1172. # Check the system's architecture and rename the file accordingly.
  1173. # The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
  1174. # so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
  1175. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  1176. mv bin/xray-linux-$(arch) bin/xray-linux-arm32 > /dev/null 2>&1
  1177. chmod +x bin/xray-linux-arm32 > /dev/null 2>&1
  1178. if [[ -f bin/mtg-linux-$(arch) ]]; then
  1179. mv bin/mtg-linux-$(arch) bin/mtg-linux-arm > /dev/null 2>&1
  1180. chmod +x bin/mtg-linux-arm > /dev/null 2>&1
  1181. fi
  1182. fi
  1183. chmod +x x-ui bin/xray-linux-$(arch) > /dev/null 2>&1
  1184. if [[ -f bin/mtg-linux-arm ]]; then
  1185. chmod +x bin/mtg-linux-arm > /dev/null 2>&1
  1186. elif [[ -f bin/mtg-linux-$(arch) ]]; then
  1187. chmod +x bin/mtg-linux-$(arch) > /dev/null 2>&1
  1188. fi
  1189. echo -e "${green}Downloading and installing x-ui.sh script...${plain}"
  1190. local xui_script_temp="/usr/bin/x-ui-temp.$$"
  1191. rm -f "${xui_script_temp}"
  1192. ${curl_bin} -fLRo "${xui_script_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.sh" > /dev/null 2>&1
  1193. if [[ $? -ne 0 ]]; then
  1194. rm -f "${xui_script_temp}"
  1195. _fail "ERROR: Failed to download x-ui.sh script, please be sure that your server can access GitHub"
  1196. fi
  1197. if [[ ! -s "${xui_script_temp}" ]]; then
  1198. rm -f "${xui_script_temp}"
  1199. _fail "ERROR: Downloaded x-ui.sh script is empty, please be sure that your server can access GitHub"
  1200. fi
  1201. mv -f "${xui_script_temp}" /usr/bin/x-ui
  1202. if [[ $? -ne 0 ]]; then
  1203. rm -f "${xui_script_temp}"
  1204. _fail "ERROR: Failed to install x-ui.sh script"
  1205. fi
  1206. chmod +x ${xui_folder}/x-ui.sh > /dev/null 2>&1
  1207. chmod +x /usr/bin/x-ui > /dev/null 2>&1
  1208. mkdir -p /var/log/x-ui > /dev/null 2>&1
  1209. echo -e "${green}Changing owner...${plain}"
  1210. chown -R root:root ${xui_folder} > /dev/null 2>&1
  1211. if [ -f "${xui_folder}/bin/config.json" ]; then
  1212. echo -e "${green}Changing on config file permissions...${plain}"
  1213. chmod 640 ${xui_folder}/bin/config.json > /dev/null 2>&1
  1214. fi
  1215. # Finish the schema/data migrations before the service starts, so the service and
  1216. # config_after_update's CLI calls never run them on the same database at once (#6728).
  1217. echo -e "${green}Migrating database...${plain}"
  1218. "${xui_folder}/x-ui" migrate
  1219. if [[ $release == "alpine" ]]; then
  1220. echo -e "${green}Downloading and installing startup unit x-ui.rc...${plain}"
  1221. xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
  1222. rm -f "${xui_rc_temp}"
  1223. ${curl_bin} -fLRo "${xui_rc_temp}" "https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.rc" > /dev/null 2>&1
  1224. if [[ $? -ne 0 ]]; then
  1225. rm -f "${xui_rc_temp}"
  1226. _fail "ERROR: Failed to download startup unit x-ui.rc, please be sure that your server can access GitHub"
  1227. fi
  1228. if [[ ! -s "${xui_rc_temp}" ]]; then
  1229. rm -f "${xui_rc_temp}"
  1230. _fail "ERROR: Downloaded startup unit x-ui.rc is empty, please be sure that your server can access GitHub"
  1231. fi
  1232. mv -f "${xui_rc_temp}" /etc/init.d/x-ui
  1233. if [[ $? -ne 0 ]]; then
  1234. rm -f "${xui_rc_temp}"
  1235. _fail "ERROR: Failed to install startup unit x-ui.rc"
  1236. fi
  1237. chmod +x /etc/init.d/x-ui > /dev/null 2>&1
  1238. chown root:root /etc/init.d/x-ui > /dev/null 2>&1
  1239. rc-update add x-ui > /dev/null 2>&1
  1240. rc-service x-ui start > /dev/null 2>&1
  1241. else
  1242. if [ -f "x-ui.service" ]; then
  1243. echo -e "${green}Installing systemd unit...${plain}"
  1244. if ! _install_xui_service_unit "x-ui.service" "false"; then
  1245. echo -e "${red}Failed to copy x-ui.service${plain}"
  1246. exit 1
  1247. fi
  1248. else
  1249. service_installed=false
  1250. case "${release}" in
  1251. ubuntu | debian | armbian)
  1252. if [ -f "x-ui.service.debian" ]; then
  1253. echo -e "${green}Installing debian-like systemd unit...${plain}"
  1254. if _install_xui_service_unit "x-ui.service.debian" "false"; then
  1255. service_installed=true
  1256. fi
  1257. fi
  1258. ;;
  1259. arch | manjaro | parch)
  1260. if [ -f "x-ui.service.arch" ]; then
  1261. echo -e "${green}Installing arch-like systemd unit...${plain}"
  1262. if _install_xui_service_unit "x-ui.service.arch" "false"; then
  1263. service_installed=true
  1264. fi
  1265. fi
  1266. ;;
  1267. *)
  1268. if [ -f "x-ui.service.rhel" ]; then
  1269. echo -e "${green}Installing rhel-like systemd unit...${plain}"
  1270. if _install_xui_service_unit "x-ui.service.rhel" "false"; then
  1271. service_installed=true
  1272. fi
  1273. fi
  1274. ;;
  1275. esac
  1276. # If service file not found in tar.gz, download from GitHub
  1277. if [ "$service_installed" = false ]; then
  1278. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  1279. case "${release}" in
  1280. ubuntu | debian | armbian)
  1281. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.debian"
  1282. ;;
  1283. arch | manjaro | parch)
  1284. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.arch"
  1285. ;;
  1286. *)
  1287. service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/${script_ref}/x-ui.service.rhel"
  1288. ;;
  1289. esac
  1290. if ! _install_xui_service_unit "$service_unit_url" "true"; then
  1291. echo -e "${red}Failed to install x-ui.service from GitHub (${script_ref}) -- the release tarball did not ship one either${plain}"
  1292. exit 1
  1293. fi
  1294. fi
  1295. fi
  1296. chown root:root ${xui_service}/x-ui.service > /dev/null 2>&1
  1297. chmod 644 ${xui_service}/x-ui.service > /dev/null 2>&1
  1298. systemctl daemon-reload > /dev/null 2>&1
  1299. systemctl enable x-ui > /dev/null 2>&1
  1300. systemctl start x-ui > /dev/null 2>&1
  1301. fi
  1302. config_after_update
  1303. # IP Limit relies on fail2ban; install + configure it now so the feature
  1304. # works out of the box on update too (no-op when XUI_ENABLE_FAIL2BAN=false).
  1305. # Never fatal.
  1306. setup_fail2ban
  1307. echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
  1308. echo -e ""
  1309. echo -e "┌───────────────────────────────────────────────────────┐
  1310. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  1311. │ │
  1312. │ ${blue}x-ui${plain} - Admin Management Script │
  1313. │ ${blue}x-ui start${plain} - Start │
  1314. │ ${blue}x-ui stop${plain} - Stop │
  1315. │ ${blue}x-ui restart${plain} - Restart │
  1316. │ ${blue}x-ui status${plain} - Current Status │
  1317. │ ${blue}x-ui settings${plain} - Current Settings │
  1318. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  1319. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  1320. │ ${blue}x-ui log${plain} - Check logs │
  1321. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  1322. │ ${blue}x-ui update${plain} - Update │
  1323. │ ${blue}x-ui legacy${plain} - Legacy version │
  1324. │ ${blue}x-ui install${plain} - Install │
  1325. │ ${blue}x-ui uninstall${plain} - Uninstall │
  1326. └───────────────────────────────────────────────────────┘"
  1327. }
  1328. echo -e "${green}Running...${plain}"
  1329. require_writable_update_paths
  1330. install_base
  1331. update_x-ui $1