update.sh 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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])*\.)+(xn--[a-z0-9]{2,}|[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 "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  475. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  476. read -rp "Choose an option (default 2 for IP): " ssl_choice
  477. ssl_choice="${ssl_choice// /}" # Trim whitespace
  478. # Default to 2 (IP cert) if input is empty or invalid (not 1 or 3)
  479. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" ]]; then
  480. ssl_choice="2"
  481. fi
  482. case "$ssl_choice" in
  483. 1)
  484. # User chose Let's Encrypt domain option
  485. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  486. ssl_cert_issue
  487. # Extract the domain that was used from the certificate
  488. local cert_domain=$(~/.acme.sh/acme.sh --list 2>/dev/null | tail -1 | awk '{print $1}')
  489. if [[ -n "${cert_domain}" ]]; then
  490. SSL_HOST="${cert_domain}"
  491. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  492. else
  493. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  494. SSL_HOST="${server_ip}"
  495. fi
  496. ;;
  497. 2)
  498. # User chose Let's Encrypt IP certificate option
  499. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  500. # Ask for optional IPv6
  501. local ipv6_addr=""
  502. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  503. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  504. # Stop panel if running (port 80 needed)
  505. if [[ $release == "alpine" ]]; then
  506. rc-service x-ui stop >/dev/null 2>&1
  507. else
  508. systemctl stop x-ui >/dev/null 2>&1
  509. fi
  510. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  511. if [ $? -eq 0 ]; then
  512. SSL_HOST="${server_ip}"
  513. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  514. else
  515. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  516. SSL_HOST="${server_ip}"
  517. fi
  518. # Restart panel after SSL is configured (restart applies new cert settings)
  519. if [[ $release == "alpine" ]]; then
  520. rc-service x-ui restart >/dev/null 2>&1
  521. else
  522. systemctl restart x-ui >/dev/null 2>&1
  523. fi
  524. ;;
  525. 3)
  526. # User chose Custom Paths (User Provided) option
  527. echo -e "${green}Using custom existing certificate...${plain}"
  528. local custom_cert=""
  529. local custom_key=""
  530. local custom_domain=""
  531. # 3.1 Request Domain to compose Panel URL later
  532. read -rp "Please enter domain name certificate issued for: " custom_domain
  533. custom_domain="${custom_domain// /}" # Убираем пробелы
  534. # 3.2 Loop for Certificate Path
  535. while true; do
  536. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  537. # Strip quotes if present
  538. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  539. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  540. break
  541. elif [[ ! -f "$custom_cert" ]]; then
  542. echo -e "${red}Error: File does not exist! Try again.${plain}"
  543. elif [[ ! -r "$custom_cert" ]]; then
  544. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  545. else
  546. echo -e "${red}Error: File is empty!${plain}"
  547. fi
  548. done
  549. # 3.3 Loop for Private Key Path
  550. while true; do
  551. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  552. # Strip quotes if present
  553. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  554. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  555. break
  556. elif [[ ! -f "$custom_key" ]]; then
  557. echo -e "${red}Error: File does not exist! Try again.${plain}"
  558. elif [[ ! -r "$custom_key" ]]; then
  559. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  560. else
  561. echo -e "${red}Error: File is empty!${plain}"
  562. fi
  563. done
  564. # 3.4 Apply Settings via x-ui binary
  565. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" >/dev/null 2>&1
  566. # Set SSL_HOST for composing Panel URL
  567. if [[ -n "$custom_domain" ]]; then
  568. SSL_HOST="$custom_domain"
  569. else
  570. SSL_HOST="${server_ip}"
  571. fi
  572. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  573. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  574. systemctl restart x-ui >/dev/null 2>&1 || rc-service x-ui restart >/dev/null 2>&1
  575. ;;
  576. *)
  577. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  578. SSL_HOST="${server_ip}"
  579. ;;
  580. esac
  581. }
  582. config_after_update() {
  583. echo -e "${yellow}x-ui settings:${plain}"
  584. ${xui_folder}/x-ui setting -show true
  585. ${xui_folder}/x-ui migrate
  586. # Properly detect empty cert by checking if cert: line exists and has content after it
  587. local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2>/dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  588. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  589. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  590. # Get server IP
  591. local URL_lists=(
  592. "https://api4.ipify.org"
  593. "https://ipv4.icanhazip.com"
  594. "https://v4.api.ipinfo.io/ip"
  595. "https://ipv4.myexternalip.com/raw"
  596. "https://4.ident.me"
  597. "https://check-host.net/ip"
  598. )
  599. local server_ip=""
  600. for ip_address in "${URL_lists[@]}"; do
  601. server_ip=$(${curl_bin} -s --max-time 3 "${ip_address}" 2>/dev/null | tr -d '[:space:]')
  602. if [[ -n "${server_ip}" ]]; then
  603. break
  604. fi
  605. done
  606. # Handle missing/short webBasePath
  607. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  608. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  609. local config_webBasePath=$(gen_random_string 18)
  610. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  611. existing_webBasePath="${config_webBasePath}"
  612. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  613. fi
  614. # Check and prompt for SSL if missing
  615. if [[ -z "$existing_cert" ]]; then
  616. echo ""
  617. echo -e "${red}═══════════════════════════════════════════${plain}"
  618. echo -e "${red} ⚠ NO SSL CERTIFICATE DETECTED ⚠ ${plain}"
  619. echo -e "${red}═══════════════════════════════════════════${plain}"
  620. echo -e "${yellow}For security, SSL certificate is MANDATORY for all panels.${plain}"
  621. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  622. echo ""
  623. if [[ -z "${server_ip}" ]]; then
  624. echo -e "${red}Failed to detect server IP${plain}"
  625. echo -e "${yellow}Please configure SSL manually using: x-ui${plain}"
  626. return
  627. fi
  628. # Prompt and setup SSL (domain or IP)
  629. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  630. echo ""
  631. echo -e "${green}═══════════════════════════════════════════${plain}"
  632. echo -e "${green} Panel Access Information ${plain}"
  633. echo -e "${green}═══════════════════════════════════════════${plain}"
  634. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  635. echo -e "${green}═══════════════════════════════════════════${plain}"
  636. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  637. else
  638. echo -e "${green}SSL certificate is already configured${plain}"
  639. # Show access URL with existing certificate
  640. local cert_domain=$(basename "$(dirname "$existing_cert")")
  641. echo ""
  642. echo -e "${green}═══════════════════════════════════════════${plain}"
  643. echo -e "${green} Panel Access Information ${plain}"
  644. echo -e "${green}═══════════════════════════════════════════${plain}"
  645. echo -e "${green}Access URL: https://${cert_domain}:${existing_port}/${existing_webBasePath}${plain}"
  646. echo -e "${green}═══════════════════════════════════════════${plain}"
  647. fi
  648. }
  649. update_x-ui() {
  650. cd ${xui_folder%/x-ui}/
  651. if [ -f "${xui_folder}/x-ui" ]; then
  652. current_xui_version=$(${xui_folder}/x-ui -v)
  653. echo -e "${green}Current x-ui version: ${current_xui_version}${plain}"
  654. else
  655. _fail "ERROR: Current x-ui version: unknown"
  656. fi
  657. echo -e "${green}Downloading new x-ui version...${plain}"
  658. 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/')
  659. if [[ ! -n "$tag_version" ]]; then
  660. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  661. tag_version=$(${curl_bin} -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  662. if [[ ! -n "$tag_version" ]]; then
  663. _fail "ERROR: Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later"
  664. fi
  665. fi
  666. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  667. ${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
  668. if [[ $? -ne 0 ]]; then
  669. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  670. ${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
  671. if [[ $? -ne 0 ]]; then
  672. _fail "ERROR: Failed to download x-ui, please be sure that your server can access GitHub"
  673. fi
  674. fi
  675. if [[ -e ${xui_folder}/ ]]; then
  676. echo -e "${green}Stopping x-ui...${plain}"
  677. if [[ $release == "alpine" ]]; then
  678. if [ -f "/etc/init.d/x-ui" ]; then
  679. rc-service x-ui stop >/dev/null 2>&1
  680. rc-update del x-ui >/dev/null 2>&1
  681. echo -e "${green}Removing old service unit version...${plain}"
  682. rm -f /etc/init.d/x-ui >/dev/null 2>&1
  683. else
  684. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  685. _fail "ERROR: x-ui service unit not installed."
  686. fi
  687. else
  688. if [ -f "${xui_service}/x-ui.service" ]; then
  689. systemctl stop x-ui >/dev/null 2>&1
  690. systemctl disable x-ui >/dev/null 2>&1
  691. echo -e "${green}Removing old systemd unit version...${plain}"
  692. rm ${xui_service}/x-ui.service -f >/dev/null 2>&1
  693. systemctl daemon-reload >/dev/null 2>&1
  694. else
  695. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  696. _fail "ERROR: x-ui systemd unit not installed."
  697. fi
  698. fi
  699. echo -e "${green}Removing old x-ui version...${plain}"
  700. rm ${xui_folder} -f >/dev/null 2>&1
  701. rm ${xui_folder}/x-ui.service -f >/dev/null 2>&1
  702. rm ${xui_folder}/x-ui.service.debian -f >/dev/null 2>&1
  703. rm ${xui_folder}/x-ui.service.arch -f >/dev/null 2>&1
  704. rm ${xui_folder}/x-ui.service.rhel -f >/dev/null 2>&1
  705. rm ${xui_folder}/x-ui -f >/dev/null 2>&1
  706. rm ${xui_folder}/x-ui.sh -f >/dev/null 2>&1
  707. echo -e "${green}Removing old xray version...${plain}"
  708. rm ${xui_folder}/bin/xray-linux-amd64 -f >/dev/null 2>&1
  709. echo -e "${green}Removing old README and LICENSE file...${plain}"
  710. rm ${xui_folder}/bin/README.md -f >/dev/null 2>&1
  711. rm ${xui_folder}/bin/LICENSE -f >/dev/null 2>&1
  712. else
  713. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  714. _fail "ERROR: x-ui not installed."
  715. fi
  716. echo -e "${green}Installing new x-ui version...${plain}"
  717. tar zxvf x-ui-linux-$(arch).tar.gz >/dev/null 2>&1
  718. rm x-ui-linux-$(arch).tar.gz -f >/dev/null 2>&1
  719. cd x-ui >/dev/null 2>&1
  720. chmod +x x-ui >/dev/null 2>&1
  721. # Check the system's architecture and rename the file accordingly
  722. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  723. mv bin/xray-linux-$(arch) bin/xray-linux-arm >/dev/null 2>&1
  724. chmod +x bin/xray-linux-arm >/dev/null 2>&1
  725. fi
  726. chmod +x x-ui bin/xray-linux-$(arch) >/dev/null 2>&1
  727. echo -e "${green}Downloading and installing x-ui.sh script...${plain}"
  728. ${curl_bin} -fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh >/dev/null 2>&1
  729. if [[ $? -ne 0 ]]; then
  730. echo -e "${yellow}Trying to fetch x-ui with IPv4...${plain}"
  731. ${curl_bin} -4fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh >/dev/null 2>&1
  732. if [[ $? -ne 0 ]]; then
  733. _fail "ERROR: Failed to download x-ui.sh script, please be sure that your server can access GitHub"
  734. fi
  735. fi
  736. chmod +x ${xui_folder}/x-ui.sh >/dev/null 2>&1
  737. chmod +x /usr/bin/x-ui >/dev/null 2>&1
  738. mkdir -p /var/log/x-ui >/dev/null 2>&1
  739. echo -e "${green}Changing owner...${plain}"
  740. chown -R root:root ${xui_folder} >/dev/null 2>&1
  741. if [ -f "${xui_folder}/bin/config.json" ]; then
  742. echo -e "${green}Changing on config file permissions...${plain}"
  743. chmod 640 ${xui_folder}/bin/config.json >/dev/null 2>&1
  744. fi
  745. if [[ $release == "alpine" ]]; then
  746. echo -e "${green}Downloading and installing startup unit x-ui.rc...${plain}"
  747. ${curl_bin} -fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc >/dev/null 2>&1
  748. if [[ $? -ne 0 ]]; then
  749. ${curl_bin} -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc >/dev/null 2>&1
  750. if [[ $? -ne 0 ]]; then
  751. _fail "ERROR: Failed to download startup unit x-ui.rc, please be sure that your server can access GitHub"
  752. fi
  753. fi
  754. chmod +x /etc/init.d/x-ui >/dev/null 2>&1
  755. chown root:root /etc/init.d/x-ui >/dev/null 2>&1
  756. rc-update add x-ui >/dev/null 2>&1
  757. rc-service x-ui start >/dev/null 2>&1
  758. else
  759. if [ -f "x-ui.service" ]; then
  760. echo -e "${green}Installing systemd unit...${plain}"
  761. cp -f x-ui.service ${xui_service}/ >/dev/null 2>&1
  762. if [[ $? -ne 0 ]]; then
  763. echo -e "${red}Failed to copy x-ui.service${plain}"
  764. exit 1
  765. fi
  766. else
  767. service_installed=false
  768. case "${release}" in
  769. ubuntu | debian | armbian)
  770. if [ -f "x-ui.service.debian" ]; then
  771. echo -e "${green}Installing debian-like systemd unit...${plain}"
  772. cp -f x-ui.service.debian ${xui_service}/x-ui.service >/dev/null 2>&1
  773. if [[ $? -eq 0 ]]; then
  774. service_installed=true
  775. fi
  776. fi
  777. ;;
  778. arch | manjaro | parch)
  779. if [ -f "x-ui.service.arch" ]; then
  780. echo -e "${green}Installing arch-like systemd unit...${plain}"
  781. cp -f x-ui.service.arch ${xui_service}/x-ui.service >/dev/null 2>&1
  782. if [[ $? -eq 0 ]]; then
  783. service_installed=true
  784. fi
  785. fi
  786. ;;
  787. *)
  788. if [ -f "x-ui.service.rhel" ]; then
  789. echo -e "${green}Installing rhel-like systemd unit...${plain}"
  790. cp -f x-ui.service.rhel ${xui_service}/x-ui.service >/dev/null 2>&1
  791. if [[ $? -eq 0 ]]; then
  792. service_installed=true
  793. fi
  794. fi
  795. ;;
  796. esac
  797. # If service file not found in tar.gz, download from GitHub
  798. if [ "$service_installed" = false ]; then
  799. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  800. case "${release}" in
  801. ubuntu | debian | armbian)
  802. ${curl_bin} -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian >/dev/null 2>&1
  803. ;;
  804. arch | manjaro | parch)
  805. ${curl_bin} -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch >/dev/null 2>&1
  806. ;;
  807. *)
  808. ${curl_bin} -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel >/dev/null 2>&1
  809. ;;
  810. esac
  811. if [[ $? -ne 0 ]]; then
  812. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  813. exit 1
  814. fi
  815. fi
  816. fi
  817. chown root:root ${xui_service}/x-ui.service >/dev/null 2>&1
  818. chmod 644 ${xui_service}/x-ui.service >/dev/null 2>&1
  819. systemctl daemon-reload >/dev/null 2>&1
  820. systemctl enable x-ui >/dev/null 2>&1
  821. systemctl start x-ui >/dev/null 2>&1
  822. fi
  823. config_after_update
  824. echo -e "${green}x-ui ${tag_version}${plain} updating finished, it is running now..."
  825. echo -e ""
  826. echo -e "┌───────────────────────────────────────────────────────┐
  827. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  828. │ │
  829. │ ${blue}x-ui${plain} - Admin Management Script │
  830. │ ${blue}x-ui start${plain} - Start │
  831. │ ${blue}x-ui stop${plain} - Stop │
  832. │ ${blue}x-ui restart${plain} - Restart │
  833. │ ${blue}x-ui status${plain} - Current Status │
  834. │ ${blue}x-ui settings${plain} - Current Settings │
  835. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  836. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  837. │ ${blue}x-ui log${plain} - Check logs │
  838. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  839. │ ${blue}x-ui update${plain} - Update │
  840. │ ${blue}x-ui legacy${plain} - Legacy version │
  841. │ ${blue}x-ui install${plain} - Install │
  842. │ ${blue}x-ui uninstall${plain} - Uninstall │
  843. └───────────────────────────────────────────────────────┘"
  844. }
  845. echo -e "${green}Running...${plain}"
  846. install_base
  847. update_x-ui $1