sub.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // Package sub provides subscription server functionality for the 3x-ui panel,
  2. // including HTTP/HTTPS servers for serving subscription links and JSON configurations.
  3. package sub
  4. import (
  5. "context"
  6. "crypto/tls"
  7. "html/template"
  8. "io"
  9. "io/fs"
  10. "net"
  11. "net/http"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "github.com/mhsanaei/3x-ui/v2/logger"
  17. "github.com/mhsanaei/3x-ui/v2/util/common"
  18. webpkg "github.com/mhsanaei/3x-ui/v2/web"
  19. "github.com/mhsanaei/3x-ui/v2/web/locale"
  20. "github.com/mhsanaei/3x-ui/v2/web/middleware"
  21. "github.com/mhsanaei/3x-ui/v2/web/network"
  22. "github.com/mhsanaei/3x-ui/v2/web/service"
  23. "github.com/gin-gonic/gin"
  24. )
  25. // setEmbeddedTemplates parses and sets embedded templates on the engine
  26. func setEmbeddedTemplates(engine *gin.Engine) error {
  27. t, err := template.New("").Funcs(engine.FuncMap).ParseFS(
  28. webpkg.EmbeddedHTML(),
  29. "html/common/page.html",
  30. "html/component/aThemeSwitch.html",
  31. "html/settings/panel/subscription/subpage.html",
  32. )
  33. if err != nil {
  34. return err
  35. }
  36. engine.SetHTMLTemplate(t)
  37. return nil
  38. }
  39. // Server represents the subscription server that serves subscription links and JSON configurations.
  40. type Server struct {
  41. httpServer *http.Server
  42. listener net.Listener
  43. sub *SUBController
  44. settingService service.SettingService
  45. ctx context.Context
  46. cancel context.CancelFunc
  47. }
  48. // NewServer creates a new subscription server instance with a cancellable context.
  49. func NewServer() *Server {
  50. ctx, cancel := context.WithCancel(context.Background())
  51. return &Server{
  52. ctx: ctx,
  53. cancel: cancel,
  54. }
  55. }
  56. // initRouter configures the subscription server's Gin engine, middleware,
  57. // templates and static assets and returns the ready-to-use engine.
  58. func (s *Server) initRouter() (*gin.Engine, error) {
  59. // Always run in release mode for the subscription server
  60. gin.DefaultWriter = io.Discard
  61. gin.DefaultErrorWriter = io.Discard
  62. gin.SetMode(gin.ReleaseMode)
  63. engine := gin.Default()
  64. subDomain, err := s.settingService.GetSubDomain()
  65. if err != nil {
  66. return nil, err
  67. }
  68. if subDomain != "" {
  69. engine.Use(middleware.DomainValidatorMiddleware(subDomain))
  70. }
  71. LinksPath, err := s.settingService.GetSubPath()
  72. if err != nil {
  73. return nil, err
  74. }
  75. JsonPath, err := s.settingService.GetSubJsonPath()
  76. if err != nil {
  77. return nil, err
  78. }
  79. // Determine if JSON subscription endpoint is enabled
  80. subJsonEnable, err := s.settingService.GetSubJsonEnable()
  81. if err != nil {
  82. return nil, err
  83. }
  84. // Set base_path based on LinksPath for template rendering
  85. // Ensure LinksPath ends with "/" for proper asset URL generation
  86. basePath := LinksPath
  87. if basePath != "/" && !strings.HasSuffix(basePath, "/") {
  88. basePath += "/"
  89. }
  90. // logger.Debug("sub: Setting base_path to:", basePath)
  91. engine.Use(func(c *gin.Context) {
  92. c.Set("base_path", basePath)
  93. })
  94. Encrypt, err := s.settingService.GetSubEncrypt()
  95. if err != nil {
  96. return nil, err
  97. }
  98. ShowInfo, err := s.settingService.GetSubShowInfo()
  99. if err != nil {
  100. return nil, err
  101. }
  102. RemarkModel, err := s.settingService.GetRemarkModel()
  103. if err != nil {
  104. RemarkModel = "-ieo"
  105. }
  106. SubUpdates, err := s.settingService.GetSubUpdates()
  107. if err != nil {
  108. SubUpdates = "10"
  109. }
  110. SubJsonFragment, err := s.settingService.GetSubJsonFragment()
  111. if err != nil {
  112. SubJsonFragment = ""
  113. }
  114. SubJsonNoises, err := s.settingService.GetSubJsonNoises()
  115. if err != nil {
  116. SubJsonNoises = ""
  117. }
  118. SubJsonMux, err := s.settingService.GetSubJsonMux()
  119. if err != nil {
  120. SubJsonMux = ""
  121. }
  122. SubJsonRules, err := s.settingService.GetSubJsonRules()
  123. if err != nil {
  124. SubJsonRules = ""
  125. }
  126. SubTitle, err := s.settingService.GetSubTitle()
  127. if err != nil {
  128. SubTitle = ""
  129. }
  130. SubSupportUrl, err := s.settingService.GetSubSupportUrl()
  131. if err != nil {
  132. SubSupportUrl = ""
  133. }
  134. SubProfileUrl, err := s.settingService.GetSubProfileUrl()
  135. if err != nil {
  136. SubProfileUrl = ""
  137. }
  138. SubAnnounce, err := s.settingService.GetSubAnnounce()
  139. if err != nil {
  140. SubAnnounce = ""
  141. }
  142. SubEnableRouting, err := s.settingService.GetSubEnableRouting()
  143. if err != nil {
  144. return nil, err
  145. }
  146. SubRoutingRules, err := s.settingService.GetSubRoutingRules()
  147. if err != nil {
  148. SubRoutingRules = ""
  149. }
  150. // set per-request localizer from headers/cookies
  151. engine.Use(locale.LocalizerMiddleware())
  152. // register i18n function similar to web server
  153. i18nWebFunc := func(key string, params ...string) string {
  154. return locale.I18n(locale.Web, key, params...)
  155. }
  156. engine.SetFuncMap(map[string]any{"i18n": i18nWebFunc})
  157. // Templates: prefer embedded; fallback to disk if necessary
  158. if err := setEmbeddedTemplates(engine); err != nil {
  159. logger.Warning("sub: failed to parse embedded templates:", err)
  160. if files, derr := s.getHtmlFiles(); derr == nil {
  161. engine.LoadHTMLFiles(files...)
  162. } else {
  163. logger.Error("sub: no templates available (embedded parse and disk load failed)", err, derr)
  164. }
  165. }
  166. // Assets: use disk if present, fallback to embedded
  167. // Serve under both root (/assets) and under the subscription path prefix (LinksPath + "assets")
  168. // so reverse proxies with a URI prefix can load assets correctly.
  169. // Determine LinksPath earlier to compute prefixed assets mount.
  170. // Note: LinksPath always starts and ends with "/" (validated in settings).
  171. var linksPathForAssets string
  172. if LinksPath == "/" {
  173. linksPathForAssets = "/assets"
  174. } else {
  175. // ensure single slash join
  176. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  177. }
  178. // Mount assets in multiple paths to handle different URL patterns
  179. var assetsFS http.FileSystem
  180. if _, err := os.Stat("web/assets"); err == nil {
  181. assetsFS = http.FS(os.DirFS("web/assets"))
  182. } else {
  183. if subFS, err := fs.Sub(webpkg.EmbeddedAssets(), "assets"); err == nil {
  184. assetsFS = http.FS(subFS)
  185. } else {
  186. logger.Error("sub: failed to mount embedded assets:", err)
  187. }
  188. }
  189. if assetsFS != nil {
  190. engine.StaticFS("/assets", assetsFS)
  191. if linksPathForAssets != "/assets" {
  192. engine.StaticFS(linksPathForAssets, assetsFS)
  193. }
  194. // Add middleware to handle dynamic asset paths with subid
  195. if LinksPath != "/" {
  196. engine.Use(func(c *gin.Context) {
  197. path := c.Request.URL.Path
  198. // Check if this is an asset request with subid pattern: /sub/path/{subid}/assets/...
  199. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  200. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  201. // Extract the asset path after /assets/
  202. assetsIndex := strings.Index(path, "/assets/")
  203. if assetsIndex != -1 {
  204. assetPath := path[assetsIndex+8:] // +8 to skip "/assets/"
  205. if assetPath != "" {
  206. // Serve the asset file
  207. c.FileFromFS(assetPath, assetsFS)
  208. c.Abort()
  209. return
  210. }
  211. }
  212. }
  213. c.Next()
  214. })
  215. }
  216. }
  217. g := engine.Group("/")
  218. s.sub = NewSUBController(
  219. g, LinksPath, JsonPath, subJsonEnable, Encrypt, ShowInfo, RemarkModel, SubUpdates,
  220. SubJsonFragment, SubJsonNoises, SubJsonMux, SubJsonRules, SubTitle, SubSupportUrl,
  221. SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules)
  222. return engine, nil
  223. }
  224. // getHtmlFiles loads templates from local folder (used in debug mode)
  225. func (s *Server) getHtmlFiles() ([]string, error) {
  226. dir, _ := os.Getwd()
  227. files := []string{}
  228. // common layout
  229. common := filepath.Join(dir, "web", "html", "common", "page.html")
  230. if _, err := os.Stat(common); err == nil {
  231. files = append(files, common)
  232. }
  233. // components used
  234. theme := filepath.Join(dir, "web", "html", "component", "aThemeSwitch.html")
  235. if _, err := os.Stat(theme); err == nil {
  236. files = append(files, theme)
  237. }
  238. // page itself
  239. page := filepath.Join(dir, "web", "html", "subpage.html")
  240. if _, err := os.Stat(page); err == nil {
  241. files = append(files, page)
  242. } else {
  243. return nil, err
  244. }
  245. return files, nil
  246. }
  247. // Start initializes and starts the subscription server with configured settings.
  248. func (s *Server) Start() (err error) {
  249. // This is an anonymous function, no function name
  250. defer func() {
  251. if err != nil {
  252. s.Stop()
  253. }
  254. }()
  255. subEnable, err := s.settingService.GetSubEnable()
  256. if err != nil {
  257. return err
  258. }
  259. if !subEnable {
  260. return nil
  261. }
  262. engine, err := s.initRouter()
  263. if err != nil {
  264. return err
  265. }
  266. certFile, err := s.settingService.GetSubCertFile()
  267. if err != nil {
  268. return err
  269. }
  270. keyFile, err := s.settingService.GetSubKeyFile()
  271. if err != nil {
  272. return err
  273. }
  274. listen, err := s.settingService.GetSubListen()
  275. if err != nil {
  276. return err
  277. }
  278. port, err := s.settingService.GetSubPort()
  279. if err != nil {
  280. return err
  281. }
  282. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  283. listener, err := net.Listen("tcp", listenAddr)
  284. if err != nil {
  285. return err
  286. }
  287. if certFile != "" || keyFile != "" {
  288. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  289. if err == nil {
  290. c := &tls.Config{
  291. Certificates: []tls.Certificate{cert},
  292. }
  293. listener = network.NewAutoHttpsListener(listener)
  294. listener = tls.NewListener(listener, c)
  295. logger.Info("Sub server running HTTPS on", listener.Addr())
  296. } else {
  297. logger.Error("Error loading certificates:", err)
  298. logger.Info("Sub server running HTTP on", listener.Addr())
  299. }
  300. } else {
  301. logger.Info("Sub server running HTTP on", listener.Addr())
  302. }
  303. s.listener = listener
  304. s.httpServer = &http.Server{
  305. Handler: engine,
  306. }
  307. go func() {
  308. s.httpServer.Serve(listener)
  309. }()
  310. return nil
  311. }
  312. // Stop gracefully shuts down the subscription server and closes the listener.
  313. func (s *Server) Stop() error {
  314. s.cancel()
  315. var err1 error
  316. var err2 error
  317. if s.httpServer != nil {
  318. err1 = s.httpServer.Shutdown(s.ctx)
  319. }
  320. if s.listener != nil {
  321. err2 = s.listener.Close()
  322. }
  323. return common.Combine(err1, err2)
  324. }
  325. // GetCtx returns the server's context for cancellation and deadline management.
  326. func (s *Server) GetCtx() context.Context {
  327. return s.ctx
  328. }