server.go 11 KB

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