1
0

main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "syscall"
  9. _ "unsafe"
  10. "x-ui/config"
  11. "x-ui/database"
  12. "x-ui/logger"
  13. "x-ui/sub"
  14. "x-ui/web"
  15. "x-ui/web/global"
  16. "x-ui/web/service"
  17. "github.com/op/go-logging"
  18. )
  19. func runWebServer() {
  20. log.Printf("Starting %v %v", config.GetName(), config.GetVersion())
  21. switch config.GetLogLevel() {
  22. case config.Debug:
  23. logger.InitLogger(logging.DEBUG)
  24. case config.Info:
  25. logger.InitLogger(logging.INFO)
  26. case config.Notice:
  27. logger.InitLogger(logging.NOTICE)
  28. case config.Warn:
  29. logger.InitLogger(logging.WARNING)
  30. case config.Error:
  31. logger.InitLogger(logging.ERROR)
  32. default:
  33. log.Fatalf("Unknown log level: %v", config.GetLogLevel())
  34. }
  35. err := database.InitDB(config.GetDBPath())
  36. if err != nil {
  37. log.Fatalf("Error initializing database: %v", err)
  38. }
  39. var server *web.Server
  40. server = web.NewServer()
  41. global.SetWebServer(server)
  42. err = server.Start()
  43. if err != nil {
  44. log.Fatalf("Error starting web server: %v", err)
  45. return
  46. }
  47. var subServer *sub.Server
  48. subServer = sub.NewServer()
  49. global.SetSubServer(subServer)
  50. err = subServer.Start()
  51. if err != nil {
  52. log.Fatalf("Error starting sub server: %v", err)
  53. return
  54. }
  55. sigCh := make(chan os.Signal, 1)
  56. // Trap shutdown signals
  57. signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM)
  58. for {
  59. sig := <-sigCh
  60. switch sig {
  61. case syscall.SIGHUP:
  62. logger.Info("Received SIGHUP signal. Restarting servers...")
  63. err := server.Stop()
  64. if err != nil {
  65. logger.Debug("Error stopping web server:", err)
  66. }
  67. err = subServer.Stop()
  68. if err != nil {
  69. logger.Debug("Error stopping sub server:", err)
  70. }
  71. server = web.NewServer()
  72. global.SetWebServer(server)
  73. err = server.Start()
  74. if err != nil {
  75. log.Fatalf("Error restarting web server: %v", err)
  76. return
  77. }
  78. log.Println("Web server restarted successfully.")
  79. subServer = sub.NewServer()
  80. global.SetSubServer(subServer)
  81. err = subServer.Start()
  82. if err != nil {
  83. log.Fatalf("Error restarting sub server: %v", err)
  84. return
  85. }
  86. log.Println("Sub server restarted successfully.")
  87. default:
  88. server.Stop()
  89. subServer.Stop()
  90. log.Println("Shutting down servers.")
  91. return
  92. }
  93. }
  94. }
  95. func resetSetting() {
  96. err := database.InitDB(config.GetDBPath())
  97. if err != nil {
  98. fmt.Println("Failed to initialize database:", err)
  99. return
  100. }
  101. settingService := service.SettingService{}
  102. err = settingService.ResetSettings()
  103. if err != nil {
  104. fmt.Println("Failed to reset settings:", err)
  105. } else {
  106. fmt.Println("Settings successfully reset.")
  107. }
  108. }
  109. func showSetting(show bool) {
  110. if show {
  111. settingService := service.SettingService{}
  112. port, err := settingService.GetPort()
  113. if err != nil {
  114. fmt.Println("get current port failed, error info:", err)
  115. }
  116. webBasePath, err := settingService.GetBasePath()
  117. if err != nil {
  118. fmt.Println("get webBasePath failed, error info:", err)
  119. }
  120. userService := service.UserService{}
  121. userModel, err := userService.GetFirstUser()
  122. if err != nil {
  123. fmt.Println("get current user info failed, error info:", err)
  124. }
  125. username := userModel.Username
  126. userpasswd := userModel.Password
  127. if username == "" || userpasswd == "" {
  128. fmt.Println("current username or password is empty")
  129. }
  130. fmt.Println("current panel settings as follows:")
  131. fmt.Println("username:", username)
  132. fmt.Println("password:", userpasswd)
  133. fmt.Println("port:", port)
  134. if webBasePath != "" {
  135. fmt.Println("webBasePath:", webBasePath)
  136. } else {
  137. fmt.Println("webBasePath is not set")
  138. }
  139. }
  140. }
  141. func updateTgbotEnableSts(status bool) {
  142. settingService := service.SettingService{}
  143. currentTgSts, err := settingService.GetTgbotEnabled()
  144. if err != nil {
  145. fmt.Println(err)
  146. return
  147. }
  148. logger.Infof("current enabletgbot status[%v],need update to status[%v]", currentTgSts, status)
  149. if currentTgSts != status {
  150. err := settingService.SetTgbotEnabled(status)
  151. if err != nil {
  152. fmt.Println(err)
  153. return
  154. } else {
  155. logger.Infof("SetTgbotEnabled[%v] success", status)
  156. }
  157. }
  158. }
  159. func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime string) {
  160. err := database.InitDB(config.GetDBPath())
  161. if err != nil {
  162. fmt.Println("Error initializing database:", err)
  163. return
  164. }
  165. settingService := service.SettingService{}
  166. if tgBotToken != "" {
  167. err := settingService.SetTgBotToken(tgBotToken)
  168. if err != nil {
  169. fmt.Printf("Error setting Telegram bot token: %v\n", err)
  170. return
  171. }
  172. logger.Info("Successfully updated Telegram bot token.")
  173. }
  174. if tgBotRuntime != "" {
  175. err := settingService.SetTgbotRuntime(tgBotRuntime)
  176. if err != nil {
  177. fmt.Printf("Error setting Telegram bot runtime: %v\n", err)
  178. return
  179. }
  180. logger.Infof("Successfully updated Telegram bot runtime to [%s].", tgBotRuntime)
  181. }
  182. if tgBotChatid != "" {
  183. err := settingService.SetTgBotChatId(tgBotChatid)
  184. if err != nil {
  185. fmt.Printf("Error setting Telegram bot chat ID: %v\n", err)
  186. return
  187. }
  188. logger.Info("Successfully updated Telegram bot chat ID.")
  189. }
  190. }
  191. func updateSetting(port int, username string, password string, webBasePath string, listenIP string) {
  192. err := database.InitDB(config.GetDBPath())
  193. if err != nil {
  194. fmt.Println("Database initialization failed:", err)
  195. return
  196. }
  197. settingService := service.SettingService{}
  198. userService := service.UserService{}
  199. if port > 0 {
  200. err := settingService.SetPort(port)
  201. if err != nil {
  202. fmt.Println("Failed to set port:", err)
  203. } else {
  204. fmt.Printf("Port set successfully: %v\n", port)
  205. }
  206. }
  207. if username != "" || password != "" {
  208. err := userService.UpdateFirstUser(username, password)
  209. if err != nil {
  210. fmt.Println("Failed to update username and password:", err)
  211. } else {
  212. fmt.Println("Username and password updated successfully")
  213. }
  214. }
  215. if webBasePath != "" {
  216. err := settingService.SetBasePath(webBasePath)
  217. if err != nil {
  218. fmt.Println("Failed to set base URI path:", err)
  219. } else {
  220. fmt.Println("Base URI path set successfully")
  221. }
  222. }
  223. if listenIP != "" {
  224. err := settingService.SetListen(listenIP)
  225. if err != nil {
  226. fmt.Println("Failed to set listen IP:", err)
  227. } else {
  228. fmt.Printf("listen %v set successfully", listenIP)
  229. }
  230. }
  231. }
  232. func updateCert(publicKey string, privateKey string) {
  233. err := database.InitDB(config.GetDBPath())
  234. if err != nil {
  235. fmt.Println(err)
  236. return
  237. }
  238. if (privateKey != "" && publicKey != "") || (privateKey == "" && publicKey == "") {
  239. settingService := service.SettingService{}
  240. err = settingService.SetCertFile(publicKey)
  241. if err != nil {
  242. fmt.Println("set certificate public key failed:", err)
  243. } else {
  244. fmt.Println("set certificate public key success")
  245. }
  246. err = settingService.SetKeyFile(privateKey)
  247. if err != nil {
  248. fmt.Println("set certificate private key failed:", err)
  249. } else {
  250. fmt.Println("set certificate private key success")
  251. }
  252. } else {
  253. fmt.Println("both public and private key should be entered.")
  254. }
  255. }
  256. func migrateDb() {
  257. inboundService := service.InboundService{}
  258. err := database.InitDB(config.GetDBPath())
  259. if err != nil {
  260. log.Fatal(err)
  261. }
  262. fmt.Println("Start migrating database...")
  263. inboundService.MigrateDB()
  264. fmt.Println("Migration done!")
  265. }
  266. func removeSecret() {
  267. userService := service.UserService{}
  268. secretExists, err := userService.CheckSecretExistence()
  269. if err != nil {
  270. fmt.Println("Error checking secret existence:", err)
  271. return
  272. }
  273. if !secretExists {
  274. fmt.Println("No secret exists to remove.")
  275. return
  276. }
  277. err = userService.RemoveUserSecret()
  278. if err != nil {
  279. fmt.Println("Error removing secret:", err)
  280. return
  281. }
  282. settingService := service.SettingService{}
  283. err = settingService.SetSecretStatus(false)
  284. if err != nil {
  285. fmt.Println("Error updating secret status:", err)
  286. return
  287. }
  288. fmt.Println("Secret removed successfully.")
  289. }
  290. func main() {
  291. if len(os.Args) < 2 {
  292. runWebServer()
  293. return
  294. }
  295. var showVersion bool
  296. flag.BoolVar(&showVersion, "v", false, "show version")
  297. runCmd := flag.NewFlagSet("run", flag.ExitOnError)
  298. settingCmd := flag.NewFlagSet("setting", flag.ExitOnError)
  299. var port int
  300. var username string
  301. var password string
  302. var webBasePath string
  303. var listenIP string
  304. var webCertFile string
  305. var webKeyFile string
  306. var tgbottoken string
  307. var tgbotchatid string
  308. var enabletgbot bool
  309. var tgbotRuntime string
  310. var reset bool
  311. var show bool
  312. var remove_secret bool
  313. settingCmd.BoolVar(&reset, "reset", false, "Reset all settings")
  314. settingCmd.BoolVar(&show, "show", false, "Display current settings")
  315. settingCmd.BoolVar(&remove_secret, "remove_secret", false, "Remove secret key")
  316. settingCmd.IntVar(&port, "port", 0, "Set panel port number")
  317. settingCmd.StringVar(&username, "username", "", "Set login username")
  318. settingCmd.StringVar(&password, "password", "", "Set login password")
  319. settingCmd.StringVar(&webBasePath, "webBasePath", "", "Set base path for Panel")
  320. settingCmd.StringVar(&listenIP, "listen", "", "set panel listen IP")
  321. settingCmd.StringVar(&webCertFile, "webCert", "", "Set path to public key file for panel")
  322. settingCmd.StringVar(&webKeyFile, "webCertKey", "", "Set path to private key file for panel")
  323. settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "Set token for Telegram bot")
  324. settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "Set cron time for Telegram bot notifications")
  325. settingCmd.StringVar(&tgbotchatid, "tgbotchatid", "", "Set chat ID for Telegram bot notifications")
  326. settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "Enable notifications via Telegram bot")
  327. oldUsage := flag.Usage
  328. flag.Usage = func() {
  329. oldUsage()
  330. fmt.Println()
  331. fmt.Println("Commands:")
  332. fmt.Println(" run run web panel")
  333. fmt.Println(" migrate migrate form other/old x-ui")
  334. fmt.Println(" setting set settings")
  335. }
  336. flag.Parse()
  337. if showVersion {
  338. fmt.Println(config.GetVersion())
  339. return
  340. }
  341. switch os.Args[1] {
  342. case "run":
  343. err := runCmd.Parse(os.Args[2:])
  344. if err != nil {
  345. fmt.Println(err)
  346. return
  347. }
  348. runWebServer()
  349. case "migrate":
  350. migrateDb()
  351. case "setting":
  352. err := settingCmd.Parse(os.Args[2:])
  353. if err != nil {
  354. fmt.Println(err)
  355. return
  356. }
  357. if reset {
  358. resetSetting()
  359. } else {
  360. updateSetting(port, username, password, webBasePath, listenIP)
  361. }
  362. if show {
  363. showSetting(show)
  364. }
  365. if (tgbottoken != "") || (tgbotchatid != "") || (tgbotRuntime != "") {
  366. updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime)
  367. }
  368. if remove_secret {
  369. removeSecret()
  370. }
  371. if enabletgbot {
  372. updateTgbotEnableSts(enabletgbot)
  373. }
  374. case "cert":
  375. err := settingCmd.Parse(os.Args[2:])
  376. if err != nil {
  377. fmt.Println(err)
  378. return
  379. }
  380. if reset {
  381. updateCert("", "")
  382. } else {
  383. updateCert(webCertFile, webKeyFile)
  384. }
  385. default:
  386. fmt.Println("Invalid subcommands")
  387. fmt.Println()
  388. runCmd.Usage()
  389. fmt.Println()
  390. settingCmd.Usage()
  391. }
  392. }