x-ui.sh 115 KB

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