sub.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. // set per-request localizer from headers/cookies
  131. engine.Use(locale.LocalizerMiddleware())
  132. // register i18n function similar to web server
  133. i18nWebFunc := func(key string, params ...string) string {
  134. return locale.I18n(locale.Web, key, params...)
  135. }
  136. engine.SetFuncMap(map[string]any{"i18n": i18nWebFunc})
  137. // Templates: prefer embedded; fallback to disk if necessary
  138. if err := setEmbeddedTemplates(engine); err != nil {
  139. logger.Warning("sub: failed to parse embedded templates:", err)
  140. if files, derr := s.getHtmlFiles(); derr == nil {
  141. engine.LoadHTMLFiles(files...)
  142. } else {
  143. logger.Error("sub: no templates available (embedded parse and disk load failed)", err, derr)
  144. }
  145. }
  146. // Assets: use disk if present, fallback to embedded
  147. // Serve under both root (/assets) and under the subscription path prefix (LinksPath + "assets")
  148. // so reverse proxies with a URI prefix can load assets correctly.
  149. // Determine LinksPath earlier to compute prefixed assets mount.
  150. // Note: LinksPath always starts and ends with "/" (validated in settings).
  151. var linksPathForAssets string
  152. if LinksPath == "/" {
  153. linksPathForAssets = "/assets"
  154. } else {
  155. // ensure single slash join
  156. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  157. }
  158. // Mount assets in multiple paths to handle different URL patterns
  159. var assetsFS http.FileSystem
  160. if _, err := os.Stat("web/assets"); err == nil {
  161. assetsFS = http.FS(os.DirFS("web/assets"))
  162. } else {
  163. if subFS, err := fs.Sub(webpkg.EmbeddedAssets(), "assets"); err == nil {
  164. assetsFS = http.FS(subFS)
  165. } else {
  166. logger.Error("sub: failed to mount embedded assets:", err)
  167. }
  168. }
  169. if assetsFS != nil {
  170. engine.StaticFS("/assets", assetsFS)
  171. if linksPathForAssets != "/assets" {
  172. engine.StaticFS(linksPathForAssets, assetsFS)
  173. }
  174. // Add middleware to handle dynamic asset paths with subid
  175. if LinksPath != "/" {
  176. engine.Use(func(c *gin.Context) {
  177. path := c.Request.URL.Path
  178. // Check if this is an asset request with subid pattern: /sub/path/{subid}/assets/...
  179. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  180. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  181. // Extract the asset path after /assets/
  182. assetsIndex := strings.Index(path, "/assets/")
  183. if assetsIndex != -1 {
  184. assetPath := path[assetsIndex+8:] // +8 to skip "/assets/"
  185. if assetPath != "" {
  186. // Serve the asset file
  187. c.FileFromFS(assetPath, assetsFS)
  188. c.Abort()
  189. return
  190. }
  191. }
  192. }
  193. c.Next()
  194. })
  195. }
  196. }
  197. g := engine.Group("/")
  198. s.sub = NewSUBController(
  199. g, LinksPath, JsonPath, subJsonEnable, Encrypt, ShowInfo, RemarkModel, SubUpdates,
  200. SubJsonFragment, SubJsonNoises, SubJsonMux, SubJsonRules, SubTitle)
  201. return engine, nil
  202. }
  203. // getHtmlFiles loads templates from local folder (used in debug mode)
  204. func (s *Server) getHtmlFiles() ([]string, error) {
  205. dir, _ := os.Getwd()
  206. files := []string{}
  207. // common layout
  208. common := filepath.Join(dir, "web", "html", "common", "page.html")
  209. if _, err := os.Stat(common); err == nil {
  210. files = append(files, common)
  211. }
  212. // components used
  213. theme := filepath.Join(dir, "web", "html", "component", "aThemeSwitch.html")
  214. if _, err := os.Stat(theme); err == nil {
  215. files = append(files, theme)
  216. }
  217. // page itself
  218. page := filepath.Join(dir, "web", "html", "subpage.html")
  219. if _, err := os.Stat(page); err == nil {
  220. files = append(files, page)
  221. } else {
  222. return nil, err
  223. }
  224. return files, nil
  225. }
  226. // Start initializes and starts the subscription server with configured settings.
  227. func (s *Server) Start() (err error) {
  228. // This is an anonymous function, no function name
  229. defer func() {
  230. if err != nil {
  231. s.Stop()
  232. }
  233. }()
  234. subEnable, err := s.settingService.GetSubEnable()
  235. if err != nil {
  236. return err
  237. }
  238. if !subEnable {
  239. return nil
  240. }
  241. engine, err := s.initRouter()
  242. if err != nil {
  243. return err
  244. }
  245. certFile, err := s.settingService.GetSubCertFile()
  246. if err != nil {
  247. return err
  248. }
  249. keyFile, err := s.settingService.GetSubKeyFile()
  250. if err != nil {
  251. return err
  252. }
  253. listen, err := s.settingService.GetSubListen()
  254. if err != nil {
  255. return err
  256. }
  257. port, err := s.settingService.GetSubPort()
  258. if err != nil {
  259. return err
  260. }
  261. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  262. listener, err := net.Listen("tcp", listenAddr)
  263. if err != nil {
  264. return err
  265. }
  266. if certFile != "" || keyFile != "" {
  267. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  268. if err == nil {
  269. c := &tls.Config{
  270. Certificates: []tls.Certificate{cert},
  271. }
  272. listener = network.NewAutoHttpsListener(listener)
  273. listener = tls.NewListener(listener, c)
  274. logger.Info("Sub server running HTTPS on", listener.Addr())
  275. } else {
  276. logger.Error("Error loading certificates:", err)
  277. logger.Info("Sub server running HTTP on", listener.Addr())
  278. }
  279. } else {
  280. logger.Info("Sub server running HTTP on", listener.Addr())
  281. }
  282. s.listener = listener
  283. s.httpServer = &http.Server{
  284. Handler: engine,
  285. }
  286. go func() {
  287. s.httpServer.Serve(listener)
  288. }()
  289. return nil
  290. }
  291. // Stop gracefully shuts down the subscription server and closes the listener.
  292. func (s *Server) Stop() error {
  293. s.cancel()
  294. var err1 error
  295. var err2 error
  296. if s.httpServer != nil {
  297. err1 = s.httpServer.Shutdown(s.ctx)
  298. }
  299. if s.listener != nil {
  300. err2 = s.listener.Close()
  301. }
  302. return common.Combine(err1, err2)
  303. }
  304. // GetCtx returns the server's context for cancellation and deadline management.
  305. func (s *Server) GetCtx() context.Context {
  306. return s.ctx
  307. }