x-ui.sh 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266
  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. update_geofiles "main"
  1051. update_geofiles "IR"
  1052. update_geofiles "RU"
  1053. }
  1054. update_geofiles() {
  1055. case "${1}" in
  1056. "main")
  1057. dat_files=(geoip geosite)
  1058. dat_source="Loyalsoldier/v2ray-rules-dat"
  1059. ;;
  1060. "IR")
  1061. dat_files=(geoip_IR geosite_IR)
  1062. dat_source="chocolate4u/Iran-v2ray-rules"
  1063. ;;
  1064. "RU")
  1065. dat_files=(geoip_RU geosite_RU)
  1066. dat_source="runetfreedom/russia-v2ray-rules-dat"
  1067. ;;
  1068. esac
  1069. for dat in "${dat_files[@]}"; do
  1070. # Remove suffix for remote filename (e.g., geoip_IR -> geoip)
  1071. remote_file="${dat%%_*}"
  1072. curl -fLRo ${xui_folder}/bin/${dat}.dat -z ${xui_folder}/bin/${dat}.dat \
  1073. https://github.com/${dat_source}/releases/latest/download/${remote_file}.dat
  1074. done
  1075. }
  1076. update_geo() {
  1077. echo -e "${green}\t1.${plain} Loyalsoldier (geoip.dat, geosite.dat)"
  1078. echo -e "${green}\t2.${plain} chocolate4u (geoip_IR.dat, geosite_IR.dat)"
  1079. echo -e "${green}\t3.${plain} runetfreedom (geoip_RU.dat, geosite_RU.dat)"
  1080. echo -e "${green}\t4.${plain} All"
  1081. echo -e "${green}\t0.${plain} Back to Main Menu"
  1082. read -rp "Choose an option: " choice
  1083. case "$choice" in
  1084. 0)
  1085. show_menu
  1086. ;;
  1087. 1)
  1088. update_geofiles "main"
  1089. echo -e "${green}Loyalsoldier datasets have been updated successfully!${plain}"
  1090. restart
  1091. ;;
  1092. 2)
  1093. update_geofiles "IR"
  1094. echo -e "${green}chocolate4u datasets have been updated successfully!${plain}"
  1095. restart
  1096. ;;
  1097. 3)
  1098. update_geofiles "RU"
  1099. echo -e "${green}runetfreedom datasets have been updated successfully!${plain}"
  1100. restart
  1101. ;;
  1102. 4)
  1103. update_all_geofiles
  1104. echo -e "${green}All geo files have been updated successfully!${plain}"
  1105. restart
  1106. ;;
  1107. *)
  1108. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1109. update_geo
  1110. ;;
  1111. esac
  1112. before_show_menu
  1113. }
  1114. install_acme() {
  1115. # Check if acme.sh is already installed
  1116. if command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1117. LOGI "acme.sh is already installed."
  1118. return 0
  1119. fi
  1120. LOGI "Installing acme.sh..."
  1121. cd ~ || return 1 # Ensure you can change to the home directory
  1122. curl -s https://get.acme.sh | sh
  1123. if [ $? -ne 0 ]; then
  1124. LOGE "Installation of acme.sh failed."
  1125. return 1
  1126. else
  1127. LOGI "Installation of acme.sh succeeded."
  1128. fi
  1129. return 0
  1130. }
  1131. ssl_cert_issue_main() {
  1132. echo -e "${green}\t1.${plain} Get SSL (Domain)"
  1133. echo -e "${green}\t2.${plain} Revoke & Remove"
  1134. echo -e "${green}\t3.${plain} Force Renew"
  1135. echo -e "${green}\t4.${plain} Show Existing Domains"
  1136. echo -e "${green}\t5.${plain} Set Cert paths for the panel"
  1137. echo -e "${green}\t6.${plain} Get SSL for IP Address (6-day cert, auto-renews)"
  1138. echo -e "${green}\t0.${plain} Back to Main Menu"
  1139. read -rp "Choose an option: " choice
  1140. case "$choice" in
  1141. 0)
  1142. show_menu
  1143. ;;
  1144. 1)
  1145. ssl_cert_issue
  1146. ssl_cert_issue_main
  1147. ;;
  1148. 2)
  1149. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1150. if [ -z "$domains" ]; then
  1151. echo "No certificates found to revoke."
  1152. else
  1153. echo "Existing domains:"
  1154. echo "$domains"
  1155. read -rp "Please enter a domain from the list to revoke and remove the certificate: " domain
  1156. if echo "$domains" | grep -qw "$domain"; then
  1157. # The IP-cert flow (option 6) stores files under /root/cert/ip, but acme.sh
  1158. # tracks the cert under the actual IP address(es). Resolve those so renewal
  1159. # state is torn down too; otherwise the acme.sh cron re-creates the deleted cert.
  1160. local acme_ids="${domain}"
  1161. if [[ "${domain}" == "ip" ]]; then
  1162. 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}$|:')
  1163. fi
  1164. for id in ${acme_ids}; do
  1165. # Best-effort revoke at the CA, then drop acme.sh renewal tracking.
  1166. ~/.acme.sh/acme.sh --revoke -d "${id}" 2> /dev/null
  1167. ~/.acme.sh/acme.sh --remove -d "${id}" 2> /dev/null
  1168. # --remove leaves the cert files on disk, so delete the state dirs (RSA + ECC).
  1169. rm -rf ~/.acme.sh/"${id}" ~/.acme.sh/"${id}_ecc"
  1170. done
  1171. # Delete the local certificate files for this domain.
  1172. rm -rf "/root/cert/${domain}"
  1173. LOGI "Certificate revoked and removed for domain: ${domain}"
  1174. # If the panel currently serves this domain's cert, clear the stored paths
  1175. # so it stops loading the now-deleted files, then restart.
  1176. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1177. if [[ "${existing_cert}" == "/root/cert/${domain}/"* ]]; then
  1178. ${xui_folder}/x-ui cert -reset
  1179. LOGI "Cleared panel certificate paths referencing ${domain}; restarting panel."
  1180. restart
  1181. fi
  1182. else
  1183. echo "Invalid domain entered."
  1184. fi
  1185. fi
  1186. ssl_cert_issue_main
  1187. ;;
  1188. 3)
  1189. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1190. if [ -z "$domains" ]; then
  1191. echo "No certificates found to renew."
  1192. else
  1193. echo "Existing domains:"
  1194. echo "$domains"
  1195. read -rp "Please enter a domain from the list to renew the SSL certificate: " domain
  1196. if echo "$domains" | grep -qw "$domain"; then
  1197. ~/.acme.sh/acme.sh --renew -d ${domain} --force
  1198. LOGI "Certificate forcefully renewed for domain: $domain"
  1199. else
  1200. echo "Invalid domain entered."
  1201. fi
  1202. fi
  1203. ssl_cert_issue_main
  1204. ;;
  1205. 4)
  1206. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1207. if [ -z "$domains" ]; then
  1208. echo "No certificates found under /root/cert."
  1209. else
  1210. echo "Existing domains and their paths:"
  1211. for domain in $domains; do
  1212. local cert_path="/root/cert/${domain}/fullchain.pem"
  1213. local key_path="/root/cert/${domain}/privkey.pem"
  1214. if [[ -f "${cert_path}" && -f "${key_path}" ]]; then
  1215. echo -e "Domain: ${domain}"
  1216. echo -e "\tCertificate Path: ${cert_path}"
  1217. echo -e "\tPrivate Key Path: ${key_path}"
  1218. else
  1219. echo -e "Domain: ${domain} - Certificate or Key missing."
  1220. fi
  1221. done
  1222. fi
  1223. # The panel's configured certificate may live outside /root/cert
  1224. # (e.g. certbot under /etc/letsencrypt) — show it too (#5070).
  1225. local panel_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  1226. if [[ -n "${panel_cert}" && "${panel_cert}" != /root/cert/* ]]; then
  1227. echo -e "Panel certificate (custom path): ${panel_cert}"
  1228. if [[ -f "${panel_cert}" ]] && command -v openssl > /dev/null 2>&1; then
  1229. local panel_sans=$(openssl x509 -in "${panel_cert}" -noout -ext subjectAltName 2> /dev/null \
  1230. | grep -Eo 'DNS:[^,[:space:]]+' | cut -d: -f2 | tr '\n' ' ')
  1231. [[ -n "${panel_sans}" ]] && echo -e "\tCovers: ${panel_sans}"
  1232. fi
  1233. fi
  1234. ssl_cert_issue_main
  1235. ;;
  1236. 5)
  1237. echo -e "${green}\t1.${plain} Use a certificate from /root/cert"
  1238. echo -e "${green}\t2.${plain} Enter custom certificate file paths (e.g. certbot, /etc/letsencrypt/...)"
  1239. read -rp "Choose an option: " pathChoice
  1240. if [[ "$pathChoice" == "2" ]]; then
  1241. read -rp "Certificate file path (fullchain): " webCertFile
  1242. read -rp "Private key file path: " webKeyFile
  1243. if [[ -f "${webCertFile}" && -f "${webKeyFile}" ]]; then
  1244. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1245. echo "Panel certificate paths set:"
  1246. echo " - Certificate File: $webCertFile"
  1247. echo " - Private Key File: $webKeyFile"
  1248. restart
  1249. else
  1250. echo "Certificate or private key file not found."
  1251. fi
  1252. ssl_cert_issue_main
  1253. return
  1254. fi
  1255. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \; 2> /dev/null)
  1256. if [ -z "$domains" ]; then
  1257. echo "No certificates found."
  1258. else
  1259. echo "Available domains:"
  1260. echo "$domains"
  1261. read -rp "Please choose a domain to set the panel paths: " domain
  1262. if echo "$domains" | grep -qw "$domain"; then
  1263. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1264. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1265. if [[ -f "${webCertFile}" && -f "${webKeyFile}" ]]; then
  1266. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1267. echo "Panel paths set for domain: $domain"
  1268. echo " - Certificate File: $webCertFile"
  1269. echo " - Private Key File: $webKeyFile"
  1270. # Register the acme.sh install-cert hook so auto-renewal copies the
  1271. # renewed cert to these paths and reloads the panel. Without it acme.sh
  1272. # renews but never updates /root/cert, silently serving a stale cert.
  1273. if command -v ~/.acme.sh/acme.sh &> /dev/null && ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  1274. ~/.acme.sh/acme.sh --installcert -d "${domain}" \
  1275. --key-file "${webKeyFile}" \
  1276. --fullchain-file "${webCertFile}" \
  1277. --reloadcmd "x-ui restart" 2>&1 || true
  1278. echo "Registered acme.sh auto-renewal hook for ${domain}."
  1279. fi
  1280. restart
  1281. else
  1282. echo "Certificate or private key not found for domain: $domain."
  1283. fi
  1284. else
  1285. echo "Invalid domain entered."
  1286. fi
  1287. fi
  1288. ssl_cert_issue_main
  1289. ;;
  1290. 6)
  1291. echo -e "${yellow}Let's Encrypt SSL Certificate for IP Address${plain}"
  1292. echo -e "This will obtain a certificate for your server's IP using the shortlived profile."
  1293. echo -e "${yellow}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  1294. echo -e "${yellow}Port 80 must be open and accessible from the internet.${plain}"
  1295. confirm "Do you want to proceed?" "y"
  1296. if [[ $? == 0 ]]; then
  1297. ssl_cert_issue_for_ip
  1298. fi
  1299. ssl_cert_issue_main
  1300. ;;
  1301. *)
  1302. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1303. ssl_cert_issue_main
  1304. ;;
  1305. esac
  1306. }
  1307. ssl_cert_issue_for_ip() {
  1308. LOGI "Starting automatic SSL certificate generation for server IP..."
  1309. LOGI "Using Let's Encrypt shortlived profile (~6 days validity, auto-renews)"
  1310. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1311. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1312. # Get server IP
  1313. local URL_lists=(
  1314. "https://api4.ipify.org"
  1315. "https://ipv4.icanhazip.com"
  1316. "https://v4.api.ipinfo.io/ip"
  1317. "https://ipv4.myexternalip.com/raw"
  1318. "https://4.ident.me"
  1319. "https://check-host.net/ip"
  1320. )
  1321. local server_ip=""
  1322. for ip_address in "${URL_lists[@]}"; do
  1323. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  1324. local http_code=$(echo "$response" | tail -n1)
  1325. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  1326. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1327. server_ip="${ip_result}"
  1328. break
  1329. fi
  1330. done
  1331. if [[ -z "$server_ip" ]]; then
  1332. LOGI "Could not auto-detect server IP from any provider."
  1333. while [[ -z "$server_ip" ]]; do
  1334. read -rp "Please enter your server's public IPv4 address: " server_ip
  1335. server_ip="${server_ip// /}"
  1336. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1337. LOGE "Invalid IPv4 address. Please try again."
  1338. server_ip=""
  1339. fi
  1340. done
  1341. fi
  1342. LOGI "Server IP detected: ${server_ip}"
  1343. # Ask for optional IPv6
  1344. local ipv6_addr=""
  1345. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  1346. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  1347. # check for acme.sh first
  1348. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1349. LOGI "acme.sh not found, installing..."
  1350. install_acme
  1351. if [ $? -ne 0 ]; then
  1352. LOGE "Failed to install acme.sh"
  1353. return 1
  1354. fi
  1355. fi
  1356. # install socat
  1357. case "${release}" in
  1358. ubuntu | debian | armbian)
  1359. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1360. ;;
  1361. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1362. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1363. ;;
  1364. centos)
  1365. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1366. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1367. else
  1368. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1369. fi
  1370. ;;
  1371. arch | manjaro | parch)
  1372. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1373. ;;
  1374. opensuse-tumbleweed | opensuse-leap)
  1375. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1376. ;;
  1377. alpine)
  1378. apk add socat curl openssl > /dev/null 2>&1
  1379. ;;
  1380. *)
  1381. LOGW "Unsupported OS for automatic socat installation"
  1382. ;;
  1383. esac
  1384. # Create certificate directory
  1385. certPath="/root/cert/ip"
  1386. mkdir -p "$certPath"
  1387. # Build domain arguments
  1388. local domain_args="-d ${server_ip}"
  1389. if [[ -n "$ipv6_addr" ]] && is_ipv6 "$ipv6_addr"; then
  1390. domain_args="${domain_args} -d ${ipv6_addr}"
  1391. LOGI "Including IPv6 address: ${ipv6_addr}"
  1392. fi
  1393. # Choose port for HTTP-01 listener (default 80, allow override)
  1394. local WebPort=""
  1395. read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
  1396. WebPort="${WebPort:-80}"
  1397. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  1398. LOGE "Invalid port provided. Falling back to 80."
  1399. WebPort=80
  1400. fi
  1401. LOGI "Using port ${WebPort} to issue certificate for IP: ${server_ip}"
  1402. if [[ "${WebPort}" -ne 80 ]]; then
  1403. LOGI "Reminder: Let's Encrypt still reaches port 80; forward external port 80 to ${WebPort} for validation."
  1404. fi
  1405. while true; do
  1406. if is_port_in_use "${WebPort}"; then
  1407. LOGI "Port ${WebPort} is currently in use."
  1408. local alt_port=""
  1409. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  1410. alt_port="${alt_port// /}"
  1411. if [[ -z "${alt_port}" ]]; then
  1412. LOGE "Port ${WebPort} is busy; cannot proceed with issuance."
  1413. return 1
  1414. fi
  1415. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  1416. LOGE "Invalid port provided."
  1417. return 1
  1418. fi
  1419. WebPort="${alt_port}"
  1420. continue
  1421. else
  1422. LOGI "Port ${WebPort} is free and ready for standalone validation."
  1423. break
  1424. fi
  1425. done
  1426. # Reload command - restarts panel after renewal
  1427. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null"
  1428. # issue the certificate for IP with shortlived profile
  1429. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1430. ~/.acme.sh/acme.sh --issue \
  1431. ${domain_args} \
  1432. --standalone \
  1433. --server letsencrypt \
  1434. --certificate-profile shortlived \
  1435. --days 6 \
  1436. --httpport ${WebPort} \
  1437. --force
  1438. if [ $? -ne 0 ]; then
  1439. LOGE "Failed to issue certificate for IP: ${server_ip}"
  1440. LOGE "Make sure port ${WebPort} is open and the server is accessible from the internet"
  1441. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1442. rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null
  1443. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null
  1444. rm -rf ${certPath} 2> /dev/null
  1445. return 1
  1446. else
  1447. LOGI "Certificate issued successfully for IP: ${server_ip}"
  1448. fi
  1449. # Install the certificate
  1450. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  1451. # but the cert files are still installed. We check for files instead of exit code.
  1452. ~/.acme.sh/acme.sh --installcert -d ${server_ip} \
  1453. --key-file "${certPath}/privkey.pem" \
  1454. --fullchain-file "${certPath}/fullchain.pem" \
  1455. --reloadcmd "${reloadCmd}" 2>&1 || true
  1456. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  1457. if [[ ! -f "${certPath}/fullchain.pem" || ! -f "${certPath}/privkey.pem" ]]; then
  1458. LOGE "Certificate files not found after installation"
  1459. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1460. rm -rf ~/.acme.sh/${server_ip} ~/.acme.sh/${server_ip}_ecc 2> /dev/null
  1461. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} ~/.acme.sh/${ipv6_addr}_ecc 2> /dev/null
  1462. rm -rf ${certPath} 2> /dev/null
  1463. return 1
  1464. fi
  1465. LOGI "Certificate files installed successfully"
  1466. # enable auto-renew
  1467. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  1468. chmod 600 $certPath/privkey.pem 2> /dev/null
  1469. chmod 644 $certPath/fullchain.pem 2> /dev/null
  1470. # Prompt user to set panel paths after successful certificate installation
  1471. local webCertFile="${certPath}/fullchain.pem"
  1472. local webKeyFile="${certPath}/privkey.pem"
  1473. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1474. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1475. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1476. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1477. LOGI "Panel paths set for IP: $server_ip"
  1478. LOGI " - Certificate File: $webCertFile"
  1479. LOGI " - Private Key File: $webKeyFile"
  1480. LOGI " - Validity: ~6 days (auto-renews via acme.sh cron)"
  1481. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  1482. LOGI "Panel will restart to apply SSL certificate..."
  1483. restart
  1484. else
  1485. LOGE "Error: Certificate or private key file not found for IP: $server_ip."
  1486. return 1
  1487. fi
  1488. else
  1489. LOGI "Skipping panel path setting."
  1490. fi
  1491. return 0
  1492. }
  1493. ssl_cert_issue() {
  1494. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1495. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1496. # check for acme.sh first
  1497. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1498. echo "acme.sh could not be found. we will install it"
  1499. install_acme
  1500. if [ $? -ne 0 ]; then
  1501. LOGE "install acme failed, please check logs"
  1502. exit 1
  1503. fi
  1504. fi
  1505. # install socat
  1506. case "${release}" in
  1507. ubuntu | debian | armbian)
  1508. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1509. ;;
  1510. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1511. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1512. ;;
  1513. centos)
  1514. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1515. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1516. else
  1517. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1518. fi
  1519. ;;
  1520. arch | manjaro | parch)
  1521. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1522. ;;
  1523. opensuse-tumbleweed | opensuse-leap)
  1524. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1525. ;;
  1526. alpine)
  1527. apk add socat curl openssl > /dev/null 2>&1
  1528. ;;
  1529. *)
  1530. LOGW "Unsupported OS for automatic socat installation"
  1531. ;;
  1532. esac
  1533. if [ $? -ne 0 ]; then
  1534. LOGE "install socat failed, please check logs"
  1535. exit 1
  1536. else
  1537. LOGI "install socat succeed..."
  1538. fi
  1539. # get the domain here, and we need to verify it
  1540. local domain=""
  1541. while true; do
  1542. read -rp "Please enter your domain name: " domain
  1543. domain="${domain// /}" # Trim whitespace
  1544. if [[ -z "$domain" ]]; then
  1545. LOGE "Domain name cannot be empty. Please try again."
  1546. continue
  1547. fi
  1548. if ! is_domain "$domain"; then
  1549. LOGE "Invalid domain format: ${domain}. Please enter a valid domain name."
  1550. continue
  1551. fi
  1552. break
  1553. done
  1554. LOGD "Your domain is: ${domain}, checking it..."
  1555. SSL_ISSUED_DOMAIN="${domain}"
  1556. # detect existing certificate and reuse it only if its files are actually
  1557. # present and non-empty. acme.sh stores ECC certs under ${domain}_ecc and RSA
  1558. # certs under ${domain}; a failed issuance can leave a domain entry in --list
  1559. # with no usable cert files, which must not be reused (it produces a 0-byte
  1560. # fullchain.pem). Broken partial state is cleaned up so issuance can proceed.
  1561. local cert_exists=0
  1562. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  1563. local acmeCertDir=""
  1564. if [[ -s ~/.acme.sh/${domain}_ecc/fullchain.cer && -s ~/.acme.sh/${domain}_ecc/${domain}.key ]]; then
  1565. acmeCertDir=~/.acme.sh/${domain}_ecc
  1566. elif [[ -s ~/.acme.sh/${domain}/fullchain.cer && -s ~/.acme.sh/${domain}/${domain}.key ]]; then
  1567. acmeCertDir=~/.acme.sh/${domain}
  1568. fi
  1569. if [[ -n "${acmeCertDir}" ]]; then
  1570. cert_exists=1
  1571. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  1572. LOGI "Existing certificate found for ${domain}, will reuse it."
  1573. [[ -n "${certInfo}" ]] && LOGI "${certInfo}"
  1574. else
  1575. LOGW "Found incomplete acme.sh state for ${domain} (no valid certificate files); cleaning it up and re-issuing."
  1576. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1577. fi
  1578. fi
  1579. if [[ ${cert_exists} -eq 0 ]]; then
  1580. LOGI "Your domain is ready for issuing certificates now..."
  1581. fi
  1582. # create a directory for the certificate
  1583. certPath="/root/cert/${domain}"
  1584. if [ ! -d "$certPath" ]; then
  1585. mkdir -p "$certPath"
  1586. else
  1587. rm -rf "$certPath"
  1588. mkdir -p "$certPath"
  1589. fi
  1590. # get the port number for the standalone server
  1591. local WebPort=80
  1592. read -rp "Please choose which port to use (default is 80): " WebPort
  1593. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  1594. LOGE "Your input ${WebPort} is invalid, will use default port 80."
  1595. WebPort=80
  1596. fi
  1597. LOGI "Will use port: ${WebPort} to issue certificates. Please make sure this port is open."
  1598. if [[ ${cert_exists} -eq 0 ]]; then
  1599. # issue the certificate
  1600. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1601. ~/.acme.sh/acme.sh --issue -d ${domain} $(acme_listen_flag) --standalone --httpport ${WebPort} --force
  1602. if [ $? -ne 0 ]; then
  1603. LOGE "Issuing certificate failed, please check logs."
  1604. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1605. exit 1
  1606. else
  1607. LOGE "Issuing certificate succeeded, installing certificates..."
  1608. fi
  1609. else
  1610. LOGI "Using existing certificate, installing certificates..."
  1611. fi
  1612. reloadCmd="x-ui restart"
  1613. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1614. LOGI "This command will run on every certificate issue and renew."
  1615. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1616. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1617. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1618. echo -e "${green}\t2.${plain} Input your own command"
  1619. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1620. read -rp "Choose an option: " choice
  1621. case "$choice" in
  1622. 1)
  1623. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1624. reloadCmd="systemctl reload nginx ; x-ui restart"
  1625. ;;
  1626. 2)
  1627. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1628. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1629. LOGI "Your reloadcmd is: ${reloadCmd}"
  1630. ;;
  1631. *)
  1632. LOGI "Keep default reloadcmd"
  1633. ;;
  1634. esac
  1635. fi
  1636. # install the certificate
  1637. local installOutput=""
  1638. installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \
  1639. --key-file /root/cert/${domain}/privkey.pem \
  1640. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  1641. local installRc=$?
  1642. echo "${installOutput}"
  1643. local installWroteFiles=0
  1644. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  1645. installWroteFiles=1
  1646. fi
  1647. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  1648. LOGI "Installing certificate succeeded, enabling auto renew..."
  1649. else
  1650. LOGE "Installing certificate failed, exiting."
  1651. if [[ ${cert_exists} -eq 0 ]]; then
  1652. rm -rf ~/.acme.sh/${domain} ~/.acme.sh/${domain}_ecc
  1653. fi
  1654. exit 1
  1655. fi
  1656. # enable auto-renew
  1657. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1658. if [ $? -ne 0 ]; then
  1659. LOGE "Auto renew failed, certificate details:"
  1660. ls -lah cert/*
  1661. chmod 600 $certPath/privkey.pem
  1662. chmod 644 $certPath/fullchain.pem
  1663. exit 1
  1664. else
  1665. LOGI "Auto renew succeeded, certificate details:"
  1666. ls -lah cert/*
  1667. chmod 600 $certPath/privkey.pem
  1668. chmod 644 $certPath/fullchain.pem
  1669. fi
  1670. # Prompt user to set panel paths after successful certificate installation
  1671. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1672. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1673. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1674. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1675. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1676. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1677. LOGI "Panel paths set for domain: $domain"
  1678. LOGI " - Certificate File: $webCertFile"
  1679. LOGI " - Private Key File: $webKeyFile"
  1680. echo -e "${green}Access URL: https://${domain}:${existing_port}${existing_webBasePath}${plain}"
  1681. restart
  1682. else
  1683. LOGE "Error: Certificate or private key file not found for domain: $domain."
  1684. fi
  1685. else
  1686. LOGI "Skipping panel path setting."
  1687. fi
  1688. }
  1689. ssl_cert_issue_CF() {
  1690. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1691. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1692. LOGI "****** Instructions for Use ******"
  1693. LOGI "Follow the steps below to complete the process:"
  1694. LOGI "1. A Cloudflare API Token (recommended, scoped to Zone:DNS:Edit) or the Global API Key + registered email."
  1695. LOGI "2. The Domain Name."
  1696. LOGI "3. Once the certificate is issued, you will be prompted to set the certificate for the panel (optional)."
  1697. LOGI "4. The script also supports automatic renewal of the SSL certificate after installation."
  1698. confirm "Do you confirm the information and wish to proceed? [y/n]" "y"
  1699. if [ $? -eq 0 ]; then
  1700. # Check for acme.sh first
  1701. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1702. echo "acme.sh could not be found. We will install it."
  1703. install_acme
  1704. if [ $? -ne 0 ]; then
  1705. LOGE "Install acme failed, please check logs."
  1706. exit 1
  1707. fi
  1708. fi
  1709. CF_Domain=""
  1710. LOGD "Please set a domain name:"
  1711. read -rp "Input your domain here: " CF_Domain
  1712. LOGD "Your domain name is set to: ${CF_Domain}"
  1713. # Cloudflare API credentials: an API Token (recommended, scoped to a
  1714. # single zone) or the account-wide Global API Key. acme.sh reads
  1715. # CF_Token for tokens, or CF_Key + CF_Email for the Global Key.
  1716. CF_KeyType=""
  1717. read -rp "Are you using a Cloudflare API Token or Global API Key? (t/g) [Default t]: " CF_KeyType
  1718. CF_KeyType=${CF_KeyType:-t}
  1719. if [[ "$CF_KeyType" == "g" || "$CF_KeyType" == "G" ]]; then
  1720. CF_GlobalKey=""
  1721. CF_AccountEmail=""
  1722. LOGD "Please set the Global API Key:"
  1723. read -rp "Input your key here: " CF_GlobalKey
  1724. LOGD "Please set up the registered email:"
  1725. read -rp "Input your email here: " CF_AccountEmail
  1726. export CF_Key="${CF_GlobalKey}"
  1727. export CF_Email="${CF_AccountEmail}"
  1728. else
  1729. CF_ApiToken=""
  1730. LOGD "Please set the API Token:"
  1731. read -rp "Input your token here: " CF_ApiToken
  1732. export CF_Token="${CF_ApiToken}"
  1733. fi
  1734. # Set the default CA to Let's Encrypt
  1735. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1736. if [ $? -ne 0 ]; then
  1737. LOGE "Default CA, Let'sEncrypt fail, script exiting..."
  1738. exit 1
  1739. fi
  1740. # Issue the certificate using Cloudflare DNS
  1741. ~/.acme.sh/acme.sh --issue --dns dns_cf -d ${CF_Domain} -d *.${CF_Domain} --log --force
  1742. if [ $? -ne 0 ]; then
  1743. LOGE "Certificate issuance failed, script exiting..."
  1744. exit 1
  1745. else
  1746. LOGI "Certificate issued successfully, Installing..."
  1747. fi
  1748. # Install the certificate
  1749. certPath="/root/cert/${CF_Domain}"
  1750. if [ -d "$certPath" ]; then
  1751. rm -rf ${certPath}
  1752. fi
  1753. mkdir -p ${certPath}
  1754. if [ $? -ne 0 ]; then
  1755. LOGE "Failed to create directory: ${certPath}"
  1756. exit 1
  1757. fi
  1758. reloadCmd="x-ui restart"
  1759. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1760. LOGI "This command will run on every certificate issue and renew."
  1761. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1762. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1763. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1764. echo -e "${green}\t2.${plain} Input your own command"
  1765. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1766. read -rp "Choose an option: " choice
  1767. case "$choice" in
  1768. 1)
  1769. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1770. reloadCmd="systemctl reload nginx ; x-ui restart"
  1771. ;;
  1772. 2)
  1773. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1774. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1775. LOGI "Your reloadcmd is: ${reloadCmd}"
  1776. ;;
  1777. *)
  1778. LOGI "Keep default reloadcmd"
  1779. ;;
  1780. esac
  1781. fi
  1782. ~/.acme.sh/acme.sh --installcert -d ${CF_Domain} -d *.${CF_Domain} \
  1783. --key-file ${certPath}/privkey.pem \
  1784. --fullchain-file ${certPath}/fullchain.pem --reloadcmd "${reloadCmd}"
  1785. if [ $? -ne 0 ]; then
  1786. LOGE "Certificate installation failed, script exiting..."
  1787. exit 1
  1788. else
  1789. LOGI "Certificate installed successfully, Turning on automatic updates..."
  1790. fi
  1791. # Enable auto-update
  1792. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1793. if [ $? -ne 0 ]; then
  1794. LOGE "Auto update setup failed, script exiting..."
  1795. exit 1
  1796. else
  1797. LOGI "The certificate is installed and auto-renewal is turned on. Specific information is as follows:"
  1798. ls -lah ${certPath}/*
  1799. chmod 600 ${certPath}/privkey.pem
  1800. chmod 644 ${certPath}/fullchain.pem
  1801. fi
  1802. # Prompt user to set panel paths after successful certificate installation
  1803. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1804. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1805. local webCertFile="${certPath}/fullchain.pem"
  1806. local webKeyFile="${certPath}/privkey.pem"
  1807. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1808. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1809. LOGI "Panel paths set for domain: $CF_Domain"
  1810. LOGI " - Certificate File: $webCertFile"
  1811. LOGI " - Private Key File: $webKeyFile"
  1812. echo -e "${green}Access URL: https://${CF_Domain}:${existing_port}${existing_webBasePath}${plain}"
  1813. restart
  1814. else
  1815. LOGE "Error: Certificate or private key file not found for domain: $CF_Domain."
  1816. fi
  1817. else
  1818. LOGI "Skipping panel path setting."
  1819. fi
  1820. else
  1821. show_menu
  1822. fi
  1823. }
  1824. run_speedtest() {
  1825. # Check if Speedtest is already installed
  1826. if ! command -v speedtest &> /dev/null; then
  1827. # If not installed, determine installation method
  1828. if command -v snap &> /dev/null; then
  1829. # Use snap to install Speedtest
  1830. echo "Installing Speedtest using snap..."
  1831. snap install speedtest
  1832. else
  1833. # Fallback to using package managers
  1834. local pkg_manager=""
  1835. local speedtest_install_script=""
  1836. if command -v dnf &> /dev/null; then
  1837. pkg_manager="dnf"
  1838. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1839. elif command -v yum &> /dev/null; then
  1840. pkg_manager="yum"
  1841. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1842. elif command -v apt-get &> /dev/null; then
  1843. pkg_manager="apt-get"
  1844. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1845. elif command -v apt &> /dev/null; then
  1846. pkg_manager="apt"
  1847. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1848. fi
  1849. if [[ -z $pkg_manager ]]; then
  1850. echo "Error: Package manager not found. You may need to install Speedtest manually."
  1851. return 1
  1852. else
  1853. echo "Installing Speedtest using $pkg_manager..."
  1854. curl -s $speedtest_install_script | bash
  1855. $pkg_manager install -y speedtest
  1856. fi
  1857. fi
  1858. fi
  1859. speedtest
  1860. }
  1861. ip_validation() {
  1862. 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]))$"
  1863. 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)$"
  1864. }
  1865. iplimit_main() {
  1866. echo -e "\n${green}\t1.${plain} Install Fail2ban and configure IP Limit"
  1867. echo -e "${green}\t2.${plain} Change Ban Duration"
  1868. echo -e "${green}\t3.${plain} Unban Everyone"
  1869. echo -e "${green}\t4.${plain} Ban Logs"
  1870. echo -e "${green}\t5.${plain} Ban an IP Address"
  1871. echo -e "${green}\t6.${plain} Unban an IP Address"
  1872. echo -e "${green}\t7.${plain} Real-Time Logs"
  1873. echo -e "${green}\t8.${plain} Service Status"
  1874. echo -e "${green}\t9.${plain} Service Restart"
  1875. echo -e "${green}\t10.${plain} Uninstall Fail2ban and IP Limit"
  1876. echo -e "${green}\t0.${plain} Back to Main Menu"
  1877. read -rp "Choose an option: " choice
  1878. case "$choice" in
  1879. 0)
  1880. show_menu
  1881. ;;
  1882. 1)
  1883. confirm "Proceed with installation of Fail2ban & IP Limit?" "y"
  1884. if [[ $? == 0 ]]; then
  1885. install_iplimit
  1886. else
  1887. iplimit_main
  1888. fi
  1889. ;;
  1890. 2)
  1891. read -rp "Please enter new Ban Duration in Minutes [default 30]: " NUM
  1892. if [[ $NUM =~ ^[0-9]+$ ]]; then
  1893. create_iplimit_jails ${NUM}
  1894. if [[ $release == "alpine" ]]; then
  1895. rc-service fail2ban restart
  1896. else
  1897. systemctl restart fail2ban
  1898. fi
  1899. else
  1900. echo -e "${red}${NUM} is not a number! Please, try again.${plain}"
  1901. fi
  1902. iplimit_main
  1903. ;;
  1904. 3)
  1905. confirm "Proceed with Unbanning everyone from IP Limit jail?" "y"
  1906. if [[ $? == 0 ]]; then
  1907. fail2ban-client reload --restart --unban 3x-ipl
  1908. truncate -s 0 "${iplimit_banned_log_path}"
  1909. echo -e "${green}All users Unbanned successfully.${plain}"
  1910. iplimit_main
  1911. else
  1912. echo -e "${yellow}Cancelled.${plain}"
  1913. fi
  1914. iplimit_main
  1915. ;;
  1916. 4)
  1917. show_banlog
  1918. iplimit_main
  1919. ;;
  1920. 5)
  1921. read -rp "Enter the IP address you want to ban: " ban_ip
  1922. ip_validation
  1923. if [[ $ban_ip =~ $ipv4_regex || $ban_ip =~ $ipv6_regex ]]; then
  1924. fail2ban-client set 3x-ipl banip "$ban_ip"
  1925. echo -e "${green}IP Address ${ban_ip} has been banned successfully.${plain}"
  1926. else
  1927. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1928. fi
  1929. iplimit_main
  1930. ;;
  1931. 6)
  1932. read -rp "Enter the IP address you want to unban: " unban_ip
  1933. ip_validation
  1934. if [[ $unban_ip =~ $ipv4_regex || $unban_ip =~ $ipv6_regex ]]; then
  1935. fail2ban-client set 3x-ipl unbanip "$unban_ip"
  1936. echo -e "${green}IP Address ${unban_ip} has been unbanned successfully.${plain}"
  1937. else
  1938. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1939. fi
  1940. iplimit_main
  1941. ;;
  1942. 7)
  1943. tail -f /var/log/fail2ban.log
  1944. iplimit_main
  1945. ;;
  1946. 8)
  1947. service fail2ban status
  1948. iplimit_main
  1949. ;;
  1950. 9)
  1951. if [[ $release == "alpine" ]]; then
  1952. rc-service fail2ban restart
  1953. else
  1954. systemctl restart fail2ban
  1955. fi
  1956. iplimit_main
  1957. ;;
  1958. 10)
  1959. remove_iplimit
  1960. iplimit_main
  1961. ;;
  1962. *)
  1963. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1964. iplimit_main
  1965. ;;
  1966. esac
  1967. }
  1968. install_iplimit() {
  1969. if ! command -v fail2ban-client &> /dev/null; then
  1970. echo -e "${green}Fail2ban is not installed. Installing now...!${plain}\n"
  1971. # Install fail2ban together with nftables. Recent fail2ban packages
  1972. # default to `banaction = nftables-multiport` in /etc/fail2ban/jail.conf,
  1973. # but the `nftables` package isn't pulled in as a dependency on most
  1974. # minimal server images (Debian 12+, Ubuntu 24+, fresh RHEL-family).
  1975. # Without `nft` in PATH the default sshd jail fails to ban with
  1976. # stderr: '/bin/sh: 1: nft: not found'
  1977. # even though our own 3x-ipl jail uses iptables. Bundling the binary
  1978. # at install time prevents that confusing log spam for new installs.
  1979. case "${release}" in
  1980. ubuntu)
  1981. apt-get update
  1982. if [[ "${os_version}" -ge 2400 ]]; then
  1983. apt-get install python3-pip -y
  1984. python3 -m pip install pyasynchat --break-system-packages
  1985. fi
  1986. apt-get install fail2ban nftables -y
  1987. ;;
  1988. debian)
  1989. apt-get update
  1990. if [ "$os_version" -ge 12 ]; then
  1991. apt-get install -y python3-systemd
  1992. fi
  1993. apt-get install -y fail2ban nftables
  1994. ;;
  1995. armbian)
  1996. apt-get update && apt-get install fail2ban nftables -y
  1997. ;;
  1998. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1999. dnf -y update && dnf -y install fail2ban nftables
  2000. ;;
  2001. centos)
  2002. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2003. yum update -y && yum install epel-release -y
  2004. yum -y install fail2ban nftables
  2005. else
  2006. dnf -y update && dnf -y install fail2ban nftables
  2007. fi
  2008. ;;
  2009. arch | manjaro | parch)
  2010. pacman -Syu --noconfirm fail2ban nftables
  2011. ;;
  2012. alpine)
  2013. apk add fail2ban nftables
  2014. ;;
  2015. *)
  2016. echo -e "${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\n"
  2017. exit 1
  2018. ;;
  2019. esac
  2020. if ! command -v fail2ban-client &> /dev/null; then
  2021. echo -e "${red}Fail2ban installation failed.${plain}\n"
  2022. exit 1
  2023. fi
  2024. echo -e "${green}Fail2ban installed successfully!${plain}\n"
  2025. else
  2026. echo -e "${yellow}Fail2ban is already installed.${plain}\n"
  2027. fi
  2028. echo -e "${green}Configuring IP Limit...${plain}\n"
  2029. # make sure there's no conflict for jail files
  2030. iplimit_remove_conflicts
  2031. # Check if log file exists
  2032. if ! test -f "${iplimit_banned_log_path}"; then
  2033. touch ${iplimit_banned_log_path}
  2034. fi
  2035. # Check if service log file exists so fail2ban won't return error
  2036. if ! test -f "${iplimit_log_path}"; then
  2037. touch ${iplimit_log_path}
  2038. fi
  2039. # Create the iplimit jail files
  2040. # we didn't pass the bantime here to use the default value
  2041. create_iplimit_jails
  2042. # Launching fail2ban
  2043. if [[ $release == "alpine" ]]; then
  2044. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2045. rc-service fail2ban start
  2046. else
  2047. rc-service fail2ban restart
  2048. fi
  2049. rc-update add fail2ban
  2050. else
  2051. if ! systemctl is-active --quiet fail2ban; then
  2052. systemctl start fail2ban
  2053. else
  2054. systemctl restart fail2ban
  2055. fi
  2056. systemctl enable fail2ban
  2057. fi
  2058. echo -e "${green}IP Limit installed and configured successfully!${plain}\n"
  2059. before_show_menu
  2060. }
  2061. remove_iplimit() {
  2062. echo -e "${green}\t1.${plain} Only remove IP Limit configurations"
  2063. echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit"
  2064. echo -e "${green}\t0.${plain} Back to Main Menu"
  2065. read -rp "Choose an option: " num
  2066. case "$num" in
  2067. 1)
  2068. rm -f /etc/fail2ban/filter.d/3x-ipl.conf
  2069. rm -f /etc/fail2ban/action.d/3x-ipl.conf
  2070. rm -f /etc/fail2ban/jail.d/3x-ipl.conf
  2071. if [[ $release == "alpine" ]]; then
  2072. rc-service fail2ban restart
  2073. else
  2074. systemctl restart fail2ban
  2075. fi
  2076. echo -e "${green}IP Limit removed successfully!${plain}\n"
  2077. before_show_menu
  2078. ;;
  2079. 2)
  2080. rm -rf /etc/fail2ban
  2081. if [[ $release == "alpine" ]]; then
  2082. rc-service fail2ban stop
  2083. else
  2084. systemctl stop fail2ban
  2085. fi
  2086. case "${release}" in
  2087. ubuntu | debian | armbian)
  2088. apt-get remove -y fail2ban
  2089. apt-get purge -y fail2ban -y
  2090. apt-get autoremove -y
  2091. ;;
  2092. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2093. dnf remove fail2ban -y
  2094. dnf autoremove -y
  2095. ;;
  2096. centos)
  2097. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2098. yum remove fail2ban -y
  2099. yum autoremove -y
  2100. else
  2101. dnf remove fail2ban -y
  2102. dnf autoremove -y
  2103. fi
  2104. ;;
  2105. arch | manjaro | parch)
  2106. pacman -Rns --noconfirm fail2ban
  2107. ;;
  2108. alpine)
  2109. apk del fail2ban
  2110. ;;
  2111. *)
  2112. echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n"
  2113. exit 1
  2114. ;;
  2115. esac
  2116. echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n"
  2117. before_show_menu
  2118. ;;
  2119. 0)
  2120. show_menu
  2121. ;;
  2122. *)
  2123. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2124. remove_iplimit
  2125. ;;
  2126. esac
  2127. }
  2128. show_banlog() {
  2129. local system_log="/var/log/fail2ban.log"
  2130. echo -e "${green}Checking ban logs...${plain}\n"
  2131. if [[ $release == "alpine" ]]; then
  2132. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2133. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2134. return 1
  2135. fi
  2136. else
  2137. if ! systemctl is-active --quiet fail2ban; then
  2138. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2139. return 1
  2140. fi
  2141. fi
  2142. if [[ -f "$system_log" ]]; then
  2143. echo -e "${green}Recent system ban activities from fail2ban.log:${plain}"
  2144. grep "3x-ipl" "$system_log" | grep -E "Ban|Unban" | tail -n 10 || echo -e "${yellow}No recent system ban activities found${plain}"
  2145. echo ""
  2146. fi
  2147. if [[ -f "${iplimit_banned_log_path}" ]]; then
  2148. echo -e "${green}3X-IPL ban log entries:${plain}"
  2149. if [[ -s "${iplimit_banned_log_path}" ]]; then
  2150. grep -v "INIT" "${iplimit_banned_log_path}" | tail -n 10 || echo -e "${yellow}No ban entries found${plain}"
  2151. else
  2152. echo -e "${yellow}Ban log file is empty${plain}"
  2153. fi
  2154. else
  2155. echo -e "${red}Ban log file not found at: ${iplimit_banned_log_path}${plain}"
  2156. fi
  2157. echo -e "\n${green}Current jail status:${plain}"
  2158. fail2ban-client status 3x-ipl || echo -e "${yellow}Unable to get jail status${plain}"
  2159. }
  2160. create_iplimit_jails() {
  2161. # Use default bantime if not passed => 30 minutes
  2162. local bantime="${1:-30}"
  2163. # Uncomment 'allowipv6 = auto' in fail2ban.conf
  2164. sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf
  2165. # On Debian 12+ and Ubuntu 22.04+ fail2ban's default backend should be changed to systemd
  2166. if [[ ( "${release}" == "debian" && ${os_version} -ge 12 ) || ( "${release}" == "ubuntu" && ${os_version} -ge 2200 ) ]]; then
  2167. sed -i '0,/action =/s/backend = auto/backend = systemd/' /etc/fail2ban/jail.conf
  2168. fi
  2169. cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf
  2170. [3x-ipl]
  2171. enabled=true
  2172. backend=auto
  2173. filter=3x-ipl
  2174. action=3x-ipl
  2175. logpath=${iplimit_log_path}
  2176. maxretry=1
  2177. findtime=32
  2178. bantime=${bantime}m
  2179. EOF
  2180. cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf
  2181. [Definition]
  2182. datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S
  2183. 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+
  2184. ignoreregex =
  2185. EOF
  2186. # Ports to exempt from the ban so an over-limit proxy client can never lock
  2187. # the administrator out of SSH or the panel. The ban still covers every other
  2188. # TCP port (including all Xray inbounds), so IP-limit keeps working for inbounds
  2189. # added later without regenerating these files.
  2190. local ssh_ports
  2191. ssh_ports=$(grep -oP '^[[:space:]]*Port[[:space:]]+\K[0-9]+' /etc/ssh/sshd_config 2>/dev/null | paste -sd, -)
  2192. [[ -z "${ssh_ports}" ]] && ssh_ports="22"
  2193. local panel_port
  2194. panel_port=$(${xui_folder}/x-ui setting -show true 2>/dev/null | grep -Eo 'port: .+' | awk '{print $2}')
  2195. local exempt_ports="${ssh_ports}"
  2196. [[ -n "${panel_port}" ]] && exempt_ports="${exempt_ports},${panel_port}"
  2197. cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf
  2198. [INCLUDES]
  2199. before = iptables-allports.conf
  2200. [Definition]
  2201. actionstart = <iptables> -N f2b-<name>
  2202. <iptables> -A f2b-<name> -j <returntype>
  2203. <iptables> -I <chain> -p <protocol> -j f2b-<name>
  2204. actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
  2205. <actionflush>
  2206. <iptables> -X f2b-<name>
  2207. actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
  2208. actionban = <iptables> -I f2b-<name> 1 -s <ip> -p <protocol> -m multiport ! --dports <exemptports> -j <blocktype>
  2209. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") BAN [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
  2210. actionunban = <iptables> -D f2b-<name> -s <ip> -p <protocol> -m multiport ! --dports <exemptports> -j <blocktype>
  2211. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") UNBAN [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
  2212. [Init]
  2213. name = default
  2214. protocol = tcp
  2215. chain = INPUT
  2216. exemptports = ${exempt_ports}
  2217. EOF
  2218. echo -e "${green}Ip Limit jail files created with a bantime of ${bantime} minutes.${plain}"
  2219. }
  2220. iplimit_remove_conflicts() {
  2221. local jail_files=(
  2222. /etc/fail2ban/jail.conf
  2223. /etc/fail2ban/jail.local
  2224. )
  2225. for file in "${jail_files[@]}"; do
  2226. # Check for [3x-ipl] config in jail file then remove it
  2227. if test -f "${file}" && grep -qw '3x-ipl' ${file}; then
  2228. sed -i "/\[3x-ipl\]/,/^$/d" ${file}
  2229. echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n"
  2230. fi
  2231. done
  2232. }
  2233. SSH_port_forwarding() {
  2234. local URL_lists=(
  2235. "https://api4.ipify.org"
  2236. "https://ipv4.icanhazip.com"
  2237. "https://v4.api.ipinfo.io/ip"
  2238. "https://ipv4.myexternalip.com/raw"
  2239. "https://4.ident.me"
  2240. "https://check-host.net/ip"
  2241. )
  2242. local server_ip=""
  2243. for ip_address in "${URL_lists[@]}"; do
  2244. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  2245. local http_code=$(echo "$response" | tail -n1)
  2246. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  2247. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2248. server_ip="${ip_result}"
  2249. break
  2250. fi
  2251. done
  2252. if [[ -z "$server_ip" ]]; then
  2253. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  2254. while [[ -z "$server_ip" ]]; do
  2255. read -rp "Please enter your server's public IPv4 address: " server_ip
  2256. server_ip="${server_ip// /}"
  2257. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2258. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  2259. server_ip=""
  2260. fi
  2261. done
  2262. fi
  2263. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  2264. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  2265. local existing_listenIP=$(${xui_folder}/x-ui setting -getListen true | grep -Eo 'listenIP: .+' | awk '{print $2}')
  2266. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'cert: .+' | awk '{print $2}')
  2267. local existing_key=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'key: .+' | awk '{print $2}')
  2268. local config_listenIP=""
  2269. local listen_choice=""
  2270. if [[ -n "$existing_cert" && -n "$existing_key" ]]; then
  2271. echo -e "${green}Panel is secure with SSL.${plain}"
  2272. before_show_menu
  2273. fi
  2274. if [[ -z "$existing_cert" && -z "$existing_key" && (-z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0") ]]; then
  2275. echo -e "\n${red}Warning: No Cert and Key found! The panel is not secure.${plain}"
  2276. echo "Please obtain a certificate or set up SSH port forwarding."
  2277. fi
  2278. if [[ -n "$existing_listenIP" && "$existing_listenIP" != "0.0.0.0" && (-z "$existing_cert" && -z "$existing_key") ]]; then
  2279. echo -e "\n${green}Current SSH Port Forwarding Configuration:${plain}"
  2280. echo -e "Standard SSH command:"
  2281. echo -e "${yellow}ssh -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2282. echo -e "\nIf using SSH key:"
  2283. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2284. echo -e "\nAfter connecting, access the panel at:"
  2285. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2286. fi
  2287. echo -e "\nChoose an option:"
  2288. echo -e "${green}1.${plain} Set listen IP"
  2289. echo -e "${green}2.${plain} Clear listen IP"
  2290. echo -e "${green}0.${plain} Back to Main Menu"
  2291. read -rp "Choose an option: " num
  2292. case "$num" in
  2293. 1)
  2294. if [[ -z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0" ]]; then
  2295. echo -e "\nNo listenIP configured. Choose an option:"
  2296. echo -e "1. Use default IP (127.0.0.1)"
  2297. echo -e "2. Set a custom IP"
  2298. read -rp "Select an option (1 or 2): " listen_choice
  2299. config_listenIP="127.0.0.1"
  2300. [[ "$listen_choice" == "2" ]] && read -rp "Enter custom IP to listen on: " config_listenIP
  2301. ${xui_folder}/x-ui setting -listenIP "${config_listenIP}" > /dev/null 2>&1
  2302. echo -e "${green}listen IP has been set to ${config_listenIP}.${plain}"
  2303. echo -e "\n${green}SSH Port Forwarding Configuration:${plain}"
  2304. echo -e "Standard SSH command:"
  2305. echo -e "${yellow}ssh -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2306. echo -e "\nIf using SSH key:"
  2307. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2308. echo -e "\nAfter connecting, access the panel at:"
  2309. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2310. restart
  2311. else
  2312. config_listenIP="${existing_listenIP}"
  2313. echo -e "${green}Current listen IP is already set to ${config_listenIP}.${plain}"
  2314. fi
  2315. ;;
  2316. 2)
  2317. ${xui_folder}/x-ui setting -listenIP 0.0.0.0 > /dev/null 2>&1
  2318. echo -e "${green}Listen IP has been cleared.${plain}"
  2319. restart
  2320. ;;
  2321. 0)
  2322. show_menu
  2323. ;;
  2324. *)
  2325. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2326. SSH_port_forwarding
  2327. ;;
  2328. esac
  2329. }
  2330. # PostgreSQL service management (for panels configured with XUI_DB_TYPE=postgres).
  2331. postgresql_installed() {
  2332. command -v pg_lsclusters > /dev/null 2>&1 || command -v psql > /dev/null 2>&1 || command -v postgres > /dev/null 2>&1
  2333. }
  2334. # Prints "VER CLUSTER" of the first configured cluster on Debian-style installs (e.g. "16 main").
  2335. pg_cluster_info() {
  2336. if command -v pg_lsclusters > /dev/null 2>&1; then
  2337. pg_lsclusters 2> /dev/null | awk '$1 ~ /^[0-9]+$/ {print $1, $2; exit}'
  2338. fi
  2339. }
  2340. # Resolves the systemd unit used to manage the PostgreSQL server.
  2341. pg_systemd_unit() {
  2342. local info ver cluster
  2343. info="$(pg_cluster_info)"
  2344. if [[ -n "$info" ]]; then
  2345. ver="${info%% *}"
  2346. cluster="${info##* }"
  2347. echo "postgresql@${ver}-${cluster}"
  2348. else
  2349. echo "postgresql"
  2350. fi
  2351. }
  2352. postgresql_status() {
  2353. if ! postgresql_installed; then
  2354. LOGE "PostgreSQL does not appear to be installed on this system."
  2355. return 1
  2356. fi
  2357. if command -v pg_lsclusters > /dev/null 2>&1; then
  2358. pg_lsclusters
  2359. else
  2360. systemctl status "$(pg_systemd_unit)" --no-pager
  2361. fi
  2362. echo ""
  2363. if command -v ss > /dev/null 2>&1; then
  2364. local listening
  2365. listening=$(ss -ltnp 2> /dev/null | grep ':5432')
  2366. if [[ -n "$listening" ]]; then
  2367. echo -e "${green}PostgreSQL is listening on port 5432:${plain}"
  2368. echo "$listening"
  2369. else
  2370. echo -e "${red}Nothing is listening on port 5432 - the database is not running.${plain}"
  2371. fi
  2372. fi
  2373. }
  2374. postgresql_start() {
  2375. pg_require_installed || return 1
  2376. if [[ $release == "alpine" ]]; then
  2377. rc-service postgresql start
  2378. else
  2379. systemctl start "$(pg_systemd_unit)"
  2380. fi
  2381. sleep 1
  2382. postgresql_status
  2383. }
  2384. postgresql_stop() {
  2385. pg_require_installed || return 1
  2386. if [[ $release == "alpine" ]]; then
  2387. rc-service postgresql stop
  2388. else
  2389. systemctl stop "$(pg_systemd_unit)"
  2390. fi
  2391. LOGI "PostgreSQL stop signal sent."
  2392. }
  2393. postgresql_restart() {
  2394. pg_require_installed || return 1
  2395. if [[ $release == "alpine" ]]; then
  2396. rc-service postgresql restart
  2397. else
  2398. systemctl restart "$(pg_systemd_unit)"
  2399. fi
  2400. sleep 1
  2401. postgresql_status
  2402. }
  2403. postgresql_enable() {
  2404. pg_require_installed || return 1
  2405. if [[ $release == "alpine" ]]; then
  2406. rc-update add postgresql default
  2407. else
  2408. systemctl enable "$(pg_systemd_unit)"
  2409. fi
  2410. if [[ $? == 0 ]]; then
  2411. LOGI "PostgreSQL set to start automatically on boot."
  2412. else
  2413. LOGE "Failed to enable PostgreSQL autostart."
  2414. fi
  2415. }
  2416. postgresql_log() {
  2417. pg_require_installed || return 1
  2418. local info ver cluster logfile
  2419. info="$(pg_cluster_info)"
  2420. if [[ -n "$info" ]]; then
  2421. ver="${info%% *}"
  2422. cluster="${info##* }"
  2423. logfile="/var/log/postgresql/postgresql-${ver}-${cluster}.log"
  2424. fi
  2425. if [[ -n "$logfile" && -f "$logfile" ]]; then
  2426. tail -n 40 "$logfile"
  2427. elif command -v journalctl > /dev/null 2>&1; then
  2428. journalctl -u "$(pg_systemd_unit)" -n 40 --no-pager
  2429. else
  2430. LOGE "No PostgreSQL log found."
  2431. fi
  2432. }
  2433. pg_require_installed() {
  2434. if ! postgresql_installed; then
  2435. LOGE "PostgreSQL is not installed. Use option 1 (Install PostgreSQL) in this menu first."
  2436. return 1
  2437. fi
  2438. }
  2439. # Installs a local PostgreSQL server and creates a dedicated xui user/database.
  2440. # Progress goes to stderr; on success the connection DSN is printed to stdout so
  2441. # callers can capture it. Mirrors install_postgres_local() from install.sh, so the
  2442. # panel can be set up without re-running the remote install script.
  2443. pg_install_local() {
  2444. local pg_user pg_pass pg_db pg_host pg_port
  2445. pg_pass=$(gen_random_string 24)
  2446. pg_db="xui"
  2447. pg_host="127.0.0.1"
  2448. pg_port="5432"
  2449. case "${release}" in
  2450. ubuntu | debian | armbian)
  2451. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  2452. ;;
  2453. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2454. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2455. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2456. ;;
  2457. centos)
  2458. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2459. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  2460. else
  2461. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2462. fi
  2463. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2464. ;;
  2465. arch | manjaro | parch)
  2466. pacman -Syu --noconfirm postgresql >&2 || return 1
  2467. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  2468. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  2469. fi
  2470. ;;
  2471. opensuse-tumbleweed | opensuse-leap)
  2472. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  2473. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  2474. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  2475. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  2476. fi
  2477. ;;
  2478. alpine)
  2479. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  2480. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  2481. /etc/init.d/postgresql setup >&2 || return 1
  2482. fi
  2483. rc-update add postgresql default >&2 2> /dev/null || true
  2484. rc-service postgresql start >&2 || return 1
  2485. ;;
  2486. *)
  2487. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  2488. return 1
  2489. ;;
  2490. esac
  2491. if [[ "${release}" != "alpine" ]]; then
  2492. systemctl enable --now postgresql >&2 || return 1
  2493. fi
  2494. local i
  2495. for i in 1 2 3 4 5; do
  2496. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  2497. sleep 1
  2498. done
  2499. local existing_owner=""
  2500. existing_owner=$(sudo -u postgres psql -tAc \
  2501. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2502. | tr -d '[:space:]')
  2503. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  2504. pg_user="${existing_owner}"
  2505. else
  2506. pg_user=$(gen_random_string 8)
  2507. fi
  2508. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  2509. | grep -q 1 \
  2510. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2511. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2512. | grep -q 1 \
  2513. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  2514. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2515. local pg_pass_enc
  2516. 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')
  2517. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  2518. return 0
  2519. }
  2520. # Installs the PostgreSQL client tools (pg_dump/pg_restore) used by in-panel backup.
  2521. pg_ensure_client() {
  2522. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  2523. return 0
  2524. fi
  2525. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore)...${plain}" >&2
  2526. case "${release}" in
  2527. ubuntu | debian | armbian)
  2528. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  2529. ;;
  2530. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2531. dnf install -y -q postgresql >&2 || return 1
  2532. ;;
  2533. centos)
  2534. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2535. yum install -y postgresql >&2 || return 1
  2536. else
  2537. dnf install -y -q postgresql >&2 || return 1
  2538. fi
  2539. ;;
  2540. arch | manjaro | parch)
  2541. pacman -Sy --noconfirm postgresql >&2 || return 1
  2542. ;;
  2543. opensuse-tumbleweed | opensuse-leap)
  2544. zypper -q install -y postgresql >&2 || return 1
  2545. ;;
  2546. alpine)
  2547. apk add --no-cache postgresql-client >&2 || return 1
  2548. ;;
  2549. *)
  2550. return 1
  2551. ;;
  2552. esac
  2553. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  2554. }
  2555. # Writes XUI_DB_TYPE/XUI_DB_DSN into the service env file, preserving other entries.
  2556. pg_write_env() {
  2557. local dsn="$1" envfile
  2558. envfile="$(xui_env_file_path)"
  2559. install -d -m 755 "$(dirname "$envfile")"
  2560. touch "$envfile"
  2561. sed -i '/^XUI_DB_TYPE=/d; /^XUI_DB_DSN=/d' "$envfile"
  2562. {
  2563. echo "XUI_DB_TYPE=postgres"
  2564. echo "XUI_DB_DSN=${dsn}"
  2565. } >> "$envfile"
  2566. chmod 600 "$envfile"
  2567. }
  2568. pg_install_server_action() {
  2569. if postgresql_installed; then
  2570. LOGI "PostgreSQL already appears to be installed on this system."
  2571. confirm "Run setup anyway (ensures the xui database/user exist)?" "n" || return 0
  2572. fi
  2573. LOGI "Installing PostgreSQL server and creating a dedicated user/database..."
  2574. local dsn
  2575. dsn=$(pg_install_local)
  2576. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2577. LOGE "PostgreSQL installation failed."
  2578. return 1
  2579. fi
  2580. PG_LAST_DSN="$dsn"
  2581. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (panel DB backup may be unavailable)."
  2582. echo ""
  2583. LOGI "PostgreSQL is installed and ready."
  2584. echo -e "${green}Connection DSN:${plain} ${dsn}"
  2585. echo -e "${yellow}Use option 2 to migrate your SQLite data and switch the panel to PostgreSQL.${plain}"
  2586. }
  2587. # Copies the current SQLite data into PostgreSQL, then switches the panel over.
  2588. migrate_to_postgres() {
  2589. if [[ ! -x "${xui_folder}/x-ui" ]]; then
  2590. LOGE "x-ui is not installed."
  2591. return 1
  2592. fi
  2593. echo ""
  2594. echo -e "${yellow}This copies your current SQLite data into a PostgreSQL database,${plain}"
  2595. echo -e "${yellow}then switches the panel to PostgreSQL and restarts it.${plain}"
  2596. echo -e "${red}Any existing panel tables in the destination will be cleared and overwritten.${plain}"
  2597. confirm "Continue?" "n" || return 0
  2598. local dsn="" pg_mode
  2599. if [[ -n "$PG_LAST_DSN" ]]; then
  2600. echo -e "A PostgreSQL database was created in this session:"
  2601. echo -e " ${green}${PG_LAST_DSN}${plain}"
  2602. confirm "Migrate into this database?" "y" && dsn="$PG_LAST_DSN"
  2603. fi
  2604. if [[ -z "$dsn" ]]; then
  2605. echo ""
  2606. echo -e "${green}\t1.${plain} Install PostgreSQL locally and create a dedicated user/db (recommended)"
  2607. echo -e "${green}\t2.${plain} Use an existing PostgreSQL server (enter DSN)"
  2608. read -rp "Choose [1]: " pg_mode
  2609. pg_mode="${pg_mode:-1}"
  2610. if [[ "$pg_mode" == "2" ]]; then
  2611. while [[ -z "$dsn" ]]; do
  2612. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " dsn
  2613. dsn="${dsn// /}"
  2614. done
  2615. else
  2616. LOGI "Installing PostgreSQL locally (this may take a moment)..."
  2617. dsn=$(pg_install_local)
  2618. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2619. LOGE "PostgreSQL installation failed. Aborting migration."
  2620. return 1
  2621. fi
  2622. PG_LAST_DSN="$dsn"
  2623. fi
  2624. fi
  2625. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (in-panel DB backup/restore may be unavailable)."
  2626. LOGI "Stopping panel to take a consistent snapshot..."
  2627. stop 0 > /dev/null 2>&1
  2628. echo ""
  2629. LOGI "Migrating data into PostgreSQL..."
  2630. if ! ${xui_folder}/x-ui migrate-db --dsn "$dsn"; then
  2631. LOGE "Migration failed. The panel was NOT switched to PostgreSQL."
  2632. start 0 > /dev/null 2>&1
  2633. return 1
  2634. fi
  2635. pg_write_env "$dsn"
  2636. LOGI "Wrote database settings to $(xui_env_file_path) (XUI_DB_TYPE=postgres)."
  2637. LOGI "Restarting panel on PostgreSQL..."
  2638. restart 0
  2639. sleep 1
  2640. if check_status; then
  2641. LOGI "Migration complete. The panel is now running on PostgreSQL."
  2642. else
  2643. LOGE "Panel did not come up. Check logs (option 16). Your SQLite data is left intact."
  2644. fi
  2645. }
  2646. postgresql_menu() {
  2647. echo -e "${green}\t1.${plain} ${green}Install${plain} PostgreSQL (server + client + xui db)"
  2648. echo -e "${green}\t2.${plain} Migrate SQLite ${green}->${plain} PostgreSQL"
  2649. echo -e "${green}\t3.${plain} Status (clusters & port 5432)"
  2650. echo -e "${green}\t4.${plain} ${green}Start${plain} PostgreSQL"
  2651. echo -e "${green}\t5.${plain} ${red}Stop${plain} PostgreSQL"
  2652. echo -e "${green}\t6.${plain} Restart PostgreSQL"
  2653. echo -e "${green}\t7.${plain} ${green}Enable${plain} Autostart on boot"
  2654. echo -e "${green}\t8.${plain} View PostgreSQL Log"
  2655. echo -e "${green}\t9.${plain} Convert SQLite ${green}.db <-> .dump${plain}"
  2656. echo -e "${green}\t0.${plain} Back to Main Menu"
  2657. read -rp "Choose an option: " choice
  2658. case "$choice" in
  2659. 0)
  2660. show_menu
  2661. ;;
  2662. 1)
  2663. pg_install_server_action
  2664. postgresql_menu
  2665. ;;
  2666. 2)
  2667. migrate_to_postgres
  2668. postgresql_menu
  2669. ;;
  2670. 3)
  2671. postgresql_status
  2672. postgresql_menu
  2673. ;;
  2674. 4)
  2675. postgresql_start
  2676. postgresql_menu
  2677. ;;
  2678. 5)
  2679. postgresql_stop
  2680. postgresql_menu
  2681. ;;
  2682. 6)
  2683. postgresql_restart
  2684. postgresql_menu
  2685. ;;
  2686. 7)
  2687. postgresql_enable
  2688. postgresql_menu
  2689. ;;
  2690. 8)
  2691. postgresql_log
  2692. postgresql_menu
  2693. ;;
  2694. 9)
  2695. migrate_db_prompt
  2696. postgresql_menu
  2697. ;;
  2698. *)
  2699. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2700. postgresql_menu
  2701. ;;
  2702. esac
  2703. }
  2704. # Convert between the panel's SQLite database and a portable .dump (SQL text)
  2705. # file using the bundled x-ui binary. With no arguments it dumps the installed
  2706. # panel database; an optional second argument overrides the output path.
  2707. # x-ui migrateDB [file.db|file.dump] [output]
  2708. migrate_db() {
  2709. local input="$1" output="$2"
  2710. local default_db="/etc/x-ui/x-ui.db"
  2711. local bin="${xui_folder}/x-ui"
  2712. [[ -z "$input" ]] && input="$default_db"
  2713. if [[ ! -x "$bin" ]]; then
  2714. LOGE "x-ui binary not found at ${bin}. Is the panel installed?"
  2715. return 1
  2716. fi
  2717. if ! "$bin" migrate-db -h 2>&1 | grep -q -- '-dump'; then
  2718. LOGE "This x-ui build does not support .db <-> .dump conversion yet."
  2719. LOGE "Update the panel first (x-ui update) to a version with 'migrate-db --dump/--restore'."
  2720. return 1
  2721. fi
  2722. if [[ ! -f "$input" ]]; then
  2723. LOGE "Input file not found: ${input}"
  2724. echo -e "Usage: ${green}x-ui migrateDB [file.db|file.dump] [output]${plain}"
  2725. return 1
  2726. fi
  2727. local mode
  2728. case "$input" in
  2729. *.db | *.sqlite | *.sqlite3)
  2730. mode="dump"
  2731. ;;
  2732. *.dump | *.sql)
  2733. mode="restore"
  2734. ;;
  2735. *)
  2736. if head -c 16 "$input" | grep -q "SQLite format 3"; then
  2737. mode="dump"
  2738. else
  2739. mode="restore"
  2740. fi
  2741. ;;
  2742. esac
  2743. if [[ "$mode" == "dump" ]]; then
  2744. [[ -z "$output" ]] && output="${input%.*}.dump"
  2745. if [[ -f "$output" ]]; then
  2746. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2747. fi
  2748. LOGI "Dumping SQLite database to SQL text:"
  2749. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2750. if "$bin" migrate-db --src "$input" --dump "$output"; then
  2751. LOGI "Done. Wrote ${output}."
  2752. else
  2753. LOGE "Dump failed."
  2754. return 1
  2755. fi
  2756. else
  2757. [[ -z "$output" ]] && output="${input%.*}.db"
  2758. if [[ "$output" == "$default_db" ]] && check_status > /dev/null 2>&1; then
  2759. LOGE "Refusing to restore into the live database (${default_db}) while x-ui is running."
  2760. LOGE "Stop the panel first (x-ui stop) or choose a different output path."
  2761. return 1
  2762. fi
  2763. if [[ -f "$output" ]]; then
  2764. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2765. rm -f "$output"
  2766. fi
  2767. LOGI "Rebuilding SQLite database from SQL text:"
  2768. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2769. if "$bin" migrate-db --restore "$input" --out "$output"; then
  2770. LOGI "Done. Created ${output}."
  2771. else
  2772. LOGE "Restore failed."
  2773. rm -f "$output"
  2774. return 1
  2775. fi
  2776. fi
  2777. }
  2778. # Interactive wrapper around migrate_db for the menu: prompts for the paths and
  2779. # lets migrate_db auto-detect the direction.
  2780. migrate_db_prompt() {
  2781. local default_db="/etc/x-ui/x-ui.db"
  2782. local input output
  2783. echo -e "Convert between a SQLite ${green}.db${plain} and a portable ${green}.dump${plain} (direction auto-detected)."
  2784. read -rp "Input file [${default_db}]: " input
  2785. input="${input:-$default_db}"
  2786. read -rp "Output file (leave empty to auto-name next to input): " output
  2787. migrate_db "$input" "$output"
  2788. }
  2789. show_usage() {
  2790. echo -e "┌────────────────────────────────────────────────────────────────┐
  2791. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  2792. │ │
  2793. │ ${blue}x-ui${plain} - Admin Management Script │
  2794. │ ${blue}x-ui start${plain} - Start │
  2795. │ ${blue}x-ui stop${plain} - Stop │
  2796. │ ${blue}x-ui restart${plain} - Restart │
  2797. | ${blue}x-ui restart-xray${plain} - Restart Xray │
  2798. │ ${blue}x-ui status${plain} - Current Status │
  2799. │ ${blue}x-ui settings${plain} - Current Settings │
  2800. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  2801. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  2802. │ ${blue}x-ui log${plain} - Check logs │
  2803. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  2804. │ ${blue}x-ui update${plain} - Update │
  2805. │ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
  2806. │ ${blue}x-ui migrateDB [file]${plain} - Convert .db <-> .dump (SQLite) │
  2807. │ ${blue}x-ui legacy${plain} - Legacy version │
  2808. │ ${blue}x-ui install${plain} - Install │
  2809. │ ${blue}x-ui uninstall${plain} - Uninstall │
  2810. └────────────────────────────────────────────────────────────────┘"
  2811. }
  2812. show_menu() {
  2813. echo -e "
  2814. ╔────────────────────────────────────────────────╗
  2815. │ ${green}3X-UI Panel Management Script${plain} │
  2816. │ ${green}0.${plain} Exit Script │
  2817. │────────────────────────────────────────────────│
  2818. │ ${green}1.${plain} Install │
  2819. │ ${green}2.${plain} Update │
  2820. │ ${green}3.${plain} Update Menu │
  2821. │ ${green}4.${plain} Legacy Version │
  2822. │ ${green}5.${plain} Uninstall │
  2823. │────────────────────────────────────────────────│
  2824. │ ${green}6.${plain} Reset Username & Password │
  2825. │ ${green}7.${plain} Reset Web Base Path │
  2826. │ ${green}8.${plain} Reset Settings │
  2827. │ ${green}9.${plain} Change Port │
  2828. │ ${green}10.${plain} View Current Settings │
  2829. │────────────────────────────────────────────────│
  2830. │ ${green}11.${plain} Start │
  2831. │ ${green}12.${plain} Stop │
  2832. │ ${green}13.${plain} Restart │
  2833. | ${green}14.${plain} Restart Xray │
  2834. │ ${green}15.${plain} Check Status │
  2835. │ ${green}16.${plain} Logs Management │
  2836. │────────────────────────────────────────────────│
  2837. │ ${green}17.${plain} Enable Autostart │
  2838. │ ${green}18.${plain} Disable Autostart │
  2839. │────────────────────────────────────────────────│
  2840. │ ${green}19.${plain} SSL Certificate Management │
  2841. │ ${green}20.${plain} Cloudflare SSL Certificate │
  2842. │ ${green}21.${plain} IP Limit Management │
  2843. │ ${green}22.${plain} Firewall Management │
  2844. │ ${green}23.${plain} SSH Port Forwarding Management │
  2845. │────────────────────────────────────────────────│
  2846. │ ${green}24.${plain} Enable BBR │
  2847. │ ${green}25.${plain} Update Geo Files │
  2848. │ ${green}26.${plain} Speedtest by Ookla │
  2849. │────────────────────────────────────────────────│
  2850. │ ${green}27.${plain} PostgreSQL Management │
  2851. ╚────────────────────────────────────────────────╝
  2852. "
  2853. show_status
  2854. echo && read -rp "Please enter your selection [0-27]: " num
  2855. case "${num}" in
  2856. 0)
  2857. exit 0
  2858. ;;
  2859. 1)
  2860. check_uninstall && install
  2861. ;;
  2862. 2)
  2863. check_install && update
  2864. ;;
  2865. 3)
  2866. check_install && update_menu
  2867. ;;
  2868. 4)
  2869. check_install && legacy_version
  2870. ;;
  2871. 5)
  2872. check_install && uninstall
  2873. ;;
  2874. 6)
  2875. check_install && reset_user
  2876. ;;
  2877. 7)
  2878. check_install && reset_webbasepath
  2879. ;;
  2880. 8)
  2881. check_install && reset_config
  2882. ;;
  2883. 9)
  2884. check_install && set_port
  2885. ;;
  2886. 10)
  2887. check_install && check_config
  2888. ;;
  2889. 11)
  2890. check_install && start
  2891. ;;
  2892. 12)
  2893. check_install && stop
  2894. ;;
  2895. 13)
  2896. check_install && restart
  2897. ;;
  2898. 14)
  2899. check_install && restart_xray
  2900. ;;
  2901. 15)
  2902. check_install && status
  2903. ;;
  2904. 16)
  2905. check_install && show_log
  2906. ;;
  2907. 17)
  2908. check_install && enable
  2909. ;;
  2910. 18)
  2911. check_install && disable
  2912. ;;
  2913. 19)
  2914. ssl_cert_issue_main
  2915. ;;
  2916. 20)
  2917. ssl_cert_issue_CF
  2918. ;;
  2919. 21)
  2920. iplimit_main
  2921. ;;
  2922. 22)
  2923. firewall_menu
  2924. ;;
  2925. 23)
  2926. SSH_port_forwarding
  2927. ;;
  2928. 24)
  2929. bbr_menu
  2930. ;;
  2931. 25)
  2932. update_geo
  2933. ;;
  2934. 26)
  2935. run_speedtest
  2936. ;;
  2937. 27)
  2938. postgresql_menu
  2939. ;;
  2940. *)
  2941. LOGE "Please enter the correct number [0-27]"
  2942. ;;
  2943. esac
  2944. }
  2945. if [[ $# > 0 ]]; then
  2946. case $1 in
  2947. "start")
  2948. check_install 0 && start 0
  2949. ;;
  2950. "stop")
  2951. check_install 0 && stop 0
  2952. ;;
  2953. "restart")
  2954. check_install 0 && restart 0
  2955. ;;
  2956. "restart-xray")
  2957. check_install 0 && restart_xray 0
  2958. ;;
  2959. "status")
  2960. check_install 0 && status 0
  2961. ;;
  2962. "settings")
  2963. check_install 0 && check_config 0
  2964. ;;
  2965. "enable")
  2966. check_install 0 && enable 0
  2967. ;;
  2968. "disable")
  2969. check_install 0 && disable 0
  2970. ;;
  2971. "log")
  2972. check_install 0 && show_log 0
  2973. ;;
  2974. "banlog")
  2975. check_install 0 && show_banlog 0
  2976. ;;
  2977. "update")
  2978. check_install 0 && update 0
  2979. ;;
  2980. "legacy")
  2981. check_install 0 && legacy_version 0
  2982. ;;
  2983. "install")
  2984. check_uninstall 0 && install 0
  2985. ;;
  2986. "uninstall")
  2987. check_install 0 && uninstall 0
  2988. ;;
  2989. "update-all-geofiles")
  2990. check_install 0 && update_all_geofiles 0 && restart 0
  2991. ;;
  2992. "migrateDB")
  2993. migrate_db "$2" "$3"
  2994. ;;
  2995. *) show_usage ;;
  2996. esac
  2997. else
  2998. show_menu
  2999. fi