1
0

server.go 13 KB

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