server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package controller
  2. import (
  3. "fmt"
  4. "net/http"
  5. "regexp"
  6. "strconv"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v2/web/global"
  9. "github.com/mhsanaei/3x-ui/v2/web/service"
  10. "github.com/mhsanaei/3x-ui/v2/web/websocket"
  11. "github.com/gin-gonic/gin"
  12. )
  13. var filenameRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-.]+$`)
  14. // ServerController handles server management and status-related operations.
  15. type ServerController struct {
  16. BaseController
  17. serverService service.ServerService
  18. settingService service.SettingService
  19. lastStatus *service.Status
  20. lastVersions []string
  21. lastGetVersionsTime int64 // unix seconds
  22. }
  23. // NewServerController creates a new ServerController, initializes routes, and starts background tasks.
  24. func NewServerController(g *gin.RouterGroup) *ServerController {
  25. a := &ServerController{}
  26. a.initRouter(g)
  27. a.startTask()
  28. return a
  29. }
  30. // initRouter sets up the routes for server status, Xray management, and utility endpoints.
  31. func (a *ServerController) initRouter(g *gin.RouterGroup) {
  32. g.GET("/status", a.status)
  33. g.GET("/cpuHistory/:bucket", a.getCpuHistoryBucket)
  34. g.GET("/getXrayVersion", a.getXrayVersion)
  35. g.GET("/getConfigJson", a.getConfigJson)
  36. g.GET("/getDb", a.getDb)
  37. g.GET("/getNewUUID", a.getNewUUID)
  38. g.GET("/getNewX25519Cert", a.getNewX25519Cert)
  39. g.GET("/getNewmldsa65", a.getNewmldsa65)
  40. g.GET("/getNewmlkem768", a.getNewmlkem768)
  41. g.GET("/getNewVlessEnc", a.getNewVlessEnc)
  42. g.POST("/stopXrayService", a.stopXrayService)
  43. g.POST("/restartXrayService", a.restartXrayService)
  44. g.POST("/installXray/:version", a.installXray)
  45. g.POST("/updateGeofile", a.updateGeofile)
  46. g.POST("/updateGeofile/:fileName", a.updateGeofile)
  47. g.POST("/logs/:count", a.getLogs)
  48. g.POST("/xraylogs/:count", a.getXrayLogs)
  49. g.POST("/importDB", a.importDB)
  50. g.POST("/getNewEchCert", a.getNewEchCert)
  51. }
  52. // refreshStatus updates the cached server status and collects CPU history.
  53. func (a *ServerController) refreshStatus() {
  54. a.lastStatus = a.serverService.GetStatus(a.lastStatus)
  55. // collect cpu history when status is fresh
  56. if a.lastStatus != nil {
  57. a.serverService.AppendCpuSample(time.Now(), a.lastStatus.Cpu)
  58. // Broadcast status update via WebSocket
  59. websocket.BroadcastStatus(a.lastStatus)
  60. }
  61. }
  62. // startTask initiates background tasks for continuous status monitoring.
  63. func (a *ServerController) startTask() {
  64. webServer := global.GetWebServer()
  65. c := webServer.GetCron()
  66. c.AddFunc("@every 2s", func() {
  67. // Always refresh to keep CPU history collected continuously.
  68. // Sampling is lightweight and capped to ~6 hours in memory.
  69. a.refreshStatus()
  70. })
  71. }
  72. // status returns the current server status information.
  73. func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.lastStatus, nil) }
  74. // getCpuHistoryBucket retrieves aggregated CPU usage history based on the specified time bucket.
  75. func (a *ServerController) getCpuHistoryBucket(c *gin.Context) {
  76. bucketStr := c.Param("bucket")
  77. bucket, err := strconv.Atoi(bucketStr)
  78. if err != nil || bucket <= 0 {
  79. jsonMsg(c, "invalid bucket", fmt.Errorf("bad bucket"))
  80. return
  81. }
  82. allowed := map[int]bool{
  83. 2: true, // Real-time view
  84. 30: true, // 30s intervals
  85. 60: true, // 1m intervals
  86. 120: true, // 2m intervals
  87. 180: true, // 3m intervals
  88. 300: true, // 5m intervals
  89. }
  90. if !allowed[bucket] {
  91. jsonMsg(c, "invalid bucket", fmt.Errorf("unsupported bucket"))
  92. return
  93. }
  94. points := a.serverService.AggregateCpuHistory(bucket, 60)
  95. jsonObj(c, points, nil)
  96. }
  97. // getXrayVersion retrieves available Xray versions, with caching for 1 minute.
  98. func (a *ServerController) getXrayVersion(c *gin.Context) {
  99. now := time.Now().Unix()
  100. if now-a.lastGetVersionsTime <= 60 { // 1 minute cache
  101. jsonObj(c, a.lastVersions, nil)
  102. return
  103. }
  104. versions, err := a.serverService.GetXrayVersions()
  105. if err != nil {
  106. jsonMsg(c, I18nWeb(c, "getVersion"), err)
  107. return
  108. }
  109. a.lastVersions = versions
  110. a.lastGetVersionsTime = now
  111. jsonObj(c, versions, nil)
  112. }
  113. // installXray installs or updates Xray to the specified version.
  114. func (a *ServerController) installXray(c *gin.Context) {
  115. version := c.Param("version")
  116. err := a.serverService.UpdateXray(version)
  117. jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
  118. }
  119. // updateGeofile updates the specified geo file for Xray.
  120. func (a *ServerController) updateGeofile(c *gin.Context) {
  121. fileName := c.Param("fileName")
  122. // Validate the filename for security (prevent path traversal attacks)
  123. if fileName != "" && !a.serverService.IsValidGeofileName(fileName) {
  124. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"),
  125. fmt.Errorf("invalid filename: contains unsafe characters or path traversal patterns"))
  126. return
  127. }
  128. err := a.serverService.UpdateGeofile(fileName)
  129. jsonMsg(c, I18nWeb(c, "pages.index.geofileUpdatePopover"), err)
  130. }
  131. // stopXrayService stops the Xray service.
  132. func (a *ServerController) stopXrayService(c *gin.Context) {
  133. err := a.serverService.StopXrayService()
  134. if err != nil {
  135. jsonMsg(c, I18nWeb(c, "pages.xray.stopError"), err)
  136. websocket.BroadcastXrayState("error", err.Error())
  137. return
  138. }
  139. jsonMsg(c, I18nWeb(c, "pages.xray.stopSuccess"), err)
  140. websocket.BroadcastXrayState("stop", "")
  141. websocket.BroadcastNotification(
  142. I18nWeb(c, "pages.xray.stopSuccess"),
  143. "Xray service has been stopped",
  144. "warning",
  145. )
  146. }
  147. // restartXrayService restarts the Xray service.
  148. func (a *ServerController) restartXrayService(c *gin.Context) {
  149. err := a.serverService.RestartXrayService()
  150. if err != nil {
  151. jsonMsg(c, I18nWeb(c, "pages.xray.restartError"), err)
  152. websocket.BroadcastXrayState("error", err.Error())
  153. return
  154. }
  155. jsonMsg(c, I18nWeb(c, "pages.xray.restartSuccess"), err)
  156. websocket.BroadcastXrayState("running", "")
  157. websocket.BroadcastNotification(
  158. I18nWeb(c, "pages.xray.restartSuccess"),
  159. "Xray service has been restarted successfully",
  160. "success",
  161. )
  162. }
  163. // getLogs retrieves the application logs based on count, level, and syslog filters.
  164. func (a *ServerController) getLogs(c *gin.Context) {
  165. count := c.Param("count")
  166. level := c.PostForm("level")
  167. syslog := c.PostForm("syslog")
  168. logs := a.serverService.GetLogs(count, level, syslog)
  169. jsonObj(c, logs, nil)
  170. }
  171. // getXrayLogs retrieves Xray logs with filtering options for direct, blocked, and proxy traffic.
  172. func (a *ServerController) getXrayLogs(c *gin.Context) {
  173. count := c.Param("count")
  174. filter := c.PostForm("filter")
  175. showDirect := c.PostForm("showDirect")
  176. showBlocked := c.PostForm("showBlocked")
  177. showProxy := c.PostForm("showProxy")
  178. var freedoms []string
  179. var blackholes []string
  180. //getting tags for freedom and blackhole outbounds
  181. config, err := a.settingService.GetDefaultXrayConfig()
  182. if err == nil && config != nil {
  183. if cfgMap, ok := config.(map[string]interface{}); ok {
  184. if outbounds, ok := cfgMap["outbounds"].([]interface{}); ok {
  185. for _, outbound := range outbounds {
  186. if obMap, ok := outbound.(map[string]interface{}); ok {
  187. switch obMap["protocol"] {
  188. case "freedom":
  189. if tag, ok := obMap["tag"].(string); ok {
  190. freedoms = append(freedoms, tag)
  191. }
  192. case "blackhole":
  193. if tag, ok := obMap["tag"].(string); ok {
  194. blackholes = append(blackholes, tag)
  195. }
  196. }
  197. }
  198. }
  199. }
  200. }
  201. }
  202. if len(freedoms) == 0 {
  203. freedoms = []string{"direct"}
  204. }
  205. if len(blackholes) == 0 {
  206. blackholes = []string{"blocked"}
  207. }
  208. logs := a.serverService.GetXrayLogs(count, filter, showDirect, showBlocked, showProxy, freedoms, blackholes)
  209. jsonObj(c, logs, nil)
  210. }
  211. // getConfigJson retrieves the Xray configuration as JSON.
  212. func (a *ServerController) getConfigJson(c *gin.Context) {
  213. configJson, err := a.serverService.GetConfigJson()
  214. if err != nil {
  215. jsonMsg(c, I18nWeb(c, "pages.index.getConfigError"), err)
  216. return
  217. }
  218. jsonObj(c, configJson, nil)
  219. }
  220. // getDb downloads the database file.
  221. func (a *ServerController) getDb(c *gin.Context) {
  222. db, err := a.serverService.GetDb()
  223. if err != nil {
  224. jsonMsg(c, I18nWeb(c, "pages.index.getDatabaseError"), err)
  225. return
  226. }
  227. filename := "x-ui.db"
  228. if !isValidFilename(filename) {
  229. c.AbortWithError(http.StatusBadRequest, fmt.Errorf("invalid filename"))
  230. return
  231. }
  232. // Set the headers for the response
  233. c.Header("Content-Type", "application/octet-stream")
  234. c.Header("Content-Disposition", "attachment; filename="+filename)
  235. // Write the file contents to the response
  236. c.Writer.Write(db)
  237. }
  238. func isValidFilename(filename string) bool {
  239. // Validate that the filename only contains allowed characters
  240. return filenameRegex.MatchString(filename)
  241. }
  242. // importDB imports a database file and restarts the Xray service.
  243. func (a *ServerController) importDB(c *gin.Context) {
  244. // Get the file from the request body
  245. file, _, err := c.Request.FormFile("db")
  246. if err != nil {
  247. jsonMsg(c, I18nWeb(c, "pages.index.readDatabaseError"), err)
  248. return
  249. }
  250. defer file.Close()
  251. // Always restart Xray before return
  252. defer a.serverService.RestartXrayService()
  253. // lastGetStatusTime removed; no longer needed
  254. // Import it
  255. err = a.serverService.ImportDB(file)
  256. if err != nil {
  257. jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
  258. return
  259. }
  260. jsonObj(c, I18nWeb(c, "pages.index.importDatabaseSuccess"), nil)
  261. }
  262. // getNewX25519Cert generates a new X25519 certificate.
  263. func (a *ServerController) getNewX25519Cert(c *gin.Context) {
  264. cert, err := a.serverService.GetNewX25519Cert()
  265. if err != nil {
  266. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewX25519CertError"), err)
  267. return
  268. }
  269. jsonObj(c, cert, nil)
  270. }
  271. // getNewmldsa65 generates a new ML-DSA-65 key.
  272. func (a *ServerController) getNewmldsa65(c *gin.Context) {
  273. cert, err := a.serverService.GetNewmldsa65()
  274. if err != nil {
  275. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewmldsa65Error"), err)
  276. return
  277. }
  278. jsonObj(c, cert, nil)
  279. }
  280. // getNewEchCert generates a new ECH certificate for the given SNI.
  281. func (a *ServerController) getNewEchCert(c *gin.Context) {
  282. sni := c.PostForm("sni")
  283. cert, err := a.serverService.GetNewEchCert(sni)
  284. if err != nil {
  285. jsonMsg(c, "get ech certificate", err)
  286. return
  287. }
  288. jsonObj(c, cert, nil)
  289. }
  290. // getNewVlessEnc generates a new VLESS encryption key.
  291. func (a *ServerController) getNewVlessEnc(c *gin.Context) {
  292. out, err := a.serverService.GetNewVlessEnc()
  293. if err != nil {
  294. jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.getNewVlessEncError"), err)
  295. return
  296. }
  297. jsonObj(c, out, nil)
  298. }
  299. // getNewUUID generates a new UUID.
  300. func (a *ServerController) getNewUUID(c *gin.Context) {
  301. uuidResp, err := a.serverService.GetNewUUID()
  302. if err != nil {
  303. jsonMsg(c, "Failed to generate UUID", err)
  304. return
  305. }
  306. jsonObj(c, uuidResp, nil)
  307. }
  308. // getNewmlkem768 generates a new ML-KEM-768 key.
  309. func (a *ServerController) getNewmlkem768(c *gin.Context) {
  310. out, err := a.serverService.GetNewmlkem768()
  311. if err != nil {
  312. jsonMsg(c, "Failed to generate mlkem768 keys", err)
  313. return
  314. }
  315. jsonObj(c, out, nil)
  316. }