x-ui.sh 131 KB

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