x-ui.sh 113 KB

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