x-ui.sh 133 KB

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