1
0

server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. func (a *ServerController) getPanelUpdateInfo(c *gin.Context) {
  145. info, err := a.panelService.GetUpdateInfo()
  146. if err != nil {
  147. logger.Debug("panel update check failed:", err)
  148. c.JSON(http.StatusOK, entity.Msg{Success: false})
  149. return
  150. }
  151. jsonObj(c, info, nil)
  152. }
  153. // installXray installs or updates Xray to the specified version.
  154. func (a *ServerController) installXray(c *gin.Context) {
  155. version := c.Param("version")
  156. err := a.serverService.UpdateXray(version)
  157. jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
  158. }
  159. // updatePanel starts a panel self-update to the latest release.
  160. func (a *ServerController) updatePanel(c *gin.Context) {
  161. err := a.panelService.StartUpdate()
  162. jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
  163. }
  164. // updateGeofile updates the specified geo file for Xray.
  165. func (a *ServerController) updateGeofile(c *gin.Context) {
  166. fileName := c.Param("fileName")
  167. // Validate the filename for security (prevent path traversal attacks)
  168. if fileName != "" && !a.serverService.IsValidGeofileName(fileName) {
  169. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"),
  170. fmt.Errorf("invalid filename: contains unsafe characters or path traversal patterns"))
  171. return
  172. }
  173. err := a.serverService.UpdateGeofile(fileName)
  174. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"), err)
  175. }
  176. // stopXrayService stops the Xray service.
  177. func (a *ServerController) stopXrayService(c *gin.Context) {
  178. err := a.serverService.StopXrayService()
  179. if err != nil {
  180. jsonMsg(c, I18nWeb(c, "pages.xray.stopError"), err)
  181. websocket.BroadcastXrayState("error", err.Error())
  182. return
  183. }
  184. jsonMsg(c, I18nWeb(c, "pages.xray.stopSuccess"), err)
  185. websocket.BroadcastXrayState("stop", "")
  186. websocket.BroadcastNotification(
  187. I18nWeb(c, "pages.xray.stopSuccess"),
  188. "Xray service has been stopped",
  189. "warning",
  190. )
  191. }
  192. // restartXrayService restarts the Xray service.
  193. func (a *ServerController) restartXrayService(c *gin.Context) {
  194. err := a.serverService.RestartXrayService()
  195. if err != nil {
  196. jsonMsg(c, I18nWeb(c, "pages.xray.restartError"), err)
  197. websocket.BroadcastXrayState("error", err.Error())
  198. return
  199. }
  200. jsonMsg(c, I18nWeb(c, "pages.xray.restartSuccess"), err)
  201. websocket.BroadcastXrayState("running", "")
  202. websocket.BroadcastNotification(
  203. I18nWeb(c, "pages.xray.restartSuccess"),
  204. "Xray service has been restarted successfully",
  205. "success",
  206. )
  207. }
  208. // getLogs retrieves the application logs based on count, level, and syslog filters.
  209. func (a *ServerController) getLogs(c *gin.Context) {
  210. count := c.Param("count")
  211. level := c.PostForm("level")
  212. syslog := c.PostForm("syslog")
  213. logs := a.serverService.GetLogs(count, level, syslog)
  214. jsonObj(c, logs, nil)
  215. }
  216. // getXrayLogs retrieves Xray logs with filtering options for direct, blocked, and proxy traffic.
  217. func (a *ServerController) getXrayLogs(c *gin.Context) {
  218. count := c.Param("count")
  219. filter := c.PostForm("filter")
  220. showDirect := c.PostForm("showDirect")
  221. showBlocked := c.PostForm("showBlocked")
  222. showProxy := c.PostForm("showProxy")
  223. var freedoms []string
  224. var blackholes []string
  225. //getting tags for freedom and blackhole outbounds
  226. config, err := a.settingService.GetDefaultXrayConfig()
  227. if err == nil && config != nil {
  228. if cfgMap, ok := config.(map[string]any); ok {
  229. if outbounds, ok := cfgMap["outbounds"].([]any); ok {
  230. for _, outbound := range outbounds {
  231. if obMap, ok := outbound.(map[string]any); ok {
  232. switch obMap["protocol"] {
  233. case "freedom":
  234. if tag, ok := obMap["tag"].(string); ok {
  235. freedoms = append(freedoms, tag)
  236. }
  237. case "blackhole":
  238. if tag, ok := obMap["tag"].(string); ok {
  239. blackholes = append(blackholes, tag)
  240. }
  241. }
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if len(freedoms) == 0 {
  248. freedoms = []string{"direct"}
  249. }
  250. if len(blackholes) == 0 {
  251. blackholes = []string{"blocked"}
  252. }
  253. logs := a.serverService.GetXrayLogs(count, filter, showDirect, showBlocked, showProxy, freedoms, blackholes)
  254. jsonObj(c, logs, nil)
  255. }
  256. // getConfigJson retrieves the Xray configuration as JSON.
  257. func (a *ServerController) getConfigJson(c *gin.Context) {
  258. configJson, err := a.serverService.GetConfigJson()
  259. if err != nil {
  260. jsonMsg(c, I18nWeb(c, "pages.index.getConfigError"), err)
  261. return
  262. }
  263. jsonObj(c, configJson, nil)
  264. }
  265. // getDb downloads the database file.
  266. func (a *ServerController) getDb(c *gin.Context) {
  267. db, err := a.serverService.GetDb()
  268. if err != nil {
  269. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  270. return
  271. }
  272. filename := "x-ui.db"
  273. if !isValidFilename(filename) {
  274. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  275. return
  276. }
  277. // Set the headers for the response
  278. c.Header("Content-Type", "application/octet-stream")
  279. c.Header("Content-Disposition", "attachment; filename="+filename)
  280. // Write the file contents to the response
  281. c.Writer.Write(db)
  282. }
  283. func isValidFilename(filename string) bool {
  284. // Validate that the filename only contains allowed characters
  285. return filenameRegex.MatchString(filename)
  286. }
  287. // importDB imports a database file and restarts the Xray service.
  288. func (a *ServerController) importDB(c *gin.Context) {
  289. // Get the file from the request body
  290. file, _, err := c.Request.FormFile("db")
  291. if err != nil {
  292. jsonMsg(c, I18nWeb(c, "pages.index.readDatabaseError"), err)
  293. return
  294. }
  295. defer file.Close()
  296. // Always restart Xray before return
  297. defer a.serverService.RestartXrayService()
  298. // lastGetStatusTime removed; no longer needed
  299. // Import it
  300. err = a.serverService.ImportDB(file)
  301. if err != nil {
  302. jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
  303. return
  304. }
  305. jsonObj(c, I18nWeb(c, "pages.index.importDatabaseSuccess"), nil)
  306. }
  307. // getNewX25519Cert generates a new X25519 certificate.
  308. func (a *ServerController) getNewX25519Cert(c *gin.Context) {
  309. cert, err := a.serverService.GetNewX25519Cert()
  310. if err != nil {
  311. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewX25519CertError"), err)
  312. return
  313. }
  314. jsonObj(c, cert, nil)
  315. }
  316. // getNewmldsa65 generates a new ML-DSA-65 key.
  317. func (a *ServerController) getNewmldsa65(c *gin.Context) {
  318. cert, err := a.serverService.GetNewmldsa65()
  319. if err != nil {
  320. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewmldsa65Error"), err)
  321. return
  322. }
  323. jsonObj(c, cert, nil)
  324. }
  325. // getNewEchCert generates a new ECH certificate for the given SNI.
  326. func (a *ServerController) getNewEchCert(c *gin.Context) {
  327. sni := c.PostForm("sni")
  328. cert, err := a.serverService.GetNewEchCert(sni)
  329. if err != nil {
  330. jsonMsg(c, "get ech certificate", err)
  331. return
  332. }
  333. jsonObj(c, cert, nil)
  334. }
  335. // getNewVlessEnc generates a new VLESS encryption key.
  336. func (a *ServerController) getNewVlessEnc(c *gin.Context) {
  337. out, err := a.serverService.GetNewVlessEnc()
  338. if err != nil {
  339. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewVlessEncError"), err)
  340. return
  341. }
  342. jsonObj(c, out, nil)
  343. }
  344. // getNewUUID generates a new UUID.
  345. func (a *ServerController) getNewUUID(c *gin.Context) {
  346. uuidResp, err := a.serverService.GetNewUUID()
  347. if err != nil {
  348. jsonMsg(c, "Failed to generate UUID", err)
  349. return
  350. }
  351. jsonObj(c, uuidResp, nil)
  352. }
  353. // getNewmlkem768 generates a new ML-KEM-768 key.
  354. func (a *ServerController) getNewmlkem768(c *gin.Context) {
  355. out, err := a.serverService.GetNewmlkem768()
  356. if err != nil {
  357. jsonMsg(c, "Failed to generate mlkem768 keys", err)
  358. return
  359. }
  360. jsonObj(c, out, nil)
  361. }