server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. lastStatus *service.Status
  24. lastVersions []string
  25. lastGetVersionsTime int64 // unix seconds
  26. }
  27. // NewServerController creates a new ServerController, initializes routes, and starts background tasks.
  28. func NewServerController(g *gin.RouterGroup) *ServerController {
  29. a := &ServerController{}
  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("/getXrayVersion", a.getXrayVersion)
  40. g.GET("/getPanelUpdateInfo", a.getPanelUpdateInfo)
  41. g.GET("/getConfigJson", a.getConfigJson)
  42. g.GET("/getDb", a.getDb)
  43. g.GET("/getNewUUID", a.getNewUUID)
  44. g.GET("/getNewX25519Cert", a.getNewX25519Cert)
  45. g.GET("/getNewmldsa65", a.getNewmldsa65)
  46. g.GET("/getNewmlkem768", a.getNewmlkem768)
  47. g.GET("/getNewVlessEnc", a.getNewVlessEnc)
  48. g.POST("/stopXrayService", a.stopXrayService)
  49. g.POST("/restartXrayService", a.restartXrayService)
  50. g.POST("/installXray/:version", a.installXray)
  51. g.POST("/updatePanel", a.updatePanel)
  52. g.POST("/updateGeofile", a.updateGeofile)
  53. g.POST("/updateGeofile/:fileName", a.updateGeofile)
  54. g.POST("/logs/:count", a.getLogs)
  55. g.POST("/xraylogs/:count", a.getXrayLogs)
  56. g.POST("/importDB", a.importDB)
  57. g.POST("/getNewEchCert", a.getNewEchCert)
  58. }
  59. // refreshStatus updates the cached server status and collects time-series
  60. // metrics. CPU/Mem/Net/Online/Load are all written in one call so the
  61. // SystemHistoryModal's tabs share an identical x-axis.
  62. func (a *ServerController) refreshStatus() {
  63. a.lastStatus = a.serverService.GetStatus(a.lastStatus)
  64. if a.lastStatus != nil {
  65. a.serverService.AppendStatusSample(time.Now(), a.lastStatus)
  66. // Broadcast status update via WebSocket
  67. websocket.BroadcastStatus(a.lastStatus)
  68. }
  69. }
  70. // startTask initiates background tasks for continuous status monitoring.
  71. func (a *ServerController) startTask() {
  72. webServer := global.GetWebServer()
  73. c := webServer.GetCron()
  74. c.AddFunc("@every 2s", func() {
  75. // Always refresh to keep CPU history collected continuously.
  76. // Sampling is lightweight and capped to ~6 hours in memory.
  77. a.refreshStatus()
  78. })
  79. }
  80. // status returns the current server status information.
  81. func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.lastStatus, nil) }
  82. // allowedHistoryBuckets is the bucket-second whitelist shared by both
  83. // /cpuHistory/:bucket and /history/:metric/:bucket. Restricting it
  84. // prevents callers from triggering arbitrary aggregation work and keeps
  85. // the front-end's bucket selector self-documenting.
  86. var allowedHistoryBuckets = map[int]bool{
  87. 2: true, // Real-time view
  88. 30: true, // 30s intervals
  89. 60: true, // 1m intervals
  90. 120: true, // 2m intervals
  91. 180: true, // 3m intervals
  92. 300: true, // 5m intervals
  93. }
  94. // getCpuHistoryBucket retrieves aggregated CPU usage history based on the specified time bucket.
  95. // Kept for back-compat; new callers should use /history/cpu/:bucket which
  96. // returns {"t","v"} (uniform across all metrics) instead of {"t","cpu"}.
  97. func (a *ServerController) getCpuHistoryBucket(c *gin.Context) {
  98. bucketStr := c.Param("bucket")
  99. bucket, err := strconv.Atoi(bucketStr)
  100. if err != nil || bucket <= 0 {
  101. jsonMsg(c, "invalid bucket", fmt.Errorf("bad bucket"))
  102. return
  103. }
  104. if !allowedHistoryBuckets[bucket] {
  105. jsonMsg(c, "invalid bucket", fmt.Errorf("unsupported bucket"))
  106. return
  107. }
  108. points := a.serverService.AggregateCpuHistory(bucket, 60)
  109. jsonObj(c, points, nil)
  110. }
  111. // getMetricHistoryBucket returns up to 60 buckets of history for a single
  112. // system metric (cpu, mem, netUp, netDown, online, load1/5/15). The
  113. // SystemHistoryModal calls one endpoint per active tab.
  114. func (a *ServerController) getMetricHistoryBucket(c *gin.Context) {
  115. metric := c.Param("metric")
  116. if !slices.Contains(service.SystemMetricKeys, metric) {
  117. jsonMsg(c, "invalid metric", fmt.Errorf("unknown metric"))
  118. return
  119. }
  120. bucket, err := strconv.Atoi(c.Param("bucket"))
  121. if err != nil || bucket <= 0 || !allowedHistoryBuckets[bucket] {
  122. jsonMsg(c, "invalid bucket", fmt.Errorf("unsupported bucket"))
  123. return
  124. }
  125. jsonObj(c, a.serverService.AggregateSystemMetric(metric, bucket, 60), nil)
  126. }
  127. func (a *ServerController) getXrayVersion(c *gin.Context) {
  128. const cacheTTLSeconds = 15 * 60
  129. now := time.Now().Unix()
  130. if a.lastVersions != nil && now-a.lastGetVersionsTime <= cacheTTLSeconds {
  131. jsonObj(c, a.lastVersions, nil)
  132. return
  133. }
  134. versions, err := a.serverService.GetXrayVersions()
  135. if err != nil {
  136. if a.lastVersions != nil {
  137. logger.Warning("getXrayVersion failed; serving cached list:", err)
  138. jsonObj(c, a.lastVersions, nil)
  139. return
  140. }
  141. jsonMsg(c, I18nWeb(c, "getVersion"), err)
  142. return
  143. }
  144. a.lastVersions = versions
  145. a.lastGetVersionsTime = now
  146. jsonObj(c, versions, nil)
  147. }
  148. // getPanelUpdateInfo retrieves the current and latest panel version.
  149. func (a *ServerController) getPanelUpdateInfo(c *gin.Context) {
  150. info, err := a.panelService.GetUpdateInfo()
  151. if err != nil {
  152. logger.Debug("panel update check failed:", err)
  153. c.JSON(http.StatusOK, entity.Msg{Success: false})
  154. return
  155. }
  156. jsonObj(c, info, nil)
  157. }
  158. // installXray installs or updates Xray to the specified version.
  159. func (a *ServerController) installXray(c *gin.Context) {
  160. version := c.Param("version")
  161. err := a.serverService.UpdateXray(version)
  162. jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
  163. }
  164. // updatePanel starts a panel self-update to the latest release.
  165. func (a *ServerController) updatePanel(c *gin.Context) {
  166. err := a.panelService.StartUpdate()
  167. jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
  168. }
  169. // updateGeofile updates the specified geo file for Xray.
  170. func (a *ServerController) updateGeofile(c *gin.Context) {
  171. fileName := c.Param("fileName")
  172. // Validate the filename for security (prevent path traversal attacks)
  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. count := c.Param("count")
  216. level := c.PostForm("level")
  217. syslog := c.PostForm("syslog")
  218. logs := a.serverService.GetLogs(count, level, syslog)
  219. jsonObj(c, logs, nil)
  220. }
  221. // getXrayLogs retrieves Xray logs with filtering options for direct, blocked, and proxy traffic.
  222. func (a *ServerController) getXrayLogs(c *gin.Context) {
  223. count := c.Param("count")
  224. filter := c.PostForm("filter")
  225. showDirect := c.PostForm("showDirect")
  226. showBlocked := c.PostForm("showBlocked")
  227. showProxy := c.PostForm("showProxy")
  228. var freedoms []string
  229. var blackholes []string
  230. //getting tags for freedom and blackhole outbounds
  231. config, err := a.settingService.GetDefaultXrayConfig()
  232. if err == nil && config != nil {
  233. if cfgMap, ok := config.(map[string]any); ok {
  234. if outbounds, ok := cfgMap["outbounds"].([]any); ok {
  235. for _, outbound := range outbounds {
  236. if obMap, ok := outbound.(map[string]any); ok {
  237. switch obMap["protocol"] {
  238. case "freedom":
  239. if tag, ok := obMap["tag"].(string); ok {
  240. freedoms = append(freedoms, tag)
  241. }
  242. case "blackhole":
  243. if tag, ok := obMap["tag"].(string); ok {
  244. blackholes = append(blackholes, tag)
  245. }
  246. }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. if len(freedoms) == 0 {
  253. freedoms = []string{"direct"}
  254. }
  255. if len(blackholes) == 0 {
  256. blackholes = []string{"blocked"}
  257. }
  258. logs := a.serverService.GetXrayLogs(count, filter, showDirect, showBlocked, showProxy, freedoms, blackholes)
  259. jsonObj(c, logs, nil)
  260. }
  261. // getConfigJson retrieves the Xray configuration as JSON.
  262. func (a *ServerController) getConfigJson(c *gin.Context) {
  263. configJson, err := a.serverService.GetConfigJson()
  264. if err != nil {
  265. jsonMsg(c, I18nWeb(c, "pages.index.getConfigError"), err)
  266. return
  267. }
  268. jsonObj(c, configJson, nil)
  269. }
  270. // getDb downloads the database file.
  271. func (a *ServerController) getDb(c *gin.Context) {
  272. db, err := a.serverService.GetDb()
  273. if err != nil {
  274. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  275. return
  276. }
  277. filename := "x-ui.db"
  278. if !isValidFilename(filename) {
  279. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  280. return
  281. }
  282. // Set the headers for the response
  283. c.Header("Content-Type", "application/octet-stream")
  284. c.Header("Content-Disposition", "attachment; filename="+filename)
  285. // Write the file contents to the response
  286. c.Writer.Write(db)
  287. }
  288. func isValidFilename(filename string) bool {
  289. // Validate that the filename only contains allowed characters
  290. return filenameRegex.MatchString(filename)
  291. }
  292. // importDB imports a database file and restarts the Xray service.
  293. func (a *ServerController) importDB(c *gin.Context) {
  294. // Get the file from the request body
  295. file, _, err := c.Request.FormFile("db")
  296. if err != nil {
  297. jsonMsg(c, I18nWeb(c, "pages.index.readDatabaseError"), err)
  298. return
  299. }
  300. defer file.Close()
  301. // Always restart Xray before return
  302. defer a.serverService.RestartXrayService()
  303. // lastGetStatusTime removed; no longer needed
  304. // Import it
  305. err = a.serverService.ImportDB(file)
  306. if err != nil {
  307. jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
  308. return
  309. }
  310. jsonObj(c, I18nWeb(c, "pages.index.importDatabaseSuccess"), nil)
  311. }
  312. // getNewX25519Cert generates a new X25519 certificate.
  313. func (a *ServerController) getNewX25519Cert(c *gin.Context) {
  314. cert, err := a.serverService.GetNewX25519Cert()
  315. if err != nil {
  316. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewX25519CertError"), err)
  317. return
  318. }
  319. jsonObj(c, cert, nil)
  320. }
  321. // getNewmldsa65 generates a new ML-DSA-65 key.
  322. func (a *ServerController) getNewmldsa65(c *gin.Context) {
  323. cert, err := a.serverService.GetNewmldsa65()
  324. if err != nil {
  325. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewmldsa65Error"), err)
  326. return
  327. }
  328. jsonObj(c, cert, nil)
  329. }
  330. // getNewEchCert generates a new ECH certificate for the given SNI.
  331. func (a *ServerController) getNewEchCert(c *gin.Context) {
  332. sni := c.PostForm("sni")
  333. cert, err := a.serverService.GetNewEchCert(sni)
  334. if err != nil {
  335. jsonMsg(c, "get ech certificate", err)
  336. return
  337. }
  338. jsonObj(c, cert, nil)
  339. }
  340. // getNewVlessEnc generates a new VLESS encryption key.
  341. func (a *ServerController) getNewVlessEnc(c *gin.Context) {
  342. out, err := a.serverService.GetNewVlessEnc()
  343. if err != nil {
  344. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewVlessEncError"), err)
  345. return
  346. }
  347. jsonObj(c, out, nil)
  348. }
  349. // getNewUUID generates a new UUID.
  350. func (a *ServerController) getNewUUID(c *gin.Context) {
  351. uuidResp, err := a.serverService.GetNewUUID()
  352. if err != nil {
  353. jsonMsg(c, "Failed to generate UUID", err)
  354. return
  355. }
  356. jsonObj(c, uuidResp, nil)
  357. }
  358. // getNewmlkem768 generates a new ML-KEM-768 key.
  359. func (a *ServerController) getNewmlkem768(c *gin.Context) {
  360. out, err := a.serverService.GetNewmlkem768()
  361. if err != nil {
  362. jsonMsg(c, "Failed to generate mlkem768 keys", err)
  363. return
  364. }
  365. jsonObj(c, out, nil)
  366. }