x-ui.sh 132 KB

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