x-ui.sh 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290
  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. #Add some basic function here
  8. function LOGD() {
  9. echo -e "${yellow}[DEG] $* ${plain}"
  10. }
  11. function LOGE() {
  12. echo -e "${red}[ERR] $* ${plain}"
  13. }
  14. function LOGI() {
  15. echo -e "${green}[INF] $* ${plain}"
  16. }
  17. # Port helpers: detect listener and owning process (best effort)
  18. is_port_in_use() {
  19. local port="$1"
  20. if command -v ss > /dev/null 2>&1; then
  21. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  22. return
  23. fi
  24. if command -v netstat > /dev/null 2>&1; then
  25. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  26. return
  27. fi
  28. if command -v lsof > /dev/null 2>&1; then
  29. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  30. fi
  31. return 1
  32. }
  33. # Simple helpers for domain/IP validation
  34. is_ipv4() {
  35. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  36. }
  37. is_ipv6() {
  38. [[ "$1" =~ : ]] && return 0 || return 1
  39. }
  40. is_ip() {
  41. is_ipv4 "$1" || is_ipv6 "$1"
  42. }
  43. is_domain() {
  44. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  45. }
  46. # acme.sh's standalone server binds IPv4 by default; --listen-v6 makes it
  47. # v6-only, which breaks HTTP-01 validation when the domain's A record points
  48. # at this host's IPv4 (#4994). Only force IPv6 when the host has no global
  49. # IPv4 address at all.
  50. acme_listen_flag() {
  51. if ip -4 addr show scope global 2> /dev/null | grep -q "inet "; then
  52. echo ""
  53. else
  54. echo "--listen-v6"
  55. fi
  56. }
  57. # check root
  58. [[ $EUID -ne 0 ]] && LOGE "ERROR: You must be root to run this script! \n" && exit 1
  59. # Check OS and set release variable
  60. if [[ -f /etc/os-release ]]; then
  61. source /etc/os-release
  62. release=$ID
  63. elif [[ -f /usr/lib/os-release ]]; then
  64. source /usr/lib/os-release
  65. release=$ID
  66. else
  67. echo "Failed to check the system OS, please contact the author!" >&2
  68. exit 1
  69. fi
  70. echo "The OS release is: $release"
  71. os_version=""
  72. os_version=$(grep "^VERSION_ID" /etc/os-release | cut -d '=' -f2 | tr -d '"' | tr -d '.')
  73. running_in_docker="false"
  74. if [[ -f /.dockerenv ]] || [[ "${XUI_IN_DOCKER}" == "true" ]]; then
  75. running_in_docker="true"
  76. fi
  77. # Declare Variables
  78. if [[ "${running_in_docker}" == "true" ]]; then
  79. xui_folder="${XUI_MAIN_FOLDER:=/app}"
  80. else
  81. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  82. fi
  83. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  84. log_folder="${XUI_LOG_FOLDER:=/var/log/x-ui}"
  85. mkdir -p "${log_folder}"
  86. iplimit_log_path="${log_folder}/3xipl.log"
  87. iplimit_banned_log_path="${log_folder}/3xipl-banned.log"
  88. confirm() {
  89. if [[ $# > 1 ]]; then
  90. echo && read -rp "$1 [Default $2]: " temp
  91. if [[ "${temp}" == "" ]]; then
  92. temp=$2
  93. fi
  94. else
  95. read -rp "$1 [y/n]: " temp
  96. fi
  97. if [[ "${temp}" == "y" || "${temp}" == "Y" ]]; then
  98. return 0
  99. else
  100. return 1
  101. fi
  102. }
  103. confirm_restart() {
  104. confirm "Restart the panel, Attention: Restarting the panel will also restart xray" "y"
  105. if [[ $? == 0 ]]; then
  106. restart
  107. else
  108. show_menu
  109. fi
  110. }
  111. before_show_menu() {
  112. echo && echo -n -e "${yellow}Press enter to return to the main menu: ${plain}" && read -r temp
  113. show_menu
  114. }
  115. install() {
  116. bash <(curl -Ls https://raw.githubusercontent.com/MHSanaei/3x-ui/main/install.sh)
  117. if [[ $? == 0 ]]; then
  118. if [[ $# == 0 ]]; then
  119. start
  120. else
  121. start 0
  122. fi
  123. fi
  124. }
  125. update() {
  126. confirm "This function will update all x-ui components to the latest version, and the data will not be lost. Do you want to continue?" "y"
  127. if [[ $? != 0 ]]; then
  128. LOGE "Cancelled"
  129. if [[ $# == 0 ]]; then
  130. before_show_menu
  131. fi
  132. return 0
  133. fi
  134. bash <(curl -Ls https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh)
  135. if [[ $? == 0 ]]; then
  136. LOGI "Update is complete, Panel has automatically restarted "
  137. before_show_menu
  138. fi
  139. }
  140. update_menu() {
  141. echo -e "${yellow}Updating Menu${plain}"
  142. confirm "This function will update the menu to the latest changes." "y"
  143. if [[ $? != 0 ]]; then
  144. LOGE "Cancelled"
  145. if [[ $# == 0 ]]; then
  146. before_show_menu
  147. fi
  148. return 0
  149. fi
  150. curl -fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  151. chmod +x ${xui_folder}/x-ui.sh
  152. chmod +x /usr/bin/x-ui
  153. if [[ $? == 0 ]]; then
  154. echo -e "${green}Update successful. The panel has automatically restarted.${plain}"
  155. exit 0
  156. else
  157. echo -e "${red}Failed to update the menu.${plain}"
  158. return 1
  159. fi
  160. }
  161. legacy_version() {
  162. echo -n "Enter the panel version (like 2.4.0):"
  163. read -r tag_version
  164. if [ -z "$tag_version" ]; then
  165. echo "Panel version cannot be empty. Exiting."
  166. exit 1
  167. fi
  168. # Use the entered panel version in the download link
  169. install_command="bash <(curl -Ls "https://raw.githubusercontent.com/mhsanaei/3x-ui/v$tag_version/install.sh") v$tag_version"
  170. echo "Downloading and installing panel version $tag_version..."
  171. eval $install_command
  172. }
  173. # Function to handle the deletion of the script file
  174. delete_script() {
  175. rm "$0" # Remove the script file itself
  176. exit 1
  177. }
  178. xui_env_file_path() {
  179. case "${release}" in
  180. ubuntu | debian | armbian)
  181. echo "/etc/default/x-ui"
  182. ;;
  183. arch | manjaro | parch | alpine)
  184. echo "/etc/conf.d/x-ui"
  185. ;;
  186. *)
  187. echo "/etc/sysconfig/x-ui"
  188. ;;
  189. esac
  190. }
  191. uninstall() {
  192. confirm "Are you sure you want to uninstall the panel? xray will also uninstalled!" "n"
  193. if [[ $? != 0 ]]; then
  194. if [[ $# == 0 ]]; then
  195. show_menu
  196. fi
  197. return 0
  198. fi
  199. if [[ $release == "alpine" ]]; then
  200. rc-service x-ui stop
  201. rc-update del x-ui
  202. rm /etc/init.d/x-ui -f
  203. else
  204. systemctl stop x-ui
  205. systemctl disable x-ui
  206. rm ${xui_service}/x-ui.service -f
  207. systemctl daemon-reload
  208. systemctl reset-failed
  209. fi
  210. rm /etc/x-ui/ -rf
  211. rm ${xui_folder}/ -rf
  212. rm -f "$(xui_env_file_path)"
  213. echo ""
  214. echo -e "Uninstalled Successfully.\n"
  215. echo "If you need to install this panel again, you can use below command:"
  216. echo -e "${green}bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)${plain}"
  217. echo ""
  218. # Trap the SIGTERM signal
  219. trap delete_script SIGTERM
  220. delete_script
  221. }
  222. reset_user() {
  223. confirm "Are you sure to reset the username and password of the panel?" "n"
  224. if [[ $? != 0 ]]; then
  225. if [[ $# == 0 ]]; then
  226. show_menu
  227. fi
  228. return 0
  229. fi
  230. read -rp "Please set the login username [default is a random username]: " config_account
  231. [[ -z $config_account ]] && config_account=$(gen_random_string 10)
  232. read -rp "Please set the login password [default is a random password]: " config_password
  233. [[ -z $config_password ]] && config_password=$(gen_random_string 18)
  234. read -rp "Do you want to disable currently configured two-factor authentication? (y/n): " twoFactorConfirm
  235. if [[ $twoFactorConfirm != "y" && $twoFactorConfirm != "Y" ]]; then
  236. ${xui_folder}/x-ui setting -username "${config_account}" -password "${config_password}" > /dev/null 2>&1
  237. else
  238. ${xui_folder}/x-ui setting -username "${config_account}" -password "${config_password}" -resetTwoFactor=true > /dev/null 2>&1
  239. echo -e "Two factor authentication has been disabled."
  240. fi
  241. echo -e "Panel login username has been reset to: ${green} ${config_account} ${plain}"
  242. echo -e "Panel login password has been reset to: ${green} ${config_password} ${plain}"
  243. echo -e "${green} Please use the new login username and password to access the X-UI panel. Also remember them! ${plain}"
  244. confirm_restart
  245. }
  246. gen_random_string() {
  247. local length="$1"
  248. openssl rand -base64 $((length * 2)) \
  249. | tr -dc 'a-zA-Z0-9' \
  250. | head -c "$length"
  251. }
  252. reset_webbasepath() {
  253. echo -e "${yellow}Resetting Web Base Path${plain}"
  254. read -rp "Are you sure you want to reset the web base path? (y/n): " confirm
  255. if [[ $confirm != "y" && $confirm != "Y" ]]; then
  256. echo -e "${yellow}Operation canceled.${plain}"
  257. return
  258. fi
  259. config_webBasePath=$(gen_random_string 18)
  260. # Apply the new web base path setting
  261. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}" > /dev/null 2>&1
  262. echo -e "Web base path has been reset to: ${green}${config_webBasePath}${plain}"
  263. echo -e "${green}Please use the new web base path to access the panel.${plain}"
  264. restart
  265. }
  266. reset_config() {
  267. confirm "Are you sure you want to reset all panel settings, Account data will not be lost, Username and password will not change" "n"
  268. if [[ $? != 0 ]]; then
  269. if [[ $# == 0 ]]; then
  270. show_menu
  271. fi
  272. return 0
  273. fi
  274. ${xui_folder}/x-ui setting -reset
  275. echo -e "All panel settings have been reset to default."
  276. restart
  277. }
  278. check_config() {
  279. local info=$(${xui_folder}/x-ui setting -show true)
  280. if [[ $? != 0 ]]; then
  281. LOGE "get current settings error, please check logs"
  282. show_menu
  283. return
  284. fi
  285. LOGI "${info}"
  286. local db_env_file
  287. db_env_file="$(xui_env_file_path)"
  288. if [[ -r "$db_env_file" ]] && grep -q '^XUI_DB_TYPE=postgres' "$db_env_file"; then
  289. local dsn
  290. dsn="$(grep -E '^XUI_DB_DSN=' "$db_env_file" | head -1 | cut -d= -f2-)"
  291. local dsn_safe
  292. dsn_safe="$(echo "$dsn" | sed -E 's|(://[^:/@]+:)[^@]+@|\1****@|')"
  293. echo -e "${green}Database: PostgreSQL — ${dsn_safe}${plain}"
  294. else
  295. echo -e "${green}Database: SQLite (/etc/x-ui/x-ui.db)${plain}"
  296. fi
  297. local existing_webBasePath=$(echo "$info" | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  298. local existing_port=$(echo "$info" | grep -Eo 'port: .+' | awk '{print $2}')
  299. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  300. local URL_lists=(
  301. "https://api4.ipify.org"
  302. "https://ipv4.icanhazip.com"
  303. "https://v4.api.ipinfo.io/ip"
  304. "https://ipv4.myexternalip.com/raw"
  305. "https://4.ident.me"
  306. "https://check-host.net/ip"
  307. )
  308. local server_ip=""
  309. for ip_address in "${URL_lists[@]}"; do
  310. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  311. local http_code=$(echo "$response" | tail -n1)
  312. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  313. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  314. server_ip="${ip_result}"
  315. break
  316. fi
  317. done
  318. if [[ -z "$server_ip" ]]; then
  319. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  320. while [[ -z "$server_ip" ]]; do
  321. read -rp "Please enter your server's public IPv4 address: " server_ip
  322. server_ip="${server_ip// /}"
  323. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  324. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  325. server_ip=""
  326. fi
  327. done
  328. fi
  329. if [[ -n "$existing_cert" ]]; then
  330. local domain=$(basename "$(dirname "$existing_cert")")
  331. # The cert folder name is only the certificate's first domain. A
  332. # multidomain (SAN) certificate may be served under any name it covers,
  333. # so read the real names from the certificate itself (#5070).
  334. local cert_sans=""
  335. if [[ -f "$existing_cert" ]] && command -v openssl > /dev/null 2>&1; then
  336. cert_sans=$(openssl x509 -in "$existing_cert" -noout -ext subjectAltName 2> /dev/null \
  337. | grep -Eo 'DNS:[^,[:space:]]+' | cut -d: -f2)
  338. if [[ -n "$cert_sans" ]] && ! echo "$cert_sans" | grep -qx "$domain"; then
  339. domain=$(echo "$cert_sans" | head -n1)
  340. fi
  341. fi
  342. if [[ "$domain" =~ ^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
  343. echo -e "${green}Access URL: https://${domain}:${existing_port}${existing_webBasePath}${plain}"
  344. else
  345. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  346. fi
  347. if [[ -n "$cert_sans" && $(echo "$cert_sans" | wc -l) -gt 1 ]]; then
  348. echo -e "${yellow}The certificate also covers:${plain} $(echo "$cert_sans" | grep -vx "$domain" | tr '\n' ' ')"
  349. fi
  350. else
  351. echo -e "${red}⚠ WARNING: No SSL certificate configured!${plain}"
  352. echo -e "${yellow}You can get a Let's Encrypt certificate for your IP address (valid ~6 days, auto-renews).${plain}"
  353. read -rp "Generate SSL certificate for IP now? [y/N]: " gen_ssl
  354. if [[ "$gen_ssl" == "y" || "$gen_ssl" == "Y" ]]; then
  355. stop 0 > /dev/null 2>&1
  356. ssl_cert_issue_for_ip
  357. if [[ $? -eq 0 ]]; then
  358. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  359. # ssl_cert_issue_for_ip already restarts the panel, but ensure it's running
  360. start 0 > /dev/null 2>&1
  361. else
  362. LOGE "IP certificate setup failed."
  363. echo -e "${yellow}You can try again via option 19 (SSL Certificate Management).${plain}"
  364. start 0 > /dev/null 2>&1
  365. fi
  366. else
  367. echo -e "${yellow}Access URL: http://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  368. echo -e "${yellow}For security, please configure SSL certificate using option 19 (SSL Certificate Management)${plain}"
  369. fi
  370. fi
  371. }
  372. set_port() {
  373. echo -n "Enter port number[1-65535]: "
  374. read -r port
  375. if [[ -z "${port}" ]]; then
  376. LOGD "Cancelled"
  377. before_show_menu
  378. else
  379. ${xui_folder}/x-ui setting -port ${port}
  380. echo -e "The port is set, Please restart the panel now, and use the new port ${green}${port}${plain} to access web panel"
  381. confirm_restart
  382. fi
  383. }
  384. start() {
  385. check_status
  386. if [[ $? == 0 ]]; then
  387. echo ""
  388. LOGI "Panel is running, No need to start again, If you need to restart, please select restart"
  389. else
  390. if [[ "${running_in_docker}" == "true" ]]; then
  391. LOGE "Panel process is not running inside this container."
  392. LOGI "In Docker the panel is the container's main process. Restart the container to bring it back up:"
  393. LOGI " docker restart <container_name>"
  394. if [[ $# == 0 ]]; then
  395. before_show_menu
  396. fi
  397. return 0
  398. fi
  399. if [[ $release == "alpine" ]]; then
  400. rc-service x-ui start
  401. else
  402. systemctl start x-ui
  403. fi
  404. sleep 2
  405. check_status
  406. if [[ $? == 0 ]]; then
  407. LOGI "x-ui Started Successfully"
  408. else
  409. LOGE "panel Failed to start, Probably because it takes longer than two seconds to start, Please check the log information later"
  410. fi
  411. fi
  412. if [[ $# == 0 ]]; then
  413. before_show_menu
  414. fi
  415. }
  416. stop() {
  417. check_status
  418. if [[ $? == 1 ]]; then
  419. echo ""
  420. LOGI "Panel stopped, No need to stop again!"
  421. else
  422. if [[ "${running_in_docker}" == "true" ]]; then
  423. LOGI "In Docker the panel runs as the container's main process."
  424. LOGI "To stop it, stop the container from the host:"
  425. LOGI " docker stop <container_name>"
  426. if [[ $# == 0 ]]; then
  427. before_show_menu
  428. fi
  429. return 0
  430. fi
  431. if [[ $release == "alpine" ]]; then
  432. rc-service x-ui stop
  433. else
  434. systemctl stop x-ui
  435. fi
  436. sleep 2
  437. check_status
  438. if [[ $? == 1 ]]; then
  439. LOGI "x-ui and xray stopped successfully"
  440. else
  441. LOGE "Panel stop failed, Probably because the stop time exceeds two seconds, Please check the log information later"
  442. fi
  443. fi
  444. if [[ $# == 0 ]]; then
  445. before_show_menu
  446. fi
  447. }
  448. restart() {
  449. if [[ "${running_in_docker}" == "true" ]]; then
  450. if signal_xui HUP; then
  451. sleep 1
  452. signal_xui USR1
  453. LOGI "Restart signal sent to the panel and xray-core."
  454. else
  455. LOGE "Could not find the running panel process to signal."
  456. fi
  457. sleep 2
  458. check_status
  459. if [[ $? == 0 ]]; then
  460. LOGI "x-ui and xray Restarted successfully"
  461. else
  462. LOGE "Panel restart failed, Please check the log information later"
  463. fi
  464. if [[ $# == 0 ]]; then
  465. before_show_menu
  466. fi
  467. return 0
  468. fi
  469. if [[ $release == "alpine" ]]; then
  470. rc-service x-ui restart
  471. else
  472. systemctl restart x-ui
  473. fi
  474. sleep 2
  475. check_status
  476. if [[ $? == 0 ]]; then
  477. LOGI "x-ui and xray Restarted successfully"
  478. else
  479. LOGE "Panel restart failed, Probably because it takes longer than two seconds to start, Please check the log information later"
  480. fi
  481. if [[ $# == 0 ]]; then
  482. before_show_menu
  483. fi
  484. }
  485. restart_xray() {
  486. if [[ "${running_in_docker}" == "true" ]]; then
  487. if signal_xui USR1; then
  488. LOGI "xray-core Restart signal sent successfully, Please check the log information to confirm whether xray restarted successfully"
  489. else
  490. LOGE "Could not find the running panel process to signal."
  491. fi
  492. sleep 2
  493. show_xray_status
  494. if [[ $# == 0 ]]; then
  495. before_show_menu
  496. fi
  497. return 0
  498. fi
  499. if [[ $release == "alpine" ]]; then
  500. rc-service x-ui reload
  501. else
  502. systemctl reload x-ui
  503. fi
  504. LOGI "xray-core Restart signal sent successfully, Please check the log information to confirm whether xray restarted successfully"
  505. sleep 2
  506. show_xray_status
  507. if [[ $# == 0 ]]; then
  508. before_show_menu
  509. fi
  510. }
  511. status() {
  512. if [[ "${running_in_docker}" == "true" ]]; then
  513. show_status
  514. if [[ $# == 0 ]]; then
  515. before_show_menu
  516. fi
  517. return 0
  518. fi
  519. if [[ $release == "alpine" ]]; then
  520. rc-service x-ui status
  521. else
  522. systemctl status x-ui -l
  523. fi
  524. if [[ $# == 0 ]]; then
  525. before_show_menu
  526. fi
  527. }
  528. enable() {
  529. if [[ "${running_in_docker}" == "true" ]]; then
  530. LOGI "Autostart is controlled by the Docker restart policy (e.g. 'restart: unless-stopped' in docker-compose.yml)."
  531. LOGI "There is no service to enable inside the container."
  532. if [[ $# == 0 ]]; then
  533. before_show_menu
  534. fi
  535. return 0
  536. fi
  537. if [[ $release == "alpine" ]]; then
  538. rc-update add x-ui default
  539. else
  540. systemctl enable x-ui
  541. fi
  542. if [[ $? == 0 ]]; then
  543. LOGI "x-ui Set to boot automatically on startup successfully"
  544. else
  545. LOGE "x-ui Failed to set Autostart"
  546. fi
  547. if [[ $# == 0 ]]; then
  548. before_show_menu
  549. fi
  550. }
  551. disable() {
  552. if [[ "${running_in_docker}" == "true" ]]; then
  553. LOGI "Autostart is controlled by the Docker restart policy (e.g. 'restart: unless-stopped' in docker-compose.yml)."
  554. LOGI "Set 'restart: no' for the container on the host to disable autostart."
  555. if [[ $# == 0 ]]; then
  556. before_show_menu
  557. fi
  558. return 0
  559. fi
  560. if [[ $release == "alpine" ]]; then
  561. rc-update del x-ui
  562. else
  563. systemctl disable x-ui
  564. fi
  565. if [[ $? == 0 ]]; then
  566. LOGI "x-ui Autostart Cancelled successfully"
  567. else
  568. LOGE "x-ui Failed to cancel autostart"
  569. fi
  570. if [[ $# == 0 ]]; then
  571. before_show_menu
  572. fi
  573. }
  574. show_log() {
  575. if [[ $release == "alpine" ]]; then
  576. echo -e "${green}\t1.${plain} Debug Log"
  577. echo -e "${green}\t0.${plain} Back to Main Menu"
  578. read -rp "Choose an option: " choice
  579. case "$choice" in
  580. 0)
  581. show_menu
  582. ;;
  583. 1)
  584. grep -F 'x-ui[' /var/log/messages
  585. if [[ $# == 0 ]]; then
  586. before_show_menu
  587. fi
  588. ;;
  589. *)
  590. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  591. show_log
  592. ;;
  593. esac
  594. else
  595. echo -e "${green}\t1.${plain} Debug Log"
  596. echo -e "${green}\t2.${plain} Clear All logs"
  597. echo -e "${green}\t0.${plain} Back to Main Menu"
  598. read -rp "Choose an option: " choice
  599. case "$choice" in
  600. 0)
  601. show_menu
  602. ;;
  603. 1)
  604. journalctl -u x-ui -e --no-pager -f -p debug
  605. if [[ $# == 0 ]]; then
  606. before_show_menu
  607. fi
  608. ;;
  609. 2)
  610. sudo journalctl --rotate
  611. sudo journalctl --vacuum-time=1s
  612. echo "All Logs cleared."
  613. restart
  614. ;;
  615. *)
  616. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  617. show_log
  618. ;;
  619. esac
  620. fi
  621. }
  622. bbr_menu() {
  623. echo -e "${green}\t1.${plain} Enable BBR"
  624. echo -e "${green}\t2.${plain} Disable BBR"
  625. echo -e "${green}\t0.${plain} Back to Main Menu"
  626. read -rp "Choose an option: " choice
  627. case "$choice" in
  628. 0)
  629. show_menu
  630. ;;
  631. 1)
  632. enable_bbr
  633. bbr_menu
  634. ;;
  635. 2)
  636. disable_bbr
  637. bbr_menu
  638. ;;
  639. *)
  640. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  641. bbr_menu
  642. ;;
  643. esac
  644. }
  645. disable_bbr() {
  646. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) != "bbr" ]] || [[ ! $(sysctl -n net.core.default_qdisc) =~ ^(fq|cake)$ ]]; then
  647. echo -e "${yellow}BBR is not currently enabled.${plain}"
  648. before_show_menu
  649. fi
  650. if [ -f "/etc/sysctl.d/99-bbr-x-ui.conf" ]; then
  651. old_settings=$(head -1 /etc/sysctl.d/99-bbr-x-ui.conf | tr -d '#')
  652. # sysctl -w already restores the live values, so no `sysctl --system`
  653. # afterwards — it would re-apply every sysctl file on the host and
  654. # surface unrelated errors from the distro's own defaults (see issue #5160)
  655. sysctl -w net.core.default_qdisc="${old_settings%:*}"
  656. sysctl -w net.ipv4.tcp_congestion_control="${old_settings#*:}"
  657. rm /etc/sysctl.d/99-bbr-x-ui.conf
  658. else
  659. # Replace BBR with CUBIC configurations
  660. if [ -f "/etc/sysctl.conf" ]; then
  661. sed -i 's/net.core.default_qdisc=fq/net.core.default_qdisc=pfifo_fast/' /etc/sysctl.conf
  662. sed -i 's/net.ipv4.tcp_congestion_control=bbr/net.ipv4.tcp_congestion_control=cubic/' /etc/sysctl.conf
  663. sysctl -p
  664. fi
  665. fi
  666. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) != "bbr" ]]; then
  667. echo -e "${green}BBR has been replaced with CUBIC successfully.${plain}"
  668. else
  669. echo -e "${red}Failed to replace BBR with CUBIC. Please check your system configuration.${plain}"
  670. fi
  671. }
  672. enable_bbr() {
  673. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" ]] && [[ $(sysctl -n net.core.default_qdisc) =~ ^(fq|cake)$ ]]; then
  674. echo -e "${green}BBR is already enabled!${plain}"
  675. before_show_menu
  676. fi
  677. # Enable BBR
  678. if [ -d "/etc/sysctl.d/" ]; then
  679. {
  680. echo "#$(sysctl -n net.core.default_qdisc):$(sysctl -n net.ipv4.tcp_congestion_control)"
  681. echo "net.core.default_qdisc = fq"
  682. echo "net.ipv4.tcp_congestion_control = bbr"
  683. } > "/etc/sysctl.d/99-bbr-x-ui.conf"
  684. if [ -f "/etc/sysctl.conf" ]; then
  685. # Backup old settings from sysctl.conf, if any
  686. sed -i 's/^net.core.default_qdisc/# &/' /etc/sysctl.conf
  687. sed -i 's/^net.ipv4.tcp_congestion_control/# &/' /etc/sysctl.conf
  688. fi
  689. # Apply only our config file; `sysctl --system` would re-apply every
  690. # sysctl file on the host and surface unrelated errors from the distro's
  691. # own defaults (see issue #5160)
  692. sysctl -p /etc/sysctl.d/99-bbr-x-ui.conf
  693. else
  694. sed -i '/net.core.default_qdisc/d' /etc/sysctl.conf
  695. sed -i '/net.ipv4.tcp_congestion_control/d' /etc/sysctl.conf
  696. echo "net.core.default_qdisc=fq" | tee -a /etc/sysctl.conf
  697. echo "net.ipv4.tcp_congestion_control=bbr" | tee -a /etc/sysctl.conf
  698. sysctl -p
  699. fi
  700. # Verify that BBR is enabled
  701. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" ]]; then
  702. echo -e "${green}BBR has been enabled successfully.${plain}"
  703. else
  704. echo -e "${red}Failed to enable BBR. Please check your system configuration.${plain}"
  705. fi
  706. }
  707. update_shell() {
  708. curl -fLRo /usr/bin/x-ui -z /usr/bin/x-ui https://github.com/MHSanaei/3x-ui/raw/main/x-ui.sh
  709. if [[ $? != 0 ]]; then
  710. echo ""
  711. LOGE "Failed to download script, Please check whether the machine can connect Github"
  712. before_show_menu
  713. else
  714. chmod +x /usr/bin/x-ui
  715. LOGI "Upgrade script succeeded, Please rerun the script"
  716. before_show_menu
  717. fi
  718. }
  719. xui_pid() {
  720. ps -ef 2> /dev/null | grep -F "${xui_folder}/x-ui" | grep -v grep | awk 'NR==1 {print $1}'
  721. }
  722. signal_xui() {
  723. local sig="$1" pid
  724. pid="$(xui_pid)"
  725. if [[ -z "${pid}" ]]; then
  726. return 1
  727. fi
  728. kill -"${sig}" "${pid}" 2> /dev/null
  729. }
  730. # 0: running, 1: not running, 2: not installed
  731. check_status() {
  732. if [[ "${running_in_docker}" == "true" ]]; then
  733. if [[ ! -x "${xui_folder}/x-ui" ]]; then
  734. return 2
  735. fi
  736. if [[ -n "$(xui_pid)" ]]; then
  737. return 0
  738. else
  739. return 1
  740. fi
  741. fi
  742. if [[ $release == "alpine" ]]; then
  743. if [[ ! -f /etc/init.d/x-ui ]]; then
  744. return 2
  745. fi
  746. if [[ $(rc-service x-ui status | grep -F 'status: started' -c) == 1 ]]; then
  747. return 0
  748. else
  749. return 1
  750. fi
  751. else
  752. if [[ ! -f ${xui_service}/x-ui.service ]]; then
  753. return 2
  754. fi
  755. temp=$(systemctl status x-ui | grep Active | awk '{print $3}' | cut -d "(" -f2 | cut -d ")" -f1)
  756. if [[ "${temp}" == "running" ]]; then
  757. return 0
  758. else
  759. return 1
  760. fi
  761. fi
  762. }
  763. check_enabled() {
  764. if [[ $release == "alpine" ]]; then
  765. if [[ $(rc-update show | grep -F 'x-ui' | grep default -c) == 1 ]]; then
  766. return 0
  767. else
  768. return 1
  769. fi
  770. else
  771. temp=$(systemctl is-enabled x-ui)
  772. if [[ "${temp}" == "enabled" ]]; then
  773. return 0
  774. else
  775. return 1
  776. fi
  777. fi
  778. }
  779. check_uninstall() {
  780. check_status
  781. if [[ $? != 2 ]]; then
  782. echo ""
  783. LOGE "Panel installed, Please do not reinstall"
  784. if [[ $# == 0 ]]; then
  785. before_show_menu
  786. fi
  787. return 1
  788. else
  789. return 0
  790. fi
  791. }
  792. check_install() {
  793. check_status
  794. if [[ $? == 2 ]]; then
  795. echo ""
  796. LOGE "Please install the panel first"
  797. if [[ $# == 0 ]]; then
  798. before_show_menu
  799. fi
  800. return 1
  801. else
  802. return 0
  803. fi
  804. }
  805. show_status() {
  806. check_status
  807. case $? in
  808. 0)
  809. echo -e "Panel state: ${green}Running${plain}"
  810. show_enable_status
  811. ;;
  812. 1)
  813. echo -e "Panel state: ${yellow}Not Running${plain}"
  814. show_enable_status
  815. ;;
  816. 2)
  817. echo -e "Panel state: ${red}Not Installed${plain}"
  818. ;;
  819. esac
  820. show_xray_status
  821. show_mtproto_status
  822. }
  823. show_enable_status() {
  824. if [[ "${running_in_docker}" == "true" ]]; then
  825. echo -e "Start automatically: ${green}Managed by Docker${plain}"
  826. return
  827. fi
  828. check_enabled
  829. if [[ $? == 0 ]]; then
  830. echo -e "Start automatically: ${green}Yes${plain}"
  831. else
  832. echo -e "Start automatically: ${red}No${plain}"
  833. fi
  834. }
  835. check_xray_status() {
  836. count=$(ps -ef | grep "xray-linux" | grep -v "grep" | wc -l)
  837. if [[ count -ne 0 ]]; then
  838. return 0
  839. else
  840. return 1
  841. fi
  842. }
  843. show_xray_status() {
  844. check_xray_status
  845. if [[ $? == 0 ]]; then
  846. echo -e "xray state: ${green}Running${plain}"
  847. else
  848. echo -e "xray state: ${red}Not Running${plain}"
  849. fi
  850. }
  851. # show_mtproto_status reports each mtproto inbound's mtg sidecar (one process per
  852. # inbound, run outside xray). Silent when no mtproto inbound is configured.
  853. show_mtproto_status() {
  854. local cfg_dir="${xui_folder}/bin/mtproto"
  855. local cfgs=()
  856. if [[ -d "${cfg_dir}" ]]; then
  857. for f in "${cfg_dir}"/mtg-*.toml; do
  858. [[ -e "$f" ]] && cfgs+=("$f")
  859. done
  860. fi
  861. [[ ${#cfgs[@]} -eq 0 ]] && return
  862. local running
  863. running=$(ps -ef | grep "mtg-linux" | grep -v "grep" | grep -oE 'mtg-[0-9]+\.toml')
  864. for f in "${cfgs[@]}"; do
  865. local name id bind
  866. name=$(basename "$f")
  867. id=$(echo "${name}" | sed -E 's/mtg-([0-9]+)\.toml/\1/')
  868. bind=$(grep -E '^[[:space:]]*bind-to' "$f" | head -1 | cut -d'"' -f2)
  869. if echo "${running}" | grep -qx "${name}"; then
  870. echo -e "mtproto inbound ${id} (${bind}): ${green}Running${plain}"
  871. else
  872. echo -e "mtproto inbound ${id} (${bind}): ${red}Not Running${plain}"
  873. fi
  874. done
  875. }
  876. firewall_menu() {
  877. echo -e "${green}\t1.${plain} ${green}Install${plain} Firewall"
  878. echo -e "${green}\t2.${plain} Port List [numbered]"
  879. echo -e "${green}\t3.${plain} ${green}Open${plain} Ports"
  880. echo -e "${green}\t4.${plain} ${red}Delete${plain} Ports from List"
  881. echo -e "${green}\t5.${plain} ${green}Enable${plain} Firewall"
  882. echo -e "${green}\t6.${plain} ${red}Disable${plain} Firewall"
  883. echo -e "${green}\t7.${plain} Firewall Status"
  884. echo -e "${green}\t0.${plain} Back to Main Menu"
  885. read -rp "Choose an option: " choice
  886. case "$choice" in
  887. 0)
  888. show_menu
  889. ;;
  890. 1)
  891. install_firewall
  892. firewall_menu
  893. ;;
  894. 2)
  895. ufw status numbered
  896. firewall_menu
  897. ;;
  898. 3)
  899. open_ports
  900. firewall_menu
  901. ;;
  902. 4)
  903. delete_ports
  904. firewall_menu
  905. ;;
  906. 5)
  907. ufw enable
  908. firewall_menu
  909. ;;
  910. 6)
  911. ufw disable
  912. firewall_menu
  913. ;;
  914. 7)
  915. ufw status verbose
  916. firewall_menu
  917. ;;
  918. *)
  919. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  920. firewall_menu
  921. ;;
  922. esac
  923. }
  924. install_firewall() {
  925. if ! command -v ufw &> /dev/null; then
  926. echo "ufw firewall is not installed. Installing now..."
  927. apt-get update
  928. apt-get install -y ufw
  929. else
  930. echo "ufw firewall is already installed"
  931. fi
  932. # Check if the firewall is inactive
  933. if ufw status | grep -q "Status: active"; then
  934. echo "Firewall is already active"
  935. else
  936. echo "Activating firewall..."
  937. # Open the necessary ports
  938. ufw allow ssh
  939. ufw allow http
  940. ufw allow https
  941. ufw allow 2053/tcp #webPort
  942. ufw allow 2096/tcp #subport
  943. # Enable the firewall
  944. ufw --force enable
  945. fi
  946. }
  947. open_ports() {
  948. # Prompt the user to enter the ports they want to open
  949. read -rp "Enter the ports you want to open (e.g. 80,443,2053 or range 400-500): " ports
  950. # Check if the input is valid
  951. if ! [[ $ports =~ ^([0-9]+|[0-9]+-[0-9]+)(,([0-9]+|[0-9]+-[0-9]+))*$ ]]; then
  952. echo "Error: Invalid input. Please enter a comma-separated list of ports or a range of ports (e.g. 80,443,2053 or 400-500)." >&2
  953. exit 1
  954. fi
  955. # Open the specified ports using ufw
  956. IFS=',' read -ra PORT_LIST <<< "$ports"
  957. for port in "${PORT_LIST[@]}"; do
  958. if [[ $port == *-* ]]; then
  959. # Split the range into start and end ports
  960. start_port=$(echo $port | cut -d'-' -f1)
  961. end_port=$(echo $port | cut -d'-' -f2)
  962. # Open the port range
  963. ufw allow $start_port:$end_port/tcp
  964. ufw allow $start_port:$end_port/udp
  965. else
  966. # Open the single port
  967. ufw allow "$port"
  968. fi
  969. done
  970. # Confirm that the ports are opened
  971. echo "Opened the specified ports:"
  972. for port in "${PORT_LIST[@]}"; do
  973. if [[ $port == *-* ]]; then
  974. start_port=$(echo $port | cut -d'-' -f1)
  975. end_port=$(echo $port | cut -d'-' -f2)
  976. # Check if the port range has been successfully opened
  977. (ufw status | grep -q "$start_port:$end_port") && echo "$start_port-$end_port"
  978. else
  979. # Check if the individual port has been successfully opened
  980. (ufw status | grep -q "$port") && echo "$port"
  981. fi
  982. done
  983. }
  984. delete_ports() {
  985. # Display current rules with numbers
  986. echo "Current UFW rules:"
  987. ufw status numbered
  988. # Ask the user how they want to delete rules
  989. echo "Do you want to delete rules by:"
  990. echo "1) Rule numbers"
  991. echo "2) Ports"
  992. read -rp "Enter your choice (1 or 2): " choice
  993. if [[ $choice -eq 1 ]]; then
  994. # Deleting by rule numbers
  995. read -rp "Enter the rule numbers you want to delete (1, 2, etc.): " rule_numbers
  996. # Validate the input
  997. if ! [[ $rule_numbers =~ ^([0-9]+)(,[0-9]+)*$ ]]; then
  998. echo "Error: Invalid input. Please enter a comma-separated list of rule numbers." >&2
  999. exit 1
  1000. fi
  1001. # Split numbers into an array
  1002. IFS=',' read -ra RULE_NUMBERS <<< "$rule_numbers"
  1003. for rule_number in "${RULE_NUMBERS[@]}"; do
  1004. # Delete the rule by number
  1005. ufw delete "$rule_number" || echo "Failed to delete rule number $rule_number"
  1006. done
  1007. echo "Selected rules have been deleted."
  1008. elif [[ $choice -eq 2 ]]; then
  1009. # Deleting by ports
  1010. read -rp "Enter the ports you want to delete (e.g. 80,443,2053 or range 400-500): " ports
  1011. # Validate the input
  1012. if ! [[ $ports =~ ^([0-9]+|[0-9]+-[0-9]+)(,([0-9]+|[0-9]+-[0-9]+))*$ ]]; then
  1013. echo "Error: Invalid input. Please enter a comma-separated list of ports or a range of ports (e.g. 80,443,2053 or 400-500)." >&2
  1014. exit 1
  1015. fi
  1016. # Split ports into an array
  1017. IFS=',' read -ra PORT_LIST <<< "$ports"
  1018. for port in "${PORT_LIST[@]}"; do
  1019. if [[ $port == *-* ]]; then
  1020. # Split the port range
  1021. start_port=$(echo $port | cut -d'-' -f1)
  1022. end_port=$(echo $port | cut -d'-' -f2)
  1023. # Delete the port range
  1024. ufw delete allow $start_port:$end_port/tcp
  1025. ufw delete allow $start_port:$end_port/udp
  1026. else
  1027. # Delete a single port
  1028. ufw delete allow "$port"
  1029. fi
  1030. done
  1031. # Confirmation of deletion
  1032. echo "Deleted the specified ports:"
  1033. for port in "${PORT_LIST[@]}"; do
  1034. if [[ $port == *-* ]]; then
  1035. start_port=$(echo $port | cut -d'-' -f1)
  1036. end_port=$(echo $port | cut -d'-' -f2)
  1037. # Check if the port range has been deleted
  1038. (ufw status | grep -q "$start_port:$end_port") || echo "$start_port-$end_port"
  1039. else
  1040. # Check if the individual port has been deleted
  1041. (ufw status | grep -q "$port") || echo "$port"
  1042. fi
  1043. done
  1044. else
  1045. echo "${red}Error:${plain} Invalid choice. Please enter 1 or 2." >&2
  1046. exit 1
  1047. fi
  1048. }
  1049. update_all_geofiles() {
  1050. local failed=0
  1051. update_geofiles "main" || failed=1
  1052. update_geofiles "IR" || failed=1
  1053. update_geofiles "RU" || failed=1
  1054. return $failed
  1055. }
  1056. update_geofiles() {
  1057. case "${1}" in
  1058. "main")
  1059. dat_files=(geoip geosite)
  1060. dat_source="Loyalsoldier/v2ray-rules-dat"
  1061. ;;
  1062. "IR")
  1063. dat_files=(geoip_IR geosite_IR)
  1064. dat_source="chocolate4u/Iran-v2ray-rules"
  1065. ;;
  1066. "RU")
  1067. dat_files=(geoip_RU geosite_RU)
  1068. dat_source="runetfreedom/russia-v2ray-rules-dat"
  1069. ;;
  1070. esac
  1071. local failed=0 http_code
  1072. for dat in "${dat_files[@]}"; do
  1073. # Remove suffix for remote filename (e.g., geoip_IR -> geoip)
  1074. remote_file="${dat%%_*}"
  1075. # -z skips the download (server answers 304) when the local copy is already current
  1076. http_code=$(curl -sSfLRo ${xui_folder}/bin/${dat}.dat -z ${xui_folder}/bin/${dat}.dat -w '%{http_code}' \
  1077. https://github.com/${dat_source}/releases/latest/download/${remote_file}.dat)
  1078. if [[ $? -ne 0 ]]; then
  1079. echo -e "${red}${dat}.dat: download failed${plain}"
  1080. failed=1
  1081. elif [[ "$http_code" == "304" ]]; then
  1082. echo -e "${dat}.dat: already up to date"
  1083. else
  1084. echo -e "${green}${dat}.dat: updated${plain}"
  1085. geo_updated=1
  1086. fi
  1087. done
  1088. return $failed
  1089. }
  1090. run_geo_update() {
  1091. local name="$1"
  1092. shift
  1093. geo_updated=0
  1094. "$@"
  1095. if [[ $? -ne 0 ]]; then
  1096. echo -e "${red}Some ${name} could not be updated. Check the errors above.${plain}"
  1097. elif [[ $geo_updated -eq 1 ]]; then
  1098. echo -e "${green}${name} have been updated successfully!${plain}"
  1099. restart
  1100. else
  1101. echo -e "${green}${name} are already up to date, restart is not needed.${plain}"
  1102. fi
  1103. }
  1104. update_geo() {
  1105. echo -e "${green}\t1.${plain} Loyalsoldier (geoip.dat, geosite.dat)"
  1106. echo -e "${green}\t2.${plain} chocolate4u (geoip_IR.dat, geosite_IR.dat)"
  1107. echo -e "${green}\t3.${plain} runetfreedom (geoip_RU.dat, geosite_RU.dat)"
  1108. echo -e "${green}\t4.${plain} All"
  1109. echo -e "${green}\t0.${plain} Back to Main Menu"
  1110. read -rp "Choose an option: " choice
  1111. case "$choice" in
  1112. 0)
  1113. show_menu
  1114. ;;
  1115. 1)
  1116. run_geo_update "Loyalsoldier datasets" update_geofiles "main"
  1117. ;;
  1118. 2)
  1119. run_geo_update "chocolate4u datasets" update_geofiles "IR"
  1120. ;;
  1121. 3)
  1122. run_geo_update "runetfreedom datasets" update_geofiles "RU"
  1123. ;;
  1124. 4)
  1125. run_geo_update "geo files" update_all_geofiles
  1126. ;;
  1127. *)
  1128. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1129. update_geo
  1130. ;;
  1131. esac
  1132. before_show_menu
  1133. }
  1134. install_acme() {
  1135. # Check if acme.sh is already installed
  1136. if command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1137. LOGI "acme.sh is already installed."
  1138. return 0
  1139. fi
  1140. LOGI "Installing acme.sh..."
  1141. cd ~ || return 1 # Ensure you can change to the home directory
  1142. curl -s https://get.acme.sh | sh
  1143. if [ $? -ne 0 ]; then
  1144. LOGE "Installation of acme.sh failed."
  1145. return 1
  1146. else
  1147. LOGI "Installation of acme.sh succeeded."
  1148. fi
  1149. return 0
  1150. }
  1151. ssl_cert_issue_main() {
  1152. echo -e "${green}\t1.${plain} Get SSL (Domain)"
  1153. echo -e "${green}\t2.${plain} Revoke & Remove"
  1154. echo -e "${green}\t3.${plain} Force Renew"
  1155. echo -e "${green}\t4.${plain} Show Existing Domains"
  1156. echo -e "${green}\t5.${plain} Set Cert paths for the panel"
  1157. echo -e "${green}\t6.${plain} Get SSL for IP Address (6-day cert, auto-renews)"
  1158. echo -e "${green}\t0.${plain} Back to Main Menu"
  1159. read -rp "Choose an option: " choice
  1160. case "$choice" in
  1161. 0)
  1162. show_menu
  1163. ;;
  1164. 1)
  1165. ssl_cert_issue
  1166. ssl_cert_issue_main
  1167. ;;
  1168. 2)
  1169. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1170. if [ -z "$domains" ]; then
  1171. echo "No certificates found to revoke."
  1172. else
  1173. echo "Existing domains:"
  1174. echo "$domains"
  1175. read -rp "Please enter a domain from the list to revoke and remove the certificate: " domain
  1176. if echo "$domains" | grep -qw "$domain"; then
  1177. # The IP-cert flow (option 6) stores files under /root/cert/ip, but acme.sh
  1178. # tracks the cert under the actual IP address(es). Resolve those so renewal
  1179. # state is torn down too; otherwise the acme.sh cron re-creates the deleted cert.
  1180. local acme_ids="${domain}"
  1181. if [[ "${domain}" == "ip" ]]; then
  1182. acme_ids=$(~/.acme.sh/acme.sh --list 2> /dev/null | awk 'NR>1 {print $1}' | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}$|:')
  1183. fi
  1184. for id in ${acme_ids}; do
  1185. # Best-effort revoke at the CA, then drop acme.sh renewal tracking.
  1186. ~/.acme.sh/acme.sh --revoke -d "${id}" 2> /dev/null
  1187. ~/.acme.sh/acme.sh --remove -d "${id}" 2> /dev/null
  1188. # --remove leaves the cert files on disk, so delete the state dirs (RSA + ECC).
  1189. rm -rf ~/.acme.sh/"${id}" ~/.acme.sh/"${id}_ecc"
  1190. done
  1191. # Delete the local certificate files for this domain.
  1192. rm -rf "/root/cert/${domain}"
  1193. LOGI "Certificate revoked and removed for domain: ${domain}"
  1194. # If the panel currently serves this domain's cert, clear the stored paths
  1195. # so it stops loading the now-deleted files, then restart.
  1196. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1197. if [[ "${existing_cert}" == "/root/cert/${domain}/"* ]]; then
  1198. ${xui_folder}/x-ui cert -reset
  1199. LOGI "Cleared panel certificate paths referencing ${domain}; restarting panel."
  1200. restart
  1201. fi
  1202. else
  1203. echo "Invalid domain entered."
  1204. fi
  1205. fi
  1206. ssl_cert_issue_main
  1207. ;;
  1208. 3)
  1209. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1210. if [ -z "$domains" ]; then
  1211. echo "No certificates found to renew."
  1212. else
  1213. echo "Existing domains:"
  1214. echo "$domains"
  1215. read -rp "Please enter a domain from the list to renew the SSL certificate: " domain
  1216. if echo "$domains" | grep -qw "$domain"; then
  1217. ~/.acme.sh/acme.sh --renew -d ${domain} --force
  1218. LOGI "Certificate forcefully renewed for domain: $domain"
  1219. else
  1220. echo "Invalid domain entered."
  1221. fi
  1222. fi
  1223. ssl_cert_issue_main
  1224. ;;
  1225. 4)
  1226. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1227. if [ -z "$domains" ]; then
  1228. echo "No certificates found under /root/cert."
  1229. else
  1230. echo "Existing domains and their paths:"
  1231. for domain in $domains; do
  1232. local cert_path="/root/cert/${domain}/fullchain.pem"
  1233. local key_path="/root/cert/${domain}/privkey.pem"
  1234. if [[ -f "${cert_path}" && -f "${key_path}" ]]; then
  1235. echo -e "Domain: ${domain}"
  1236. echo -e "\tCertificate Path: ${cert_path}"
  1237. echo -e "\tPrivate Key Path: ${key_path}"
  1238. else
  1239. echo -e "Domain: ${domain} - Certificate or Key missing."
  1240. fi
  1241. done
  1242. fi
  1243. # The panel's configured certificate may live outside /root/cert
  1244. # (e.g. certbot under /etc/letsencrypt) — show it too (#5070).
  1245. local panel_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1246. if [[ -n "${panel_cert}" && "${panel_cert}" != /root/cert/* ]]; then
  1247. echo -e "Panel certificate (custom path): ${panel_cert}"
  1248. if [[ -f "${panel_cert}" ]] && command -v openssl > /dev/null 2>&1; then
  1249. local panel_sans=$(openssl x509 -in "${panel_cert}" -noout -ext subjectAltName 2> /dev/null \
  1250. | grep -Eo 'DNS:[^,[:space:]]+' | cut -d: -f2 | tr '\n' ' ')
  1251. [[ -n "${panel_sans}" ]] && echo -e "\tCovers: ${panel_sans}"
  1252. fi
  1253. fi
  1254. ssl_cert_issue_main
  1255. ;;
  1256. 5)
  1257. echo -e "${green}\t1.${plain} Use a certificate from /root/cert"
  1258. echo -e "${green}\t2.${plain} Enter custom certificate file paths (e.g. certbot, /etc/letsencrypt/...)"
  1259. read -rp "Choose an option: " pathChoice
  1260. if [[ "$pathChoice" == "2" ]]; then
  1261. read -rp "Certificate file path (fullchain): " webCertFile
  1262. read -rp "Private key file path: " webKeyFile
  1263. if [[ -f "${webCertFile}" && -f "${webKeyFile}" ]]; then
  1264. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1265. echo "Panel certificate paths set:"
  1266. echo " - Certificate File: $webCertFile"
  1267. echo " - Private Key File: $webKeyFile"
  1268. restart
  1269. else
  1270. echo "Certificate or private key file not found."
  1271. fi
  1272. ssl_cert_issue_main
  1273. return
  1274. fi
  1275. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1276. if [ -z "$domains" ]; then
  1277. echo "No certificates found."
  1278. else
  1279. echo "Available domains:"
  1280. echo "$domains"
  1281. read -rp "Please choose a domain to set the panel paths: " domain
  1282. if echo "$domains" | grep -qw "$domain"; then
  1283. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1284. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1285. if [[ -f "${webCertFile}" && -f "${webKeyFile}" ]]; then
  1286. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1287. echo "Panel paths set for domain: $domain"
  1288. echo " - Certificate File: $webCertFile"
  1289. echo " - Private Key File: $webKeyFile"
  1290. # Register the acme.sh install-cert hook so auto-renewal copies the
  1291. # renewed cert to these paths and reloads the panel. Without it acme.sh
  1292. # renews but never updates /root/cert, silently serving a stale cert.
  1293. if command -v ~/.acme.sh/acme.sh &> /dev/null && ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  1294. ~/.acme.sh/acme.sh --installcert -d "${domain}" \
  1295. --key-file "${webKeyFile}" \
  1296. --fullchain-file "${webCertFile}" \
  1297. --reloadcmd "x-ui restart" 2>&1 || true
  1298. echo "Registered acme.sh auto-renewal hook for ${domain}."
  1299. fi
  1300. restart
  1301. else
  1302. echo "Certificate or private key not found for domain: $domain."
  1303. fi
  1304. else
  1305. echo "Invalid domain entered."
  1306. fi
  1307. fi
  1308. ssl_cert_issue_main
  1309. ;;
  1310. 6)
  1311. echo -e "${yellow}Let's Encrypt SSL Certificate for IP Address${plain}"
  1312. echo -e "This will obtain a certificate for your server's IP using the shortlived profile."
  1313. echo -e "${yellow}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  1314. echo -e "${yellow}Port 80 must be open and accessible from the internet.${plain}"
  1315. confirm "Do you want to proceed?" "y"
  1316. if [[ $? == 0 ]]; then
  1317. ssl_cert_issue_for_ip
  1318. fi
  1319. ssl_cert_issue_main
  1320. ;;
  1321. *)
  1322. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1323. ssl_cert_issue_main
  1324. ;;
  1325. esac
  1326. }
  1327. ssl_cert_issue_for_ip() {
  1328. LOGI "Starting automatic SSL certificate generation for server IP..."
  1329. LOGI "Using Let's Encrypt shortlived profile (~6 days validity, auto-renews)"
  1330. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1331. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1332. # Get server IP
  1333. local URL_lists=(
  1334. "https://api4.ipify.org"
  1335. "https://ipv4.icanhazip.com"
  1336. "https://v4.api.ipinfo.io/ip"
  1337. "https://ipv4.myexternalip.com/raw"
  1338. "https://4.ident.me"
  1339. "https://check-host.net/ip"
  1340. )
  1341. local server_ip=""
  1342. for ip_address in "${URL_lists[@]}"; do
  1343. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  1344. local http_code=$(echo "$response" | tail -n1)
  1345. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  1346. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1347. server_ip="${ip_result}"
  1348. break
  1349. fi
  1350. done
  1351. if [[ -z "$server_ip" ]]; then
  1352. LOGI "Could not auto-detect server IP from any provider."
  1353. while [[ -z "$server_ip" ]]; do
  1354. read -rp "Please enter your server's public IPv4 address: " server_ip
  1355. server_ip="${server_ip// /}"
  1356. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1357. LOGE "Invalid IPv4 address. Please try again."
  1358. server_ip=""
  1359. fi
  1360. done
  1361. fi
  1362. LOGI "Server IP detected: ${server_ip}"
  1363. # Ask for optional IPv6
  1364. local ipv6_addr=""
  1365. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  1366. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  1367. # check for acme.sh first
  1368. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1369. LOGI "acme.sh not found, installing..."
  1370. install_acme
  1371. if [ $? -ne 0 ]; then
  1372. LOGE "Failed to install acme.sh"
  1373. return 1
  1374. fi
  1375. fi
  1376. # install socat
  1377. case "${release}" in
  1378. ubuntu | debian | armbian)
  1379. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1380. ;;
  1381. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1382. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1383. ;;
  1384. centos)
  1385. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1386. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1387. else
  1388. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1389. fi
  1390. ;;
  1391. arch | manjaro | parch)
  1392. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1393. ;;
  1394. opensuse-tumbleweed | opensuse-leap)
  1395. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1396. ;;
  1397. alpine)
  1398. apk add socat curl openssl > /dev/null 2>&1
  1399. ;;
  1400. *)
  1401. LOGW "Unsupported OS for automatic socat installation"
  1402. ;;
  1403. esac
  1404. # Create certificate directory
  1405. certPath="/root/cert/ip"
  1406. mkdir -p "$certPath"
  1407. # Build domain arguments
  1408. local domain_args="-d ${server_ip}"
  1409. if [[ -n "$ipv6_addr" ]] && is_ipv6 "$ipv6_addr"; then
  1410. domain_args="${domain_args} -d ${ipv6_addr}"
  1411. LOGI "Including IPv6 address: ${ipv6_addr}"
  1412. fi
  1413. # Choose port for HTTP-01 listener (default 80, allow override)
  1414. local WebPort=""
  1415. read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
  1416. WebPort="${WebPort:-80}"
  1417. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  1418. LOGE "Invalid port provided. Falling back to 80."
  1419. WebPort=80
  1420. fi
  1421. LOGI "Using port ${WebPort} to issue certificate for IP: ${server_ip}"
  1422. if [[ "${WebPort}" -ne 80 ]]; then
  1423. LOGI "Reminder: Let's Encrypt still reaches port 80; forward external port 80 to ${WebPort} for validation."
  1424. fi
  1425. while true; do
  1426. if is_port_in_use "${WebPort}"; then
  1427. LOGI "Port ${WebPort} is currently in use."
  1428. local alt_port=""
  1429. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  1430. alt_port="${alt_port// /}"
  1431. if [[ -z "${alt_port}" ]]; then
  1432. LOGE "Port ${WebPort} is busy; cannot proceed with issuance."
  1433. return 1
  1434. fi
  1435. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  1436. LOGE "Invalid port provided."
  1437. return 1
  1438. fi
  1439. WebPort="${alt_port}"
  1440. continue
  1441. else
  1442. LOGI "Port ${WebPort} is free and ready for standalone validation."
  1443. break
  1444. fi
  1445. done
  1446. # Reload command - restarts panel after renewal
  1447. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null"
  1448. # issue the certificate for IP with shortlived profile
  1449. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1450. ~/.acme.sh/acme.sh --issue \
  1451. ${domain_args} \
  1452. --standalone \
  1453. --server letsencrypt \
  1454. --certificate-profile shortlived \
  1455. --days 6 \
  1456. --httpport ${WebPort} \
  1457. --force
  1458. if [ $? -ne 0 ]; then
  1459. LOGE "Failed to issue certificate for IP: ${server_ip}"
  1460. LOGE "Make sure port ${WebPort} is open and the server is accessible from the internet"
  1461. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1462. rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null
  1463. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null
  1464. rm -rf ${certPath} 2> /dev/null
  1465. return 1
  1466. else
  1467. LOGI "Certificate issued successfully for IP: ${server_ip}"
  1468. fi
  1469. # Install the certificate
  1470. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  1471. # but the cert files are still installed. We check for files instead of exit code.
  1472. ~/.acme.sh/acme.sh --installcert -d ${server_ip} \
  1473. --key-file "${certPath}/privkey.pem" \
  1474. --fullchain-file "${certPath}/fullchain.pem" \
  1475. --reloadcmd "${reloadCmd}" 2>&1 || true
  1476. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  1477. if [[ ! -f "${certPath}/fullchain.pem" || ! -f "${certPath}/privkey.pem" ]]; then
  1478. LOGE "Certificate files not found after installation"
  1479. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1480. rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null
  1481. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null
  1482. rm -rf ${certPath} 2> /dev/null
  1483. return 1
  1484. fi
  1485. LOGI "Certificate files installed successfully"
  1486. # enable auto-renew
  1487. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  1488. chmod 600 $certPath/privkey.pem 2> /dev/null
  1489. chmod 644 $certPath/fullchain.pem 2> /dev/null
  1490. # Prompt user to set panel paths after successful certificate installation
  1491. local webCertFile="${certPath}/fullchain.pem"
  1492. local webKeyFile="${certPath}/privkey.pem"
  1493. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1494. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1495. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1496. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1497. LOGI "Panel paths set for IP: $server_ip"
  1498. LOGI " - Certificate File: $webCertFile"
  1499. LOGI " - Private Key File: $webKeyFile"
  1500. LOGI " - Validity: ~6 days (auto-renews via acme.sh cron)"
  1501. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  1502. LOGI "Panel will restart to apply SSL certificate..."
  1503. restart
  1504. else
  1505. LOGE "Error: Certificate or private key file not found for IP: $server_ip."
  1506. return 1
  1507. fi
  1508. else
  1509. LOGI "Skipping panel path setting."
  1510. fi
  1511. return 0
  1512. }
  1513. ssl_cert_issue() {
  1514. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1515. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1516. # check for acme.sh first
  1517. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1518. echo "acme.sh could not be found. we will install it"
  1519. install_acme
  1520. if [ $? -ne 0 ]; then
  1521. LOGE "install acme failed, please check logs"
  1522. exit 1
  1523. fi
  1524. fi
  1525. # install socat
  1526. case "${release}" in
  1527. ubuntu | debian | armbian)
  1528. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1529. ;;
  1530. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1531. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1532. ;;
  1533. centos)
  1534. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1535. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1536. else
  1537. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1538. fi
  1539. ;;
  1540. arch | manjaro | parch)
  1541. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1542. ;;
  1543. opensuse-tumbleweed | opensuse-leap)
  1544. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1545. ;;
  1546. alpine)
  1547. apk add socat curl openssl > /dev/null 2>&1
  1548. ;;
  1549. *)
  1550. LOGW "Unsupported OS for automatic socat installation"
  1551. ;;
  1552. esac
  1553. if [ $? -ne 0 ]; then
  1554. LOGE "install socat failed, please check logs"
  1555. exit 1
  1556. else
  1557. LOGI "install socat succeed..."
  1558. fi
  1559. # get the domain here, and we need to verify it
  1560. local domain=""
  1561. while true; do
  1562. read -rp "Please enter your domain name: " domain
  1563. domain="${domain// /}" # Trim whitespace
  1564. if [[ -z "$domain" ]]; then
  1565. LOGE "Domain name cannot be empty. Please try again."
  1566. continue
  1567. fi
  1568. if ! is_domain "$domain"; then
  1569. LOGE "Invalid domain format: ${domain}. Please enter a valid domain name."
  1570. continue
  1571. fi
  1572. break
  1573. done
  1574. LOGD "Your domain is: ${domain}, checking it..."
  1575. SSL_ISSUED_DOMAIN="${domain}"
  1576. # detect existing certificate and reuse it only if its files are actually
  1577. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  1578. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  1579. # with no usable cert files, which must not be reused (it produces a 0-byte
  1580. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  1581. local cert_exists=0
  1582. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  1583. local acmeCertDir=""
  1584. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  1585. acmeCertDir=~/.acme.sh/${domain}_ecc
  1586. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  1587. acmeCertDir=~/.acme.sh/${domain}
  1588. fi
  1589. if [[ -n "${acmeCertDir}" ]]; then
  1590. cert_exists=1
  1591. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  1592. LOGI "Existing certificate found for ${domain}, will reuse it."
  1593. [[ -n "${certInfo}" ]] && LOGI "${certInfo}"
  1594. else
  1595. LOGW "Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing."
  1596. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1597. fi
  1598. fi
  1599. if [[ ${cert_exists} -eq 0 ]]; then
  1600. LOGI "Your domain is ready for issuing certificates now..."
  1601. fi
  1602. # create a directory for the certificate
  1603. certPath="/root/cert/${domain}"
  1604. if [ ! -d "$certPath" ]; then
  1605. mkdir -p "$certPath"
  1606. else
  1607. rm -rf "$certPath"
  1608. mkdir -p "$certPath"
  1609. fi
  1610. # get the port number for the standalone server
  1611. local WebPort=80
  1612. read -rp "Please choose which port to use (default is 80): " WebPort
  1613. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  1614. LOGE "Your input ${WebPort} is invalid, will use default port 80."
  1615. WebPort=80
  1616. fi
  1617. LOGI "Will use port: ${WebPort} to issue certificates. Please make sure this port is open."
  1618. if [[ ${cert_exists} -eq 0 ]]; then
  1619. # issue the certificate
  1620. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1621. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  1622. if [ $? -ne 0 ]; then
  1623. LOGE "Issuing certificate failed, please check logs."
  1624. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1625. exit 1
  1626. else
  1627. LOGE "Issuing certificate succeeded, installing certificates..."
  1628. fi
  1629. else
  1630. LOGI "Using existing certificate, installing certificates..."
  1631. fi
  1632. reloadCmd="x-ui restart"
  1633. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1634. LOGI "This command will run on every certificate issue and renew."
  1635. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1636. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1637. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1638. echo -e "${green}\t2.${plain} Input your own command"
  1639. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1640. read -rp "Choose an option: " choice
  1641. case "$choice" in
  1642. 1)
  1643. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1644. reloadCmd="systemctl reload nginx ; x-ui restart"
  1645. ;;
  1646. 2)
  1647. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1648. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1649. LOGI "Your reloadcmd is: ${reloadCmd}"
  1650. ;;
  1651. *)
  1652. LOGI "Keep default reloadcmd"
  1653. ;;
  1654. esac
  1655. fi
  1656. # install the certificate
  1657. local installOutput=""
  1658. installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \
  1659. --key-file /root/cert/${domain}/privkey.pem \
  1660. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  1661. local installRc=$?
  1662. echo "${installOutput}"
  1663. local installWroteFiles=0
  1664. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  1665. installWroteFiles=1
  1666. fi
  1667. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  1668. LOGI "Installing certificate succeeded, enabling auto renew..."
  1669. else
  1670. LOGE "Installing certificate failed, exiting."
  1671. if [[ ${cert_exists} -eq 0 ]]; then
  1672. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1673. fi
  1674. exit 1
  1675. fi
  1676. # enable auto-renew
  1677. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1678. if [ $? -ne 0 ]; then
  1679. LOGE "Auto renew failed, certificate details:"
  1680. ls -lah cert/*
  1681. chmod 600 $certPath/privkey.pem
  1682. chmod 644 $certPath/fullchain.pem
  1683. exit 1
  1684. else
  1685. LOGI "Auto renew succeeded, certificate details:"
  1686. ls -lah cert/*
  1687. chmod 600 $certPath/privkey.pem
  1688. chmod 644 $certPath/fullchain.pem
  1689. fi
  1690. # Prompt user to set panel paths after successful certificate installation
  1691. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1692. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1693. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1694. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1695. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1696. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1697. LOGI "Panel paths set for domain: $domain"
  1698. LOGI " - Certificate File: $webCertFile"
  1699. LOGI " - Private Key File: $webKeyFile"
  1700. echo -e "${green}Access URL: https://${domain}:${existing_port}${existing_webBasePath}${plain}"
  1701. restart
  1702. else
  1703. LOGE "Error: Certificate or private key file not found for domain: $domain."
  1704. fi
  1705. else
  1706. LOGI "Skipping panel path setting."
  1707. fi
  1708. }
  1709. ssl_cert_issue_CF() {
  1710. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1711. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1712. LOGI "****** Instructions for Use ******"
  1713. LOGI "Follow the steps below to complete the process:"
  1714. LOGI "1. A Cloudflare API Token (recommended, scoped to Zone:DNS:Edit) or the Global API Key + registered email."
  1715. LOGI "2. The Domain Name."
  1716. LOGI "3. Once the certificate is issued, you will be prompted to set the certificate for the panel (optional)."
  1717. LOGI "4. The script also supports automatic renewal of the SSL certificate after installation."
  1718. confirm "Do you confirm the information and wish to proceed? [y/n]" "y"
  1719. if [ $? -eq 0 ]; then
  1720. # Check for acme.sh first
  1721. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1722. echo "acme.sh could not be found. We will install it."
  1723. install_acme
  1724. if [ $? -ne 0 ]; then
  1725. LOGE "Install acme failed, please check logs."
  1726. exit 1
  1727. fi
  1728. fi
  1729. CF_Domain=""
  1730. LOGD "Please set a domain name:"
  1731. read -rp "Input your domain here: " CF_Domain
  1732. LOGD "Your domain name is set to: ${CF_Domain}"
  1733. # Cloudflare API credentials: an API Token (recommended, scoped to a
  1734. # single zone) or the account-wide Global API Key. acme.sh reads
  1735. # CF_Token for tokens, or CF_Key + CF_Email for the Global Key.
  1736. CF_KeyType=""
  1737. read -rp "Are you using a Cloudflare API Token or Global API Key? (t/g) [Default t]: " CF_KeyType
  1738. CF_KeyType=${CF_KeyType:-t}
  1739. if [[ "$CF_KeyType" == "g" || "$CF_KeyType" == "G" ]]; then
  1740. CF_GlobalKey=""
  1741. CF_AccountEmail=""
  1742. LOGD "Please set the Global API Key:"
  1743. read -rp "Input your key here: " CF_GlobalKey
  1744. LOGD "Please set up the registered email:"
  1745. read -rp "Input your email here: " CF_AccountEmail
  1746. export CF_Key="${CF_GlobalKey}"
  1747. export CF_Email="${CF_AccountEmail}"
  1748. else
  1749. CF_ApiToken=""
  1750. LOGD "Please set the API Token:"
  1751. read -rp "Input your token here: " CF_ApiToken
  1752. export CF_Token="${CF_ApiToken}"
  1753. fi
  1754. # Set the default CA to Let's Encrypt
  1755. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1756. if [ $? -ne 0 ]; then
  1757. LOGE "Default CA, Let'sEncrypt fail, script exiting..."
  1758. exit 1
  1759. fi
  1760. # Issue the certificate using Cloudflare DNS
  1761. ~/.acme.sh/acme.sh --issue --dns dns_cf -d ${CF_Domain} -d *.${CF_Domain} --log --force
  1762. if [ $? -ne 0 ]; then
  1763. LOGE "Certificate issuance failed, script exiting..."
  1764. exit 1
  1765. else
  1766. LOGI "Certificate issued successfully, Installing..."
  1767. fi
  1768. # Install the certificate
  1769. certPath="/root/cert/${CF_Domain}"
  1770. if [ -d "$certPath" ]; then
  1771. rm -rf ${certPath}
  1772. fi
  1773. mkdir -p ${certPath}
  1774. if [ $? -ne 0 ]; then
  1775. LOGE "Failed to create directory: ${certPath}"
  1776. exit 1
  1777. fi
  1778. reloadCmd="x-ui restart"
  1779. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1780. LOGI "This command will run on every certificate issue and renew."
  1781. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1782. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1783. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1784. echo -e "${green}\t2.${plain} Input your own command"
  1785. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1786. read -rp "Choose an option: " choice
  1787. case "$choice" in
  1788. 1)
  1789. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1790. reloadCmd="systemctl reload nginx ; x-ui restart"
  1791. ;;
  1792. 2)
  1793. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1794. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1795. LOGI "Your reloadcmd is: ${reloadCmd}"
  1796. ;;
  1797. *)
  1798. LOGI "Keep default reloadcmd"
  1799. ;;
  1800. esac
  1801. fi
  1802. ~/.acme.sh/acme.sh --installcert -d ${CF_Domain} -d *.${CF_Domain} \
  1803. --key-file ${certPath}/privkey.pem \
  1804. --fullchain-file ${certPath}/fullchain.pem --reloadcmd "${reloadCmd}"
  1805. if [ $? -ne 0 ]; then
  1806. LOGE "Certificate installation failed, script exiting..."
  1807. exit 1
  1808. else
  1809. LOGI "Certificate installed successfully, Turning on automatic updates..."
  1810. fi
  1811. # Enable auto-update
  1812. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1813. if [ $? -ne 0 ]; then
  1814. LOGE "Auto update setup failed, script exiting..."
  1815. exit 1
  1816. else
  1817. LOGI "The certificate is installed and auto-renewal is turned on. Specific information is as follows:"
  1818. ls -lah ${certPath}/*
  1819. chmod 600 ${certPath}/privkey.pem
  1820. chmod 644 ${certPath}/fullchain.pem
  1821. fi
  1822. # Prompt user to set panel paths after successful certificate installation
  1823. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1824. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1825. local webCertFile="${certPath}/fullchain.pem"
  1826. local webKeyFile="${certPath}/privkey.pem"
  1827. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1828. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1829. LOGI "Panel paths set for domain: $CF_Domain"
  1830. LOGI " - Certificate File: $webCertFile"
  1831. LOGI " - Private Key File: $webKeyFile"
  1832. echo -e "${green}Access URL: https://${CF_Domain}:${existing_port}${existing_webBasePath}${plain}"
  1833. restart
  1834. else
  1835. LOGE "Error: Certificate or private key file not found for domain: $CF_Domain."
  1836. fi
  1837. else
  1838. LOGI "Skipping panel path setting."
  1839. fi
  1840. else
  1841. show_menu
  1842. fi
  1843. }
  1844. run_speedtest() {
  1845. # Check if Speedtest is already installed
  1846. if ! command -v speedtest &> /dev/null; then
  1847. # If not installed, determine installation method
  1848. if command -v snap &> /dev/null; then
  1849. # Use snap to install Speedtest
  1850. echo "Installing Speedtest using snap..."
  1851. snap install speedtest
  1852. else
  1853. # Fallback to using package managers
  1854. local pkg_manager=""
  1855. local speedtest_install_script=""
  1856. if command -v dnf &> /dev/null; then
  1857. pkg_manager="dnf"
  1858. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1859. elif command -v yum &> /dev/null; then
  1860. pkg_manager="yum"
  1861. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1862. elif command -v apt-get &> /dev/null; then
  1863. pkg_manager="apt-get"
  1864. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1865. elif command -v apt &> /dev/null; then
  1866. pkg_manager="apt"
  1867. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1868. fi
  1869. if [[ -z $pkg_manager ]]; then
  1870. echo "Error: Package manager not found. You may need to install Speedtest manually."
  1871. return 1
  1872. else
  1873. echo "Installing Speedtest using $pkg_manager..."
  1874. curl -s $speedtest_install_script | bash
  1875. $pkg_manager install -y speedtest
  1876. fi
  1877. fi
  1878. fi
  1879. speedtest
  1880. }
  1881. ip_validation() {
  1882. ipv6_regex="^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$"
  1883. ipv4_regex="^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$"
  1884. }
  1885. iplimit_main() {
  1886. echo -e "\n${green}\t1.${plain} Install Fail2ban and configure IP Limit"
  1887. echo -e "${green}\t2.${plain} Change Ban Duration"
  1888. echo -e "${green}\t3.${plain} Unban Everyone"
  1889. echo -e "${green}\t4.${plain} Ban Logs"
  1890. echo -e "${green}\t5.${plain} Ban an IP Address"
  1891. echo -e "${green}\t6.${plain} Unban an IP Address"
  1892. echo -e "${green}\t7.${plain} Real-Time Logs"
  1893. echo -e "${green}\t8.${plain} Service Status"
  1894. echo -e "${green}\t9.${plain} Service Restart"
  1895. echo -e "${green}\t10.${plain} Uninstall Fail2ban and IP Limit"
  1896. echo -e "${green}\t0.${plain} Back to Main Menu"
  1897. read -rp "Choose an option: " choice
  1898. case "$choice" in
  1899. 0)
  1900. show_menu
  1901. ;;
  1902. 1)
  1903. confirm "Proceed with installation of Fail2ban & IP Limit?" "y"
  1904. if [[ $? == 0 ]]; then
  1905. install_iplimit
  1906. else
  1907. iplimit_main
  1908. fi
  1909. ;;
  1910. 2)
  1911. read -rp "Please enter new Ban Duration in Minutes [default 30]: " NUM
  1912. if [[ $NUM =~ ^[0-9]+$ ]]; then
  1913. create_iplimit_jails ${NUM}
  1914. if [[ $release == "alpine" ]]; then
  1915. rc-service fail2ban restart
  1916. else
  1917. systemctl restart fail2ban
  1918. fi
  1919. else
  1920. echo -e "${red}${NUM} is not a number! Please, try again.${plain}"
  1921. fi
  1922. iplimit_main
  1923. ;;
  1924. 3)
  1925. confirm "Proceed with Unbanning everyone from IP Limit jail?" "y"
  1926. if [[ $? == 0 ]]; then
  1927. fail2ban-client reload --restart --unban 3x-ipl
  1928. truncate -s 0 "${iplimit_banned_log_path}"
  1929. echo -e "${green}All users Unbanned successfully.${plain}"
  1930. iplimit_main
  1931. else
  1932. echo -e "${yellow}Cancelled.${plain}"
  1933. fi
  1934. iplimit_main
  1935. ;;
  1936. 4)
  1937. show_banlog
  1938. iplimit_main
  1939. ;;
  1940. 5)
  1941. read -rp "Enter the IP address you want to ban: " ban_ip
  1942. ip_validation
  1943. if [[ $ban_ip =~ $ipv4_regex || $ban_ip =~ $ipv6_regex ]]; then
  1944. fail2ban-client set 3x-ipl banip "$ban_ip"
  1945. echo -e "${green}IP Address ${ban_ip} has been banned successfully.${plain}"
  1946. else
  1947. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1948. fi
  1949. iplimit_main
  1950. ;;
  1951. 6)
  1952. read -rp "Enter the IP address you want to unban: " unban_ip
  1953. ip_validation
  1954. if [[ $unban_ip =~ $ipv4_regex || $unban_ip =~ $ipv6_regex ]]; then
  1955. fail2ban-client set 3x-ipl unbanip "$unban_ip"
  1956. echo -e "${green}IP Address ${unban_ip} has been unbanned successfully.${plain}"
  1957. else
  1958. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1959. fi
  1960. iplimit_main
  1961. ;;
  1962. 7)
  1963. tail -f /var/log/fail2ban.log
  1964. iplimit_main
  1965. ;;
  1966. 8)
  1967. service fail2ban status
  1968. iplimit_main
  1969. ;;
  1970. 9)
  1971. if [[ $release == "alpine" ]]; then
  1972. rc-service fail2ban restart
  1973. else
  1974. systemctl restart fail2ban
  1975. fi
  1976. iplimit_main
  1977. ;;
  1978. 10)
  1979. remove_iplimit
  1980. iplimit_main
  1981. ;;
  1982. *)
  1983. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1984. iplimit_main
  1985. ;;
  1986. esac
  1987. }
  1988. install_iplimit() {
  1989. if ! command -v fail2ban-client &> /dev/null; then
  1990. echo -e "${green}Fail2ban is not installed. Installing now...!${plain}\n"
  1991. # Install fail2ban together with nftables. Recent fail2ban packages
  1992. # default to `banaction = nftables-multiport` in /etc/fail2ban/jail.conf,
  1993. # but the `nftables` package isn't pulled in as a dependency on most
  1994. # minimal server images (Debian 12+, Ubuntu 24+, fresh RHEL-family).
  1995. # Without `nft` in PATH the default sshd jail fails to ban with
  1996. # stderr: '/bin/sh: 1: nft: not found'
  1997. # even though our own 3x-ipl jail uses iptables. Bundling the binary
  1998. # at install time prevents that confusing log spam for new installs.
  1999. case "${release}" in
  2000. ubuntu)
  2001. apt-get update
  2002. if [[ "${os_version}" -ge 2400 ]]; then
  2003. apt-get install python3-pip -y
  2004. python3 -m pip install pyasynchat --break-system-packages
  2005. fi
  2006. apt-get install fail2ban nftables -y
  2007. ;;
  2008. debian)
  2009. apt-get update
  2010. if [ "$os_version" -ge 12 ]; then
  2011. apt-get install -y python3-systemd
  2012. fi
  2013. apt-get install -y fail2ban nftables
  2014. ;;
  2015. armbian)
  2016. apt-get update && apt-get install fail2ban nftables -y
  2017. ;;
  2018. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2019. dnf -y update && dnf -y install fail2ban nftables
  2020. ;;
  2021. centos)
  2022. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2023. yum update -y && yum install epel-release -y
  2024. yum -y install fail2ban nftables
  2025. else
  2026. dnf -y update && dnf -y install fail2ban nftables
  2027. fi
  2028. ;;
  2029. arch | manjaro | parch)
  2030. pacman -Syu --noconfirm fail2ban nftables
  2031. ;;
  2032. alpine)
  2033. apk add fail2ban nftables
  2034. ;;
  2035. *)
  2036. echo -e "${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\n"
  2037. exit 1
  2038. ;;
  2039. esac
  2040. if ! command -v fail2ban-client &> /dev/null; then
  2041. echo -e "${red}Fail2ban installation failed.${plain}\n"
  2042. exit 1
  2043. fi
  2044. echo -e "${green}Fail2ban installed successfully!${plain}\n"
  2045. else
  2046. echo -e "${yellow}Fail2ban is already installed.${plain}\n"
  2047. fi
  2048. echo -e "${green}Configuring IP Limit...${plain}\n"
  2049. # make sure there's no conflict for jail files
  2050. iplimit_remove_conflicts
  2051. # Check if log file exists
  2052. if ! test -f "${iplimit_banned_log_path}"; then
  2053. touch ${iplimit_banned_log_path}
  2054. fi
  2055. # Check if service log file exists so fail2ban won't return error
  2056. if ! test -f "${iplimit_log_path}"; then
  2057. touch ${iplimit_log_path}
  2058. fi
  2059. # Create the iplimit jail files
  2060. # we didn't pass the bantime here to use the default value
  2061. create_iplimit_jails
  2062. # Launching fail2ban
  2063. if [[ $release == "alpine" ]]; then
  2064. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2065. rc-service fail2ban start
  2066. else
  2067. rc-service fail2ban restart
  2068. fi
  2069. rc-update add fail2ban
  2070. else
  2071. if ! systemctl is-active --quiet fail2ban; then
  2072. systemctl start fail2ban
  2073. else
  2074. systemctl restart fail2ban
  2075. fi
  2076. systemctl enable fail2ban
  2077. fi
  2078. echo -e "${green}IP Limit installed and configured successfully!${plain}\n"
  2079. before_show_menu
  2080. }
  2081. remove_iplimit() {
  2082. echo -e "${green}\t1.${plain} Only remove IP Limit configurations"
  2083. echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit"
  2084. echo -e "${green}\t0.${plain} Back to Main Menu"
  2085. read -rp "Choose an option: " num
  2086. case "$num" in
  2087. 1)
  2088. rm -f /etc/fail2ban/filter.d/3x-ipl.conf
  2089. rm -f /etc/fail2ban/action.d/3x-ipl.conf
  2090. rm -f /etc/fail2ban/jail.d/3x-ipl.conf
  2091. if [[ $release == "alpine" ]]; then
  2092. rc-service fail2ban restart
  2093. else
  2094. systemctl restart fail2ban
  2095. fi
  2096. echo -e "${green}IP Limit removed successfully!${plain}\n"
  2097. before_show_menu
  2098. ;;
  2099. 2)
  2100. rm -rf /etc/fail2ban
  2101. if [[ $release == "alpine" ]]; then
  2102. rc-service fail2ban stop
  2103. else
  2104. systemctl stop fail2ban
  2105. fi
  2106. case "${release}" in
  2107. ubuntu | debian | armbian)
  2108. apt-get remove -y fail2ban
  2109. apt-get purge -y fail2ban -y
  2110. apt-get autoremove -y
  2111. ;;
  2112. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2113. dnf remove fail2ban -y
  2114. dnf autoremove -y
  2115. ;;
  2116. centos)
  2117. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2118. yum remove fail2ban -y
  2119. yum autoremove -y
  2120. else
  2121. dnf remove fail2ban -y
  2122. dnf autoremove -y
  2123. fi
  2124. ;;
  2125. arch | manjaro | parch)
  2126. pacman -Rns --noconfirm fail2ban
  2127. ;;
  2128. alpine)
  2129. apk del fail2ban
  2130. ;;
  2131. *)
  2132. echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n"
  2133. exit 1
  2134. ;;
  2135. esac
  2136. echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n"
  2137. before_show_menu
  2138. ;;
  2139. 0)
  2140. show_menu
  2141. ;;
  2142. *)
  2143. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2144. remove_iplimit
  2145. ;;
  2146. esac
  2147. }
  2148. show_banlog() {
  2149. local system_log="/var/log/fail2ban.log"
  2150. echo -e "${green}Checking ban logs...${plain}\n"
  2151. if [[ $release == "alpine" ]]; then
  2152. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2153. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2154. return 1
  2155. fi
  2156. else
  2157. if ! systemctl is-active --quiet fail2ban; then
  2158. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2159. return 1
  2160. fi
  2161. fi
  2162. if [[ -f "$system_log" ]]; then
  2163. echo -e "${green}Recent system ban activities from fail2ban.log:${plain}"
  2164. grep "3x-ipl" "$system_log" | grep -E "Ban|Unban" | tail -n 10 || echo -e "${yellow}No recent system ban activities found${plain}"
  2165. echo ""
  2166. fi
  2167. if [[ -f "${iplimit_banned_log_path}" ]]; then
  2168. echo -e "${green}3X-IPL ban log entries:${plain}"
  2169. if [[ -s "${iplimit_banned_log_path}" ]]; then
  2170. grep -v "INIT" "${iplimit_banned_log_path}" | tail -n 10 || echo -e "${yellow}No ban entries found${plain}"
  2171. else
  2172. echo -e "${yellow}Ban log file is empty${plain}"
  2173. fi
  2174. else
  2175. echo -e "${red}Ban log file not found at: ${iplimit_banned_log_path}${plain}"
  2176. fi
  2177. echo -e "\n${green}Current jail status:${plain}"
  2178. fail2ban-client status 3x-ipl || echo -e "${yellow}Unable to get jail status${plain}"
  2179. }
  2180. create_iplimit_jails() {
  2181. # Use default bantime if not passed => 30 minutes
  2182. local bantime="${1:-30}"
  2183. # Uncomment 'allowipv6 = auto' in fail2ban.conf
  2184. sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf
  2185. # On Debian 12+ and Ubuntu 22.04+ fail2ban's default backend should be changed to systemd
  2186. if [[ ( "${release}" == "debian" && ${os_version} -ge 12 ) || ( "${release}" == "ubuntu" && ${os_version} -ge 2200 ) ]]; then
  2187. sed -i '0,/action =/s/backend = auto/backend = systemd/' /etc/fail2ban/jail.conf
  2188. fi
  2189. cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf
  2190. [3x-ipl]
  2191. enabled=true
  2192. backend=auto
  2193. filter=3x-ipl
  2194. action=3x-ipl
  2195. logpath=${iplimit_log_path}
  2196. maxretry=1
  2197. findtime=32
  2198. bantime=${bantime}m
  2199. EOF
  2200. cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf
  2201. [Definition]
  2202. datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S
  2203. failregex = \[LIMIT_IP\]\s*Email\s*=\s*<F-USER>.+</F-USER>\s*\|\|\s*Disconnecting OLD IP\s*=\s*<ADDR>\s*\|\|\s*Timestamp\s*=\s*\d+
  2204. ignoreregex =
  2205. EOF
  2206. # Ports to exempt from the ban so an over-limit proxy client can never lock
  2207. # the administrator out of SSH or the panel. The ban still covers every other
  2208. # TCP port (including all Xray inbounds), so IP-limit keeps working for inbounds
  2209. # added later without regenerating these files.
  2210. local ssh_ports
  2211. ssh_ports=$(grep -oP '^[[:space:]]*Port[[:space:]]+\K[0-9]+' /etc/ssh/sshd_config 2>/dev/null | paste -sd, -)
  2212. [[ -z "${ssh_ports}" ]] && ssh_ports="22"
  2213. local panel_port
  2214. panel_port=$(${xui_folder}/x-ui setting -show true 2>/dev/null | grep -Eo 'port: .+' | awk '{print $2}')
  2215. local exempt_ports="${ssh_ports}"
  2216. [[ -n "${panel_port}" ]] && exempt_ports="${exempt_ports},${panel_port}"
  2217. cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf
  2218. [INCLUDES]
  2219. before = iptables-allports.conf
  2220. [Definition]
  2221. actionstart = <iptables> -N f2b-<name>
  2222. <iptables> -A f2b-<name> -j <returntype>
  2223. <iptables> -I <chain> -p <protocol> -j f2b-<name>
  2224. actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
  2225. <actionflush>
  2226. <iptables> -X f2b-<name>
  2227. actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
  2228. actionban = <iptables> -I f2b-<name> 1 -s <ip> -p <protocol> -m multiport ! --dports <exemptports> -j <blocktype>
  2229. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") BAN [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
  2230. actionunban = <iptables> -D f2b-<name> -s <ip> -p <protocol> -m multiport ! --dports <exemptports> -j <blocktype>
  2231. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") UNBAN [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
  2232. [Init]
  2233. name = default
  2234. protocol = tcp
  2235. chain = INPUT
  2236. exemptports = ${exempt_ports}
  2237. EOF
  2238. echo -e "${green}Ip Limit jail files created with a bantime of ${bantime} minutes.${plain}"
  2239. }
  2240. iplimit_remove_conflicts() {
  2241. local jail_files=(
  2242. /etc/fail2ban/jail.conf
  2243. /etc/fail2ban/jail.local
  2244. )
  2245. for file in "${jail_files[@]}"; do
  2246. # Check for [3x-ipl] config in jail file then remove it
  2247. if test -f "${file}" && grep -qw '3x-ipl' ${file}; then
  2248. sed -i "/\[3x-ipl\]/,/^$/d" ${file}
  2249. echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n"
  2250. fi
  2251. done
  2252. }
  2253. SSH_port_forwarding() {
  2254. local URL_lists=(
  2255. "https://api4.ipify.org"
  2256. "https://ipv4.icanhazip.com"
  2257. "https://v4.api.ipinfo.io/ip"
  2258. "https://ipv4.myexternalip.com/raw"
  2259. "https://4.ident.me"
  2260. "https://check-host.net/ip"
  2261. )
  2262. local server_ip=""
  2263. for ip_address in "${URL_lists[@]}"; do
  2264. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  2265. local http_code=$(echo "$response" | tail -n1)
  2266. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  2267. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2268. server_ip="${ip_result}"
  2269. break
  2270. fi
  2271. done
  2272. if [[ -z "$server_ip" ]]; then
  2273. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  2274. while [[ -z "$server_ip" ]]; do
  2275. read -rp "Please enter your server's public IPv4 address: " server_ip
  2276. server_ip="${server_ip// /}"
  2277. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2278. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  2279. server_ip=""
  2280. fi
  2281. done
  2282. fi
  2283. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  2284. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  2285. local existing_listenIP=$(${xui_folder}/x-ui setting -getListen true | grep -Eo 'listenIP: .+' | awk '{print $2}')
  2286. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'cert: .+' | awk '{print $2}')
  2287. local existing_key=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'key: .+' | awk '{print $2}')
  2288. local config_listenIP=""
  2289. local listen_choice=""
  2290. if [[ -n "$existing_cert" && -n "$existing_key" ]]; then
  2291. echo -e "${green}Panel is secure with SSL.${plain}"
  2292. before_show_menu
  2293. fi
  2294. if [[ -z "$existing_cert" && -z "$existing_key" && (-z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0") ]]; then
  2295. echo -e "\n${red}Warning: No Cert and Key found! The panel is not secure.${plain}"
  2296. echo "Please obtain a certificate or set up SSH port forwarding."
  2297. fi
  2298. if [[ -n "$existing_listenIP" && "$existing_listenIP" != "0.0.0.0" && (-z "$existing_cert" && -z "$existing_key") ]]; then
  2299. echo -e "\n${green}Current SSH Port Forwarding Configuration:${plain}"
  2300. echo -e "Standard SSH command:"
  2301. echo -e "${yellow}ssh -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2302. echo -e "\nIf using SSH key:"
  2303. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2304. echo -e "\nAfter connecting, access the panel at:"
  2305. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2306. fi
  2307. echo -e "\nChoose an option:"
  2308. echo -e "${green}1.${plain} Set listen IP"
  2309. echo -e "${green}2.${plain} Clear listen IP"
  2310. echo -e "${green}0.${plain} Back to Main Menu"
  2311. read -rp "Choose an option: " num
  2312. case "$num" in
  2313. 1)
  2314. if [[ -z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0" ]]; then
  2315. echo -e "\nNo listenIP configured. Choose an option:"
  2316. echo -e "1. Use default IP (127.0.0.1)"
  2317. echo -e "2. Set a custom IP"
  2318. read -rp "Select an option (1 or 2): " listen_choice
  2319. config_listenIP="127.0.0.1"
  2320. [[ "$listen_choice" == "2" ]] && read -rp "Enter custom IP to listen on: " config_listenIP
  2321. ${xui_folder}/x-ui setting -listenIP "${config_listenIP}" > /dev/null 2>&1
  2322. echo -e "${green}listen IP has been set to ${config_listenIP}.${plain}"
  2323. echo -e "\n${green}SSH Port Forwarding Configuration:${plain}"
  2324. echo -e "Standard SSH command:"
  2325. echo -e "${yellow}ssh -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2326. echo -e "\nIf using SSH key:"
  2327. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2328. echo -e "\nAfter connecting, access the panel at:"
  2329. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2330. restart
  2331. else
  2332. config_listenIP="${existing_listenIP}"
  2333. echo -e "${green}Current listen IP is already set to ${config_listenIP}.${plain}"
  2334. fi
  2335. ;;
  2336. 2)
  2337. ${xui_folder}/x-ui setting -listenIP 0.0.0.0 > /dev/null 2>&1
  2338. echo -e "${green}Listen IP has been cleared.${plain}"
  2339. restart
  2340. ;;
  2341. 0)
  2342. show_menu
  2343. ;;
  2344. *)
  2345. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2346. SSH_port_forwarding
  2347. ;;
  2348. esac
  2349. }
  2350. # PostgreSQL service management (for panels configured with XUI_DB_TYPE=postgres).
  2351. postgresql_installed() {
  2352. command -v pg_lsclusters > /dev/null 2>&1 || command -v psql > /dev/null 2>&1 || command -v postgres > /dev/null 2>&1
  2353. }
  2354. # Prints "VER CLUSTER" of the first configured cluster on Debian-style installs (e.g. "16 main").
  2355. pg_cluster_info() {
  2356. if command -v pg_lsclusters > /dev/null 2>&1; then
  2357. pg_lsclusters 2> /dev/null | awk '$1 ~ /^[0-9]+$/ {print $1, $2; exit}'
  2358. fi
  2359. }
  2360. # Resolves the systemd unit used to manage the PostgreSQL server.
  2361. pg_systemd_unit() {
  2362. local info ver cluster
  2363. info="$(pg_cluster_info)"
  2364. if [[ -n "$info" ]]; then
  2365. ver="${info%% *}"
  2366. cluster="${info##* }"
  2367. echo "postgresql@${ver}-${cluster}"
  2368. else
  2369. echo "postgresql"
  2370. fi
  2371. }
  2372. postgresql_status() {
  2373. if ! postgresql_installed; then
  2374. LOGE "PostgreSQL does not appear to be installed on this system."
  2375. return 1
  2376. fi
  2377. if command -v pg_lsclusters > /dev/null 2>&1; then
  2378. pg_lsclusters
  2379. else
  2380. systemctl status "$(pg_systemd_unit)" --no-pager
  2381. fi
  2382. echo ""
  2383. if command -v ss > /dev/null 2>&1; then
  2384. local listening
  2385. listening=$(ss -ltnp 2> /dev/null | grep ':5432')
  2386. if [[ -n "$listening" ]]; then
  2387. echo -e "${green}PostgreSQL is listening on port 5432:${plain}"
  2388. echo "$listening"
  2389. else
  2390. echo -e "${red}Nothing is listening on port 5432 - the database is not running.${plain}"
  2391. fi
  2392. fi
  2393. }
  2394. postgresql_start() {
  2395. pg_require_installed || return 1
  2396. if [[ $release == "alpine" ]]; then
  2397. rc-service postgresql start
  2398. else
  2399. systemctl start "$(pg_systemd_unit)"
  2400. fi
  2401. sleep 1
  2402. postgresql_status
  2403. }
  2404. postgresql_stop() {
  2405. pg_require_installed || return 1
  2406. if [[ $release == "alpine" ]]; then
  2407. rc-service postgresql stop
  2408. else
  2409. systemctl stop "$(pg_systemd_unit)"
  2410. fi
  2411. LOGI "PostgreSQL stop signal sent."
  2412. }
  2413. postgresql_restart() {
  2414. pg_require_installed || return 1
  2415. if [[ $release == "alpine" ]]; then
  2416. rc-service postgresql restart
  2417. else
  2418. systemctl restart "$(pg_systemd_unit)"
  2419. fi
  2420. sleep 1
  2421. postgresql_status
  2422. }
  2423. postgresql_enable() {
  2424. pg_require_installed || return 1
  2425. if [[ $release == "alpine" ]]; then
  2426. rc-update add postgresql default
  2427. else
  2428. systemctl enable "$(pg_systemd_unit)"
  2429. fi
  2430. if [[ $? == 0 ]]; then
  2431. LOGI "PostgreSQL set to start automatically on boot."
  2432. else
  2433. LOGE "Failed to enable PostgreSQL autostart."
  2434. fi
  2435. }
  2436. postgresql_log() {
  2437. pg_require_installed || return 1
  2438. local info ver cluster logfile
  2439. info="$(pg_cluster_info)"
  2440. if [[ -n "$info" ]]; then
  2441. ver="${info%% *}"
  2442. cluster="${info##* }"
  2443. logfile="/var/log/postgresql/postgresql-${ver}-${cluster}.log"
  2444. fi
  2445. if [[ -n "$logfile" && -f "$logfile" ]]; then
  2446. tail -n 40 "$logfile"
  2447. elif command -v journalctl > /dev/null 2>&1; then
  2448. journalctl -u "$(pg_systemd_unit)" -n 40 --no-pager
  2449. else
  2450. LOGE "No PostgreSQL log found."
  2451. fi
  2452. }
  2453. pg_require_installed() {
  2454. if ! postgresql_installed; then
  2455. LOGE "PostgreSQL is not installed. Use option 1 (Install PostgreSQL) in this menu first."
  2456. return 1
  2457. fi
  2458. }
  2459. # Installs a local PostgreSQL server and creates a dedicated xui user/database.
  2460. # Progress goes to stderr; on success the connection DSN is printed to stdout so
  2461. # callers can capture it. Mirrors install_postgres_local() from install.sh, so the
  2462. # panel can be set up without re-running the remote install script.
  2463. pg_install_local() {
  2464. local pg_user pg_pass pg_db pg_host pg_port
  2465. pg_pass=$(gen_random_string 24)
  2466. pg_db="xui"
  2467. pg_host="127.0.0.1"
  2468. pg_port="5432"
  2469. case "${release}" in
  2470. ubuntu | debian | armbian)
  2471. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  2472. ;;
  2473. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2474. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2475. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2476. ;;
  2477. centos)
  2478. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2479. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  2480. else
  2481. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2482. fi
  2483. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2484. ;;
  2485. arch | manjaro | parch)
  2486. pacman -Syu --noconfirm postgresql >&2 || return 1
  2487. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  2488. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  2489. fi
  2490. ;;
  2491. opensuse-tumbleweed | opensuse-leap)
  2492. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  2493. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  2494. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  2495. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  2496. fi
  2497. ;;
  2498. alpine)
  2499. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  2500. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  2501. /etc/init.d/postgresql setup >&2 || return 1
  2502. fi
  2503. rc-update add postgresql default >&2 2> /dev/null || true
  2504. rc-service postgresql start >&2 || return 1
  2505. ;;
  2506. *)
  2507. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  2508. return 1
  2509. ;;
  2510. esac
  2511. if [[ "${release}" != "alpine" ]]; then
  2512. systemctl enable --now postgresql >&2 || return 1
  2513. fi
  2514. local i
  2515. for i in 1 2 3 4 5; do
  2516. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  2517. sleep 1
  2518. done
  2519. local existing_owner=""
  2520. existing_owner=$(sudo -u postgres psql -tAc \
  2521. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2522. | tr -d '[:space:]')
  2523. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  2524. pg_user="${existing_owner}"
  2525. else
  2526. pg_user=$(gen_random_string 8)
  2527. fi
  2528. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  2529. | grep -q 1 \
  2530. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2531. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2532. | grep -q 1 \
  2533. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  2534. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2535. local pg_pass_enc
  2536. pg_pass_enc=$(printf '%s' "${pg_pass}" | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g')
  2537. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  2538. return 0
  2539. }
  2540. # Installs the PostgreSQL client tools (pg_dump/pg_restore) used by in-panel backup.
  2541. pg_ensure_client() {
  2542. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  2543. return 0
  2544. fi
  2545. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore)...${plain}" >&2
  2546. case "${release}" in
  2547. ubuntu | debian | armbian)
  2548. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  2549. ;;
  2550. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2551. dnf install -y -q postgresql >&2 || return 1
  2552. ;;
  2553. centos)
  2554. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2555. yum install -y postgresql >&2 || return 1
  2556. else
  2557. dnf install -y -q postgresql >&2 || return 1
  2558. fi
  2559. ;;
  2560. arch | manjaro | parch)
  2561. pacman -Sy --noconfirm postgresql >&2 || return 1
  2562. ;;
  2563. opensuse-tumbleweed | opensuse-leap)
  2564. zypper -q install -y postgresql >&2 || return 1
  2565. ;;
  2566. alpine)
  2567. apk add --no-cache postgresql-client >&2 || return 1
  2568. ;;
  2569. *)
  2570. return 1
  2571. ;;
  2572. esac
  2573. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  2574. }
  2575. # Writes XUI_DB_TYPE/XUI_DB_DSN into the service env file, preserving other entries.
  2576. pg_write_env() {
  2577. local dsn="$1" envfile
  2578. envfile="$(xui_env_file_path)"
  2579. install -d -m 755 "$(dirname "$envfile")"
  2580. touch "$envfile"
  2581. sed -i '/^XUI_DB_TYPE=/d; /^XUI_DB_DSN=/d' "$envfile"
  2582. {
  2583. echo "XUI_DB_TYPE=postgres"
  2584. echo "XUI_DB_DSN=${dsn}"
  2585. } >> "$envfile"
  2586. chmod 600 "$envfile"
  2587. }
  2588. pg_install_server_action() {
  2589. if postgresql_installed; then
  2590. LOGI "PostgreSQL already appears to be installed on this system."
  2591. confirm "Run setup anyway (ensures the xui database/user exist)?" "n" || return 0
  2592. fi
  2593. LOGI "Installing PostgreSQL server and creating a dedicated user/database..."
  2594. local dsn
  2595. dsn=$(pg_install_local)
  2596. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2597. LOGE "PostgreSQL installation failed."
  2598. return 1
  2599. fi
  2600. PG_LAST_DSN="$dsn"
  2601. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (panel DB backup may be unavailable)."
  2602. echo ""
  2603. LOGI "PostgreSQL is installed and ready."
  2604. echo -e "${green}Connection DSN:${plain} ${dsn}"
  2605. echo -e "${yellow}Use option 2 to migrate your SQLite data and switch the panel to PostgreSQL.${plain}"
  2606. }
  2607. # Copies the current SQLite data into PostgreSQL, then switches the panel over.
  2608. migrate_to_postgres() {
  2609. if [[ ! -x "${xui_folder}/x-ui" ]]; then
  2610. LOGE "x-ui is not installed."
  2611. return 1
  2612. fi
  2613. echo ""
  2614. echo -e "${yellow}This copies your current SQLite data into a PostgreSQL database,${plain}"
  2615. echo -e "${yellow}then switches the panel to PostgreSQL and restarts it.${plain}"
  2616. echo -e "${red}Any existing panel tables in the destination will be cleared and overwritten.${plain}"
  2617. confirm "Continue?" "n" || return 0
  2618. local dsn="" pg_mode
  2619. if [[ -n "$PG_LAST_DSN" ]]; then
  2620. echo -e "A PostgreSQL database was created in this session:"
  2621. echo -e " ${green}${PG_LAST_DSN}${plain}"
  2622. confirm "Migrate into this database?" "y" && dsn="$PG_LAST_DSN"
  2623. fi
  2624. if [[ -z "$dsn" ]]; then
  2625. echo ""
  2626. echo -e "${green}\t1.${plain} Install PostgreSQL locally and create a dedicated user/db (recommended)"
  2627. echo -e "${green}\t2.${plain} Use an existing PostgreSQL server (enter DSN)"
  2628. read -rp "Choose [1]: " pg_mode
  2629. pg_mode="${pg_mode:-1}"
  2630. if [[ "$pg_mode" == "2" ]]; then
  2631. while [[ -z "$dsn" ]]; do
  2632. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " dsn
  2633. dsn="${dsn// /}"
  2634. done
  2635. else
  2636. LOGI "Installing PostgreSQL locally (this may take a moment)..."
  2637. dsn=$(pg_install_local)
  2638. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2639. LOGE "PostgreSQL installation failed. Aborting migration."
  2640. return 1
  2641. fi
  2642. PG_LAST_DSN="$dsn"
  2643. fi
  2644. fi
  2645. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (in-panel DB backup/restore may be unavailable)."
  2646. LOGI "Stopping panel to take a consistent snapshot..."
  2647. stop 0 > /dev/null 2>&1
  2648. echo ""
  2649. LOGI "Migrating data into PostgreSQL..."
  2650. if ! ${xui_folder}/x-ui migrate-db --dsn "$dsn"; then
  2651. LOGE "Migration failed. The panel was NOT switched to PostgreSQL."
  2652. start 0 > /dev/null 2>&1
  2653. return 1
  2654. fi
  2655. pg_write_env "$dsn"
  2656. LOGI "Wrote database settings to $(xui_env_file_path) (XUI_DB_TYPE=postgres)."
  2657. LOGI "Restarting panel on PostgreSQL..."
  2658. restart 0
  2659. sleep 1
  2660. if check_status; then
  2661. LOGI "Migration complete. The panel is now running on PostgreSQL."
  2662. else
  2663. LOGE "Panel did not come up. Check logs (option 16). Your SQLite data is left intact."
  2664. fi
  2665. }
  2666. postgresql_menu() {
  2667. echo -e "${green}\t1.${plain} ${green}Install${plain} PostgreSQL (server + client + xui db)"
  2668. echo -e "${green}\t2.${plain} Migrate SQLite ${green}->${plain} PostgreSQL"
  2669. echo -e "${green}\t3.${plain} Status (clusters & port 5432)"
  2670. echo -e "${green}\t4.${plain} ${green}Start${plain} PostgreSQL"
  2671. echo -e "${green}\t5.${plain} ${red}Stop${plain} PostgreSQL"
  2672. echo -e "${green}\t6.${plain} Restart PostgreSQL"
  2673. echo -e "${green}\t7.${plain} ${green}Enable${plain} Autostart on boot"
  2674. echo -e "${green}\t8.${plain} View PostgreSQL Log"
  2675. echo -e "${green}\t9.${plain} Convert SQLite ${green}.db <-> .dump${plain}"
  2676. echo -e "${green}\t0.${plain} Back to Main Menu"
  2677. read -rp "Choose an option: " choice
  2678. case "$choice" in
  2679. 0)
  2680. show_menu
  2681. ;;
  2682. 1)
  2683. pg_install_server_action
  2684. postgresql_menu
  2685. ;;
  2686. 2)
  2687. migrate_to_postgres
  2688. postgresql_menu
  2689. ;;
  2690. 3)
  2691. postgresql_status
  2692. postgresql_menu
  2693. ;;
  2694. 4)
  2695. postgresql_start
  2696. postgresql_menu
  2697. ;;
  2698. 5)
  2699. postgresql_stop
  2700. postgresql_menu
  2701. ;;
  2702. 6)
  2703. postgresql_restart
  2704. postgresql_menu
  2705. ;;
  2706. 7)
  2707. postgresql_enable
  2708. postgresql_menu
  2709. ;;
  2710. 8)
  2711. postgresql_log
  2712. postgresql_menu
  2713. ;;
  2714. 9)
  2715. migrate_db_prompt
  2716. postgresql_menu
  2717. ;;
  2718. *)
  2719. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2720. postgresql_menu
  2721. ;;
  2722. esac
  2723. }
  2724. # Convert between the panel's SQLite database and a portable .dump (SQL text)
  2725. # file using the bundled x-ui binary. With no arguments it dumps the installed
  2726. # panel database; an optional second argument overrides the output path.
  2727. # x-ui migrateDB [file.db|file.dump] [output]
  2728. migrate_db() {
  2729. local input="$1" output="$2"
  2730. local default_db="/etc/x-ui/x-ui.db"
  2731. local bin="${xui_folder}/x-ui"
  2732. [[ -z "$input" ]] && input="$default_db"
  2733. if [[ ! -x "$bin" ]]; then
  2734. LOGE "x-ui binary not found at ${bin}. Is the panel installed?"
  2735. return 1
  2736. fi
  2737. if ! "$bin" migrate-db -h 2>&1 | grep -q -- '-dump'; then
  2738. LOGE "This x-ui build does not support .db <-> .dump conversion yet."
  2739. LOGE "Update the panel first (x-ui update) to a version with 'migrate-db --dump/--restore'."
  2740. return 1
  2741. fi
  2742. if [[ ! -f "$input" ]]; then
  2743. LOGE "Input file not found: ${input}"
  2744. echo -e "Usage: ${green}x-ui migrateDB [file.db|file.dump] [output]${plain}"
  2745. return 1
  2746. fi
  2747. local mode
  2748. case "$input" in
  2749. *.db | *.sqlite | *.sqlite3)
  2750. mode="dump"
  2751. ;;
  2752. *.dump | *.sql)
  2753. mode="restore"
  2754. ;;
  2755. *)
  2756. if head -c 16 "$input" | grep -q "SQLite format 3"; then
  2757. mode="dump"
  2758. else
  2759. mode="restore"
  2760. fi
  2761. ;;
  2762. esac
  2763. if [[ "$mode" == "dump" ]]; then
  2764. [[ -z "$output" ]] && output="${input%.*}.dump"
  2765. if [[ -f "$output" ]]; then
  2766. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2767. fi
  2768. LOGI "Dumping SQLite database to SQL text:"
  2769. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2770. if "$bin" migrate-db --src "$input" --dump "$output"; then
  2771. LOGI "Done. Wrote ${output}."
  2772. else
  2773. LOGE "Dump failed."
  2774. return 1
  2775. fi
  2776. else
  2777. [[ -z "$output" ]] && output="${input%.*}.db"
  2778. if [[ "$output" == "$default_db" ]] && check_status > /dev/null 2>&1; then
  2779. LOGE "Refusing to restore into the live database (${default_db}) while x-ui is running."
  2780. LOGE "Stop the panel first (x-ui stop) or choose a different output path."
  2781. return 1
  2782. fi
  2783. if [[ -f "$output" ]]; then
  2784. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2785. rm -f "$output"
  2786. fi
  2787. LOGI "Rebuilding SQLite database from SQL text:"
  2788. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2789. if "$bin" migrate-db --restore "$input" --out "$output"; then
  2790. LOGI "Done. Created ${output}."
  2791. else
  2792. LOGE "Restore failed."
  2793. rm -f "$output"
  2794. return 1
  2795. fi
  2796. fi
  2797. }
  2798. # Interactive wrapper around migrate_db for the menu: prompts for the paths and
  2799. # lets migrate_db auto-detect the direction.
  2800. migrate_db_prompt() {
  2801. local default_db="/etc/x-ui/x-ui.db"
  2802. local input output
  2803. echo -e "Convert between a SQLite ${green}.db${plain} and a portable ${green}.dump${plain} (direction auto-detected)."
  2804. read -rp "Input file [${default_db}]: " input
  2805. input="${input:-$default_db}"
  2806. read -rp "Output file (leave empty to auto-name next to input): " output
  2807. migrate_db "$input" "$output"
  2808. }
  2809. show_usage() {
  2810. echo -e "┌────────────────────────────────────────────────────────────────┐
  2811. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  2812. │ │
  2813. │ ${blue}x-ui${plain} - Admin Management Script │
  2814. │ ${blue}x-ui start${plain} - Start │
  2815. │ ${blue}x-ui stop${plain} - Stop │
  2816. │ ${blue}x-ui restart${plain} - Restart │
  2817. | ${blue}x-ui restart-xray${plain} - Restart Xray │
  2818. │ ${blue}x-ui status${plain} - Current Status │
  2819. │ ${blue}x-ui settings${plain} - Current Settings │
  2820. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  2821. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  2822. │ ${blue}x-ui log${plain} - Check logs │
  2823. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  2824. │ ${blue}x-ui update${plain} - Update │
  2825. │ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
  2826. │ ${blue}x-ui migrateDB [file]${plain} - Convert .db <-> .dump (SQLite) │
  2827. │ ${blue}x-ui legacy${plain} - Legacy version │
  2828. │ ${blue}x-ui install${plain} - Install │
  2829. │ ${blue}x-ui uninstall${plain} - Uninstall │
  2830. └────────────────────────────────────────────────────────────────┘"
  2831. }
  2832. show_menu() {
  2833. echo -e "
  2834. ╔────────────────────────────────────────────────╗
  2835. │ ${green}3X-UI Panel Management Script${plain} │
  2836. │ ${green}0.${plain} Exit Script │
  2837. │────────────────────────────────────────────────│
  2838. │ ${green}1.${plain} Install │
  2839. │ ${green}2.${plain} Update │
  2840. │ ${green}3.${plain} Update Menu │
  2841. │ ${green}4.${plain} Legacy Version │
  2842. │ ${green}5.${plain} Uninstall │
  2843. │────────────────────────────────────────────────│
  2844. │ ${green}6.${plain} Reset Username & Password │
  2845. │ ${green}7.${plain} Reset Web Base Path │
  2846. │ ${green}8.${plain} Reset Settings │
  2847. │ ${green}9.${plain} Change Port │
  2848. │ ${green}10.${plain} View Current Settings │
  2849. │────────────────────────────────────────────────│
  2850. │ ${green}11.${plain} Start │
  2851. │ ${green}12.${plain} Stop │
  2852. │ ${green}13.${plain} Restart │
  2853. | ${green}14.${plain} Restart Xray │
  2854. │ ${green}15.${plain} Check Status │
  2855. │ ${green}16.${plain} Logs Management │
  2856. │────────────────────────────────────────────────│
  2857. │ ${green}17.${plain} Enable Autostart │
  2858. │ ${green}18.${plain} Disable Autostart │
  2859. │────────────────────────────────────────────────│
  2860. │ ${green}19.${plain} SSL Certificate Management │
  2861. │ ${green}20.${plain} Cloudflare SSL Certificate │
  2862. │ ${green}21.${plain} IP Limit Management │
  2863. │ ${green}22.${plain} Firewall Management │
  2864. │ ${green}23.${plain} SSH Port Forwarding Management │
  2865. │────────────────────────────────────────────────│
  2866. │ ${green}24.${plain} Enable BBR │
  2867. │ ${green}25.${plain} Update Geo Files │
  2868. │ ${green}26.${plain} Speedtest by Ookla │
  2869. │────────────────────────────────────────────────│
  2870. │ ${green}27.${plain} PostgreSQL Management │
  2871. ╚────────────────────────────────────────────────╝
  2872. "
  2873. show_status
  2874. echo && read -rp "Please enter your selection [0-27]: " num
  2875. case "${num}" in
  2876. 0)
  2877. exit 0
  2878. ;;
  2879. 1)
  2880. check_uninstall && install
  2881. ;;
  2882. 2)
  2883. check_install && update
  2884. ;;
  2885. 3)
  2886. check_install && update_menu
  2887. ;;
  2888. 4)
  2889. check_install && legacy_version
  2890. ;;
  2891. 5)
  2892. check_install && uninstall
  2893. ;;
  2894. 6)
  2895. check_install && reset_user
  2896. ;;
  2897. 7)
  2898. check_install && reset_webbasepath
  2899. ;;
  2900. 8)
  2901. check_install && reset_config
  2902. ;;
  2903. 9)
  2904. check_install && set_port
  2905. ;;
  2906. 10)
  2907. check_install && check_config
  2908. ;;
  2909. 11)
  2910. check_install && start
  2911. ;;
  2912. 12)
  2913. check_install && stop
  2914. ;;
  2915. 13)
  2916. check_install && restart
  2917. ;;
  2918. 14)
  2919. check_install && restart_xray
  2920. ;;
  2921. 15)
  2922. check_install && status
  2923. ;;
  2924. 16)
  2925. check_install && show_log
  2926. ;;
  2927. 17)
  2928. check_install && enable
  2929. ;;
  2930. 18)
  2931. check_install && disable
  2932. ;;
  2933. 19)
  2934. ssl_cert_issue_main
  2935. ;;
  2936. 20)
  2937. ssl_cert_issue_CF
  2938. ;;
  2939. 21)
  2940. iplimit_main
  2941. ;;
  2942. 22)
  2943. firewall_menu
  2944. ;;
  2945. 23)
  2946. SSH_port_forwarding
  2947. ;;
  2948. 24)
  2949. bbr_menu
  2950. ;;
  2951. 25)
  2952. update_geo
  2953. ;;
  2954. 26)
  2955. run_speedtest
  2956. ;;
  2957. 27)
  2958. postgresql_menu
  2959. ;;
  2960. *)
  2961. LOGE "Please enter the correct number [0-27]"
  2962. ;;
  2963. esac
  2964. }
  2965. if [[ $# > 0 ]]; then
  2966. case $1 in
  2967. "start")
  2968. check_install 0 && start 0
  2969. ;;
  2970. "stop")
  2971. check_install 0 && stop 0
  2972. ;;
  2973. "restart")
  2974. check_install 0 && restart 0
  2975. ;;
  2976. "restart-xray")
  2977. check_install 0 && restart_xray 0
  2978. ;;
  2979. "status")
  2980. check_install 0 && status 0
  2981. ;;
  2982. "settings")
  2983. check_install 0 && check_config 0
  2984. ;;
  2985. "enable")
  2986. check_install 0 && enable 0
  2987. ;;
  2988. "disable")
  2989. check_install 0 && disable 0
  2990. ;;
  2991. "log")
  2992. check_install 0 && show_log 0
  2993. ;;
  2994. "banlog")
  2995. check_install 0 && show_banlog 0
  2996. ;;
  2997. "update")
  2998. check_install 0 && update 0
  2999. ;;
  3000. "legacy")
  3001. check_install 0 && legacy_version 0
  3002. ;;
  3003. "install")
  3004. check_uninstall 0 && install 0
  3005. ;;
  3006. "uninstall")
  3007. check_install 0 && uninstall 0
  3008. ;;
  3009. "update-all-geofiles")
  3010. geo_updated=0
  3011. if check_install 0 && update_all_geofiles 0; then
  3012. [[ $geo_updated -eq 0 ]] || restart 0
  3013. fi
  3014. ;;
  3015. "migrateDB")
  3016. migrate_db "$2" "$3"
  3017. ;;
  3018. *) show_usage ;;
  3019. esac
  3020. else
  3021. show_menu
  3022. fi