main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. certFile, err := settingService.GetCertFile()
  121. if err != nil {
  122. fmt.Println("get cert file failed, error info:", err)
  123. }
  124. keyFile, err := settingService.GetKeyFile()
  125. if err != nil {
  126. fmt.Println("get key file failed, error info:", err)
  127. }
  128. userService := service.UserService{}
  129. userModel, err := userService.GetFirstUser()
  130. if err != nil {
  131. fmt.Println("get current user info failed, error info:", err)
  132. }
  133. username := userModel.Username
  134. userpasswd := userModel.Password
  135. if username == "" || userpasswd == "" {
  136. fmt.Println("current username or password is empty")
  137. }
  138. fmt.Println("current panel settings as follows:")
  139. if certFile == "" || keyFile == "" {
  140. fmt.Println("Warning: Panel is not secure with SSL")
  141. } else {
  142. fmt.Println("Panel is secure with SSL")
  143. }
  144. fmt.Println("username:", username)
  145. fmt.Println("password:", userpasswd)
  146. fmt.Println("port:", port)
  147. fmt.Println("webBasePath:", webBasePath)
  148. }
  149. }
  150. func updateTgbotEnableSts(status bool) {
  151. settingService := service.SettingService{}
  152. currentTgSts, err := settingService.GetTgbotEnabled()
  153. if err != nil {
  154. fmt.Println(err)
  155. return
  156. }
  157. logger.Infof("current enabletgbot status[%v],need update to status[%v]", currentTgSts, status)
  158. if currentTgSts != status {
  159. err := settingService.SetTgbotEnabled(status)
  160. if err != nil {
  161. fmt.Println(err)
  162. return
  163. } else {
  164. logger.Infof("SetTgbotEnabled[%v] success", status)
  165. }
  166. }
  167. }
  168. func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime string) {
  169. err := database.InitDB(config.GetDBPath())
  170. if err != nil {
  171. fmt.Println("Error initializing database:", err)
  172. return
  173. }
  174. settingService := service.SettingService{}
  175. if tgBotToken != "" {
  176. err := settingService.SetTgBotToken(tgBotToken)
  177. if err != nil {
  178. fmt.Printf("Error setting Telegram bot token: %v\n", err)
  179. return
  180. }
  181. logger.Info("Successfully updated Telegram bot token.")
  182. }
  183. if tgBotRuntime != "" {
  184. err := settingService.SetTgbotRuntime(tgBotRuntime)
  185. if err != nil {
  186. fmt.Printf("Error setting Telegram bot runtime: %v\n", err)
  187. return
  188. }
  189. logger.Infof("Successfully updated Telegram bot runtime to [%s].", tgBotRuntime)
  190. }
  191. if tgBotChatid != "" {
  192. err := settingService.SetTgBotChatId(tgBotChatid)
  193. if err != nil {
  194. fmt.Printf("Error setting Telegram bot chat ID: %v\n", err)
  195. return
  196. }
  197. logger.Info("Successfully updated Telegram bot chat ID.")
  198. }
  199. }
  200. func updateSetting(port int, username string, password string, webBasePath string, listenIP string) {
  201. err := database.InitDB(config.GetDBPath())
  202. if err != nil {
  203. fmt.Println("Database initialization failed:", err)
  204. return
  205. }
  206. settingService := service.SettingService{}
  207. userService := service.UserService{}
  208. if port > 0 {
  209. err := settingService.SetPort(port)
  210. if err != nil {
  211. fmt.Println("Failed to set port:", err)
  212. } else {
  213. fmt.Printf("Port set successfully: %v\n", port)
  214. }
  215. }
  216. if username != "" || password != "" {
  217. err := userService.UpdateFirstUser(username, password)
  218. if err != nil {
  219. fmt.Println("Failed to update username and password:", err)
  220. } else {
  221. fmt.Println("Username and password updated successfully")
  222. }
  223. }
  224. if webBasePath != "" {
  225. err := settingService.SetBasePath(webBasePath)
  226. if err != nil {
  227. fmt.Println("Failed to set base URI path:", err)
  228. } else {
  229. fmt.Println("Base URI path set successfully")
  230. }
  231. }
  232. if listenIP != "" {
  233. err := settingService.SetListen(listenIP)
  234. if err != nil {
  235. fmt.Println("Failed to set listen IP:", err)
  236. } else {
  237. fmt.Printf("listen %v set successfully", listenIP)
  238. }
  239. }
  240. }
  241. func updateCert(publicKey string, privateKey string) {
  242. err := database.InitDB(config.GetDBPath())
  243. if err != nil {
  244. fmt.Println(err)
  245. return
  246. }
  247. if (privateKey != "" && publicKey != "") || (privateKey == "" && publicKey == "") {
  248. settingService := service.SettingService{}
  249. err = settingService.SetCertFile(publicKey)
  250. if err != nil {
  251. fmt.Println("set certificate public key failed:", err)
  252. } else {
  253. fmt.Println("set certificate public key success")
  254. }
  255. err = settingService.SetKeyFile(privateKey)
  256. if err != nil {
  257. fmt.Println("set certificate private key failed:", err)
  258. } else {
  259. fmt.Println("set certificate private key success")
  260. }
  261. } else {
  262. fmt.Println("both public and private key should be entered.")
  263. }
  264. }
  265. func GetCertificate(getCert bool) {
  266. if getCert {
  267. settingService := service.SettingService{}
  268. certFile, err := settingService.GetCertFile()
  269. if err != nil {
  270. fmt.Println("get cert file failed, error info:", err)
  271. }
  272. keyFile, err := settingService.GetKeyFile()
  273. if err != nil {
  274. fmt.Println("get key file failed, error info:", err)
  275. }
  276. fmt.Println("cert:", certFile)
  277. fmt.Println("key:", keyFile)
  278. }
  279. }
  280. func GetListenIP(getListen bool) {
  281. if getListen {
  282. settingService := service.SettingService{}
  283. ListenIP, err := settingService.GetListen()
  284. if err != nil {
  285. log.Printf("Failed to retrieve listen IP: %v", err)
  286. return
  287. }
  288. fmt.Println("listenIP:", ListenIP)
  289. }
  290. }
  291. func migrateDb() {
  292. inboundService := service.InboundService{}
  293. err := database.InitDB(config.GetDBPath())
  294. if err != nil {
  295. log.Fatal(err)
  296. }
  297. fmt.Println("Start migrating database...")
  298. inboundService.MigrateDB()
  299. fmt.Println("Migration done!")
  300. }
  301. func removeSecret() {
  302. userService := service.UserService{}
  303. secretExists, err := userService.CheckSecretExistence()
  304. if err != nil {
  305. fmt.Println("Error checking secret existence:", err)
  306. return
  307. }
  308. if !secretExists {
  309. fmt.Println("No secret exists to remove.")
  310. return
  311. }
  312. err = userService.RemoveUserSecret()
  313. if err != nil {
  314. fmt.Println("Error removing secret:", err)
  315. return
  316. }
  317. settingService := service.SettingService{}
  318. err = settingService.SetSecretStatus(false)
  319. if err != nil {
  320. fmt.Println("Error updating secret status:", err)
  321. return
  322. }
  323. fmt.Println("Secret removed successfully.")
  324. }
  325. func main() {
  326. if len(os.Args) < 2 {
  327. runWebServer()
  328. return
  329. }
  330. var showVersion bool
  331. flag.BoolVar(&showVersion, "v", false, "show version")
  332. runCmd := flag.NewFlagSet("run", flag.ExitOnError)
  333. settingCmd := flag.NewFlagSet("setting", flag.ExitOnError)
  334. var port int
  335. var username string
  336. var password string
  337. var webBasePath string
  338. var listenIP string
  339. var getListen bool
  340. var webCertFile string
  341. var webKeyFile string
  342. var tgbottoken string
  343. var tgbotchatid string
  344. var enabletgbot bool
  345. var tgbotRuntime string
  346. var reset bool
  347. var show bool
  348. var getCert bool
  349. var remove_secret bool
  350. settingCmd.BoolVar(&reset, "reset", false, "Reset all settings")
  351. settingCmd.BoolVar(&show, "show", false, "Display current settings")
  352. settingCmd.BoolVar(&remove_secret, "remove_secret", false, "Remove secret key")
  353. settingCmd.IntVar(&port, "port", 0, "Set panel port number")
  354. settingCmd.StringVar(&username, "username", "", "Set login username")
  355. settingCmd.StringVar(&password, "password", "", "Set login password")
  356. settingCmd.StringVar(&webBasePath, "webBasePath", "", "Set base path for Panel")
  357. settingCmd.StringVar(&listenIP, "listenIP", "", "set panel listenIP IP")
  358. settingCmd.BoolVar(&getListen, "getListen", false, "Display current panel listenIP IP")
  359. settingCmd.BoolVar(&getCert, "getCert", false, "Display current certificate settings")
  360. settingCmd.StringVar(&webCertFile, "webCert", "", "Set path to public key file for panel")
  361. settingCmd.StringVar(&webKeyFile, "webCertKey", "", "Set path to private key file for panel")
  362. settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "Set token for Telegram bot")
  363. settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "Set cron time for Telegram bot notifications")
  364. settingCmd.StringVar(&tgbotchatid, "tgbotchatid", "", "Set chat ID for Telegram bot notifications")
  365. settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "Enable notifications via Telegram bot")
  366. oldUsage := flag.Usage
  367. flag.Usage = func() {
  368. oldUsage()
  369. fmt.Println()
  370. fmt.Println("Commands:")
  371. fmt.Println(" run run web panel")
  372. fmt.Println(" migrate migrate form other/old x-ui")
  373. fmt.Println(" setting set settings")
  374. }
  375. flag.Parse()
  376. if showVersion {
  377. fmt.Println(config.GetVersion())
  378. return
  379. }
  380. switch os.Args[1] {
  381. case "run":
  382. err := runCmd.Parse(os.Args[2:])
  383. if err != nil {
  384. fmt.Println(err)
  385. return
  386. }
  387. runWebServer()
  388. case "migrate":
  389. migrateDb()
  390. case "setting":
  391. err := settingCmd.Parse(os.Args[2:])
  392. if err != nil {
  393. fmt.Println(err)
  394. return
  395. }
  396. if reset {
  397. resetSetting()
  398. } else {
  399. updateSetting(port, username, password, webBasePath, listenIP)
  400. }
  401. if show {
  402. showSetting(show)
  403. }
  404. if getListen {
  405. GetListenIP(getListen)
  406. }
  407. if getCert {
  408. GetCertificate(getCert)
  409. }
  410. if (tgbottoken != "") || (tgbotchatid != "") || (tgbotRuntime != "") {
  411. updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime)
  412. }
  413. if remove_secret {
  414. removeSecret()
  415. }
  416. if enabletgbot {
  417. updateTgbotEnableSts(enabletgbot)
  418. }
  419. case "cert":
  420. err := settingCmd.Parse(os.Args[2:])
  421. if err != nil {
  422. fmt.Println(err)
  423. return
  424. }
  425. if reset {
  426. updateCert("", "")
  427. } else {
  428. updateCert(webCertFile, webKeyFile)
  429. }
  430. default:
  431. fmt.Println("Invalid subcommands")
  432. fmt.Println()
  433. runCmd.Usage()
  434. fmt.Println()
  435. settingCmd.Usage()
  436. }
  437. }