x-ui.sh 123 KB

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