x-ui.sh 132 KB

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