1
0

x-ui.sh 120 KB

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