update.sh 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. # check root
  29. [[ $EUID -ne 0 ]] && _fail "FATAL ERROR: Please run this script with root privilege."
  30. if _command_exists curl; then
  31. curl_bin=$(which curl)
  32. else
  33. _fail "ERROR: Command 'curl' not found."
  34. fi
  35. # Check OS and set release variable
  36. if [[ -f /etc/os-release ]]; then
  37. source /etc/os-release
  38. release=$ID
  39. elif [[ -f /usr/lib/os-release ]]; then
  40. source /usr/lib/os-release
  41. release=$ID
  42. else
  43. _fail "Failed to check the system OS, please contact the author!"
  44. fi
  45. echo "The OS release is: $release"
  46. arch() {
  47. case "$(uname -m)" in
  48. x86_64 | x64 | amd64) echo 'amd64' ;;
  49. i*86 | x86) echo '386' ;;
  50. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  51. armv7* | armv7 | arm) echo 'armv7' ;;
  52. armv6* | armv6) echo 'armv6' ;;
  53. armv5* | armv5) echo 'armv5' ;;
  54. s390x) echo 's390x' ;;
  55. *) echo -e "${red}Unsupported CPU architecture!${plain}" && rm -f "${cur_dir}/${script_name}" >/dev/null 2>&1 && exit 2;;
  56. esac
  57. }
  58. echo "Arch: $(arch)"
  59. # Simple helpers
  60. is_ipv4() {
  61. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  62. }
  63. is_ipv6() {
  64. [[ "$1" =~ : ]] && return 0 || return 1
  65. }
  66. is_ip() {
  67. is_ipv4 "$1" || is_ipv6 "$1"
  68. }
  69. is_domain() {
  70. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+[A-Za-z]{2,}$ ]] && return 0 || return 1
  71. }
  72. gen_random_string() {
  73. local length="$1"
  74. local random_string=$(LC_ALL=C tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1)
  75. echo "$random_string"
  76. }
  77. install_base() {
  78. echo -e "${green}Updating and install dependency packages...${plain}"
  79. case "${release}" in
  80. ubuntu | debian | armbian)
  81. apt-get update >/dev/null 2>&1 && apt-get install -y -q curl tar tzdata socat >/dev/null 2>&1
  82. ;;
  83. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  84. dnf -y update >/dev/null 2>&1 && dnf install -y -q curl tar tzdata socat >/dev/null 2>&1
  85. ;;
  86. centos)
  87. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  88. yum -y update >/dev/null 2>&1 && yum install -y -q curl tar tzdata socat >/dev/null 2>&1
  89. else
  90. dnf -y update >/dev/null 2>&1 && dnf install -y -q curl tar tzdata socat >/dev/null 2>&1
  91. fi
  92. ;;
  93. arch | manjaro | parch)
  94. pacman -Syu >/dev/null 2>&1 && pacman -Syu --noconfirm curl tar tzdata socat >/dev/null 2>&1
  95. ;;
  96. opensuse-tumbleweed | opensuse-leap)
  97. zypper refresh >/dev/null 2>&1 && zypper -q install -y curl tar timezone socat >/dev/null 2>&1
  98. ;;
  99. alpine)
  100. apk update >/dev/null 2>&1 && apk add curl tar tzdata socat >/dev/null 2>&1
  101. ;;
  102. *)
  103. apt-get update >/dev/null 2>&1 && apt install -y -q curl tar tzdata socat >/dev/null 2>&1
  104. ;;
  105. esac
  106. }
  107. install_acme() {
  108. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  109. cd ~ || return 1
  110. curl -s https://get.acme.sh | sh >/dev/null 2>&1
  111. if [ $? -ne 0 ]; then
  112. echo -e "${red}Failed to install acme.sh${plain}"
  113. return 1
  114. else
  115. echo -e "${green}acme.sh installed successfully${plain}"
  116. fi
  117. return 0
  118. }
  119. setup_ssl_certificate() {
  120. local domain="$1"
  121. local server_ip="$2"
  122. local existing_port="$3"
  123. local existing_webBasePath="$4"
  124. echo -e "${green}Setting up SSL certificate...${plain}"
  125. # Check if acme.sh is installed
  126. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  127. install_acme
  128. if [ $? -ne 0 ]; then
  129. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  130. return 1
  131. fi
  132. fi
  133. # Create certificate directory
  134. local certPath="/root/cert/${domain}"
  135. mkdir -p "$certPath"
  136. # Issue certificate
  137. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  138. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  139. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt >/dev/null 2>&1
  140. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport 80 --force
  141. if [ $? -ne 0 ]; then
  142. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  143. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  144. rm -rf ~/.acme.sh/${domain} 2>/dev/null
  145. rm -rf "$certPath" 2>/dev/null
  146. return 1
  147. fi
  148. # Install certificate
  149. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  150. --key-file /root/cert/${domain}/privkey.pem \
  151. --fullchain-file /root/cert/${domain}/fullchain.pem \
  152. --reloadcmd "systemctl restart x-ui" >/dev/null 2>&1
  153. if [ $? -ne 0 ]; then
  154. echo -e "${yellow}Failed to install certificate${plain}"
  155. return 1
  156. fi
  157. # Enable auto-renew
  158. ~/.acme.sh/acme.sh --upgrade --auto-upgrade >/dev/null 2>&1
  159. chmod 600 $certPath/privkey.pem 2>/dev/null
  160. chmod 644 $certPath/fullchain.pem 2>/dev/null
  161. # Set certificate for panel
  162. local webCertFile="/root/cert/${domain}/fullchain.pem"
  163. local webKeyFile="/root/cert/${domain}/privkey.pem"
  164. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  165. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" >/dev/null 2>&1
  166. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  167. return 0
  168. else
  169. echo -e "${yellow}Certificate files not found${plain}"
  170. return 1
  171. fi
  172. }
  173. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  174. # Requires acme.sh and port 80 open for HTTP-01 challenge
  175. setup_ip_certificate() {
  176. local ipv4="$1"
  177. local ipv6="$2" # optional
  178. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  179. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  180. echo -e "${yellow}Port 80 must be open and accessible from the internet.${plain}"
  181. # Check for acme.sh
  182. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  183. install_acme
  184. if [ $? -ne 0 ]; then
  185. echo -e "${red}Failed to install acme.sh${plain}"
  186. return 1
  187. fi
  188. fi
  189. # Validate IP address
  190. if [[ -z "$ipv4" ]]; then
  191. echo -e "${red}IPv4 address is required${plain}"
  192. return 1
  193. fi
  194. if ! is_ipv4 "$ipv4"; then
  195. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  196. return 1
  197. fi
  198. # Create certificate directory
  199. local certDir="/root/cert/ip"
  200. mkdir -p "$certDir"
  201. # Build domain arguments
  202. local domain_args="-d ${ipv4}"
  203. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  204. domain_args="${domain_args} -d ${ipv6}"
  205. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  206. fi
  207. # Set reload command for auto-renewal (add || true so it doesn't fail if service stopped)
  208. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  209. # Issue certificate with shortlived profile
  210. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  211. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt >/dev/null 2>&1
  212. ~/.acme.sh/acme.sh --issue \
  213. ${domain_args} \
  214. --standalone \
  215. --server letsencrypt \
  216. --certificate-profile shortlived \
  217. --days 6 \
  218. --httpport 80 \
  219. --force
  220. if [ $? -ne 0 ]; then
  221. echo -e "${red}Failed to issue IP certificate${plain}"
  222. echo -e "${yellow}Please ensure port 80 is open and accessible from the internet${plain}"
  223. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  224. rm -rf ~/.acme.sh/${ipv4} 2>/dev/null
  225. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2>/dev/null
  226. rm -rf ${certDir} 2>/dev/null
  227. return 1
  228. fi
  229. echo -e "${green}Certificate issued successfully, installing...${plain}"
  230. # Install certificate
  231. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  232. # but the cert files are still installed. We check for files instead of exit code.
  233. ~/.acme.sh/acme.sh --installcert -d ${ipv4} \
  234. --key-file "${certDir}/privkey.pem" \
  235. --fullchain-file "${certDir}/fullchain.pem" \
  236. --reloadcmd "${reloadCmd}" 2>&1 || true
  237. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  238. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  239. echo -e "${red}Certificate files not found after installation${plain}"
  240. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  241. rm -rf ~/.acme.sh/${ipv4} 2>/dev/null
  242. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2>/dev/null
  243. rm -rf ${certDir} 2>/dev/null
  244. return 1
  245. fi
  246. echo -e "${green}Certificate files installed successfully${plain}"
  247. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  248. ~/.acme.sh/acme.sh --upgrade --auto-upgrade >/dev/null 2>&1
  249. chmod 600 ${certDir}/privkey.pem 2>/dev/null
  250. chmod 644 ${certDir}/fullchain.pem 2>/dev/null
  251. # Configure panel to use the certificate
  252. echo -e "${green}Setting certificate paths for the panel...${plain}"
  253. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  254. if [ $? -ne 0 ]; then
  255. echo -e "${yellow}Warning: Could not set certificate paths automatically.${plain}"
  256. echo -e "${yellow}You may need to set them manually in the panel settings.${plain}"
  257. echo -e "${yellow}Cert path: ${certDir}/fullchain.pem${plain}"
  258. echo -e "${yellow}Key path: ${certDir}/privkey.pem${plain}"
  259. else
  260. echo -e "${green}Certificate paths set successfully!${plain}"
  261. fi
  262. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  263. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  264. echo -e "${yellow}Panel will automatically restart after each renewal.${plain}"
  265. return 0
  266. }
  267. # Comprehensive manual SSL certificate issuance via acme.sh
  268. ssl_cert_issue() {
  269. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  270. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  271. # check for acme.sh first
  272. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  273. echo "acme.sh could not be found. Installing now..."
  274. cd ~ || return 1
  275. curl -s https://get.acme.sh | sh
  276. if [ $? -ne 0 ]; then
  277. echo -e "${red}Failed to install acme.sh${plain}"
  278. return 1
  279. else
  280. echo -e "${green}acme.sh installed successfully${plain}"
  281. fi
  282. fi
  283. # get the domain here, and we need to verify it
  284. local domain=""
  285. while true; do
  286. read -rp "Please enter your domain name: " domain
  287. domain="${domain// /}" # Trim whitespace
  288. if [[ -z "$domain" ]]; then
  289. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  290. continue
  291. fi
  292. if ! is_domain "$domain"; then
  293. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  294. continue
  295. fi
  296. break
  297. done
  298. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  299. # check if there already exists a certificate
  300. local currentCert=$(~/.acme.sh/acme.sh --list | tail -1 | awk '{print $1}')
  301. if [ "${currentCert}" == "${domain}" ]; then
  302. local certInfo=$(~/.acme.sh/acme.sh --list)
  303. echo -e "${red}System already has certificates for this domain. Cannot issue again.${plain}"
  304. echo -e "${yellow}Current certificate details:${plain}"
  305. echo "$certInfo"
  306. return 1
  307. else
  308. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  309. fi
  310. # create a directory for the certificate
  311. certPath="/root/cert/${domain}"
  312. if [ ! -d "$certPath" ]; then
  313. mkdir -p "$certPath"
  314. else
  315. rm -rf "$certPath"
  316. mkdir -p "$certPath"
  317. fi
  318. # get the port number for the standalone server
  319. local WebPort=80
  320. read -rp "Please choose which port to use (default is 80): " WebPort
  321. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  322. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  323. WebPort=80
  324. fi
  325. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  326. # Stop panel temporarily
  327. echo -e "${yellow}Stopping panel temporarily...${plain}"
  328. systemctl stop x-ui 2>/dev/null || rc-service x-ui stop 2>/dev/null
  329. # issue the certificate
  330. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt
  331. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport ${WebPort} --force
  332. if [ $? -ne 0 ]; then
  333. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  334. rm -rf ~/.acme.sh/${domain}
  335. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  336. return 1
  337. else
  338. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  339. fi
  340. # Setup reload command
  341. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  342. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  343. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  344. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  345. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  346. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  347. echo -e "${green}\t2.${plain} Input your own command"
  348. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  349. read -rp "Choose an option: " choice
  350. case "$choice" in
  351. 1)
  352. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  353. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  354. ;;
  355. 2)
  356. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  357. read -rp "Please enter your custom reloadcmd: " reloadCmd
  358. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  359. ;;
  360. *)
  361. echo -e "${green}Keeping default reloadcmd${plain}"
  362. ;;
  363. esac
  364. fi
  365. # install the certificate
  366. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  367. --key-file /root/cert/${domain}/privkey.pem \
  368. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}"
  369. if [ $? -ne 0 ]; then
  370. echo -e "${red}Installing certificate failed, exiting.${plain}"
  371. rm -rf ~/.acme.sh/${domain}
  372. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  373. return 1
  374. else
  375. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  376. fi
  377. # enable auto-renew
  378. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  379. if [ $? -ne 0 ]; then
  380. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  381. ls -lah /root/cert/${domain}/
  382. chmod 600 $certPath/privkey.pem
  383. chmod 644 $certPath/fullchain.pem
  384. else
  385. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  386. ls -lah /root/cert/${domain}/
  387. chmod 600 $certPath/privkey.pem
  388. chmod 644 $certPath/fullchain.pem
  389. fi
  390. # Restart panel
  391. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  392. # Prompt user to set panel paths after successful certificate installation
  393. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  394. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  395. local webCertFile="/root/cert/${domain}/fullchain.pem"
  396. local webKeyFile="/root/cert/${domain}/privkey.pem"
  397. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  398. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  399. echo -e "${green}Certificate paths set for the panel${plain}"
  400. echo -e "${green}Certificate File: $webCertFile${plain}"
  401. echo -e "${green}Private Key File: $webKeyFile${plain}"
  402. echo ""
  403. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  404. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  405. systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null
  406. else
  407. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  408. fi
  409. else
  410. echo -e "${yellow}Skipping panel path setting.${plain}"
  411. fi
  412. return 0
  413. }
  414. # Unified interactive SSL setup (domain or IP)
  415. # Sets global `SSL_HOST` to the chosen domain/IP
  416. prompt_and_setup_ssl() {
  417. local panel_port="$1"
  418. local web_base_path="$2" # expected without leading slash
  419. local server_ip="$3"
  420. local ssl_choice=""
  421. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  422. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  423. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  424. echo -e "${blue}Note:${plain} Both options require port 80 open. IP certs use shortlived profile."
  425. read -rp "Choose an option (default 2 for IP): " ssl_choice
  426. ssl_choice="${ssl_choice// /}" # Trim whitespace
  427. # Default to 2 (IP cert) if not 1
  428. if [[ "$ssl_choice" != "1" ]]; then
  429. ssl_choice="2"
  430. fi
  431. case "$ssl_choice" in
  432. 1)
  433. # User chose Let's Encrypt domain option
  434. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  435. ssl_cert_issue
  436. # Extract the domain that was used from the certificate
  437. local cert_domain=$(~/.acme.sh/acme.sh --list 2>/dev/null | tail -1 | awk '{print $1}')
  438. if [[ -n "${cert_domain}" ]]; then
  439. SSL_HOST="${cert_domain}"
  440. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  441. else
  442. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  443. SSL_HOST="${server_ip}"
  444. fi
  445. ;;
  446. 2)
  447. # User chose Let's Encrypt IP certificate option
  448. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  449. # Ask for optional IPv6
  450. local ipv6_addr=""
  451. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  452. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  453. # Stop panel if running (port 80 needed)
  454. if [[ $release == "alpine" ]]; then
  455. rc-service x-ui stop >/dev/null 2>&1
  456. else
  457. systemctl stop x-ui >/dev/null 2>&1
  458. fi
  459. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  460. if [ $? -eq 0 ]; then
  461. SSL_HOST="${server_ip}"
  462. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  463. else
  464. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  465. SSL_HOST="${server_ip}"
  466. fi
  467. # Restart panel after SSL is configured (restart applies new cert settings)
  468. if [[ $release == "alpine" ]]; then
  469. rc-service x-ui restart >/dev/null 2>&1
  470. else
  471. systemctl restart x-ui >/dev/null 2>&1
  472. fi
  473. ;;
  474. *)
  475. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  476. SSL_HOST="${server_ip}"
  477. ;;
  478. esac
  479. }
  480. config_after_update() {
  481. echo -e "${yellow}x-ui settings:${plain}"
  482. ${xui_folder}/x-ui setting -show true
  483. ${xui_folder}/x-ui migrate
  484. # Properly detect empty cert by checking if cert: line exists and has content after it
  485. local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2>/dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  486. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  487. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  488. # Get server IP
  489. local URL_lists=(
  490. "https://api4.ipify.org"
  491. "https://ipv4.icanhazip.com"
  492. "https://v4.api.ipinfo.io/ip"
  493. "https://ipv4.myexternalip.com/raw"
  494. "https://4.ident.me"
  495. "https://check-host.net/ip"
  496. )
  497. local server_ip=""
  498. for ip_address in "${URL_lists[@]}"; do
  499. server_ip=$(${curl_bin} -s --max-time 3 "${ip_address}" 2>/dev/null | tr -d '[:space:]')
  500. if [[ -n "${server_ip}" ]]; then
  501. break
  502. fi
  503. done
  504. # Handle missing/short webBasePath
  505. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  506. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  507. local config_webBasePath=$(gen_random_string 18)
  508. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  509. existing_webBasePath="${config_webBasePath}"
  510. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  511. fi
  512. # Check and prompt for SSL if missing
  513. if [[ -z "$existing_cert" ]]; then
  514. echo ""
  515. echo -e "${red}═══════════════════════════════════════════${plain}"
  516. echo -e "${red} ⚠ NO SSL CERTIFICATE DETECTED ⚠ ${plain}"
  517. echo -e "${red}═══════════════════════════════════════════${plain}"
  518. echo -e "${yellow}For security, SSL certificate is MANDATORY for all panels.${plain}"
  519. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  520. echo ""
  521. if [[ -z "${server_ip}" ]]; then
  522. echo -e "${red}Failed to detect server IP${plain}"
  523. echo -e "${yellow}Please configure SSL manually using: x-ui${plain}"
  524. return
  525. fi
  526. # Prompt and setup SSL (domain or IP)
  527. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  528. echo ""
  529. echo -e "${green}═══════════════════════════════════════════${plain}"
  530. echo -e "${green} Panel Access Information ${plain}"
  531. echo -e "${green}═══════════════════════════════════════════${plain}"
  532. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  533. echo -e "${green}═══════════════════════════════════════════${plain}"
  534. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  535. else
  536. echo -e "${green}SSL certificate is already configured${plain}"
  537. # Show access URL with existing certificate
  538. local cert_domain=$(basename "$(dirname "$existing_cert")")
  539. echo ""
  540. echo -e "${green}═══════════════════════════════════════════${plain}"
  541. echo -e "${green} Panel Access Information ${plain}"
  542. echo -e "${green}═══════════════════════════════════════════${plain}"
  543. echo -e "${green}Access URL: https://${cert_domain}:${existing_port}/${existing_webBasePath}${plain}"
  544. echo -e "${green}═══════════════════════════════════════════${plain}"
  545. fi
  546. }
  547. update_x-ui() {
  548. cd ${xui_folder%/x-ui}/
  549. if [ -f "${xui_folder}/x-ui" ]; then
  550. current_xui_version=$(${xui_folder}/x-ui -v)
  551. echo -e "${green}Current x-ui version: ${current_xui_version}${plain}"
  552. else
  553. _fail "ERROR: Current x-ui version: unknown"
  554. fi
  555. echo -e "${green}Downloading new x-ui version...${plain}"
  556. 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/')
  557. if [[ ! -n "$tag_version" ]]; then
  558. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  559. tag_version=$(${curl_bin} -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  560. if [[ ! -n "$tag_version" ]]; then
  561. _fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
  562. fi
  563. fi
  564. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  565. ${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
  566. if [[ $? -ne 0 ]]; then
  567. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  568. ${curl_bin} -4fLRo ${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
  569. if [[ $? -ne 0 ]]; then
  570. _fail "ERROR: Failed to download x-ui, please be sure that your server can access GitHub"
  571. fi
  572. fi
  573. if [[ -e ${xui_folder}/ ]]; then
  574. echo -e "${green}Stopping x-ui...${plain}"
  575. if [[ $release == "alpine" ]]; then
  576. if [ -f "/etc/init.d/x-ui" ]; then
  577. rc-service x-ui stop >/dev/null 2>&1
  578. rc-update del x-ui >/dev/null 2>&1
  579. echo -e "${green}Removing old service unit version...${plain}"
  580. rm -f /etc/init.d/x-ui >/dev/null 2>&1
  581. else
  582. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  583. _fail "ERROR: x-ui service unit not installed."
  584. fi
  585. else
  586. if [ -f "${xui_service}/x-ui.service" ]; then
  587. systemctl stop x-ui >/dev/null 2>&1
  588. systemctl disable x-ui >/dev/null 2>&1
  589. echo -e "${green}Removing old systemd unit version...${plain}"
  590. rm ${xui_service}/x-ui.service -f >/dev/null 2>&1
  591. systemctl daemon-reload >/dev/null 2>&1
  592. else
  593. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  594. _fail "ERROR: x-ui systemd unit not installed."
  595. fi
  596. fi
  597. echo -e "${green}Removing old x-ui version...${plain}"
  598. rm ${xui_folder} -f >/dev/null 2>&1
  599. rm ${xui_folder}/x-ui.service -f >/dev/null 2>&1
  600. rm ${xui_folder}/x-ui.service.debian -f >/dev/null 2>&1
  601. rm ${xui_folder}/x-ui.service.rhel -f >/dev/null 2>&1
  602. rm ${xui_folder}/x-ui -f >/dev/null 2>&1
  603. rm ${xui_folder}/x-ui.sh -f >/dev/null 2>&1
  604. echo -e "${green}Removing old xray version...${plain}"
  605. rm ${xui_folder}/bin/xray-linux-amd64 -f >/dev/null 2>&1
  606. echo -e "${green}Removing old README and LICENSE file...${plain}"
  607. rm ${xui_folder}/bin/README.md -f >/dev/null 2>&1
  608. rm ${xui_folder}/bin/LICENSE -f >/dev/null 2>&1
  609. else
  610. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  611. _fail "ERROR: x-ui not installed."
  612. fi
  613. echo -e "${green}Installing new x-ui version...${plain}"
  614. tar zxvf x-ui-linux-$(arch).tar.gz >/dev/null 2>&1
  615. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  616. cd x-ui >/dev/null 2>&1
  617. chmod +x x-ui >/dev/null 2>&1
  618. # Check the system's architecture and rename the file accordingly
  619. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  620. mv bin/xray-linux-$(arch) bin/xray-linux-arm >/dev/null 2>&1
  621. chmod +x bin/xray-linux-arm >/dev/null 2>&1
  622. fi
  623. chmod +x x-ui bin/xray-linux-$(arch) >/dev/null 2>&1
  624. echo -e "${green}Downloading and installing x-ui.sh script...${plain}"
  625. ${curl_bin} -fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh >/dev/null 2>&1
  626. if [[ $? -ne 0 ]]; then
  627. echo -e "${yellow}Trying to fetch x-ui with IPv4...${plain}"
  628. ${curl_bin} -4fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh >/dev/null 2>&1
  629. if [[ $? -ne 0 ]]; then
  630. _fail "ERROR: Failed to download x-ui.sh script, please be sure that your server can access GitHub"
  631. fi
  632. fi
  633. chmod +x ${xui_folder}/x-ui.sh >/dev/null 2>&1
  634. chmod +x /usr/bin/x-ui >/dev/null 2>&1
  635. mkdir -p /var/log/x-ui >/dev/null 2>&1
  636. echo -e "${green}Changing owner...${plain}"
  637. chown -R root:root ${xui_folder} >/dev/null 2>&1
  638. if [ -f "${xui_folder}/bin/config.json" ]; then
  639. echo -e "${green}Changing on config file permissions...${plain}"
  640. chmod 640 ${xui_folder}/bin/config.json >/dev/null 2>&1
  641. fi
  642. if [[ $release == "alpine" ]]; then
  643. echo -e "${green}Downloading and installing startup unit x-ui.rc...${plain}"
  644. ${curl_bin} -fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc >/dev/null 2>&1
  645. if [[ $? -ne 0 ]]; then
  646. ${curl_bin} -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc >/dev/null 2>&1
  647. if [[ $? -ne 0 ]]; then
  648. _fail "ERROR: Failed to download startup unit x-ui.rc, please be sure that your server can access GitHub"
  649. fi
  650. fi
  651. chmod +x /etc/init.d/x-ui >/dev/null 2>&1
  652. chown root:root /etc/init.d/x-ui >/dev/null 2>&1
  653. rc-update add x-ui >/dev/null 2>&1
  654. rc-service x-ui start >/dev/null 2>&1
  655. else
  656. if [ -f "x-ui.service" ]; then
  657. echo -e "${green}Installing systemd unit...${plain}"
  658. cp -f x-ui.service ${xui_service}/ >/dev/null 2>&1
  659. if [[ $? -ne 0 ]]; then
  660. echo -e "${red}Failed to copy x-ui.service${plain}"
  661. exit 1
  662. fi
  663. else
  664. service_installed=false
  665. case "${release}" in
  666. ubuntu | debian | armbian)
  667. if [ -f "x-ui.service.debian" ]; then
  668. echo -e "${green}Installing debian-like systemd unit...${plain}"
  669. cp -f x-ui.service.debian ${xui_service}/x-ui.service >/dev/null 2>&1
  670. if [[ $? -eq 0 ]]; then
  671. service_installed=true
  672. fi
  673. fi
  674. ;;
  675. *)
  676. if [ -f "x-ui.service.rhel" ]; then
  677. echo -e "${green}Installing rhel-like systemd unit...${plain}"
  678. cp -f x-ui.service.rhel ${xui_service}/x-ui.service >/dev/null 2>&1
  679. if [[ $? -eq 0 ]]; then
  680. service_installed=true
  681. fi
  682. fi
  683. ;;
  684. esac
  685. # If service file not found in tar.gz, download from GitHub
  686. if [ "$service_installed" = false ]; then
  687. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  688. case "${release}" in
  689. ubuntu | debian | armbian)
  690. ${curl_bin} -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian >/dev/null 2>&1
  691. ;;
  692. *)
  693. ${curl_bin} -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel >/dev/null 2>&1
  694. ;;
  695. esac
  696. if [[ $? -ne 0 ]]; then
  697. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  698. exit 1
  699. fi
  700. fi
  701. fi
  702. chown root:root ${xui_service}/x-ui.service >/dev/null 2>&1
  703. chmod 644 ${xui_service}/x-ui.service >/dev/null 2>&1
  704. systemctl daemon-reload >/dev/null 2>&1
  705. systemctl enable x-ui >/dev/null 2>&1
  706. systemctl start x-ui >/dev/null 2>&1
  707. fi
  708. config_after_update
  709. echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
  710. echo -e ""
  711. echo -e "┌───────────────────────────────────────────────────────┐
  712. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  713. │ │
  714. │ ${blue}x-ui${plain} - Admin Management Script │
  715. │ ${blue}x-ui start${plain} - Start │
  716. │ ${blue}x-ui stop${plain} - Stop │
  717. │ ${blue}x-ui restart${plain} - Restart │
  718. │ ${blue}x-ui status${plain} - Current Status │
  719. │ ${blue}x-ui settings${plain} - Current Settings │
  720. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  721. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  722. │ ${blue}x-ui log${plain} - Check logs │
  723. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  724. │ ${blue}x-ui update${plain} - Update │
  725. │ ${blue}x-ui legacy${plain} - Legacy version │
  726. │ ${blue}x-ui install${plain} - Install │
  727. │ ${blue}x-ui uninstall${plain} - Uninstall │
  728. └───────────────────────────────────────────────────────┘"
  729. }
  730. echo -e "${green}Running...${plain}"
  731. install_base
  732. update_x-ui $1