server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. package controller
  2. import (
  3. "fmt"
  4. "net/http"
  5. "regexp"
  6. "slices"
  7. "strconv"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/database"
  10. "github.com/mhsanaei/3x-ui/v3/logger"
  11. "github.com/mhsanaei/3x-ui/v3/web/entity"
  12. "github.com/mhsanaei/3x-ui/v3/web/global"
  13. "github.com/mhsanaei/3x-ui/v3/web/service"
  14. "github.com/mhsanaei/3x-ui/v3/web/websocket"
  15. "github.com/gin-gonic/gin"
  16. )
  17. var filenameRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-.]+$`)
  18. // ServerController handles server management and status-related operations.
  19. type ServerController struct {
  20. BaseController
  21. serverService service.ServerService
  22. settingService service.SettingService
  23. panelService service.PanelService
  24. xrayMetricsService service.XrayMetricsService
  25. }
  26. // NewServerController creates a new ServerController, initializes routes, and starts background tasks.
  27. func NewServerController(g *gin.RouterGroup) *ServerController {
  28. a := &ServerController{}
  29. service.RestoreSystemMetrics()
  30. a.initRouter(g)
  31. a.startTask()
  32. return a
  33. }
  34. // initRouter sets up the routes for server status, Xray management, and utility endpoints.
  35. func (a *ServerController) initRouter(g *gin.RouterGroup) {
  36. g.GET("/status", a.status)
  37. g.GET("/cpuHistory/:bucket", a.getCpuHistoryBucket)
  38. g.GET("/history/:metric/:bucket", a.getMetricHistoryBucket)
  39. g.GET("/xrayMetricsState", a.getXrayMetricsState)
  40. g.GET("/xrayMetricsHistory/:metric/:bucket", a.getXrayMetricsHistoryBucket)
  41. g.GET("/xrayObservatory", a.getXrayObservatory)
  42. g.GET("/xrayObservatoryHistory/:tag/:bucket", a.getXrayObservatoryHistoryBucket)
  43. g.GET("/getXrayVersion", a.getXrayVersion)
  44. g.GET("/getPanelUpdateInfo", a.getPanelUpdateInfo)
  45. g.GET("/getConfigJson", a.getConfigJson)
  46. g.GET("/getDb", a.getDb)
  47. g.GET("/getMigration", a.getMigration)
  48. g.GET("/getNewUUID", a.getNewUUID)
  49. g.GET("/getWebCertFiles", a.getWebCertFiles)
  50. g.GET("/descendants", a.descendants)
  51. g.GET("/getNewX25519Cert", a.getNewX25519Cert)
  52. g.GET("/getNewmldsa65", a.getNewmldsa65)
  53. g.GET("/getNewmlkem768", a.getNewmlkem768)
  54. g.GET("/getNewVlessEnc", a.getNewVlessEnc)
  55. g.POST("/stopXrayService", a.stopXrayService)
  56. g.POST("/restartXrayService", a.restartXrayService)
  57. g.POST("/installXray/:version", a.installXray)
  58. g.POST("/updatePanel", a.updatePanel)
  59. g.POST("/updateGeofile", a.updateGeofile)
  60. g.POST("/updateGeofile/:fileName", a.updateGeofile)
  61. g.POST("/logs/:count", a.getLogs)
  62. g.POST("/xraylogs/:count", a.getXrayLogs)
  63. g.POST("/importDB", a.importDB)
  64. g.POST("/getNewEchCert", a.getNewEchCert)
  65. }
  66. // startTask registers the @2s ticker that refreshes server status, samples
  67. // xray metrics, and pushes the new snapshot to all websocket subscribers.
  68. // State + sampling live in ServerService; the controller only orchestrates
  69. // the cross-service side effects (xrayMetrics sample + websocket broadcast).
  70. func (a *ServerController) startTask() {
  71. c := global.GetWebServer().GetCron()
  72. c.AddFunc("@every 2s", func() {
  73. status := a.serverService.RefreshStatus()
  74. if status == nil {
  75. return
  76. }
  77. a.xrayMetricsService.Sample(time.Now())
  78. websocket.BroadcastStatus(status)
  79. })
  80. c.AddFunc("@every 1m", func() {
  81. if err := service.PersistSystemMetrics(); err != nil {
  82. logger.Warning("persist system metrics failed:", err)
  83. }
  84. })
  85. }
  86. // status returns the current server status information.
  87. func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.serverService.LastStatus(), nil) }
  88. func parseHistoryBucket(c *gin.Context) (int, bool) {
  89. bucket, err := strconv.Atoi(c.Param("bucket"))
  90. if err != nil || bucket <= 0 || !service.IsAllowedHistoryBucket(bucket) {
  91. jsonMsg(c, "invalid bucket", fmt.Errorf("unsupported bucket"))
  92. return 0, false
  93. }
  94. return bucket, true
  95. }
  96. // getCpuHistoryBucket retrieves aggregated CPU usage history based on the specified time bucket.
  97. // Kept for back-compat; new callers should use /history/cpu/:bucket which
  98. // returns {"t","v"} (uniform across all metrics) instead of {"t","cpu"}.
  99. func (a *ServerController) getCpuHistoryBucket(c *gin.Context) {
  100. bucket, ok := parseHistoryBucket(c)
  101. if !ok {
  102. return
  103. }
  104. jsonObj(c, a.serverService.AggregateCpuHistory(bucket, 60), nil)
  105. }
  106. // getMetricHistoryBucket returns up to 60 buckets of history for a single
  107. // system metric (cpu, mem, netUp, netDown, online, load1/5/15). The
  108. // SystemHistoryModal calls one endpoint per active tab.
  109. func (a *ServerController) getMetricHistoryBucket(c *gin.Context) {
  110. metric := c.Param("metric")
  111. if !slices.Contains(service.SystemMetricKeys, metric) {
  112. jsonMsg(c, "invalid metric", fmt.Errorf("unknown metric"))
  113. return
  114. }
  115. bucket, ok := parseHistoryBucket(c)
  116. if !ok {
  117. return
  118. }
  119. jsonObj(c, a.serverService.AggregateSystemMetric(metric, bucket, 60), nil)
  120. }
  121. func (a *ServerController) getXrayMetricsState(c *gin.Context) {
  122. jsonObj(c, a.xrayMetricsService.State(), nil)
  123. }
  124. func (a *ServerController) getXrayMetricsHistoryBucket(c *gin.Context) {
  125. metric := c.Param("metric")
  126. if !slices.Contains(service.XrayMetricKeys, metric) {
  127. jsonMsg(c, "invalid metric", fmt.Errorf("unknown metric"))
  128. return
  129. }
  130. bucket, ok := parseHistoryBucket(c)
  131. if !ok {
  132. return
  133. }
  134. jsonObj(c, a.xrayMetricsService.AggregateMetric(metric, bucket, 60), nil)
  135. }
  136. func (a *ServerController) getXrayObservatory(c *gin.Context) {
  137. jsonObj(c, a.xrayMetricsService.ObservatorySnapshot(), nil)
  138. }
  139. func (a *ServerController) getXrayObservatoryHistoryBucket(c *gin.Context) {
  140. tag := c.Param("tag")
  141. if !a.xrayMetricsService.HasObservatoryTag(tag) {
  142. jsonMsg(c, "invalid tag", fmt.Errorf("unknown observatory tag"))
  143. return
  144. }
  145. bucket, ok := parseHistoryBucket(c)
  146. if !ok {
  147. return
  148. }
  149. jsonObj(c, a.xrayMetricsService.AggregateObservatory(tag, bucket, 60), nil)
  150. }
  151. func (a *ServerController) getXrayVersion(c *gin.Context) {
  152. versions, err := a.serverService.GetXrayVersionsCached()
  153. if err != nil {
  154. jsonMsg(c, I18nWeb(c, "getVersion"), err)
  155. return
  156. }
  157. jsonObj(c, versions, nil)
  158. }
  159. // getPanelUpdateInfo retrieves the current and latest panel version.
  160. func (a *ServerController) getPanelUpdateInfo(c *gin.Context) {
  161. info, err := a.panelService.GetUpdateInfo()
  162. if err != nil {
  163. logger.Debug("panel update check failed:", err)
  164. c.JSON(http.StatusOK, entity.Msg{Success: false})
  165. return
  166. }
  167. jsonObj(c, info, nil)
  168. }
  169. // installXray installs or updates Xray to the specified version.
  170. func (a *ServerController) installXray(c *gin.Context) {
  171. version := c.Param("version")
  172. err := a.serverService.UpdateXray(version)
  173. jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
  174. }
  175. // updatePanel starts a panel self-update to the latest release.
  176. func (a *ServerController) updatePanel(c *gin.Context) {
  177. err := a.panelService.StartUpdate()
  178. jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
  179. }
  180. // updateGeofile updates the specified geo file for Xray.
  181. func (a *ServerController) updateGeofile(c *gin.Context) {
  182. fileName := c.Param("fileName")
  183. if fileName != "" && !a.serverService.IsValidGeofileName(fileName) {
  184. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"),
  185. fmt.Errorf("invalid filename: contains unsafe characters or path traversal patterns"))
  186. return
  187. }
  188. err := a.serverService.UpdateGeofile(fileName)
  189. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"), err)
  190. }
  191. // stopXrayService stops the Xray service.
  192. func (a *ServerController) stopXrayService(c *gin.Context) {
  193. err := a.serverService.StopXrayService()
  194. if err != nil {
  195. jsonMsg(c, I18nWeb(c, "pages.xray.stopError"), err)
  196. websocket.BroadcastXrayState("error", err.Error())
  197. return
  198. }
  199. jsonMsg(c, I18nWeb(c, "pages.xray.stopSuccess"), err)
  200. websocket.BroadcastXrayState("stop", "")
  201. websocket.BroadcastNotification(
  202. I18nWeb(c, "pages.xray.stopSuccess"),
  203. "Xray service has been stopped",
  204. "warning",
  205. )
  206. }
  207. // restartXrayService restarts the Xray service.
  208. func (a *ServerController) restartXrayService(c *gin.Context) {
  209. err := a.serverService.RestartXrayService()
  210. if err != nil {
  211. jsonMsg(c, I18nWeb(c, "pages.xray.restartError"), err)
  212. websocket.BroadcastXrayState("error", err.Error())
  213. return
  214. }
  215. jsonMsg(c, I18nWeb(c, "pages.xray.restartSuccess"), err)
  216. websocket.BroadcastXrayState("running", "")
  217. websocket.BroadcastNotification(
  218. I18nWeb(c, "pages.xray.restartSuccess"),
  219. "Xray service has been restarted successfully",
  220. "success",
  221. )
  222. }
  223. // getLogs retrieves the application logs based on count, level, and syslog filters.
  224. func (a *ServerController) getLogs(c *gin.Context) {
  225. logs := a.serverService.GetLogs(c.Param("count"), c.PostForm("level"), c.PostForm("syslog"))
  226. jsonObj(c, logs, nil)
  227. }
  228. // getXrayLogs retrieves Xray logs with filtering options for direct, blocked, and proxy traffic.
  229. func (a *ServerController) getXrayLogs(c *gin.Context) {
  230. freedoms, blackholes := a.serverService.GetDefaultLogOutboundTags()
  231. logs := a.serverService.GetXrayLogs(
  232. c.Param("count"),
  233. c.PostForm("filter"),
  234. c.PostForm("showDirect"),
  235. c.PostForm("showBlocked"),
  236. c.PostForm("showProxy"),
  237. freedoms,
  238. blackholes,
  239. )
  240. jsonObj(c, logs, nil)
  241. }
  242. // getConfigJson retrieves the Xray configuration as JSON.
  243. func (a *ServerController) getConfigJson(c *gin.Context) {
  244. configJson, err := a.serverService.GetConfigJson()
  245. if err != nil {
  246. jsonMsg(c, I18nWeb(c, "pages.index.getConfigError"), err)
  247. return
  248. }
  249. jsonObj(c, configJson, nil)
  250. }
  251. // getDb downloads the database file.
  252. func (a *ServerController) getDb(c *gin.Context) {
  253. db, err := a.serverService.GetDb()
  254. if err != nil {
  255. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  256. return
  257. }
  258. filename := "x-ui.db"
  259. if database.IsPostgres() {
  260. filename = "x-ui.dump"
  261. }
  262. if !filenameRegex.MatchString(filename) {
  263. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  264. return
  265. }
  266. c.Header("Content-Type", "application/octet-stream")
  267. c.Header("Content-Disposition", "attachment; filename="+filename)
  268. c.Writer.Write(db)
  269. }
  270. // getMigration downloads a cross-engine migration file: a .dump on SQLite or a
  271. // .db SQLite database on PostgreSQL, so the data can seed the other backend.
  272. func (a *ServerController) getMigration(c *gin.Context) {
  273. data, filename, err := a.serverService.GetMigration()
  274. if err != nil {
  275. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  276. return
  277. }
  278. if !filenameRegex.MatchString(filename) {
  279. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  280. return
  281. }
  282. c.Header("Content-Type", "application/octet-stream")
  283. c.Header("Content-Disposition", "attachment; filename="+filename)
  284. c.Writer.Write(data)
  285. }
  286. // importDB imports a database file and restarts the Xray service.
  287. func (a *ServerController) importDB(c *gin.Context) {
  288. file, _, err := c.Request.FormFile("db")
  289. if err != nil {
  290. jsonMsg(c, I18nWeb(c, "pages.index.readDatabaseError"), err)
  291. return
  292. }
  293. defer file.Close()
  294. if err := a.serverService.ImportDB(file); err != nil {
  295. jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
  296. return
  297. }
  298. jsonObj(c, I18nWeb(c, "pages.index.importDatabaseSuccess"), nil)
  299. }
  300. // descendants publishes read-only summaries of the nodes this panel manages so
  301. // a parent panel can surface them as transitive sub-nodes in a chained
  302. // topology. Called by the parent via the node's API token (#4983).
  303. func (a *ServerController) descendants(c *gin.Context) {
  304. data, err := (&service.NodeService{}).LocalDescendants()
  305. jsonObj(c, data, err)
  306. }
  307. // getWebCertFiles returns this panel's own web TLS certificate and key file
  308. // paths. The central panel calls it on a node (via the node's API token) so
  309. // "Set Cert from Panel" can fill a node-assigned inbound with paths that exist
  310. // on the node's filesystem instead of the central panel's — see issue #4854.
  311. func (a *ServerController) getWebCertFiles(c *gin.Context) {
  312. certFile, err := a.settingService.GetCertFile()
  313. if err != nil {
  314. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  315. return
  316. }
  317. keyFile, err := a.settingService.GetKeyFile()
  318. if err != nil {
  319. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  320. return
  321. }
  322. jsonObj(c, gin.H{"webCertFile": certFile, "webKeyFile": keyFile}, nil)
  323. }
  324. // getNewX25519Cert generates a new X25519 certificate.
  325. func (a *ServerController) getNewX25519Cert(c *gin.Context) {
  326. cert, err := a.serverService.GetNewX25519Cert()
  327. if err != nil {
  328. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewX25519CertError"), err)
  329. return
  330. }
  331. jsonObj(c, cert, nil)
  332. }
  333. // getNewmldsa65 generates a new ML-DSA-65 key.
  334. func (a *ServerController) getNewmldsa65(c *gin.Context) {
  335. cert, err := a.serverService.GetNewmldsa65()
  336. if err != nil {
  337. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewmldsa65Error"), err)
  338. return
  339. }
  340. jsonObj(c, cert, nil)
  341. }
  342. // getNewEchCert generates a new ECH certificate for the given SNI.
  343. func (a *ServerController) getNewEchCert(c *gin.Context) {
  344. cert, err := a.serverService.GetNewEchCert(c.PostForm("sni"))
  345. if err != nil {
  346. jsonMsg(c, "get ech certificate", err)
  347. return
  348. }
  349. jsonObj(c, cert, nil)
  350. }
  351. // getNewVlessEnc generates a new VLESS encryption key.
  352. func (a *ServerController) getNewVlessEnc(c *gin.Context) {
  353. out, err := a.serverService.GetNewVlessEnc()
  354. if err != nil {
  355. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewVlessEncError"), err)
  356. return
  357. }
  358. jsonObj(c, out, nil)
  359. }
  360. // getNewUUID generates a new UUID.
  361. func (a *ServerController) getNewUUID(c *gin.Context) {
  362. uuidResp, err := a.serverService.GetNewUUID()
  363. if err != nil {
  364. jsonMsg(c, "Failed to generate UUID", err)
  365. return
  366. }
  367. jsonObj(c, uuidResp, nil)
  368. }
  369. // getNewmlkem768 generates a new ML-KEM-768 key.
  370. func (a *ServerController) getNewmlkem768(c *gin.Context) {
  371. out, err := a.serverService.GetNewmlkem768()
  372. if err != nil {
  373. jsonMsg(c, "Failed to generate mlkem768 keys", err)
  374. return
  375. }
  376. jsonObj(c, out, nil)
  377. }