update.sh 40 KB

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