x-ui.sh 105 KB

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