server.go 15 KB

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