x-ui.sh 131 KB

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