sub.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. "io"
  8. "io/fs"
  9. "net"
  10. "net/http"
  11. "os"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. webpkg "github.com/mhsanaei/3x-ui/v3/web"
  18. "github.com/mhsanaei/3x-ui/v3/web/locale"
  19. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  20. "github.com/mhsanaei/3x-ui/v3/web/network"
  21. "github.com/mhsanaei/3x-ui/v3/web/service"
  22. "github.com/gin-gonic/gin"
  23. )
  24. // Server represents the subscription server that serves subscription links and JSON configurations.
  25. type Server struct {
  26. httpServer *http.Server
  27. listener net.Listener
  28. sub *SUBController
  29. settingService service.SettingService
  30. ctx context.Context
  31. cancel context.CancelFunc
  32. }
  33. // NewServer creates a new subscription server instance with a cancellable context.
  34. func NewServer() *Server {
  35. ctx, cancel := context.WithCancel(context.Background())
  36. return &Server{
  37. ctx: ctx,
  38. cancel: cancel,
  39. }
  40. }
  41. // initRouter configures the subscription server's Gin engine, middleware,
  42. // templates and static assets and returns the ready-to-use engine.
  43. func (s *Server) initRouter() (*gin.Engine, error) {
  44. // Always run in release mode for the subscription server
  45. gin.DefaultWriter = io.Discard
  46. gin.DefaultErrorWriter = io.Discard
  47. gin.SetMode(gin.ReleaseMode)
  48. engine := gin.Default()
  49. subDomain, err := s.settingService.GetSubDomain()
  50. if err != nil {
  51. return nil, err
  52. }
  53. if subDomain != "" {
  54. engine.Use(middleware.DomainValidatorMiddleware(subDomain))
  55. }
  56. LinksPath, err := s.settingService.GetSubPath()
  57. if err != nil {
  58. return nil, err
  59. }
  60. JsonPath, err := s.settingService.GetSubJsonPath()
  61. if err != nil {
  62. return nil, err
  63. }
  64. ClashPath, err := s.settingService.GetSubClashPath()
  65. if err != nil {
  66. return nil, err
  67. }
  68. subJsonEnable, err := s.settingService.GetSubJsonEnable()
  69. if err != nil {
  70. return nil, err
  71. }
  72. subClashEnable, err := s.settingService.GetSubClashEnable()
  73. if err != nil {
  74. return nil, err
  75. }
  76. // Set base_path based on LinksPath for template rendering
  77. // Ensure LinksPath ends with "/" for proper asset URL generation
  78. basePath := LinksPath
  79. if basePath != "/" && !strings.HasSuffix(basePath, "/") {
  80. basePath += "/"
  81. }
  82. // logger.Debug("sub: Setting base_path to:", basePath)
  83. engine.Use(func(c *gin.Context) {
  84. c.Set("base_path", basePath)
  85. })
  86. Encrypt, err := s.settingService.GetSubEncrypt()
  87. if err != nil {
  88. return nil, err
  89. }
  90. ShowInfo, err := s.settingService.GetSubShowInfo()
  91. if err != nil {
  92. return nil, err
  93. }
  94. RemarkModel, err := s.settingService.GetRemarkModel()
  95. if err != nil {
  96. RemarkModel = "-ieo"
  97. }
  98. SubUpdates, err := s.settingService.GetSubUpdates()
  99. if err != nil {
  100. SubUpdates = "10"
  101. }
  102. SubJsonFragment, err := s.settingService.GetSubJsonFragment()
  103. if err != nil {
  104. SubJsonFragment = ""
  105. }
  106. SubJsonNoises, err := s.settingService.GetSubJsonNoises()
  107. if err != nil {
  108. SubJsonNoises = ""
  109. }
  110. SubJsonMux, err := s.settingService.GetSubJsonMux()
  111. if err != nil {
  112. SubJsonMux = ""
  113. }
  114. SubJsonRules, err := s.settingService.GetSubJsonRules()
  115. if err != nil {
  116. SubJsonRules = ""
  117. }
  118. SubTitle, err := s.settingService.GetSubTitle()
  119. if err != nil {
  120. SubTitle = ""
  121. }
  122. SubSupportUrl, err := s.settingService.GetSubSupportUrl()
  123. if err != nil {
  124. SubSupportUrl = ""
  125. }
  126. SubProfileUrl, err := s.settingService.GetSubProfileUrl()
  127. if err != nil {
  128. SubProfileUrl = ""
  129. }
  130. SubAnnounce, err := s.settingService.GetSubAnnounce()
  131. if err != nil {
  132. SubAnnounce = ""
  133. }
  134. SubEnableRouting, err := s.settingService.GetSubEnableRouting()
  135. if err != nil {
  136. return nil, err
  137. }
  138. SubRoutingRules, err := s.settingService.GetSubRoutingRules()
  139. if err != nil {
  140. SubRoutingRules = ""
  141. }
  142. // set per-request localizer from headers/cookies
  143. engine.Use(locale.LocalizerMiddleware())
  144. // Mount the Vite-built dist/assets/ so the subscription page's JS/CSS
  145. // bundles load from `/assets/...`. Also mount the same FS under the
  146. // subscription path prefix (LinksPath + "assets") so reverse proxies
  147. // running the panel under a URI prefix can resolve those URLs too.
  148. // Note: LinksPath always starts and ends with "/" (validated in settings).
  149. var linksPathForAssets string
  150. if LinksPath == "/" {
  151. linksPathForAssets = "/assets"
  152. } else {
  153. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  154. }
  155. var assetsFS http.FileSystem
  156. if _, err := os.Stat("web/dist/assets"); err == nil {
  157. assetsFS = http.FS(os.DirFS("web/dist/assets"))
  158. } else if subFS, err := fs.Sub(webpkg.EmbeddedDist(), "dist/assets"); err == nil {
  159. assetsFS = http.FS(subFS)
  160. } else {
  161. logger.Error("sub: failed to mount embedded dist assets:", err)
  162. }
  163. if assetsFS != nil {
  164. engine.StaticFS("/assets", assetsFS)
  165. if linksPathForAssets != "/assets" {
  166. engine.StaticFS(linksPathForAssets, assetsFS)
  167. }
  168. // Browser may resolve subpage assets relative to the request URL —
  169. // /sub/<basePath>/<subId>/assets/... — so route those to the same FS.
  170. if LinksPath != "/" {
  171. engine.Use(func(c *gin.Context) {
  172. path := c.Request.URL.Path
  173. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  174. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  175. assetsIndex := strings.Index(path, "/assets/")
  176. if assetsIndex != -1 {
  177. assetPath := path[assetsIndex+8:] // +8 to skip "/assets/"
  178. if assetPath != "" {
  179. c.FileFromFS(assetPath, assetsFS)
  180. c.Abort()
  181. return
  182. }
  183. }
  184. }
  185. c.Next()
  186. })
  187. }
  188. }
  189. g := engine.Group("/")
  190. s.sub = NewSUBController(
  191. g, LinksPath, JsonPath, ClashPath, subJsonEnable, subClashEnable, Encrypt, ShowInfo, RemarkModel, SubUpdates,
  192. SubJsonFragment, SubJsonNoises, SubJsonMux, SubJsonRules, SubTitle, SubSupportUrl,
  193. SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules)
  194. return engine, nil
  195. }
  196. // Start initializes and starts the subscription server with configured settings.
  197. func (s *Server) Start() (err error) {
  198. // This is an anonymous function, no function name
  199. defer func() {
  200. if err != nil {
  201. s.Stop()
  202. }
  203. }()
  204. subEnable, err := s.settingService.GetSubEnable()
  205. if err != nil {
  206. return err
  207. }
  208. if !subEnable {
  209. return nil
  210. }
  211. engine, err := s.initRouter()
  212. if err != nil {
  213. return err
  214. }
  215. certFile, err := s.settingService.GetSubCertFile()
  216. if err != nil {
  217. return err
  218. }
  219. keyFile, err := s.settingService.GetSubKeyFile()
  220. if err != nil {
  221. return err
  222. }
  223. listen, err := s.settingService.GetSubListen()
  224. if err != nil {
  225. return err
  226. }
  227. port, err := s.settingService.GetSubPort()
  228. if err != nil {
  229. return err
  230. }
  231. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  232. listener, err := net.Listen("tcp", listenAddr)
  233. if err != nil {
  234. return err
  235. }
  236. if certFile != "" || keyFile != "" {
  237. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  238. if err == nil {
  239. c := &tls.Config{
  240. Certificates: []tls.Certificate{cert},
  241. }
  242. listener = network.NewAutoHttpsListener(listener)
  243. listener = tls.NewListener(listener, c)
  244. logger.Info("Sub server running HTTPS on", listener.Addr())
  245. } else {
  246. logger.Error("Error loading certificates:", err)
  247. logger.Info("Sub server running HTTP on", listener.Addr())
  248. }
  249. } else {
  250. logger.Info("Sub server running HTTP on", listener.Addr())
  251. }
  252. s.listener = listener
  253. s.httpServer = &http.Server{
  254. Handler: engine,
  255. }
  256. go func() {
  257. s.httpServer.Serve(listener)
  258. }()
  259. return nil
  260. }
  261. // Stop gracefully shuts down the subscription server and closes the listener.
  262. func (s *Server) Stop() error {
  263. s.cancel()
  264. var err1 error
  265. var err2 error
  266. if s.httpServer != nil {
  267. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  268. defer shutdownCancel()
  269. err1 = s.httpServer.Shutdown(shutdownCtx)
  270. }
  271. if s.listener != nil {
  272. err2 = s.listener.Close()
  273. }
  274. return common.Combine(err1, err2)
  275. }
  276. // GetCtx returns the server's context for cancellation and deadline management.
  277. func (s *Server) GetCtx() context.Context {
  278. return s.ctx
  279. }