1
0

sub.go 7.8 KB

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