1
0

x-ui.sh 111 KB

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