web.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. "html/template"
  9. "io"
  10. "io/fs"
  11. "net"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v2/config"
  19. "github.com/mhsanaei/3x-ui/v2/logger"
  20. "github.com/mhsanaei/3x-ui/v2/util/common"
  21. "github.com/mhsanaei/3x-ui/v2/web/controller"
  22. "github.com/mhsanaei/3x-ui/v2/web/job"
  23. "github.com/mhsanaei/3x-ui/v2/web/locale"
  24. "github.com/mhsanaei/3x-ui/v2/web/middleware"
  25. "github.com/mhsanaei/3x-ui/v2/web/network"
  26. "github.com/mhsanaei/3x-ui/v2/web/service"
  27. "github.com/mhsanaei/3x-ui/v2/web/websocket"
  28. "github.com/gin-contrib/gzip"
  29. "github.com/gin-contrib/sessions"
  30. "github.com/gin-contrib/sessions/cookie"
  31. "github.com/gin-gonic/gin"
  32. "github.com/robfig/cron/v3"
  33. )
  34. //go:embed assets
  35. var assetsFS embed.FS
  36. //go:embed html/*
  37. var htmlFS embed.FS
  38. //go:embed translation/*
  39. var i18nFS embed.FS
  40. var startTime = time.Now()
  41. type wrapAssetsFS struct {
  42. embed.FS
  43. }
  44. func (f *wrapAssetsFS) Open(name string) (fs.File, error) {
  45. file, err := f.FS.Open("assets/" + name)
  46. if err != nil {
  47. return nil, err
  48. }
  49. return &wrapAssetsFile{
  50. File: file,
  51. }, nil
  52. }
  53. type wrapAssetsFile struct {
  54. fs.File
  55. }
  56. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  57. info, err := f.File.Stat()
  58. if err != nil {
  59. return nil, err
  60. }
  61. return &wrapAssetsFileInfo{
  62. FileInfo: info,
  63. }, nil
  64. }
  65. type wrapAssetsFileInfo struct {
  66. fs.FileInfo
  67. }
  68. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  69. return startTime
  70. }
  71. // EmbeddedHTML returns the embedded HTML templates filesystem for reuse by other servers.
  72. func EmbeddedHTML() embed.FS {
  73. return htmlFS
  74. }
  75. // EmbeddedAssets returns the embedded assets filesystem for reuse by other servers.
  76. func EmbeddedAssets() embed.FS {
  77. return assetsFS
  78. }
  79. // Server represents the main web server for the 3x-ui panel with controllers, services, and scheduled jobs.
  80. type Server struct {
  81. httpServer *http.Server
  82. listener net.Listener
  83. index *controller.IndexController
  84. panel *controller.XUIController
  85. api *controller.APIController
  86. ws *controller.WebSocketController
  87. xrayService service.XrayService
  88. settingService service.SettingService
  89. tgbotService service.Tgbot
  90. customGeoService *service.CustomGeoService
  91. wsHub *websocket.Hub
  92. cron *cron.Cron
  93. ctx context.Context
  94. cancel context.CancelFunc
  95. }
  96. // NewServer creates a new web server instance with a cancellable context.
  97. func NewServer() *Server {
  98. ctx, cancel := context.WithCancel(context.Background())
  99. return &Server{
  100. ctx: ctx,
  101. cancel: cancel,
  102. }
  103. }
  104. // getHtmlFiles walks the local `web/html` directory and returns a list of
  105. // template file paths. Used only in debug/development mode.
  106. func (s *Server) getHtmlFiles() ([]string, error) {
  107. files := make([]string, 0)
  108. dir, _ := os.Getwd()
  109. err := fs.WalkDir(os.DirFS(dir), "web/html", func(path string, d fs.DirEntry, err error) error {
  110. if err != nil {
  111. return err
  112. }
  113. if d.IsDir() {
  114. return nil
  115. }
  116. files = append(files, path)
  117. return nil
  118. })
  119. if err != nil {
  120. return nil, err
  121. }
  122. return files, nil
  123. }
  124. // getHtmlTemplate parses embedded HTML templates from the bundled `htmlFS`
  125. // using the provided template function map and returns the resulting
  126. // template set for production usage.
  127. func (s *Server) getHtmlTemplate(funcMap template.FuncMap) (*template.Template, error) {
  128. t := template.New("").Funcs(funcMap)
  129. err := fs.WalkDir(htmlFS, "html", func(path string, d fs.DirEntry, err error) error {
  130. if err != nil {
  131. return err
  132. }
  133. if d.IsDir() {
  134. newT, err := t.ParseFS(htmlFS, path+"/*.html")
  135. if err != nil {
  136. // ignore
  137. return nil
  138. }
  139. t = newT
  140. }
  141. return nil
  142. })
  143. if err != nil {
  144. return nil, err
  145. }
  146. return t, nil
  147. }
  148. // initRouter initializes Gin, registers middleware, templates, static
  149. // assets, controllers and returns the configured engine.
  150. func (s *Server) initRouter() (*gin.Engine, error) {
  151. if config.IsDebug() {
  152. gin.SetMode(gin.DebugMode)
  153. } else {
  154. gin.DefaultWriter = io.Discard
  155. gin.DefaultErrorWriter = io.Discard
  156. gin.SetMode(gin.ReleaseMode)
  157. }
  158. engine := gin.Default()
  159. webDomain, err := s.settingService.GetWebDomain()
  160. if err != nil {
  161. return nil, err
  162. }
  163. if webDomain != "" {
  164. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  165. }
  166. secret, err := s.settingService.GetSecret()
  167. if err != nil {
  168. return nil, err
  169. }
  170. basePath, err := s.settingService.GetBasePath()
  171. if err != nil {
  172. return nil, err
  173. }
  174. engine.Use(gzip.Gzip(gzip.DefaultCompression))
  175. assetsBasePath := basePath + "assets/"
  176. store := cookie.NewStore(secret)
  177. // Configure default session cookie options, including expiration (MaxAge)
  178. sessionOptions := sessions.Options{
  179. Path: basePath,
  180. HttpOnly: true,
  181. SameSite: http.SameSiteLaxMode,
  182. }
  183. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil && sessionMaxAge > 0 {
  184. sessionOptions.MaxAge = sessionMaxAge * 60 // minutes -> seconds
  185. }
  186. store.Options(sessionOptions)
  187. engine.Use(sessions.Sessions("3x-ui", store))
  188. engine.Use(func(c *gin.Context) {
  189. c.Set("base_path", basePath)
  190. })
  191. engine.Use(func(c *gin.Context) {
  192. uri := c.Request.RequestURI
  193. if strings.HasPrefix(uri, assetsBasePath) {
  194. c.Header("Cache-Control", "max-age=31536000")
  195. }
  196. })
  197. // init i18n
  198. err = locale.InitLocalizer(i18nFS, &s.settingService)
  199. if err != nil {
  200. return nil, err
  201. }
  202. // Apply locale middleware for i18n
  203. i18nWebFunc := func(key string, params ...string) string {
  204. return locale.I18n(locale.Web, key, params...)
  205. }
  206. // Register template functions before loading templates
  207. funcMap := template.FuncMap{
  208. "i18n": i18nWebFunc,
  209. }
  210. engine.SetFuncMap(funcMap)
  211. engine.Use(locale.LocalizerMiddleware())
  212. // set static files and template
  213. if config.IsDebug() {
  214. // for development
  215. files, err := s.getHtmlFiles()
  216. if err != nil {
  217. return nil, err
  218. }
  219. // Use the registered func map with the loaded templates
  220. engine.LoadHTMLFiles(files...)
  221. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("web/assets")))
  222. } else {
  223. // for production
  224. template, err := s.getHtmlTemplate(funcMap)
  225. if err != nil {
  226. return nil, err
  227. }
  228. engine.SetHTMLTemplate(template)
  229. engine.StaticFS(basePath+"assets", http.FS(&wrapAssetsFS{FS: assetsFS}))
  230. }
  231. // Apply the redirect middleware (`/xui` to `/panel`)
  232. engine.Use(middleware.RedirectMiddleware(basePath))
  233. g := engine.Group(basePath)
  234. s.index = controller.NewIndexController(g)
  235. s.panel = controller.NewXUIController(g)
  236. s.api = controller.NewAPIController(g, s.customGeoService)
  237. // Initialize WebSocket hub
  238. s.wsHub = websocket.NewHub()
  239. go s.wsHub.Run()
  240. // Initialize WebSocket controller
  241. s.ws = controller.NewWebSocketController(s.wsHub)
  242. // Register WebSocket route with basePath (g already has basePath prefix)
  243. g.GET("/ws", s.ws.HandleWebSocket)
  244. // Chrome DevTools endpoint for debugging web apps
  245. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  246. c.JSON(http.StatusOK, gin.H{})
  247. })
  248. // Add a catch-all route to handle undefined paths and return 404
  249. engine.NoRoute(func(c *gin.Context) {
  250. c.AbortWithStatus(http.StatusNotFound)
  251. })
  252. return engine, nil
  253. }
  254. // normalizeExistingGeositeFiles normalizes country codes in all geosite .dat
  255. // files found in the bin directory so Xray-core can locate entries correctly.
  256. func normalizeExistingGeositeFiles() {
  257. binDir := config.GetBinFolderPath()
  258. matches, err := filepath.Glob(filepath.Join(binDir, "geosite*.dat"))
  259. if err != nil {
  260. logger.Warningf("Failed to glob geosite files: %v", err)
  261. return
  262. }
  263. for _, path := range matches {
  264. if err := service.NormalizeGeositeCountryCodes(path); err != nil {
  265. logger.Warningf("Failed to normalize geosite country codes in %s: %v", path, err)
  266. }
  267. }
  268. }
  269. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  270. // jobs) which the panel relies on for periodic maintenance and monitoring.
  271. func (s *Server) startTask() {
  272. normalizeExistingGeositeFiles()
  273. s.customGeoService.EnsureOnStartup()
  274. err := s.xrayService.RestartXray(true)
  275. if err != nil {
  276. logger.Warning("start xray failed:", err)
  277. }
  278. // Check whether xray is running every second
  279. s.cron.AddJob("@every 1s", job.NewCheckXrayRunningJob())
  280. // Check if xray needs to be restarted every 30 seconds
  281. s.cron.AddFunc("@every 30s", func() {
  282. if s.xrayService.IsNeedRestartAndSetFalse() {
  283. err := s.xrayService.RestartXray(false)
  284. if err != nil {
  285. logger.Error("restart xray failed:", err)
  286. }
  287. }
  288. })
  289. go func() {
  290. time.Sleep(time.Second * 5)
  291. // Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray
  292. s.cron.AddJob("@every 10s", job.NewXrayTrafficJob())
  293. }()
  294. // check client ips from log file every 10 sec
  295. s.cron.AddJob("@every 10s", job.NewCheckClientIpJob())
  296. // check client ips from log file every day
  297. s.cron.AddJob("@daily", job.NewClearLogsJob())
  298. // Inbound traffic reset jobs
  299. // Run every hour
  300. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  301. // Run once a day, midnight
  302. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  303. // Run once a week, midnight between Sat/Sun
  304. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  305. // Run once a month, midnight, first of month
  306. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  307. // LDAP sync scheduling
  308. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  309. runtime, err := s.settingService.GetLdapSyncCron()
  310. if err != nil || runtime == "" {
  311. runtime = "@every 1m"
  312. }
  313. j := job.NewLdapSyncJob()
  314. // job has zero-value services with method receivers that read settings on demand
  315. s.cron.AddJob(runtime, j)
  316. }
  317. // Make a traffic condition every day, 8:30
  318. var entry cron.EntryID
  319. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  320. if (err == nil) && (isTgbotenabled) {
  321. runtime, err := s.settingService.GetTgbotRuntime()
  322. if err != nil || runtime == "" {
  323. logger.Errorf("Add NewStatsNotifyJob error[%s], Runtime[%s] invalid, will run default", err, runtime)
  324. runtime = "@daily"
  325. }
  326. logger.Infof("Tg notify enabled,run at %s", runtime)
  327. _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob())
  328. if err != nil {
  329. logger.Warning("Add NewStatsNotifyJob error", err)
  330. return
  331. }
  332. // check for Telegram bot callback query hash storage reset
  333. s.cron.AddJob("@every 2m", job.NewCheckHashStorageJob())
  334. // Check CPU load and alarm to TgBot if threshold passes
  335. cpuThreshold, err := s.settingService.GetTgCpu()
  336. if (err == nil) && (cpuThreshold > 0) {
  337. s.cron.AddJob("@every 10s", job.NewCheckCpuJob())
  338. }
  339. } else {
  340. s.cron.Remove(entry)
  341. }
  342. }
  343. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  344. func (s *Server) Start() (err error) {
  345. // This is an anonymous function, no function name
  346. defer func() {
  347. if err != nil {
  348. s.Stop()
  349. }
  350. }()
  351. loc, err := s.settingService.GetTimeLocation()
  352. if err != nil {
  353. return err
  354. }
  355. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
  356. s.cron.Start()
  357. s.customGeoService = service.NewCustomGeoService()
  358. engine, err := s.initRouter()
  359. if err != nil {
  360. return err
  361. }
  362. certFile, err := s.settingService.GetCertFile()
  363. if err != nil {
  364. return err
  365. }
  366. keyFile, err := s.settingService.GetKeyFile()
  367. if err != nil {
  368. return err
  369. }
  370. listen, err := s.settingService.GetListen()
  371. if err != nil {
  372. return err
  373. }
  374. port, err := s.settingService.GetPort()
  375. if err != nil {
  376. return err
  377. }
  378. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  379. listener, err := net.Listen("tcp", listenAddr)
  380. if err != nil {
  381. return err
  382. }
  383. if certFile != "" || keyFile != "" {
  384. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  385. if err == nil {
  386. c := &tls.Config{
  387. Certificates: []tls.Certificate{cert},
  388. }
  389. listener = network.NewAutoHttpsListener(listener)
  390. listener = tls.NewListener(listener, c)
  391. logger.Info("Web server running HTTPS on", listener.Addr())
  392. } else {
  393. logger.Error("Error loading certificates:", err)
  394. logger.Info("Web server running HTTP on", listener.Addr())
  395. }
  396. } else {
  397. logger.Info("Web server running HTTP on", listener.Addr())
  398. }
  399. s.listener = listener
  400. s.httpServer = &http.Server{
  401. Handler: engine,
  402. }
  403. go func() {
  404. s.httpServer.Serve(listener)
  405. }()
  406. s.startTask()
  407. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  408. if (err == nil) && (isTgbotenabled) {
  409. tgBot := s.tgbotService.NewTgbot()
  410. tgBot.Start(i18nFS)
  411. }
  412. return nil
  413. }
  414. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  415. func (s *Server) Stop() error {
  416. s.cancel()
  417. s.xrayService.StopXray()
  418. if s.cron != nil {
  419. s.cron.Stop()
  420. }
  421. if s.tgbotService.IsRunning() {
  422. s.tgbotService.Stop()
  423. }
  424. // Gracefully stop WebSocket hub
  425. if s.wsHub != nil {
  426. s.wsHub.Stop()
  427. }
  428. var err1 error
  429. var err2 error
  430. if s.httpServer != nil {
  431. err1 = s.httpServer.Shutdown(s.ctx)
  432. }
  433. if s.listener != nil {
  434. err2 = s.listener.Close()
  435. }
  436. return common.Combine(err1, err2)
  437. }
  438. // GetCtx returns the server's context for cancellation and deadline management.
  439. func (s *Server) GetCtx() context.Context {
  440. return s.ctx
  441. }
  442. // GetCron returns the server's cron scheduler instance.
  443. func (s *Server) GetCron() *cron.Cron {
  444. return s.cron
  445. }
  446. // GetWSHub returns the WebSocket hub instance.
  447. func (s *Server) GetWSHub() any {
  448. return s.wsHub
  449. }
  450. func (s *Server) RestartXray() error {
  451. return s.xrayService.RestartXray(true)
  452. }