1
0

sub.go 8.0 KB

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