1
0

server.go 14 KB

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