web.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. if sessionMaxAge, err := s.settingService.GetSessionMaxAge(); err == nil {
  179. store.Options(sessions.Options{
  180. Path: "/",
  181. MaxAge: sessionMaxAge * 60, // minutes -> seconds
  182. HttpOnly: true,
  183. SameSite: http.SameSiteLaxMode,
  184. })
  185. }
  186. engine.Use(sessions.Sessions("3x-ui", store))
  187. engine.Use(func(c *gin.Context) {
  188. c.Set("base_path", basePath)
  189. })
  190. engine.Use(func(c *gin.Context) {
  191. uri := c.Request.RequestURI
  192. if strings.HasPrefix(uri, assetsBasePath) {
  193. c.Header("Cache-Control", "max-age=31536000")
  194. }
  195. })
  196. // init i18n
  197. err = locale.InitLocalizer(i18nFS, &s.settingService)
  198. if err != nil {
  199. return nil, err
  200. }
  201. // Apply locale middleware for i18n
  202. i18nWebFunc := func(key string, params ...string) string {
  203. return locale.I18n(locale.Web, key, params...)
  204. }
  205. // Register template functions before loading templates
  206. funcMap := template.FuncMap{
  207. "i18n": i18nWebFunc,
  208. }
  209. engine.SetFuncMap(funcMap)
  210. engine.Use(locale.LocalizerMiddleware())
  211. // set static files and template
  212. if config.IsDebug() {
  213. // for development
  214. files, err := s.getHtmlFiles()
  215. if err != nil {
  216. return nil, err
  217. }
  218. // Use the registered func map with the loaded templates
  219. engine.LoadHTMLFiles(files...)
  220. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("web/assets")))
  221. } else {
  222. // for production
  223. template, err := s.getHtmlTemplate(funcMap)
  224. if err != nil {
  225. return nil, err
  226. }
  227. engine.SetHTMLTemplate(template)
  228. engine.StaticFS(basePath+"assets", http.FS(&wrapAssetsFS{FS: assetsFS}))
  229. }
  230. // Apply the redirect middleware (`/xui` to `/panel`)
  231. engine.Use(middleware.RedirectMiddleware(basePath))
  232. g := engine.Group(basePath)
  233. s.index = controller.NewIndexController(g)
  234. s.panel = controller.NewXUIController(g)
  235. s.api = controller.NewAPIController(g, s.customGeoService)
  236. // Initialize WebSocket hub
  237. s.wsHub = websocket.NewHub()
  238. go s.wsHub.Run()
  239. // Initialize WebSocket controller
  240. s.ws = controller.NewWebSocketController(s.wsHub)
  241. // Register WebSocket route with basePath (g already has basePath prefix)
  242. g.GET("/ws", s.ws.HandleWebSocket)
  243. // Chrome DevTools endpoint for debugging web apps
  244. engine.GET("/.well-known/appspecific/com.chrome.devtools.json", func(c *gin.Context) {
  245. c.JSON(http.StatusOK, gin.H{})
  246. })
  247. // Add a catch-all route to handle undefined paths and return 404
  248. engine.NoRoute(func(c *gin.Context) {
  249. c.AbortWithStatus(http.StatusNotFound)
  250. })
  251. return engine, nil
  252. }
  253. // normalizeExistingGeositeFiles normalizes country codes in all geosite .dat
  254. // files found in the bin directory so Xray-core can locate entries correctly.
  255. func normalizeExistingGeositeFiles() {
  256. binDir := config.GetBinFolderPath()
  257. matches, err := filepath.Glob(filepath.Join(binDir, "geosite*.dat"))
  258. if err != nil {
  259. logger.Warningf("Failed to glob geosite files: %v", err)
  260. return
  261. }
  262. for _, path := range matches {
  263. if err := service.NormalizeGeositeCountryCodes(path); err != nil {
  264. logger.Warningf("Failed to normalize geosite country codes in %s: %v", path, err)
  265. }
  266. }
  267. }
  268. // startTask schedules background jobs (Xray checks, traffic jobs, cron
  269. // jobs) which the panel relies on for periodic maintenance and monitoring.
  270. func (s *Server) startTask() {
  271. normalizeExistingGeositeFiles()
  272. s.customGeoService.EnsureOnStartup()
  273. err := s.xrayService.RestartXray(true)
  274. if err != nil {
  275. logger.Warning("start xray failed:", err)
  276. }
  277. // Check whether xray is running every second
  278. s.cron.AddJob("@every 1s", job.NewCheckXrayRunningJob())
  279. // Check if xray needs to be restarted every 30 seconds
  280. s.cron.AddFunc("@every 30s", func() {
  281. if s.xrayService.IsNeedRestartAndSetFalse() {
  282. err := s.xrayService.RestartXray(false)
  283. if err != nil {
  284. logger.Error("restart xray failed:", err)
  285. }
  286. }
  287. })
  288. go func() {
  289. time.Sleep(time.Second * 5)
  290. // Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray
  291. s.cron.AddJob("@every 10s", job.NewXrayTrafficJob())
  292. }()
  293. // check client ips from log file every 10 sec
  294. s.cron.AddJob("@every 10s", job.NewCheckClientIpJob())
  295. // check client ips from log file every day
  296. s.cron.AddJob("@daily", job.NewClearLogsJob())
  297. // Inbound traffic reset jobs
  298. // Run every hour
  299. s.cron.AddJob("@hourly", job.NewPeriodicTrafficResetJob("hourly"))
  300. // Run once a day, midnight
  301. s.cron.AddJob("@daily", job.NewPeriodicTrafficResetJob("daily"))
  302. // Run once a week, midnight between Sat/Sun
  303. s.cron.AddJob("@weekly", job.NewPeriodicTrafficResetJob("weekly"))
  304. // Run once a month, midnight, first of month
  305. s.cron.AddJob("@monthly", job.NewPeriodicTrafficResetJob("monthly"))
  306. // LDAP sync scheduling
  307. if ldapEnabled, _ := s.settingService.GetLdapEnable(); ldapEnabled {
  308. runtime, err := s.settingService.GetLdapSyncCron()
  309. if err != nil || runtime == "" {
  310. runtime = "@every 1m"
  311. }
  312. j := job.NewLdapSyncJob()
  313. // job has zero-value services with method receivers that read settings on demand
  314. s.cron.AddJob(runtime, j)
  315. }
  316. // Make a traffic condition every day, 8:30
  317. var entry cron.EntryID
  318. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  319. if (err == nil) && (isTgbotenabled) {
  320. runtime, err := s.settingService.GetTgbotRuntime()
  321. if err != nil || runtime == "" {
  322. logger.Errorf("Add NewStatsNotifyJob error[%s], Runtime[%s] invalid, will run default", err, runtime)
  323. runtime = "@daily"
  324. }
  325. logger.Infof("Tg notify enabled,run at %s", runtime)
  326. _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob())
  327. if err != nil {
  328. logger.Warning("Add NewStatsNotifyJob error", err)
  329. return
  330. }
  331. // check for Telegram bot callback query hash storage reset
  332. s.cron.AddJob("@every 2m", job.NewCheckHashStorageJob())
  333. // Check CPU load and alarm to TgBot if threshold passes
  334. cpuThreshold, err := s.settingService.GetTgCpu()
  335. if (err == nil) && (cpuThreshold > 0) {
  336. s.cron.AddJob("@every 10s", job.NewCheckCpuJob())
  337. }
  338. } else {
  339. s.cron.Remove(entry)
  340. }
  341. }
  342. // Start initializes and starts the web server with configured settings, routes, and background jobs.
  343. func (s *Server) Start() (err error) {
  344. // This is an anonymous function, no function name
  345. defer func() {
  346. if err != nil {
  347. s.Stop()
  348. }
  349. }()
  350. loc, err := s.settingService.GetTimeLocation()
  351. if err != nil {
  352. return err
  353. }
  354. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
  355. s.cron.Start()
  356. s.customGeoService = service.NewCustomGeoService()
  357. engine, err := s.initRouter()
  358. if err != nil {
  359. return err
  360. }
  361. certFile, err := s.settingService.GetCertFile()
  362. if err != nil {
  363. return err
  364. }
  365. keyFile, err := s.settingService.GetKeyFile()
  366. if err != nil {
  367. return err
  368. }
  369. listen, err := s.settingService.GetListen()
  370. if err != nil {
  371. return err
  372. }
  373. port, err := s.settingService.GetPort()
  374. if err != nil {
  375. return err
  376. }
  377. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  378. listener, err := net.Listen("tcp", listenAddr)
  379. if err != nil {
  380. return err
  381. }
  382. if certFile != "" || keyFile != "" {
  383. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  384. if err == nil {
  385. c := &tls.Config{
  386. Certificates: []tls.Certificate{cert},
  387. }
  388. listener = network.NewAutoHttpsListener(listener)
  389. listener = tls.NewListener(listener, c)
  390. logger.Info("Web server running HTTPS on", listener.Addr())
  391. } else {
  392. logger.Error("Error loading certificates:", err)
  393. logger.Info("Web server running HTTP on", listener.Addr())
  394. }
  395. } else {
  396. logger.Info("Web server running HTTP on", listener.Addr())
  397. }
  398. s.listener = listener
  399. s.httpServer = &http.Server{
  400. Handler: engine,
  401. }
  402. go func() {
  403. s.httpServer.Serve(listener)
  404. }()
  405. s.startTask()
  406. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  407. if (err == nil) && (isTgbotenabled) {
  408. tgBot := s.tgbotService.NewTgbot()
  409. tgBot.Start(i18nFS)
  410. }
  411. return nil
  412. }
  413. // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot.
  414. func (s *Server) Stop() error {
  415. s.cancel()
  416. s.xrayService.StopXray()
  417. if s.cron != nil {
  418. s.cron.Stop()
  419. }
  420. if s.tgbotService.IsRunning() {
  421. s.tgbotService.Stop()
  422. }
  423. // Gracefully stop WebSocket hub
  424. if s.wsHub != nil {
  425. s.wsHub.Stop()
  426. }
  427. var err1 error
  428. var err2 error
  429. if s.httpServer != nil {
  430. err1 = s.httpServer.Shutdown(s.ctx)
  431. }
  432. if s.listener != nil {
  433. err2 = s.listener.Close()
  434. }
  435. return common.Combine(err1, err2)
  436. }
  437. // GetCtx returns the server's context for cancellation and deadline management.
  438. func (s *Server) GetCtx() context.Context {
  439. return s.ctx
  440. }
  441. // GetCron returns the server's cron scheduler instance.
  442. func (s *Server) GetCron() *cron.Cron {
  443. return s.cron
  444. }
  445. // GetWSHub returns the WebSocket hub instance.
  446. func (s *Server) GetWSHub() any {
  447. return s.wsHub
  448. }
  449. func (s *Server) RestartXray() error {
  450. return s.xrayService.RestartXray(true)
  451. }