server.go 17 KB

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