1
0

web.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. // Package web provides the main web server implementation for the 3x-ui panel,
  2. // including HTTP/HTTPS serving, routing, templates, and background job scheduling.
  3. package web
  4. import (
  5. "context"
  6. "crypto/tls"
  7. "embed"
  8. "fmt"
  9. "io"
  10. "io/fs"
  11. "net"
  12. "net/http"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  18. "github.com/mhsanaei/3x-ui/v3/internal/config"
  19. "github.com/mhsanaei/3x-ui/v3/internal/eventbus"
  20. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  21. "github.com/mhsanaei/3x-ui/v3/internal/mtproto"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/sys"
  24. "github.com/mhsanaei/3x-ui/v3/internal/web/controller"
  25. "github.com/mhsanaei/3x-ui/v3/internal/web/job"
  26. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  27. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  28. "github.com/mhsanaei/3x-ui/v3/internal/web/network"
  29. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  30. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  31. "github.com/mhsanaei/3x-ui/v3/internal/web/service/email"
  32. "github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
  33. "github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
  34. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  35. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  36. "github.com/gin-contrib/gzip"
  37. "github.com/gin-contrib/sessions"
  38. "github.com/gin-contrib/sessions/cookie"
  39. "github.com/gin-gonic/gin"
  40. "github.com/robfig/cron/v3"
  41. )
  42. //go:embed translation/*
  43. var i18nFS embed.FS
  44. // distFS embeds the Vite-built frontend (internal/web/dist/). Every user-facing
  45. // HTML route is served straight out of this FS — the legacy Go
  46. // templates and `web/assets/` tree are gone post-Phase 8.
  47. //go:embed all:dist
  48. var distFS embed.FS
  49. var startTime = time.Now()
  50. // cronPanicLogger adapts the package logger to cron's Printf-style logger so a
  51. // panicking scheduled job is recovered and logged instead of crashing the panel.
  52. type cronPanicLogger struct{}
  53. func (cronPanicLogger) Printf(format string, args ...any) { logger.Errorf(format, args...) }
  54. // wrapDistFS adapts the embedded `dist/` directory so it can be mounted
  55. // as the panel's `/assets/` static route. Vite emits its bundled JS/CSS
  56. // under `dist/assets/`; serving the FS rooted at `dist/assets` makes
  57. // `/assets/<hash>.js` URLs resolve directly.
  58. type wrapDistFS struct {
  59. embed.FS
  60. }
  61. func (f *wrapDistFS) Open(name string) (fs.File, error) {
  62. file, err := f.FS.Open("dist/assets/" + name)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return &wrapAssetsFile{
  67. File: file,
  68. }, nil
  69. }
  70. type wrapAssetsFile struct {
  71. fs.File
  72. }
  73. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  74. info, err := f.File.Stat()
  75. if err != nil {
  76. return nil, err
  77. }
  78. return &wrapAssetsFileInfo{
  79. FileInfo: info,
  80. }, nil
  81. }
  82. type wrapAssetsFileInfo struct {
  83. fs.FileInfo
  84. }
  85. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  86. return startTime
  87. }
  88. // EmbeddedDist returns the embedded Vite-built frontend filesystem.
  89. // Controllers serve their HTML out of this FS via the dist-page handler
  90. // installed in NewEngine().
  91. func EmbeddedDist() embed.FS {
  92. return distFS
  93. }
  94. // Server represents the main web server for the 3x-ui panel with controllers, services, and scheduled jobs.
  95. type Server struct {
  96. httpServer *http.Server
  97. listener net.Listener
  98. index *controller.IndexController
  99. panel *controller.XUIController
  100. api *controller.APIController
  101. ws *controller.WebSocketController
  102. xrayService service.XrayService
  103. settingService service.SettingService
  104. tgbotService tgbot.Tgbot
  105. wsHub *websocket.Hub
  106. bus *eventbus.Bus
  107. cron *cron.Cron
  108. ctx context.Context
  109. cancel context.CancelFunc
  110. }
  111. // NewServer creates a new web server instance with a cancellable context.
  112. func NewServer() *Server {
  113. ctx, cancel := context.WithCancel(context.Background())
  114. return &Server{
  115. ctx: ctx,
  116. cancel: cancel,
  117. }
  118. }
  119. func (s *Server) isDirectHTTPSConfigured() bool {
  120. certFile, certErr := s.settingService.GetCertFile()
  121. keyFile, keyErr := s.settingService.GetKeyFile()
  122. if certErr != nil || keyErr != nil || certFile == "" || keyFile == "" {
  123. return false
  124. }
  125. _, err := tls.LoadX509KeyPair(certFile, keyFile)
  126. return err == nil
  127. }
  128. // initRouter initializes Gin, registers middleware, templates, static
  129. // assets, controllers and returns the configured engine.
  130. func (s *Server) initRouter() (*gin.Engine, error) {
  131. if config.IsDebug() {
  132. gin.SetMode(gin.DebugMode)
  133. } else {
  134. gin.DefaultWriter = io.Discard
  135. gin.DefaultErrorWriter = io.Discard
  136. gin.SetMode(gin.ReleaseMode)
  137. }
  138. engine := gin.Default()
  139. directHTTPS := s.isDirectHTTPSConfigured()
  140. sendHSTS := directHTTPS && !config.IsSkipHSTS()
  141. engine.Use(middleware.SecurityHeadersMiddleware(sendHSTS))
  142. // Cap request bodies on state-changing requests so a stolen session/API
  143. // token or a buggy client can't force large allocations or long DB
  144. // transactions via bulk create/attach/import endpoints. GET/HEAD/OPTIONS
  145. // carry no body and are left untouched. Database restore legitimately accepts
  146. // large backups and streams them to disk, so only its exact route suffix is
  147. // exempt. Follow-up: make the limit a setting.
  148. const maxRequestBodyBytes = 10 << 20 // 10 MiB
  149. engine.Use(middleware.MaxBodyBytes(maxRequestBodyBytes, "/panel/api/server/importDB"))
  150. webDomain, err := s.settingService.GetWebDomain()
  151. if err != nil {
  152. return nil, err
  153. }
  154. if webDomain != "" {
  155. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  156. }
  157. secret, err := s.settingService.GetSecret()
  158. if err != nil {
  159. return nil, err
  160. }
  161. basePath, err := s.settingService.GetBasePath()
  162. if err != nil {
  163. return nil, err
  164. }
  165. engine.Use(gzip.Gzip(gzip.DefaultCompression))
  166. assetsBasePath := basePath + "assets/"
  167. store := cookie.NewStore(secret)
  168. // Configure default session cookie options, including expiration (MaxAge)
  169. sessionOptions := sessions.Options{
  170. Path: basePath,
  171. HttpOnly: true,
  172. Secure: directHTTPS,
  173. SameSite: http.SameSiteLaxMode,
  174. }
  175. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil && sessionMaxAge > 0 {
  176. sessionOptions.MaxAge = sessionMaxAge * 60 // minutes -> seconds
  177. }
  178. store.Options(sessionOptions)
  179. engine.Use(sessions.Sessions("3x-ui", store))
  180. engine.Use(func(c *gin.Context) {
  181. c.Set("base_path", basePath)
  182. })
  183. engine.Use(func(c *gin.Context) {
  184. uri := c.Request.RequestURI
  185. if strings.HasPrefix(uri, assetsBasePath) {
  186. c.Header("Cache-Control", "max-age=31536000")
  187. }
  188. })
  189. // init i18n — still used by backend strings (errors, log messages,
  190. // SubPage menu entries) even though the Go template engine is gone.
  191. err = locale.InitLocalizer(i18nFS, &s.settingService)
  192. if err != nil {
  193. return nil, err
  194. }
  195. engine.Use(locale.LocalizerMiddleware())
  196. // `/assets/` serves the Vite-built bundle. In dev we pull from disk
  197. // so the Vite watcher's incremental rebuilds show up without
  198. // restarting the binary; in prod we serve the embedded dist FS
  199. // rooted at `dist/assets/`.
  200. if config.IsDebug() {
  201. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("internal/web/dist/assets")))
  202. } else {
  203. engine.StaticFS(basePath+"assets", http.FS(&wrapDistFS{FS: distFS}))
  204. }
  205. // Hand the embedded `dist/` filesystem to the controller package
  206. // before any HTML-serving controller is constructed. Phase 8
  207. // cutover: every HTML route reads from internal/web/dist/ instead of
  208. // rendering a legacy template.
  209. controller.SetDistFS(distFS)
  210. g := engine.Group(basePath)
  211. g.GET("/manifest.webmanifest", controller.ServePWAManifest)
  212. g.GET("/pwa-register.js", controller.ServePWARegister)
  213. g.GET("/service-worker.js", controller.ServePWAServiceWorker)
  214. g.GET("/icons/:name", controller.ServePWAIcon)
  215. s.index = controller.NewIndexController(g)
  216. s.panel = controller.NewXUIController(g)
  217. s.api = controller.NewAPIController(g)
  218. // Initialize WebSocket hub
  219. s.wsHub = websocket.NewHub()
  220. go s.wsHub.Run()
  221. // Initialize WebSocket controller — service owns per-connection pumps,
  222. // controller is HTTP-layer only (auth + upgrade).
  223. s.ws = controller.NewWebSocketController(panel.NewWebSocketService(s.wsHub))
  224. // Register WebSocket route with basePath (g already has basePath prefix)
  225. g.GET("/ws", s.ws.HandleWebSocket)
  226. // Chrome DevTools endpoint for debugging web apps
  227. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  228. c.JSON(http.StatusOK, gin.H{})
  229. })
  230. // Let unknown panel document routes fall back to the SPA shell, while every
  231. // non-SPA miss still returns a hard 404.
  232. engine.NoRoute(func(c *gin.Context) {
  233. if s.panel.HandleNoRoutePanelSPA(c) {
  234. return
  235. }
  236. c.AbortWithStatus(http.StatusNotFound)
  237. })
  238. return engine, nil
  239. }
  240. // Background-job cadences. Centralized here as the single tuning surface; the
  241. // values are unchanged from the historical hardcoded cron specs. Follow-up:
  242. // make these configurable via settings, add per-tick jitter to de-synchronize
  243. // fleet load, skip expensive jobs when no WebSocket clients are connected or
  244. // node/xray state is unchanged, and export per-job duration/skipped/error
  245. // counters.
  246. const (
  247. cadenceXrayRunning = "@every 1s"
  248. cadenceXrayRestart = "@every 30s"
  249. cadenceXrayTraffic = "@every 5s"
  250. cadenceMtproto = "@every 10s"
  251. cadenceAmneziaWG = "@every 10s"
  252. cadenceClientIPScan = "@every 10s"
  253. cadenceNodeHeartbeat = "@every 5s"
  254. cadenceNodeTraffic = "@every 5s"
  255. cadenceOutboundSub = "@every 5m"
  256. cadenceReapOrphans = "@every 5m"
  257. cadenceRemoteRouting = "@every 5m"
  258. cadenceXrayLogPrune = "@every 10m"
  259. cadenceCheckHash = "@every 2m"
  260. // cpu.Percent samples over a full minute (blocking), so a finer cadence just
  261. // stacks overlapping samplers; subscribers rate-limit alerts to 1/min anyway.
  262. cadenceCPUAlarm = "@every 1m"
  263. cadenceMemoryAlarm = "@every 1m"
  264. )
  265. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  266. // jobs) which the panel relies on for periodic maintenance and monitoring.
  267. func (s *Server) startTask(restartXray bool, loc *time.Location) {
  268. if restartXray {
  269. err := s.xrayService.RestartXray(true)
  270. if err != nil {
  271. logger.Warning("start xray failed:", err)
  272. }
  273. }
  274. // Check whether xray is running every second
  275. _, _ = s.cron.AddJob(cadenceXrayRunning, job.NewCheckXrayRunningJob())
  276. // Check if xray needs to be restarted every 30 seconds
  277. _, _ = s.cron.AddFunc(cadenceXrayRestart, func() {
  278. s.xrayService.ApplyPendingRestart()
  279. })
  280. go func() {
  281. time.Sleep(time.Second * 5)
  282. _, _ = s.cron.AddJob(cadenceXrayTraffic, job.NewXrayTrafficJob())
  283. }()
  284. // Reconcile mtproto (mtg) sidecars and scrape their traffic
  285. mtJob := job.NewMtprotoJob()
  286. _, _ = s.cron.AddJob(cadenceMtproto, mtJob)
  287. go mtJob.Run()
  288. // Reconcile embedded AmneziaWG interfaces; traffic rides Xray's own stats
  289. awgJob := job.NewAmneziaWGJob()
  290. _, _ = s.cron.AddJob(cadenceAmneziaWG, awgJob)
  291. go awgJob.Run()
  292. // check client ips from log file every 10 sec
  293. _, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
  294. _, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
  295. _, _ = s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob())
  296. // Outbound subscription auto-refresh (respects per-sub updateInterval)
  297. _, _ = s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob())
  298. _, _ = s.cron.AddJob(cadenceReapOrphans, job.NewReapSyncOrphansJob())
  299. // Warm permanent routing URLs immediately and refresh them outside the
  300. // latency-sensitive subscription request path.
  301. remoteRoutingJob := job.NewRemoteRoutingJob()
  302. _, _ = s.cron.AddJob(cadenceRemoteRouting, remoteRoutingJob)
  303. common.GoRecover("remote-routing-warm", remoteRoutingJob.Run)
  304. // check client ips from log file every day
  305. _, _ = s.cron.AddJob("@daily", job.NewClearLogsJob())
  306. _, _ = s.cron.AddJob(cadenceXrayLogPrune, job.NewPruneXrayLogsJob())
  307. _, _ = s.cron.AddJob("@hourly", job.NewWarpIpJob())
  308. // Inbound traffic reset jobs
  309. // Run every hour
  310. _, _ = s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly", loc))
  311. // Run once a day, midnight
  312. _, _ = s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily", loc))
  313. // Run once a week, midnight between Sat/Sun
  314. _, _ = s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly", loc))
  315. // Check monthly reset days at midnight
  316. _, _ = s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("monthly", loc))
  317. // LDAP sync scheduling
  318. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  319. runtime, err := s.settingService.GetLdapSyncCron()
  320. if err != nil || runtime == "" {
  321. runtime = "@every 1m"
  322. }
  323. j := job.NewLdapSyncJob()
  324. // job has zero-value services with method receivers that read settings on demand
  325. _, _ = s.cron.AddJob(runtime, j)
  326. }
  327. // Telegram-bot–dependent jobs: periodic stats report + callback-hash cleanup.
  328. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  329. if (err == nil) && isTgbotenabled {
  330. runtime, err := s.settingService.GetTgbotRuntime()
  331. if err != nil {
  332. logger.Warningf("Add NewStatsNotifyJob: failed to load runtime: %v; using default @daily", err)
  333. runtime = "@daily"
  334. } else if strings.TrimSpace(runtime) == "" {
  335. logger.Warning("Add NewStatsNotifyJob runtime is empty, using default @daily")
  336. runtime = "@daily"
  337. }
  338. logger.Infof("Tg notify enabled,run at %s", runtime)
  339. if _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()); err != nil {
  340. logger.Warningf("Add NewStatsNotifyJob: failed to schedule runtime %q: %v", runtime, err)
  341. }
  342. // check for Telegram bot callback query hash storage reset
  343. _, _ = s.cron.AddJob(cadenceCheckHash, job.NewCheckHashStorageJob())
  344. }
  345. // CPU monitor publishes cpu.high events; register it whenever any notifier
  346. // (Telegram or Email) wants them, independent of the Telegram bot being on.
  347. if s.cpuAlarmWanted() {
  348. _, _ = s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
  349. }
  350. // Memory monitor publishes memory.high events; register it whenever any notifier wants them.
  351. if s.memoryAlarmWanted() {
  352. _, _ = s.cron.AddJob(cadenceMemoryAlarm, job.NewCheckMemJob())
  353. }
  354. if mins := sys.MemoryReleaseIntervalMinutes(); mins > 0 {
  355. _, _ = s.cron.AddJob(fmt.Sprintf("@every %dm", mins), job.NewMemoryReleaseJob())
  356. go func() {
  357. time.Sleep(time.Minute)
  358. job.NewMemoryReleaseJob().Run()
  359. }()
  360. }
  361. }
  362. // cpuAlarmWanted reports whether any notifier is configured to receive cpu.high
  363. // alerts, so the minute-long blocking CPU sampler only runs when it's needed.
  364. func (s *Server) cpuAlarmWanted() bool {
  365. wants := func(events string, threshold int) bool {
  366. if threshold <= 0 {
  367. return false
  368. }
  369. for e := range strings.SplitSeq(events, ",") {
  370. if strings.TrimSpace(e) == string(eventbus.EventCPUHigh) {
  371. return true
  372. }
  373. }
  374. return false
  375. }
  376. if on, _ := s.settingService.GetTgbotEnabled(); on {
  377. events, _ := s.settingService.GetTgEnabledEvents()
  378. cpu, _ := s.settingService.GetTgCpu()
  379. if wants(events, cpu) {
  380. return true
  381. }
  382. }
  383. if on, _ := s.settingService.GetSmtpEnable(); on {
  384. events, _ := s.settingService.GetSmtpEnabledEvents()
  385. cpu, _ := s.settingService.GetSmtpCpu()
  386. if wants(events, cpu) {
  387. return true
  388. }
  389. }
  390. return false
  391. }
  392. // memoryAlarmWanted reports whether any notifier is configured to receive memory.high alerts.
  393. func (s *Server) memoryAlarmWanted() bool {
  394. wants := func(events string, threshold int) bool {
  395. if threshold <= 0 {
  396. return false
  397. }
  398. for e := range strings.SplitSeq(events, ",") {
  399. if strings.TrimSpace(e) == string(eventbus.EventMemoryHigh) {
  400. return true
  401. }
  402. }
  403. return false
  404. }
  405. if on, _ := s.settingService.GetTgbotEnabled(); on {
  406. events, _ := s.settingService.GetTgEnabledEvents()
  407. mem, _ := s.settingService.GetTgMemory()
  408. if wants(events, mem) {
  409. return true
  410. }
  411. }
  412. if on, _ := s.settingService.GetSmtpEnable(); on {
  413. events, _ := s.settingService.GetSmtpEnabledEvents()
  414. mem, _ := s.settingService.GetSmtpMemory()
  415. if wants(events, mem) {
  416. return true
  417. }
  418. }
  419. return false
  420. }
  421. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  422. func (s *Server) Start() (err error) {
  423. return s.start(true, true)
  424. }
  425. func (s *Server) StartPanelOnly() (err error) {
  426. return s.start(false, true)
  427. }
  428. func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
  429. // This is an anonymous function, no function name
  430. defer func() {
  431. if err != nil {
  432. _ = s.Stop()
  433. }
  434. }()
  435. loc, err := s.settingService.GetTimeLocation()
  436. if err != nil {
  437. return err
  438. }
  439. service.StartTrafficWriter()
  440. // SkipIfStillRunning stops a slow job (e.g. the 5s traffic poll on a large
  441. // install) from overlapping itself: two concurrent runs of the same job race
  442. // the shared xrayAPI — leaking a grpc connection — and the StatsLastValues
  443. // map, whose concurrent write is a fatal runtime throw cron.Recover can't
  444. // catch. cron.Recover then logs any panic and keeps the scheduler alive.
  445. s.cron = cron.New(
  446. cron.WithLocation(loc),
  447. cron.WithSeconds(),
  448. cron.WithChain(
  449. cron.SkipIfStillRunning(cron.DiscardLogger),
  450. cron.Recover(cron.PrintfLogger(cronPanicLogger{})),
  451. ),
  452. )
  453. s.cron.Start()
  454. // Wire the inbound-runtime manager once so InboundService can route
  455. // add/update/delete to either the local xray or a remote node panel.
  456. // The closures bridge into XrayService (which owns the running xray
  457. // process state) without forcing the runtime package to import service.
  458. runtime.SetManager(runtime.NewManager(runtime.LocalDeps{
  459. APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
  460. SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
  461. }))
  462. runtime.GetManager().SetNodeEgressResolver(&s.settingService)
  463. // Supply the master client certificate for nodes in mtls mode. Issued lazily
  464. // from the node CA on first use; runtime stays free of a service import.
  465. runtime.SetMasterClientCertProvider(func() (tls.Certificate, error) {
  466. ck, err := s.settingService.EnsureMasterClientCert()
  467. if err != nil {
  468. return tls.Certificate{}, err
  469. }
  470. return tls.X509KeyPair(ck.CertPEM, ck.KeyPEM)
  471. })
  472. engine, err := s.initRouter()
  473. if err != nil {
  474. return err
  475. }
  476. certFile, err := s.settingService.GetCertFile()
  477. if err != nil {
  478. return err
  479. }
  480. keyFile, err := s.settingService.GetKeyFile()
  481. if err != nil {
  482. return err
  483. }
  484. listen, err := s.settingService.GetListen()
  485. if err != nil {
  486. return err
  487. }
  488. port, err := s.settingService.GetPort()
  489. if err != nil {
  490. return err
  491. }
  492. if envPort, configured, envErr := config.GetPortOverride(); configured {
  493. if envErr != nil {
  494. logger.Warning("Ignoring invalid XUI_PORT; using configured web port:", port, envErr)
  495. } else {
  496. port = envPort
  497. logger.Info("Using XUI_PORT override for web panel port:", port)
  498. }
  499. }
  500. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  501. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", listenAddr)
  502. if err != nil {
  503. return err
  504. }
  505. if certFile != "" || keyFile != "" {
  506. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  507. if err == nil {
  508. c := &tls.Config{
  509. Certificates: []tls.Certificate{cert},
  510. }
  511. // Opt-in node mTLS: when a trust CA is configured, request and verify
  512. // client certs (VerifyClientCertIfGiven keeps browsers working). With
  513. // no CA the listener is unchanged.
  514. if pool, perr := s.settingService.NodeMtlsClientCAPool(); perr != nil {
  515. logger.Warning("node mTLS: failed to build client CA trust pool:", perr)
  516. } else if pool != nil {
  517. applyNodeMtls(c, pool)
  518. logger.Info("Node mTLS enabled: verifying client certificates for the node API")
  519. }
  520. listener = network.NewAutoHttpsListener(listener)
  521. listener = tls.NewListener(listener, c)
  522. logger.Info("Web server running HTTPS on", listener.Addr())
  523. } else {
  524. logger.Error("Error loading certificates:", err)
  525. logger.Info("Web server running HTTP on", listener.Addr())
  526. }
  527. } else {
  528. logger.Info("Web server running HTTP on", listener.Addr())
  529. }
  530. s.listener = listener
  531. s.httpServer = &http.Server{
  532. Handler: engine,
  533. ReadHeaderTimeout: 5 * time.Second,
  534. ReadTimeout: 30 * time.Second,
  535. WriteTimeout: 30 * time.Second,
  536. IdleTimeout: 120 * time.Second,
  537. }
  538. go network.ServeHTTP(s.httpServer, listener, "Web server")
  539. // Create event bus before startTask so jobs can use it
  540. s.bus = eventbus.New(eventbus.DefaultBufferSize)
  541. service.SetEventBus(s.bus)
  542. job.EventBus = s.bus
  543. tgbot.EventBus = s.bus
  544. // Wire xray crash callback BEFORE startTask so it's ready
  545. xray.OnCrash = func(err error) {
  546. if s.bus != nil {
  547. s.bus.Publish(eventbus.Event{
  548. Type: eventbus.EventXrayCrash,
  549. Data: err.Error(),
  550. })
  551. }
  552. }
  553. // Register email subscriber (always — it checks smtpEnable at runtime)
  554. emailService := email.NewEmailService(s.settingService)
  555. emailSub := email.NewSubscriber(s.settingService, emailService)
  556. s.bus.Subscribe("email-notifier", emailSub.HandleEvent)
  557. // Wire email service to controller for test endpoint
  558. controller.SetEmailService(emailService)
  559. // Wire Telegram test function to controller
  560. controller.SetTestTgFunc(func() error {
  561. if !s.tgbotService.IsRunning() {
  562. return fmt.Errorf("telegram bot is not running (check token and chat ID)")
  563. }
  564. if err := s.tgbotService.TestConnection(); err != nil {
  565. return fmt.Errorf("telegram API test failed: %w", err)
  566. }
  567. s.tgbotService.SendMsgToTgbotAdmins("✅ Test message from 3x-ui")
  568. return nil
  569. })
  570. controller.SetReloadTgbotFunc(func() {
  571. enabled, err := s.settingService.GetTgbotEnabled()
  572. if err != nil || !enabled {
  573. if s.tgbotService.IsRunning() {
  574. s.tgbotService.Stop()
  575. }
  576. if s.bus != nil {
  577. s.bus.Unsubscribe("tg-notifier")
  578. }
  579. return
  580. }
  581. // Start() stops any previous receiver first, so it is safe whether or not the bot is already running.
  582. tgBot := s.tgbotService.NewTgbot()
  583. if startErr := tgBot.Start(i18nFS); startErr != nil {
  584. logger.Warning("reload Telegram bot failed:", startErr)
  585. return
  586. }
  587. if s.bus != nil {
  588. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  589. }
  590. })
  591. s.startTask(restartXray, loc)
  592. if startTgBot {
  593. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  594. if (err == nil) && isTgbotenabled {
  595. tgBot := s.tgbotService.NewTgbot()
  596. _ = tgBot.Start(i18nFS)
  597. // Subscribe Telegram notifications for event bus
  598. s.bus.Subscribe("tg-notifier", s.tgbotService.HandleEvent)
  599. }
  600. }
  601. return nil
  602. }
  603. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  604. func (s *Server) Stop() error {
  605. return s.stop(true, true)
  606. }
  607. func (s *Server) StopPanelOnly() error {
  608. return s.stop(false, true)
  609. }
  610. func (s *Server) stop(stopXray bool, stopTgBot bool) error {
  611. s.cancel()
  612. if stopXray {
  613. _ = s.xrayService.StopXray()
  614. mtproto.GetManager().StopAll()
  615. amneziawgnet.GetManager().StopAll()
  616. }
  617. if s.cron != nil {
  618. s.cron.Stop()
  619. }
  620. if s.bus != nil {
  621. s.bus.Stop()
  622. }
  623. if err := service.PersistSystemMetrics(); err != nil {
  624. logger.Warning("persist system metrics on shutdown failed:", err)
  625. }
  626. if stopXray {
  627. service.StopTrafficWriter()
  628. }
  629. if stopTgBot && s.tgbotService.IsRunning() {
  630. s.tgbotService.Stop()
  631. }
  632. // Gracefully stop WebSocket hub
  633. if s.wsHub != nil {
  634. s.wsHub.Stop()
  635. }
  636. var err1 error
  637. var err2 error
  638. if s.httpServer != nil {
  639. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  640. defer shutdownCancel()
  641. err1 = s.httpServer.Shutdown(shutdownCtx)
  642. }
  643. if s.listener != nil {
  644. err2 = s.listener.Close()
  645. }
  646. return common.Combine(err1, err2)
  647. }
  648. // GetCtx returns the server's context for cancellation and deadline management.
  649. func (s *Server) GetCtx() context.Context {
  650. return s.ctx
  651. }
  652. // GetCron returns the server's cron scheduler instance.
  653. func (s *Server) GetCron() *cron.Cron {
  654. return s.cron
  655. }
  656. // GetWSHub returns the WebSocket hub instance.
  657. func (s *Server) GetWSHub() any {
  658. return s.wsHub
  659. }
  660. func (s *Server) RestartXray() error {
  661. return s.xrayService.RestartXray(true)
  662. }