x-ui.sh 134 KB

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