1
0

server.go 11 KB

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