x-ui.sh 114 KB

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