sub.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. "github.com/mhsanaei/3x-ui/v3/web/locale"
  18. "github.com/mhsanaei/3x-ui/v3/web/middleware"
  19. "github.com/mhsanaei/3x-ui/v3/web/network"
  20. "github.com/mhsanaei/3x-ui/v3/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 = "-io"
  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. SubClashEnableRouting, err := s.settingService.GetSubClashEnableRouting()
  118. if err != nil {
  119. SubClashEnableRouting = false
  120. }
  121. SubClashRules, err := s.settingService.GetSubClashRules()
  122. if err != nil {
  123. SubClashRules = ""
  124. }
  125. SubTitle, err := s.settingService.GetSubTitle()
  126. if err != nil {
  127. SubTitle = ""
  128. }
  129. SubSupportUrl, err := s.settingService.GetSubSupportUrl()
  130. if err != nil {
  131. SubSupportUrl = ""
  132. }
  133. SubProfileUrl, err := s.settingService.GetSubProfileUrl()
  134. if err != nil {
  135. SubProfileUrl = ""
  136. }
  137. SubAnnounce, err := s.settingService.GetSubAnnounce()
  138. if err != nil {
  139. SubAnnounce = ""
  140. }
  141. SubEnableRouting, err := s.settingService.GetSubEnableRouting()
  142. if err != nil {
  143. return nil, err
  144. }
  145. SubRoutingRules, err := s.settingService.GetSubRoutingRules()
  146. if err != nil {
  147. SubRoutingRules = ""
  148. }
  149. // set per-request localizer from headers/cookies
  150. engine.Use(locale.LocalizerMiddleware())
  151. // Mount the Vite-built dist/assets/ so the subscription page's JS/CSS
  152. // bundles load from `/assets/...`. Also mount the same FS under the
  153. // subscription path prefix (LinksPath + "assets") so reverse proxies
  154. // running the panel under a URI prefix can resolve those URLs too.
  155. // Note: LinksPath always starts and ends with "/" (validated in settings).
  156. var linksPathForAssets string
  157. if LinksPath == "/" {
  158. linksPathForAssets = "/assets"
  159. } else {
  160. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  161. }
  162. var assetsFS http.FileSystem
  163. if _, err := os.Stat("web/dist/assets"); err == nil {
  164. assetsFS = http.FS(os.DirFS("web/dist/assets"))
  165. } else if subFS, err := fs.Sub(distFS, "dist/assets"); err == nil {
  166. assetsFS = http.FS(subFS)
  167. } else {
  168. logger.Error("sub: failed to mount embedded dist assets:", err)
  169. }
  170. if assetsFS != nil {
  171. engine.StaticFS("/assets", assetsFS)
  172. if linksPathForAssets != "/assets" {
  173. engine.StaticFS(linksPathForAssets, assetsFS)
  174. }
  175. // Browser may resolve subpage assets relative to the request URL —
  176. // /sub/<basePath>/<subId>/assets/... — so route those to the same FS.
  177. if LinksPath != "/" {
  178. engine.Use(func(c *gin.Context) {
  179. path := c.Request.URL.Path
  180. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  181. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  182. _, after, ok := strings.Cut(path, "/assets/")
  183. if ok {
  184. assetPath := after // +8 to skip "/assets/"
  185. if assetPath != "" {
  186. c.FileFromFS(assetPath, assetsFS)
  187. c.Abort()
  188. return
  189. }
  190. }
  191. }
  192. c.Next()
  193. })
  194. }
  195. }
  196. g := engine.Group("/")
  197. s.sub = NewSUBController(
  198. g, LinksPath, JsonPath, ClashPath, subJsonEnable, subClashEnable, Encrypt, ShowInfo, RemarkModel, SubUpdates,
  199. SubJsonFragment, SubJsonNoises, SubJsonMux, SubJsonRules, SubClashEnableRouting, SubClashRules, SubTitle, SubSupportUrl,
  200. SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules)
  201. return engine, nil
  202. }
  203. // Start initializes and starts the subscription server with configured settings.
  204. func (s *Server) Start() (err error) {
  205. // This is an anonymous function, no function name
  206. defer func() {
  207. if err != nil {
  208. s.Stop()
  209. }
  210. }()
  211. subEnable, err := s.settingService.GetSubEnable()
  212. if err != nil {
  213. return err
  214. }
  215. if !subEnable {
  216. return nil
  217. }
  218. engine, err := s.initRouter()
  219. if err != nil {
  220. return err
  221. }
  222. certFile, err := s.settingService.GetSubCertFile()
  223. if err != nil {
  224. return err
  225. }
  226. keyFile, err := s.settingService.GetSubKeyFile()
  227. if err != nil {
  228. return err
  229. }
  230. listen, err := s.settingService.GetSubListen()
  231. if err != nil {
  232. return err
  233. }
  234. port, err := s.settingService.GetSubPort()
  235. if err != nil {
  236. return err
  237. }
  238. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  239. listener, err := net.Listen("tcp", listenAddr)
  240. if err != nil {
  241. return err
  242. }
  243. if certFile != "" || keyFile != "" {
  244. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  245. if err == nil {
  246. c := &tls.Config{
  247. Certificates: []tls.Certificate{cert},
  248. }
  249. listener = network.NewAutoHttpsListener(listener)
  250. listener = tls.NewListener(listener, c)
  251. logger.Info("Sub server running HTTPS on", listener.Addr())
  252. } else {
  253. logger.Error("Error loading certificates:", err)
  254. logger.Info("Sub server running HTTP on", listener.Addr())
  255. }
  256. } else {
  257. logger.Info("Sub server running HTTP on", listener.Addr())
  258. }
  259. s.listener = listener
  260. s.httpServer = &http.Server{
  261. Handler: engine,
  262. }
  263. go func() {
  264. s.httpServer.Serve(listener)
  265. }()
  266. return nil
  267. }
  268. // Stop gracefully shuts down the subscription server and closes the listener.
  269. func (s *Server) Stop() error {
  270. s.cancel()
  271. var err1 error
  272. var err2 error
  273. if s.httpServer != nil {
  274. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  275. defer shutdownCancel()
  276. err1 = s.httpServer.Shutdown(shutdownCtx)
  277. }
  278. if s.listener != nil {
  279. err2 = s.listener.Close()
  280. }
  281. return common.Combine(err1, err2)
  282. }
  283. // GetCtx returns the server's context for cancellation and deadline management.
  284. func (s *Server) GetCtx() context.Context {
  285. return s.ctx
  286. }