1
0

x-ui.sh 114 KB

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