web.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package web
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "embed"
  6. "html/template"
  7. "io"
  8. "io/fs"
  9. "net"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "x-ui/config"
  16. "x-ui/logger"
  17. "x-ui/util/common"
  18. "x-ui/web/controller"
  19. "x-ui/web/job"
  20. "x-ui/web/locale"
  21. "x-ui/web/middleware"
  22. "x-ui/web/network"
  23. "x-ui/web/service"
  24. "github.com/gin-contrib/gzip"
  25. "github.com/gin-contrib/sessions"
  26. "github.com/gin-contrib/sessions/cookie"
  27. "github.com/gin-gonic/gin"
  28. "github.com/robfig/cron/v3"
  29. )
  30. //go:embed assets/*
  31. var assetsFS embed.FS
  32. //go:embed html/*
  33. var htmlFS embed.FS
  34. //go:embed translation/*
  35. var i18nFS embed.FS
  36. var startTime = time.Now()
  37. type wrapAssetsFS struct {
  38. embed.FS
  39. }
  40. func (f *wrapAssetsFS) Open(name string) (fs.File, error) {
  41. file, err := f.FS.Open("assets/" + name)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &wrapAssetsFile{
  46. File: file,
  47. }, nil
  48. }
  49. type wrapAssetsFile struct {
  50. fs.File
  51. }
  52. func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) {
  53. info, err := f.File.Stat()
  54. if err != nil {
  55. return nil, err
  56. }
  57. return &wrapAssetsFileInfo{
  58. FileInfo: info,
  59. }, nil
  60. }
  61. type wrapAssetsFileInfo struct {
  62. fs.FileInfo
  63. }
  64. func (f *wrapAssetsFileInfo) ModTime() time.Time {
  65. return startTime
  66. }
  67. type Server struct {
  68. httpServer *http.Server
  69. listener net.Listener
  70. index *controller.IndexController
  71. server *controller.ServerController
  72. panel *controller.XUIController
  73. api *controller.APIController
  74. xrayService service.XrayService
  75. settingService service.SettingService
  76. tgbotService service.Tgbot
  77. cron *cron.Cron
  78. ctx context.Context
  79. cancel context.CancelFunc
  80. }
  81. func NewServer() *Server {
  82. ctx, cancel := context.WithCancel(context.Background())
  83. return &Server{
  84. ctx: ctx,
  85. cancel: cancel,
  86. }
  87. }
  88. func (s *Server) getHtmlFiles() ([]string, error) {
  89. files := make([]string, 0)
  90. dir, _ := os.Getwd()
  91. err := fs.WalkDir(os.DirFS(dir), "web/html", func(path string, d fs.DirEntry, err error) error {
  92. if err != nil {
  93. return err
  94. }
  95. if d.IsDir() {
  96. return nil
  97. }
  98. files = append(files, path)
  99. return nil
  100. })
  101. if err != nil {
  102. return nil, err
  103. }
  104. return files, nil
  105. }
  106. func (s *Server) getHtmlTemplate(funcMap template.FuncMap) (*template.Template, error) {
  107. t := template.New("").Funcs(funcMap)
  108. err := fs.WalkDir(htmlFS, "html", func(path string, d fs.DirEntry, err error) error {
  109. if err != nil {
  110. return err
  111. }
  112. if d.IsDir() {
  113. newT, err := t.ParseFS(htmlFS, path+"/*.html")
  114. if err != nil {
  115. // ignore
  116. return nil
  117. }
  118. t = newT
  119. }
  120. return nil
  121. })
  122. if err != nil {
  123. return nil, err
  124. }
  125. return t, nil
  126. }
  127. func (s *Server) initRouter() (*gin.Engine, error) {
  128. if config.IsDebug() {
  129. gin.SetMode(gin.DebugMode)
  130. } else {
  131. gin.DefaultWriter = io.Discard
  132. gin.DefaultErrorWriter = io.Discard
  133. gin.SetMode(gin.ReleaseMode)
  134. }
  135. engine := gin.Default()
  136. webDomain, err := s.settingService.GetWebDomain()
  137. if err != nil {
  138. return nil, err
  139. }
  140. if webDomain != "" {
  141. engine.Use(middleware.DomainValidatorMiddleware(webDomain))
  142. }
  143. secret, err := s.settingService.GetSecret()
  144. if err != nil {
  145. return nil, err
  146. }
  147. basePath, err := s.settingService.GetBasePath()
  148. if err != nil {
  149. return nil, err
  150. }
  151. engine.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{basePath + "panel/API/"})))
  152. assetsBasePath := basePath + "assets/"
  153. store := cookie.NewStore(secret)
  154. engine.Use(sessions.Sessions("3x-ui", store))
  155. engine.Use(func(c *gin.Context) {
  156. c.Set("base_path", basePath)
  157. })
  158. engine.Use(func(c *gin.Context) {
  159. uri := c.Request.RequestURI
  160. if strings.HasPrefix(uri, assetsBasePath) {
  161. c.Header("Cache-Control", "max-age=31536000")
  162. }
  163. })
  164. // init i18n
  165. err = locale.InitLocalizer(i18nFS, &s.settingService)
  166. if err != nil {
  167. return nil, err
  168. }
  169. // Apply locale middleware for i18n
  170. i18nWebFunc := func(key string, params ...string) string {
  171. return locale.I18n(locale.Web, key, params...)
  172. }
  173. engine.FuncMap["i18n"] = i18nWebFunc
  174. engine.Use(locale.LocalizerMiddleware())
  175. // set static files and template
  176. if config.IsDebug() {
  177. // for development
  178. files, err := s.getHtmlFiles()
  179. if err != nil {
  180. return nil, err
  181. }
  182. engine.LoadHTMLFiles(files...)
  183. engine.StaticFS(basePath+"assets", http.FS(os.DirFS("web/assets")))
  184. } else {
  185. // for production
  186. template, err := s.getHtmlTemplate(engine.FuncMap)
  187. if err != nil {
  188. return nil, err
  189. }
  190. engine.SetHTMLTemplate(template)
  191. engine.StaticFS(basePath+"assets", http.FS(&wrapAssetsFS{FS: assetsFS}))
  192. }
  193. // Apply the redirect middleware (`/xui` to `/panel`)
  194. engine.Use(middleware.RedirectMiddleware(basePath))
  195. g := engine.Group(basePath)
  196. s.index = controller.NewIndexController(g)
  197. s.server = controller.NewServerController(g)
  198. s.panel = controller.NewXUIController(g)
  199. s.api = controller.NewAPIController(g)
  200. return engine, nil
  201. }
  202. func (s *Server) startTask() {
  203. err := s.xrayService.RestartXray(true)
  204. if err != nil {
  205. logger.Warning("start xray failed:", err)
  206. }
  207. // Check whether xray is running every second
  208. s.cron.AddJob("@every 1s", job.NewCheckXrayRunningJob())
  209. // Check if xray needs to be restarted every 30 seconds
  210. s.cron.AddFunc("@every 30s", func() {
  211. if s.xrayService.IsNeedRestartAndSetFalse() {
  212. err := s.xrayService.RestartXray(false)
  213. if err != nil {
  214. logger.Error("restart xray failed:", err)
  215. }
  216. }
  217. })
  218. go func() {
  219. time.Sleep(time.Second * 5)
  220. // Statistics every 10 seconds, start the delay for 5 seconds for the first time, and staggered with the time to restart xray
  221. s.cron.AddJob("@every 10s", job.NewXrayTrafficJob())
  222. }()
  223. // check client ips from log file every 10 sec
  224. s.cron.AddJob("@every 10s", job.NewCheckClientIpJob())
  225. // check client ips from log file every day
  226. s.cron.AddJob("@daily", job.NewClearLogsJob())
  227. // Make a traffic condition every day, 8:30
  228. var entry cron.EntryID
  229. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  230. if (err == nil) && (isTgbotenabled) {
  231. runtime, err := s.settingService.GetTgbotRuntime()
  232. if err != nil || runtime == "" {
  233. logger.Errorf("Add NewStatsNotifyJob error[%s], Runtime[%s] invalid, will run default", err, runtime)
  234. runtime = "@daily"
  235. }
  236. logger.Infof("Tg notify enabled,run at %s", runtime)
  237. _, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob())
  238. if err != nil {
  239. logger.Warning("Add NewStatsNotifyJob error", err)
  240. return
  241. }
  242. // check for Telegram bot callback query hash storage reset
  243. s.cron.AddJob("@every 2m", job.NewCheckHashStorageJob())
  244. // Check CPU load and alarm to TgBot if threshold passes
  245. cpuThreshold, err := s.settingService.GetTgCpu()
  246. if (err == nil) && (cpuThreshold > 0) {
  247. s.cron.AddJob("@every 10s", job.NewCheckCpuJob())
  248. }
  249. } else {
  250. s.cron.Remove(entry)
  251. }
  252. }
  253. func (s *Server) Start() (err error) {
  254. // This is an anonymous function, no function name
  255. defer func() {
  256. if err != nil {
  257. s.Stop()
  258. }
  259. }()
  260. loc, err := s.settingService.GetTimeLocation()
  261. if err != nil {
  262. return err
  263. }
  264. s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds())
  265. s.cron.Start()
  266. engine, err := s.initRouter()
  267. if err != nil {
  268. return err
  269. }
  270. certFile, err := s.settingService.GetCertFile()
  271. if err != nil {
  272. return err
  273. }
  274. keyFile, err := s.settingService.GetKeyFile()
  275. if err != nil {
  276. return err
  277. }
  278. listen, err := s.settingService.GetListen()
  279. if err != nil {
  280. return err
  281. }
  282. port, err := s.settingService.GetPort()
  283. if err != nil {
  284. return err
  285. }
  286. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  287. listener, err := net.Listen("tcp", listenAddr)
  288. if err != nil {
  289. return err
  290. }
  291. if certFile != "" || keyFile != "" {
  292. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  293. if err == nil {
  294. c := &tls.Config{
  295. Certificates: []tls.Certificate{cert},
  296. }
  297. listener = network.NewAutoHttpsListener(listener)
  298. listener = tls.NewListener(listener, c)
  299. logger.Info("Web server running HTTPS on", listener.Addr())
  300. } else {
  301. logger.Error("Error loading certificates:", err)
  302. logger.Info("Web server running HTTP on", listener.Addr())
  303. }
  304. } else {
  305. logger.Info("Web server running HTTP on", listener.Addr())
  306. }
  307. s.listener = listener
  308. s.httpServer = &http.Server{
  309. Handler: engine,
  310. }
  311. go func() {
  312. s.httpServer.Serve(listener)
  313. }()
  314. s.startTask()
  315. isTgbotenabled, err := s.settingService.GetTgbotEnabled()
  316. if (err == nil) && (isTgbotenabled) {
  317. tgBot := s.tgbotService.NewTgbot()
  318. tgBot.Start(i18nFS)
  319. }
  320. return nil
  321. }
  322. func (s *Server) Stop() error {
  323. s.cancel()
  324. s.xrayService.StopXray()
  325. if s.cron != nil {
  326. s.cron.Stop()
  327. }
  328. if s.tgbotService.IsRunning() {
  329. s.tgbotService.Stop()
  330. }
  331. var err1 error
  332. var err2 error
  333. if s.httpServer != nil {
  334. err1 = s.httpServer.Shutdown(s.ctx)
  335. }
  336. if s.listener != nil {
  337. err2 = s.listener.Close()
  338. }
  339. return common.Combine(err1, err2)
  340. }
  341. func (s *Server) GetCtx() context.Context {
  342. return s.ctx
  343. }
  344. func (s *Server) GetCron() *cron.Cron {
  345. return s.cron
  346. }