update.sh 37 KB

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