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/v2/logger"
  10. "github.com/mhsanaei/3x-ui/v2/web/entity"
  11. "github.com/mhsanaei/3x-ui/v2/web/global"
  12. "github.com/mhsanaei/3x-ui/v2/web/service"
  13. "github.com/mhsanaei/3x-ui/v2/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. // getXrayVersion retrieves available Xray versions, with caching for 1 minute.
  128. func (a *ServerController) getXrayVersion(c *gin.Context) {
  129. now := time.Now().Unix()
  130. if now-a.lastGetVersionsTime <= 60 { // 1 minute cache
  131. jsonObj(c, a.lastVersions, nil)
  132. return
  133. }
  134. versions, err := a.serverService.GetXrayVersions()
  135. if err != nil {
  136. jsonMsg(c, I18nWeb(c, "getVersion"), err)
  137. return
  138. }
  139. a.lastVersions = versions
  140. a.lastGetVersionsTime = now
  141. jsonObj(c, versions, nil)
  142. }
  143. // getPanelUpdateInfo retrieves the current and latest panel version.
  144. // Network failures (e.g. no internet, GitHub blocked) are logged at debug
  145. // level only — the panel keeps working offline and we don't want to spam
  146. // WARN every time a user opens the page.
  147. func (a *ServerController) getPanelUpdateInfo(c *gin.Context) {
  148. info, err := a.panelService.GetUpdateInfo()
  149. if err != nil {
  150. logger.Debug("panel update check failed:", err)
  151. c.JSON(http.StatusOK, entity.Msg{
  152. Success: false,
  153. Msg: I18nWeb(c, "pages.index.panelUpdateCheckPopover"),
  154. })
  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. // Validate the filename for security (prevent path traversal attacks)
  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. count := c.Param("count")
  217. level := c.PostForm("level")
  218. syslog := c.PostForm("syslog")
  219. logs := a.serverService.GetLogs(count, level, syslog)
  220. jsonObj(c, logs, nil)
  221. }
  222. // getXrayLogs retrieves Xray logs with filtering options for direct, blocked, and proxy traffic.
  223. func (a *ServerController) getXrayLogs(c *gin.Context) {
  224. count := c.Param("count")
  225. filter := c.PostForm("filter")
  226. showDirect := c.PostForm("showDirect")
  227. showBlocked := c.PostForm("showBlocked")
  228. showProxy := c.PostForm("showProxy")
  229. var freedoms []string
  230. var blackholes []string
  231. //getting tags for freedom and blackhole outbounds
  232. config, err := a.settingService.GetDefaultXrayConfig()
  233. if err == nil && config != nil {
  234. if cfgMap, ok := config.(map[string]any); ok {
  235. if outbounds, ok := cfgMap["outbounds"].([]any); ok {
  236. for _, outbound := range outbounds {
  237. if obMap, ok := outbound.(map[string]any); ok {
  238. switch obMap["protocol"] {
  239. case "freedom":
  240. if tag, ok := obMap["tag"].(string); ok {
  241. freedoms = append(freedoms, tag)
  242. }
  243. case "blackhole":
  244. if tag, ok := obMap["tag"].(string); ok {
  245. blackholes = append(blackholes, tag)
  246. }
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }
  253. if len(freedoms) == 0 {
  254. freedoms = []string{"direct"}
  255. }
  256. if len(blackholes) == 0 {
  257. blackholes = []string{"blocked"}
  258. }
  259. logs := a.serverService.GetXrayLogs(count, filter, showDirect, showBlocked, showProxy, freedoms, blackholes)
  260. jsonObj(c, logs, nil)
  261. }
  262. // getConfigJson retrieves the Xray configuration as JSON.
  263. func (a *ServerController) getConfigJson(c *gin.Context) {
  264. configJson, err := a.serverService.GetConfigJson()
  265. if err != nil {
  266. jsonMsg(c, I18nWeb(c, "pages.index.getConfigError"), err)
  267. return
  268. }
  269. jsonObj(c, configJson, nil)
  270. }
  271. // getDb downloads the database file.
  272. func (a *ServerController) getDb(c *gin.Context) {
  273. db, err := a.serverService.GetDb()
  274. if err != nil {
  275. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  276. return
  277. }
  278. filename := "x-ui.db"
  279. if !isValidFilename(filename) {
  280. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  281. return
  282. }
  283. // Set the headers for the response
  284. c.Header("Content-Type", "application/octet-stream")
  285. c.Header("Content-Disposition", "attachment; filename="+filename)
  286. // Write the file contents to the response
  287. c.Writer.Write(db)
  288. }
  289. func isValidFilename(filename string) bool {
  290. // Validate that the filename only contains allowed characters
  291. return filenameRegex.MatchString(filename)
  292. }
  293. // importDB imports a database file and restarts the Xray service.
  294. func (a *ServerController) importDB(c *gin.Context) {
  295. // Get the file from the request body
  296. file, _, err := c.Request.FormFile("db")
  297. if err != nil {
  298. jsonMsg(c, I18nWeb(c, "pages.index.readDatabaseError"), err)
  299. return
  300. }
  301. defer file.Close()
  302. // Always restart Xray before return
  303. defer a.serverService.RestartXrayService()
  304. // lastGetStatusTime removed; no longer needed
  305. // Import it
  306. err = a.serverService.ImportDB(file)
  307. if err != nil {
  308. jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
  309. return
  310. }
  311. jsonObj(c, I18nWeb(c, "pages.index.importDatabaseSuccess"), nil)
  312. }
  313. // getNewX25519Cert generates a new X25519 certificate.
  314. func (a *ServerController) getNewX25519Cert(c *gin.Context) {
  315. cert, err := a.serverService.GetNewX25519Cert()
  316. if err != nil {
  317. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewX25519CertError"), err)
  318. return
  319. }
  320. jsonObj(c, cert, nil)
  321. }
  322. // getNewmldsa65 generates a new ML-DSA-65 key.
  323. func (a *ServerController) getNewmldsa65(c *gin.Context) {
  324. cert, err := a.serverService.GetNewmldsa65()
  325. if err != nil {
  326. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewmldsa65Error"), err)
  327. return
  328. }
  329. jsonObj(c, cert, nil)
  330. }
  331. // getNewEchCert generates a new ECH certificate for the given SNI.
  332. func (a *ServerController) getNewEchCert(c *gin.Context) {
  333. sni := c.PostForm("sni")
  334. cert, err := a.serverService.GetNewEchCert(sni)
  335. if err != nil {
  336. jsonMsg(c, "get ech certificate", err)
  337. return
  338. }
  339. jsonObj(c, cert, nil)
  340. }
  341. // getNewVlessEnc generates a new VLESS encryption key.
  342. func (a *ServerController) getNewVlessEnc(c *gin.Context) {
  343. out, err := a.serverService.GetNewVlessEnc()
  344. if err != nil {
  345. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewVlessEncError"), err)
  346. return
  347. }
  348. jsonObj(c, out, nil)
  349. }
  350. // getNewUUID generates a new UUID.
  351. func (a *ServerController) getNewUUID(c *gin.Context) {
  352. uuidResp, err := a.serverService.GetNewUUID()
  353. if err != nil {
  354. jsonMsg(c, "Failed to generate UUID", err)
  355. return
  356. }
  357. jsonObj(c, uuidResp, nil)
  358. }
  359. // getNewmlkem768 generates a new ML-KEM-768 key.
  360. func (a *ServerController) getNewmlkem768(c *gin.Context) {
  361. out, err := a.serverService.GetNewmlkem768()
  362. if err != nil {
  363. jsonMsg(c, "Failed to generate mlkem768 keys", err)
  364. return
  365. }
  366. jsonObj(c, out, nil)
  367. }