x-ui.sh 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454
  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 option 19 (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 option 19 (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. dnf makecache -y && dnf -y install fail2ban nftables
  2101. ;;
  2102. centos)
  2103. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2104. yum makecache -y && yum install epel-release -y
  2105. yum -y install fail2ban nftables
  2106. else
  2107. dnf makecache -y && dnf -y install fail2ban nftables
  2108. fi
  2109. ;;
  2110. arch | manjaro | parch)
  2111. pacman -Syu --noconfirm fail2ban nftables
  2112. ;;
  2113. alpine)
  2114. apk add fail2ban nftables
  2115. ;;
  2116. *)
  2117. echo -e "${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\n"
  2118. return 1
  2119. ;;
  2120. esac
  2121. if ! command -v fail2ban-client &> /dev/null; then
  2122. echo -e "${red}Fail2ban installation failed.${plain}\n"
  2123. return 1
  2124. fi
  2125. echo -e "${green}Fail2ban installed successfully!${plain}\n"
  2126. else
  2127. echo -e "${yellow}Fail2ban is already installed.${plain}\n"
  2128. fi
  2129. echo -e "${green}Configuring IP Limit...${plain}\n"
  2130. # make sure there's no conflict for jail files
  2131. iplimit_remove_conflicts
  2132. # Check if log file exists
  2133. if ! test -f "${iplimit_banned_log_path}"; then
  2134. touch ${iplimit_banned_log_path}
  2135. fi
  2136. # Check if service log file exists so fail2ban won't return error
  2137. if ! test -f "${iplimit_log_path}"; then
  2138. touch ${iplimit_log_path}
  2139. fi
  2140. # Create the iplimit jail files
  2141. # we didn't pass the bantime here to use the default value
  2142. create_iplimit_jails
  2143. # Launching fail2ban
  2144. if [[ $release == "alpine" ]]; then
  2145. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2146. rc-service fail2ban start
  2147. else
  2148. rc-service fail2ban restart
  2149. fi
  2150. rc-update add fail2ban
  2151. else
  2152. if ! systemctl is-active --quiet fail2ban; then
  2153. systemctl start fail2ban
  2154. else
  2155. systemctl restart fail2ban
  2156. fi
  2157. systemctl enable fail2ban
  2158. fi
  2159. echo -e "${green}IP Limit installed and configured successfully!${plain}\n"
  2160. return 0
  2161. }
  2162. # install_iplimit is the interactive (menu) entry point: it runs the shared
  2163. # setup and then returns to the menu. The non-interactive installer path uses
  2164. # setup_fail2ban_iplimit directly via `x-ui setup-fail2ban`.
  2165. install_iplimit() {
  2166. setup_fail2ban_iplimit
  2167. before_show_menu
  2168. }
  2169. remove_iplimit() {
  2170. echo -e "${green}\t1.${plain} Only remove IP Limit configurations"
  2171. echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit"
  2172. echo -e "${green}\t0.${plain} Back to Main Menu"
  2173. read -rp "Choose an option: " num
  2174. case "$num" in
  2175. 1)
  2176. rm -f /etc/fail2ban/filter.d/3x-ipl.conf
  2177. rm -f /etc/fail2ban/action.d/3x-ipl.conf
  2178. rm -f /etc/fail2ban/jail.d/3x-ipl.conf
  2179. if [[ $release == "alpine" ]]; then
  2180. rc-service fail2ban restart
  2181. else
  2182. systemctl restart fail2ban
  2183. fi
  2184. echo -e "${green}IP Limit removed successfully!${plain}\n"
  2185. before_show_menu
  2186. ;;
  2187. 2)
  2188. rm -rf /etc/fail2ban
  2189. if [[ $release == "alpine" ]]; then
  2190. rc-service fail2ban stop
  2191. else
  2192. systemctl stop fail2ban
  2193. fi
  2194. case "${release}" in
  2195. ubuntu | debian | armbian)
  2196. apt-get remove -y fail2ban
  2197. apt-get purge -y fail2ban -y
  2198. apt-get autoremove -y
  2199. ;;
  2200. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2201. dnf remove fail2ban -y
  2202. dnf autoremove -y
  2203. ;;
  2204. centos)
  2205. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2206. yum remove fail2ban -y
  2207. yum autoremove -y
  2208. else
  2209. dnf remove fail2ban -y
  2210. dnf autoremove -y
  2211. fi
  2212. ;;
  2213. arch | manjaro | parch)
  2214. pacman -Rns --noconfirm fail2ban
  2215. ;;
  2216. alpine)
  2217. apk del fail2ban
  2218. ;;
  2219. *)
  2220. echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n"
  2221. exit 1
  2222. ;;
  2223. esac
  2224. echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n"
  2225. before_show_menu
  2226. ;;
  2227. 0)
  2228. show_menu
  2229. ;;
  2230. *)
  2231. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2232. remove_iplimit
  2233. ;;
  2234. esac
  2235. }
  2236. show_banlog() {
  2237. local system_log="/var/log/fail2ban.log"
  2238. echo -e "${green}Checking ban logs...${plain}\n"
  2239. if [[ $release == "alpine" ]]; then
  2240. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  2241. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2242. return 1
  2243. fi
  2244. else
  2245. if ! systemctl is-active --quiet fail2ban; then
  2246. echo -e "${red}Fail2ban service is not running!${plain}\n"
  2247. return 1
  2248. fi
  2249. fi
  2250. if [[ -f "$system_log" ]]; then
  2251. echo -e "${green}Recent system ban activities from fail2ban.log:${plain}"
  2252. grep "3x-ipl" "$system_log" | grep -E "Ban|Unban" | tail -n 10 || echo -e "${yellow}No recent system ban activities found${plain}"
  2253. echo ""
  2254. fi
  2255. if [[ -f "${iplimit_banned_log_path}" ]]; then
  2256. echo -e "${green}3X-IPL ban log entries:${plain}"
  2257. if [[ -s "${iplimit_banned_log_path}" ]]; then
  2258. grep -v "INIT" "${iplimit_banned_log_path}" | tail -n 10 || echo -e "${yellow}No ban entries found${plain}"
  2259. else
  2260. echo -e "${yellow}Ban log file is empty${plain}"
  2261. fi
  2262. else
  2263. echo -e "${red}Ban log file not found at: ${iplimit_banned_log_path}${plain}"
  2264. fi
  2265. echo -e "\n${green}Current jail status:${plain}"
  2266. fail2ban-client status 3x-ipl || echo -e "${yellow}Unable to get jail status${plain}"
  2267. }
  2268. create_iplimit_jails() {
  2269. # Use default bantime if not passed => 30 minutes
  2270. local bantime="${1:-30}"
  2271. # Uncomment 'allowipv6 = auto' in fail2ban.conf
  2272. sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf
  2273. # On Debian 12+ and Ubuntu 22.04+ fail2ban's default backend should be changed to systemd
  2274. if [[ ( "${release}" == "debian" && ${os_version} -ge 12 ) || ( "${release}" == "ubuntu" && ${os_version} -ge 2200 ) ]]; then
  2275. sed -i '0,/action =/s/backend = auto/backend = systemd/' /etc/fail2ban/jail.conf
  2276. fi
  2277. cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf
  2278. [3x-ipl]
  2279. enabled=true
  2280. backend=auto
  2281. filter=3x-ipl
  2282. action=3x-ipl
  2283. logpath=${iplimit_log_path}
  2284. maxretry=1
  2285. findtime=32
  2286. bantime=${bantime}m
  2287. EOF
  2288. cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf
  2289. [Definition]
  2290. datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S
  2291. 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+
  2292. ignoreregex =
  2293. EOF
  2294. # Ports to exempt from the ban so an over-limit proxy client can never lock
  2295. # the administrator out of SSH or the panel. The ban still covers every other
  2296. # TCP and UDP port (including all Xray inbounds, e.g. UDP-based Hysteria2), so
  2297. # IP-limit keeps working for inbounds added later without regenerating these files.
  2298. local ssh_ports
  2299. ssh_ports=$(grep -oP '^[[:space:]]*Port[[:space:]]+\K[0-9]+' /etc/ssh/sshd_config 2>/dev/null | paste -sd, -)
  2300. [[ -z "${ssh_ports}" ]] && ssh_ports="22"
  2301. local panel_port
  2302. panel_port=$(${xui_folder}/x-ui setting -show true 2>/dev/null | grep -Eo 'port: .+' | awk '{print $2}')
  2303. local exempt_ports="${ssh_ports}"
  2304. [[ -n "${panel_port}" ]] && exempt_ports="${exempt_ports},${panel_port}"
  2305. cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf
  2306. [INCLUDES]
  2307. before = iptables-allports.conf
  2308. [Definition]
  2309. actionstart = <iptables> -N f2b-<name>
  2310. <iptables> -A f2b-<name> -j <returntype>
  2311. <iptables> -I <chain> -j f2b-<name>
  2312. actionstop = <iptables> -D <chain> -j f2b-<name>
  2313. <actionflush>
  2314. <iptables> -X f2b-<name>
  2315. actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
  2316. actionban = <iptables> -I f2b-<name> 1 -s <ip> -p tcp -m multiport ! --dports <exemptports> -j <blocktype>
  2317. <iptables> -I f2b-<name> 1 -s <ip> -p udp -m multiport ! --dports <exemptports> -j <blocktype>
  2318. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") BAN [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
  2319. actionunban = <iptables> -D f2b-<name> -s <ip> -p tcp -m multiport ! --dports <exemptports> -j <blocktype>
  2320. <iptables> -D f2b-<name> -s <ip> -p udp -m multiport ! --dports <exemptports> -j <blocktype>
  2321. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") UNBAN [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
  2322. [Init]
  2323. name = default
  2324. chain = INPUT
  2325. exemptports = ${exempt_ports}
  2326. EOF
  2327. echo -e "${green}Ip Limit jail files created with a bantime of ${bantime} minutes.${plain}"
  2328. }
  2329. iplimit_remove_conflicts() {
  2330. local jail_files=(
  2331. /etc/fail2ban/jail.conf
  2332. /etc/fail2ban/jail.local
  2333. )
  2334. for file in "${jail_files[@]}"; do
  2335. # Check for [3x-ipl] config in jail file then remove it
  2336. if test -f "${file}" && grep -qw '3x-ipl' ${file}; then
  2337. sed -i "/\[3x-ipl\]/,/^$/d" ${file}
  2338. echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n"
  2339. fi
  2340. done
  2341. }
  2342. SSH_port_forwarding() {
  2343. local URL_lists=(
  2344. "https://api4.ipify.org"
  2345. "https://ipv4.icanhazip.com"
  2346. "https://v4.api.ipinfo.io/ip"
  2347. "https://ipv4.myexternalip.com/raw"
  2348. "https://4.ident.me"
  2349. "https://check-host.net/ip"
  2350. )
  2351. local server_ip=""
  2352. for ip_address in "${URL_lists[@]}"; do
  2353. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  2354. local http_code=$(echo "$response" | tail -n1)
  2355. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  2356. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2357. server_ip="${ip_result}"
  2358. break
  2359. fi
  2360. done
  2361. if [[ -z "$server_ip" ]]; then
  2362. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  2363. while [[ -z "$server_ip" ]]; do
  2364. read -rp "Please enter your server's public IPv4 address: " server_ip
  2365. server_ip="${server_ip// /}"
  2366. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  2367. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  2368. server_ip=""
  2369. fi
  2370. done
  2371. fi
  2372. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  2373. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  2374. local existing_listenIP=$(${xui_folder}/x-ui setting -getListen true | grep -Eo 'listenIP: .+' | awk '{print $2}')
  2375. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'cert: .+' | awk '{print $2}')
  2376. local existing_key=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'key: .+' | awk '{print $2}')
  2377. local config_listenIP=""
  2378. local listen_choice=""
  2379. if [[ -n "$existing_cert" && -n "$existing_key" ]]; then
  2380. echo -e "${green}Panel is secure with SSL.${plain}"
  2381. before_show_menu
  2382. fi
  2383. if [[ -z "$existing_cert" && -z "$existing_key" && (-z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0") ]]; then
  2384. echo -e "\n${red}Warning: No Cert and Key found! The panel is not secure.${plain}"
  2385. echo "Please obtain a certificate or set up SSH port forwarding."
  2386. fi
  2387. if [[ -n "$existing_listenIP" && "$existing_listenIP" != "0.0.0.0" && (-z "$existing_cert" && -z "$existing_key") ]]; then
  2388. echo -e "\n${green}Current SSH Port Forwarding Configuration:${plain}"
  2389. echo -e "Standard SSH command:"
  2390. echo -e "${yellow}ssh -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2391. echo -e "\nIf using SSH key:"
  2392. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2393. echo -e "\nAfter connecting, access the panel at:"
  2394. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2395. fi
  2396. echo -e "\nChoose an option:"
  2397. echo -e "${green}1.${plain} Set listen IP"
  2398. echo -e "${green}2.${plain} Clear listen IP"
  2399. echo -e "${green}0.${plain} Back to Main Menu"
  2400. read -rp "Choose an option: " num
  2401. case "$num" in
  2402. 1)
  2403. if [[ -z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0" ]]; then
  2404. echo -e "\nNo listenIP configured. Choose an option:"
  2405. echo -e "1. Use default IP (127.0.0.1)"
  2406. echo -e "2. Set a custom IP"
  2407. read -rp "Select an option (1 or 2): " listen_choice
  2408. config_listenIP="127.0.0.1"
  2409. [[ "$listen_choice" == "2" ]] && read -rp "Enter custom IP to listen on: " config_listenIP
  2410. ${xui_folder}/x-ui setting -listenIP "${config_listenIP}" > /dev/null 2>&1
  2411. echo -e "${green}listen IP has been set to ${config_listenIP}.${plain}"
  2412. echo -e "\n${green}SSH Port Forwarding Configuration:${plain}"
  2413. echo -e "Standard SSH command:"
  2414. echo -e "${yellow}ssh -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2415. echo -e "\nIf using SSH key:"
  2416. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2417. echo -e "\nAfter connecting, access the panel at:"
  2418. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2419. restart
  2420. else
  2421. config_listenIP="${existing_listenIP}"
  2422. echo -e "${green}Current listen IP is already set to ${config_listenIP}.${plain}"
  2423. fi
  2424. ;;
  2425. 2)
  2426. ${xui_folder}/x-ui setting -listenIP 0.0.0.0 > /dev/null 2>&1
  2427. echo -e "${green}Listen IP has been cleared.${plain}"
  2428. restart
  2429. ;;
  2430. 0)
  2431. show_menu
  2432. ;;
  2433. *)
  2434. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2435. SSH_port_forwarding
  2436. ;;
  2437. esac
  2438. }
  2439. # PostgreSQL service management (for panels configured with XUI_DB_TYPE=postgres).
  2440. postgresql_installed() {
  2441. command -v pg_lsclusters > /dev/null 2>&1 || command -v psql > /dev/null 2>&1 || command -v postgres > /dev/null 2>&1
  2442. }
  2443. # Prints "VER CLUSTER" of the first configured cluster on Debian-style installs (e.g. "16 main").
  2444. pg_cluster_info() {
  2445. if command -v pg_lsclusters > /dev/null 2>&1; then
  2446. pg_lsclusters 2> /dev/null | awk '$1 ~ /^[0-9]+$/ {print $1, $2; exit}'
  2447. fi
  2448. }
  2449. # Resolves the systemd unit used to manage the PostgreSQL server.
  2450. pg_systemd_unit() {
  2451. local info ver cluster
  2452. info="$(pg_cluster_info)"
  2453. if [[ -n "$info" ]]; then
  2454. ver="${info%% *}"
  2455. cluster="${info##* }"
  2456. echo "postgresql@${ver}-${cluster}"
  2457. else
  2458. echo "postgresql"
  2459. fi
  2460. }
  2461. postgresql_status() {
  2462. if ! postgresql_installed; then
  2463. LOGE "PostgreSQL does not appear to be installed on this system."
  2464. return 1
  2465. fi
  2466. if command -v pg_lsclusters > /dev/null 2>&1; then
  2467. pg_lsclusters
  2468. else
  2469. systemctl status "$(pg_systemd_unit)" --no-pager
  2470. fi
  2471. echo ""
  2472. if command -v ss > /dev/null 2>&1; then
  2473. local listening
  2474. listening=$(ss -ltnp 2> /dev/null | grep ':5432')
  2475. if [[ -n "$listening" ]]; then
  2476. echo -e "${green}PostgreSQL is listening on port 5432:${plain}"
  2477. echo "$listening"
  2478. else
  2479. echo -e "${red}Nothing is listening on port 5432 - the database is not running.${plain}"
  2480. fi
  2481. fi
  2482. }
  2483. postgresql_start() {
  2484. pg_require_installed || return 1
  2485. if [[ $release == "alpine" ]]; then
  2486. rc-service postgresql start
  2487. else
  2488. systemctl start "$(pg_systemd_unit)"
  2489. fi
  2490. sleep 1
  2491. postgresql_status
  2492. }
  2493. postgresql_stop() {
  2494. pg_require_installed || return 1
  2495. if [[ $release == "alpine" ]]; then
  2496. rc-service postgresql stop
  2497. else
  2498. systemctl stop "$(pg_systemd_unit)"
  2499. fi
  2500. LOGI "PostgreSQL stop signal sent."
  2501. }
  2502. postgresql_restart() {
  2503. pg_require_installed || return 1
  2504. if [[ $release == "alpine" ]]; then
  2505. rc-service postgresql restart
  2506. else
  2507. systemctl restart "$(pg_systemd_unit)"
  2508. fi
  2509. sleep 1
  2510. postgresql_status
  2511. }
  2512. postgresql_enable() {
  2513. pg_require_installed || return 1
  2514. if [[ $release == "alpine" ]]; then
  2515. rc-update add postgresql default
  2516. else
  2517. systemctl enable "$(pg_systemd_unit)"
  2518. fi
  2519. if [[ $? == 0 ]]; then
  2520. LOGI "PostgreSQL set to start automatically on boot."
  2521. else
  2522. LOGE "Failed to enable PostgreSQL autostart."
  2523. fi
  2524. }
  2525. postgresql_log() {
  2526. pg_require_installed || return 1
  2527. local info ver cluster logfile
  2528. info="$(pg_cluster_info)"
  2529. if [[ -n "$info" ]]; then
  2530. ver="${info%% *}"
  2531. cluster="${info##* }"
  2532. logfile="/var/log/postgresql/postgresql-${ver}-${cluster}.log"
  2533. fi
  2534. if [[ -n "$logfile" && -f "$logfile" ]]; then
  2535. tail -n 40 "$logfile"
  2536. elif command -v journalctl > /dev/null 2>&1; then
  2537. journalctl -u "$(pg_systemd_unit)" -n 40 --no-pager
  2538. else
  2539. LOGE "No PostgreSQL log found."
  2540. fi
  2541. }
  2542. pg_require_installed() {
  2543. if ! postgresql_installed; then
  2544. LOGE "PostgreSQL is not installed. Use option 1 (Install PostgreSQL) in this menu first."
  2545. return 1
  2546. fi
  2547. }
  2548. # Completely removes the PostgreSQL server and ALL of its databases from the system.
  2549. # Gated behind an explicit confirmation because this is system-wide and irreversible:
  2550. # any other application sharing this PostgreSQL instance loses its data too. Mirrors the
  2551. # package names used by pg_install_local() so the right packages are removed per distro.
  2552. purge_postgresql() {
  2553. echo ""
  2554. echo -e "${yellow}This panel was using PostgreSQL.${plain}"
  2555. echo -e "${red}WARNING:${plain} purging removes the PostgreSQL server and ${red}ALL${plain} of its databases on"
  2556. echo -e "this machine, including any used by other applications. This cannot be undone."
  2557. confirm "Also purge PostgreSQL and delete all of its data?" "n"
  2558. if [[ $? != 0 ]]; then
  2559. LOGI "Left PostgreSQL installed; its data was not removed."
  2560. return 0
  2561. fi
  2562. if [[ $release == "alpine" ]]; then
  2563. rc-service postgresql stop 2> /dev/null
  2564. rc-update del postgresql 2> /dev/null
  2565. else
  2566. systemctl stop "$(pg_systemd_unit)" 2> /dev/null
  2567. systemctl disable "$(pg_systemd_unit)" 2> /dev/null
  2568. fi
  2569. case "${release}" in
  2570. ubuntu | debian | armbian)
  2571. apt-get -y --purge remove 'postgresql*'
  2572. apt-get -y autoremove --purge
  2573. ;;
  2574. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2575. dnf remove -y postgresql postgresql-server postgresql-contrib
  2576. ;;
  2577. centos)
  2578. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2579. yum remove -y postgresql postgresql-server postgresql-contrib
  2580. else
  2581. dnf remove -y postgresql postgresql-server postgresql-contrib
  2582. fi
  2583. ;;
  2584. arch | manjaro | parch)
  2585. pacman -Rns --noconfirm postgresql
  2586. ;;
  2587. opensuse-tumbleweed | opensuse-leap)
  2588. zypper -q remove -y postgresql postgresql-server postgresql-contrib
  2589. ;;
  2590. alpine)
  2591. apk del postgresql postgresql-contrib postgresql-client
  2592. ;;
  2593. *)
  2594. LOGE "Unsupported distro for automatic PostgreSQL purge: ${release}. Remove it manually."
  2595. return 1
  2596. ;;
  2597. esac
  2598. rm -rf /var/lib/postgresql /var/lib/pgsql /var/lib/postgres /etc/postgresql
  2599. LOGI "PostgreSQL has been purged."
  2600. }
  2601. # Installs a local PostgreSQL server and creates a dedicated xui user/database.
  2602. # Progress goes to stderr; on success the connection DSN is printed to stdout so
  2603. # callers can capture it. Mirrors install_postgres_local() from install.sh, so the
  2604. # panel can be set up without re-running the remote install script.
  2605. pg_install_local() {
  2606. local pg_user pg_pass pg_db pg_host pg_port
  2607. pg_pass=$(gen_random_string 24)
  2608. pg_db="xui"
  2609. pg_host="127.0.0.1"
  2610. pg_port="5432"
  2611. case "${release}" in
  2612. ubuntu | debian | armbian)
  2613. apt-get update >&2 && apt-get install -y -q postgresql >&2 || return 1
  2614. ;;
  2615. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2616. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2617. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2618. ;;
  2619. centos)
  2620. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2621. yum install -y postgresql-server postgresql-contrib >&2 || return 1
  2622. else
  2623. dnf install -y -q postgresql-server postgresql-contrib >&2 || return 1
  2624. fi
  2625. [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
  2626. ;;
  2627. arch | manjaro | parch)
  2628. pacman -Syu --noconfirm postgresql >&2 || return 1
  2629. if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
  2630. sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
  2631. fi
  2632. ;;
  2633. opensuse-tumbleweed | opensuse-leap)
  2634. zypper -q install -y postgresql-server postgresql-contrib >&2 || return 1
  2635. if [[ ! -f /var/lib/pgsql/data/PG_VERSION ]]; then
  2636. install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >&2 || return 1
  2637. su - postgres -c "initdb -D /var/lib/pgsql/data" >&2 || return 1
  2638. fi
  2639. ;;
  2640. alpine)
  2641. apk add --no-cache postgresql postgresql-contrib >&2 || return 1
  2642. if [[ ! -f /var/lib/postgresql/data/PG_VERSION ]]; then
  2643. /etc/init.d/postgresql setup >&2 || return 1
  2644. fi
  2645. rc-update add postgresql default >&2 2> /dev/null || true
  2646. rc-service postgresql start >&2 || return 1
  2647. ;;
  2648. *)
  2649. echo -e "${red}Unsupported distro for automatic PostgreSQL install: ${release}${plain}" >&2
  2650. return 1
  2651. ;;
  2652. esac
  2653. if [[ "${release}" != "alpine" ]]; then
  2654. systemctl enable --now postgresql >&2 || return 1
  2655. fi
  2656. local i
  2657. for i in 1 2 3 4 5; do
  2658. sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>&1 && break
  2659. sleep 1
  2660. done
  2661. local existing_owner=""
  2662. existing_owner=$(sudo -u postgres psql -tAc \
  2663. "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2664. | tr -d '[:space:]')
  2665. if [[ -n "${existing_owner}" && "${existing_owner}" != "postgres" ]]; then
  2666. pg_user="${existing_owner}"
  2667. else
  2668. pg_user=$(gen_random_string 8)
  2669. fi
  2670. sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${pg_user}'" 2> /dev/null \
  2671. | grep -q 1 \
  2672. || sudo -u postgres psql -c "CREATE USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2673. sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname='${pg_db}'" 2> /dev/null \
  2674. | grep -q 1 \
  2675. || sudo -u postgres psql -c "CREATE DATABASE \"${pg_db}\" OWNER \"${pg_user}\";" >&2 || return 1
  2676. sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
  2677. local pg_pass_enc
  2678. 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')
  2679. echo "postgres://${pg_user}:${pg_pass_enc}@${pg_host}:${pg_port}/${pg_db}?sslmode=disable"
  2680. return 0
  2681. }
  2682. # Installs the PostgreSQL client tools (pg_dump/pg_restore) used by in-panel backup.
  2683. pg_ensure_client() {
  2684. if command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1; then
  2685. return 0
  2686. fi
  2687. echo -e "${yellow}Installing PostgreSQL client tools (pg_dump/pg_restore)...${plain}" >&2
  2688. case "${release}" in
  2689. ubuntu | debian | armbian)
  2690. apt-get update >&2 && apt-get install -y -q postgresql-client >&2 || return 1
  2691. ;;
  2692. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  2693. dnf install -y -q postgresql >&2 || return 1
  2694. ;;
  2695. centos)
  2696. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  2697. yum install -y postgresql >&2 || return 1
  2698. else
  2699. dnf install -y -q postgresql >&2 || return 1
  2700. fi
  2701. ;;
  2702. arch | manjaro | parch)
  2703. pacman -Sy --noconfirm postgresql >&2 || return 1
  2704. ;;
  2705. opensuse-tumbleweed | opensuse-leap)
  2706. zypper -q install -y postgresql >&2 || return 1
  2707. ;;
  2708. alpine)
  2709. apk add --no-cache postgresql-client >&2 || return 1
  2710. ;;
  2711. *)
  2712. return 1
  2713. ;;
  2714. esac
  2715. command -v pg_dump > /dev/null 2>&1 && command -v pg_restore > /dev/null 2>&1
  2716. }
  2717. # Writes XUI_DB_TYPE/XUI_DB_DSN into the service env file, preserving other entries.
  2718. pg_write_env() {
  2719. local dsn="$1" envfile
  2720. envfile="$(xui_env_file_path)"
  2721. install -d -m 755 "$(dirname "$envfile")"
  2722. touch "$envfile"
  2723. sed -i '/^XUI_DB_TYPE=/d; /^XUI_DB_DSN=/d' "$envfile"
  2724. {
  2725. echo "XUI_DB_TYPE=postgres"
  2726. echo "XUI_DB_DSN=${dsn}"
  2727. } >> "$envfile"
  2728. chmod 600 "$envfile"
  2729. }
  2730. pg_install_server_action() {
  2731. if postgresql_installed; then
  2732. LOGI "PostgreSQL already appears to be installed on this system."
  2733. confirm "Run setup anyway (ensures the xui database/user exist)?" "n" || return 0
  2734. fi
  2735. LOGI "Installing PostgreSQL server and creating a dedicated user/database..."
  2736. local dsn
  2737. dsn=$(pg_install_local)
  2738. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2739. LOGE "PostgreSQL installation failed."
  2740. return 1
  2741. fi
  2742. PG_LAST_DSN="$dsn"
  2743. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (panel DB backup may be unavailable)."
  2744. echo ""
  2745. LOGI "PostgreSQL is installed and ready."
  2746. echo -e "${green}Connection DSN:${plain} ${dsn}"
  2747. echo -e "${yellow}Use option 2 to migrate your SQLite data and switch the panel to PostgreSQL.${plain}"
  2748. }
  2749. # Copies the current SQLite data into PostgreSQL, then switches the panel over.
  2750. migrate_to_postgres() {
  2751. if [[ ! -x "${xui_folder}/x-ui" ]]; then
  2752. LOGE "x-ui is not installed."
  2753. return 1
  2754. fi
  2755. echo ""
  2756. echo -e "${yellow}This copies your current SQLite data into a PostgreSQL database,${plain}"
  2757. echo -e "${yellow}then switches the panel to PostgreSQL and restarts it.${plain}"
  2758. echo -e "${red}Any existing panel tables in the destination will be cleared and overwritten.${plain}"
  2759. confirm "Continue?" "n" || return 0
  2760. local dsn="" pg_mode
  2761. if [[ -n "$PG_LAST_DSN" ]]; then
  2762. echo -e "A PostgreSQL database was created in this session:"
  2763. echo -e " ${green}${PG_LAST_DSN}${plain}"
  2764. confirm "Migrate into this database?" "y" && dsn="$PG_LAST_DSN"
  2765. fi
  2766. if [[ -z "$dsn" ]]; then
  2767. echo ""
  2768. echo -e "${green}\t1.${plain} Install PostgreSQL locally and create a dedicated user/db (recommended)"
  2769. echo -e "${green}\t2.${plain} Use an existing PostgreSQL server (enter DSN)"
  2770. read -rp "Choose [1]: " pg_mode
  2771. pg_mode="${pg_mode:-1}"
  2772. if [[ "$pg_mode" == "2" ]]; then
  2773. while [[ -z "$dsn" ]]; do
  2774. read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " dsn
  2775. dsn="${dsn// /}"
  2776. done
  2777. else
  2778. LOGI "Installing PostgreSQL locally (this may take a moment)..."
  2779. dsn=$(pg_install_local)
  2780. if [[ $? -ne 0 || -z "$dsn" ]]; then
  2781. LOGE "PostgreSQL installation failed. Aborting migration."
  2782. return 1
  2783. fi
  2784. PG_LAST_DSN="$dsn"
  2785. fi
  2786. fi
  2787. pg_ensure_client || LOGE "Could not install pg_dump/pg_restore (in-panel DB backup/restore may be unavailable)."
  2788. LOGI "Stopping panel to take a consistent snapshot..."
  2789. stop 0 > /dev/null 2>&1
  2790. echo ""
  2791. LOGI "Migrating data into PostgreSQL..."
  2792. if ! ${xui_folder}/x-ui migrate-db --dsn "$dsn"; then
  2793. LOGE "Migration failed. The panel was NOT switched to PostgreSQL."
  2794. start 0 > /dev/null 2>&1
  2795. return 1
  2796. fi
  2797. pg_write_env "$dsn"
  2798. LOGI "Wrote database settings to $(xui_env_file_path) (XUI_DB_TYPE=postgres)."
  2799. LOGI "Restarting panel on PostgreSQL..."
  2800. restart 0
  2801. sleep 1
  2802. if check_status; then
  2803. LOGI "Migration complete. The panel is now running on PostgreSQL."
  2804. else
  2805. LOGE "Panel did not come up. Check logs (option 16). Your SQLite data is left intact."
  2806. fi
  2807. }
  2808. postgresql_menu() {
  2809. echo -e "${green}\t1.${plain} ${green}Install${plain} PostgreSQL (server + client + xui db)"
  2810. echo -e "${green}\t2.${plain} Migrate SQLite ${green}->${plain} PostgreSQL"
  2811. echo -e "${green}\t3.${plain} Status (clusters & port 5432)"
  2812. echo -e "${green}\t4.${plain} ${green}Start${plain} PostgreSQL"
  2813. echo -e "${green}\t5.${plain} ${red}Stop${plain} PostgreSQL"
  2814. echo -e "${green}\t6.${plain} Restart PostgreSQL"
  2815. echo -e "${green}\t7.${plain} ${green}Enable${plain} Autostart on boot"
  2816. echo -e "${green}\t8.${plain} View PostgreSQL Log"
  2817. echo -e "${green}\t9.${plain} Convert SQLite ${green}.db <-> .dump${plain}"
  2818. echo -e "${green}\t0.${plain} Back to Main Menu"
  2819. read -rp "Choose an option: " choice
  2820. case "$choice" in
  2821. 0)
  2822. show_menu
  2823. ;;
  2824. 1)
  2825. pg_install_server_action
  2826. postgresql_menu
  2827. ;;
  2828. 2)
  2829. migrate_to_postgres
  2830. postgresql_menu
  2831. ;;
  2832. 3)
  2833. postgresql_status
  2834. postgresql_menu
  2835. ;;
  2836. 4)
  2837. postgresql_start
  2838. postgresql_menu
  2839. ;;
  2840. 5)
  2841. postgresql_stop
  2842. postgresql_menu
  2843. ;;
  2844. 6)
  2845. postgresql_restart
  2846. postgresql_menu
  2847. ;;
  2848. 7)
  2849. postgresql_enable
  2850. postgresql_menu
  2851. ;;
  2852. 8)
  2853. postgresql_log
  2854. postgresql_menu
  2855. ;;
  2856. 9)
  2857. migrate_db_prompt
  2858. postgresql_menu
  2859. ;;
  2860. *)
  2861. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2862. postgresql_menu
  2863. ;;
  2864. esac
  2865. }
  2866. # Convert between the panel's SQLite database and a portable .dump (SQL text)
  2867. # file using the bundled x-ui binary. With no arguments it dumps the installed
  2868. # panel database; an optional second argument overrides the output path.
  2869. # x-ui migrateDB [file.db|file.dump] [output]
  2870. migrate_db() {
  2871. local input="$1" output="$2"
  2872. local default_db="/etc/x-ui/x-ui.db"
  2873. local bin="${xui_folder}/x-ui"
  2874. [[ -z "$input" ]] && input="$default_db"
  2875. if [[ ! -x "$bin" ]]; then
  2876. LOGE "x-ui binary not found at ${bin}. Is the panel installed?"
  2877. return 1
  2878. fi
  2879. if ! "$bin" migrate-db -h 2>&1 | grep -q -- '-dump'; then
  2880. LOGE "This x-ui build does not support .db <-> .dump conversion yet."
  2881. LOGE "Update the panel first (x-ui update) to a version with 'migrate-db --dump/--restore'."
  2882. return 1
  2883. fi
  2884. if [[ ! -f "$input" ]]; then
  2885. LOGE "Input file not found: ${input}"
  2886. echo -e "Usage: ${green}x-ui migrateDB [file.db|file.dump] [output]${plain}"
  2887. return 1
  2888. fi
  2889. local mode
  2890. case "$input" in
  2891. *.db | *.sqlite | *.sqlite3)
  2892. mode="dump"
  2893. ;;
  2894. *.dump | *.sql)
  2895. mode="restore"
  2896. ;;
  2897. *)
  2898. if head -c 16 "$input" | grep -q "SQLite format 3"; then
  2899. mode="dump"
  2900. else
  2901. mode="restore"
  2902. fi
  2903. ;;
  2904. esac
  2905. if [[ "$mode" == "dump" ]]; then
  2906. [[ -z "$output" ]] && output="${input%.*}.dump"
  2907. if [[ -f "$output" ]]; then
  2908. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2909. fi
  2910. LOGI "Dumping SQLite database to SQL text:"
  2911. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2912. if "$bin" migrate-db --src "$input" --dump "$output"; then
  2913. LOGI "Done. Wrote ${output}."
  2914. else
  2915. LOGE "Dump failed."
  2916. return 1
  2917. fi
  2918. else
  2919. [[ -z "$output" ]] && output="${input%.*}.db"
  2920. if [[ "$output" == "$default_db" ]] && check_status > /dev/null 2>&1; then
  2921. LOGE "Refusing to restore into the live database (${default_db}) while x-ui is running."
  2922. LOGE "Stop the panel first (x-ui stop) or choose a different output path."
  2923. return 1
  2924. fi
  2925. if [[ -f "$output" ]]; then
  2926. confirm "Output ${output} already exists and will be overwritten. Continue?" "n" || return 0
  2927. rm -f "$output"
  2928. fi
  2929. LOGI "Rebuilding SQLite database from SQL text:"
  2930. echo -e " ${green}${input}${plain} -> ${green}${output}${plain}"
  2931. if "$bin" migrate-db --restore "$input" --out "$output"; then
  2932. LOGI "Done. Created ${output}."
  2933. else
  2934. LOGE "Restore failed."
  2935. rm -f "$output"
  2936. return 1
  2937. fi
  2938. fi
  2939. }
  2940. # Interactive wrapper around migrate_db for the menu: prompts for the paths and
  2941. # lets migrate_db auto-detect the direction.
  2942. migrate_db_prompt() {
  2943. local default_db="/etc/x-ui/x-ui.db"
  2944. local input output
  2945. echo -e "Convert between a SQLite ${green}.db${plain} and a portable ${green}.dump${plain} (direction auto-detected)."
  2946. read -rp "Input file [${default_db}]: " input
  2947. input="${input:-$default_db}"
  2948. read -rp "Output file (leave empty to auto-name next to input): " output
  2949. migrate_db "$input" "$output"
  2950. }
  2951. show_usage() {
  2952. echo -e "┌────────────────────────────────────────────────────────────────┐
  2953. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  2954. │ │
  2955. │ ${blue}x-ui${plain} - Admin Management Script │
  2956. │ ${blue}x-ui start${plain} - Start │
  2957. │ ${blue}x-ui stop${plain} - Stop │
  2958. │ ${blue}x-ui restart${plain} - Restart │
  2959. | ${blue}x-ui restart-xray${plain} - Restart Xray │
  2960. │ ${blue}x-ui status${plain} - Current Status │
  2961. │ ${blue}x-ui settings${plain} - Current Settings │
  2962. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  2963. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  2964. │ ${blue}x-ui log${plain} - Check logs │
  2965. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  2966. │ ${blue}x-ui update${plain} - Update │
  2967. │ ${blue}x-ui update-dev${plain} - Update to Dev channel (latest) │
  2968. │ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
  2969. │ ${blue}x-ui migrateDB [file]${plain} - Convert .db <-> .dump (SQLite) │
  2970. │ ${blue}x-ui legacy${plain} - Legacy version │
  2971. │ ${blue}x-ui install${plain} - Install │
  2972. │ ${blue}x-ui uninstall${plain} - Uninstall │
  2973. └────────────────────────────────────────────────────────────────┘"
  2974. }
  2975. show_menu() {
  2976. echo -e "
  2977. ╔────────────────────────────────────────────────╗
  2978. │ ${green}3X-UI Panel Management Script${plain} │
  2979. │ ${green}0.${plain} Exit Script │
  2980. │────────────────────────────────────────────────│
  2981. │ ${green}1.${plain} Install │
  2982. │ ${green}2.${plain} Update │
  2983. │ ${green}3.${plain} Update to Dev Channel (latest commit) │
  2984. │ ${green}4.${plain} Update Menu │
  2985. │ ${green}5.${plain} Legacy Version │
  2986. │ ${green}6.${plain} Uninstall │
  2987. │────────────────────────────────────────────────│
  2988. │ ${green}7.${plain} Reset Username & Password │
  2989. │ ${green}8.${plain} Reset Web Base Path │
  2990. │ ${green}9.${plain} Reset Settings │
  2991. │ ${green}10.${plain} Change Port │
  2992. │ ${green}11.${plain} View Current Settings │
  2993. │────────────────────────────────────────────────│
  2994. │ ${green}12.${plain} Start │
  2995. │ ${green}13.${plain} Stop │
  2996. │ ${green}14.${plain} Restart │
  2997. | ${green}15.${plain} Restart Xray │
  2998. │ ${green}16.${plain} Check Status │
  2999. │ ${green}17.${plain} Logs Management │
  3000. │────────────────────────────────────────────────│
  3001. │ ${green}18.${plain} Enable Autostart │
  3002. │ ${green}19.${plain} Disable Autostart │
  3003. │────────────────────────────────────────────────│
  3004. │ ${green}20.${plain} SSL Certificate Management │
  3005. │ ${green}21.${plain} Cloudflare SSL Certificate │
  3006. │ ${green}22.${plain} IP Limit Management │
  3007. │ ${green}23.${plain} Firewall Management │
  3008. │ ${green}24.${plain} SSH Port Forwarding Management │
  3009. │ ${green}25.${plain} PostgreSQL Management │
  3010. │────────────────────────────────────────────────│
  3011. │ ${green}26.${plain} Enable BBR │
  3012. │ ${green}27.${plain} Update Geo Files │
  3013. │ ${green}28.${plain} Speedtest by Ookla │
  3014. ╚────────────────────────────────────────────────╝
  3015. "
  3016. show_status
  3017. echo && read -rp "Please enter your selection [0-28]: " num
  3018. case "${num}" in
  3019. 0)
  3020. exit 0
  3021. ;;
  3022. 1)
  3023. check_uninstall && install
  3024. ;;
  3025. 2)
  3026. check_install && update
  3027. ;;
  3028. 3)
  3029. check_install && update_dev
  3030. ;;
  3031. 4)
  3032. check_install && update_menu
  3033. ;;
  3034. 5)
  3035. check_install && legacy_version
  3036. ;;
  3037. 6)
  3038. check_install && uninstall
  3039. ;;
  3040. 7)
  3041. check_install && reset_user
  3042. ;;
  3043. 8)
  3044. check_install && reset_webbasepath
  3045. ;;
  3046. 9)
  3047. check_install && reset_config
  3048. ;;
  3049. 10)
  3050. check_install && set_port
  3051. ;;
  3052. 11)
  3053. check_install && check_config
  3054. ;;
  3055. 12)
  3056. check_install && start
  3057. ;;
  3058. 13)
  3059. check_install && stop
  3060. ;;
  3061. 14)
  3062. check_install && restart
  3063. ;;
  3064. 15)
  3065. check_install && restart_xray
  3066. ;;
  3067. 16)
  3068. check_install && status
  3069. ;;
  3070. 17)
  3071. check_install && show_log
  3072. ;;
  3073. 18)
  3074. check_install && enable
  3075. ;;
  3076. 19)
  3077. check_install && disable
  3078. ;;
  3079. 20)
  3080. ssl_cert_issue_main
  3081. ;;
  3082. 21)
  3083. ssl_cert_issue_CF
  3084. ;;
  3085. 22)
  3086. iplimit_main
  3087. ;;
  3088. 23)
  3089. firewall_menu
  3090. ;;
  3091. 24)
  3092. SSH_port_forwarding
  3093. ;;
  3094. 25)
  3095. postgresql_menu
  3096. ;;
  3097. 26)
  3098. bbr_menu
  3099. ;;
  3100. 27)
  3101. update_geo
  3102. ;;
  3103. 28)
  3104. run_speedtest
  3105. ;;
  3106. *)
  3107. LOGE "Please enter the correct number [0-28]"
  3108. ;;
  3109. esac
  3110. }
  3111. if [[ $# > 0 ]]; then
  3112. case $1 in
  3113. "start")
  3114. check_install 0 && start 0
  3115. ;;
  3116. "stop")
  3117. check_install 0 && stop 0
  3118. ;;
  3119. "restart")
  3120. check_install 0 && restart 0
  3121. ;;
  3122. "restart-xray")
  3123. check_install 0 && restart_xray 0
  3124. ;;
  3125. "status")
  3126. check_install 0 && status 0
  3127. ;;
  3128. "settings")
  3129. check_install 0 && check_config 0
  3130. ;;
  3131. "enable")
  3132. check_install 0 && enable 0
  3133. ;;
  3134. "disable")
  3135. check_install 0 && disable 0
  3136. ;;
  3137. "log")
  3138. check_install 0 && show_log 0
  3139. ;;
  3140. "banlog")
  3141. check_install 0 && show_banlog 0
  3142. ;;
  3143. "setup-fail2ban")
  3144. setup_fail2ban_iplimit
  3145. ;;
  3146. "update")
  3147. check_install 0 && update 0
  3148. ;;
  3149. "update-dev")
  3150. check_install 0 && update_dev 0
  3151. ;;
  3152. "legacy")
  3153. check_install 0 && legacy_version 0
  3154. ;;
  3155. "install")
  3156. check_uninstall 0 && install 0
  3157. ;;
  3158. "uninstall")
  3159. check_install 0 && uninstall 0
  3160. ;;
  3161. "update-all-geofiles")
  3162. geo_updated=0
  3163. if check_install 0 && update_all_geofiles 0; then
  3164. [[ $geo_updated -eq 0 ]] || restart 0
  3165. fi
  3166. ;;
  3167. "migrateDB")
  3168. migrate_db "$2" "$3"
  3169. ;;
  3170. *) show_usage ;;
  3171. esac
  3172. else
  3173. show_menu
  3174. fi