sub.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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/internal/logger"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  18. "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
  19. "github.com/mhsanaei/3x-ui/v3/internal/web/network"
  20. "github.com/mhsanaei/3x-ui/v3/internal/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. RemarkTemplate, err := s.settingService.GetRemarkTemplate()
  90. if err != nil {
  91. RemarkTemplate = ""
  92. }
  93. SubUpdates, err := s.settingService.GetSubUpdates()
  94. if err != nil {
  95. SubUpdates = "10"
  96. }
  97. SubJsonMux, err := s.settingService.GetSubJsonMux()
  98. if err != nil {
  99. SubJsonMux = ""
  100. }
  101. SubJsonRules, err := s.settingService.GetSubJsonRules()
  102. if err != nil {
  103. SubJsonRules = ""
  104. }
  105. SubJsonFinalMask, err := s.settingService.GetSubJsonFinalMask()
  106. if err != nil {
  107. SubJsonFinalMask = ""
  108. }
  109. SubClashEnableRouting, err := s.settingService.GetSubClashEnableRouting()
  110. if err != nil {
  111. SubClashEnableRouting = false
  112. }
  113. SubClashRules, err := s.settingService.GetSubClashRules()
  114. if err != nil {
  115. SubClashRules = ""
  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. SubHideSettings, err := s.settingService.GetSubHideSettings()
  142. if err != nil {
  143. SubHideSettings = false
  144. }
  145. SubIncyEnableRouting, err := s.settingService.GetSubIncyEnableRouting()
  146. if err != nil {
  147. SubIncyEnableRouting = false
  148. }
  149. SubIncyRoutingRules, err := s.settingService.GetSubIncyRoutingRules()
  150. if err != nil {
  151. SubIncyRoutingRules = ""
  152. }
  153. // set per-request localizer from headers/cookies
  154. engine.Use(locale.LocalizerMiddleware())
  155. // Mount the Vite-built dist/assets/ so the subscription page's JS/CSS
  156. // bundles load from `/assets/...`. Also mount the same FS under the
  157. // subscription path prefix (LinksPath + "assets") so reverse proxies
  158. // running the panel under a URI prefix can resolve those URLs too.
  159. // Note: LinksPath always starts and ends with "/" (validated in settings).
  160. var linksPathForAssets string
  161. if LinksPath == "/" {
  162. linksPathForAssets = "/assets"
  163. } else {
  164. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  165. }
  166. var assetsFS http.FileSystem
  167. if _, err := os.Stat("internal/web/dist/assets"); err == nil {
  168. assetsFS = http.FS(os.DirFS("internal/web/dist/assets"))
  169. } else if subFS, err := fs.Sub(distFS, "dist/assets"); err == nil {
  170. assetsFS = http.FS(subFS)
  171. } else {
  172. logger.Error("sub: failed to mount embedded dist assets:", err)
  173. }
  174. if assetsFS != nil {
  175. engine.StaticFS("/assets", assetsFS)
  176. if linksPathForAssets != "/assets" {
  177. engine.StaticFS(linksPathForAssets, assetsFS)
  178. }
  179. // Browser may resolve subpage assets relative to the request URL —
  180. // /sub/<basePath>/<subId>/assets/... — so route those to the same FS.
  181. if LinksPath != "/" {
  182. engine.Use(func(c *gin.Context) {
  183. path := c.Request.URL.Path
  184. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  185. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  186. _, after, ok := strings.Cut(path, "/assets/")
  187. if ok {
  188. assetPath := after // +8 to skip "/assets/"
  189. if assetPath != "" {
  190. c.FileFromFS(assetPath, assetsFS)
  191. c.Abort()
  192. return
  193. }
  194. }
  195. }
  196. c.Next()
  197. })
  198. }
  199. }
  200. g := engine.Group("/")
  201. s.sub = NewSUBController(
  202. g, LinksPath, JsonPath, ClashPath, subJsonEnable, subClashEnable, Encrypt, RemarkTemplate, SubUpdates,
  203. SubJsonMux, SubJsonRules, SubJsonFinalMask, SubClashEnableRouting, SubClashRules, SubTitle, SubSupportUrl,
  204. SubProfileUrl, SubAnnounce, SubEnableRouting, SubRoutingRules, SubHideSettings,
  205. SubIncyEnableRouting, SubIncyRoutingRules)
  206. return engine, nil
  207. }
  208. // Start initializes and starts the subscription server with configured settings.
  209. func (s *Server) Start() (err error) {
  210. // This is an anonymous function, no function name
  211. defer func() {
  212. if err != nil {
  213. s.Stop()
  214. }
  215. }()
  216. subEnable, err := s.settingService.GetSubEnable()
  217. if err != nil {
  218. return err
  219. }
  220. if !subEnable {
  221. return nil
  222. }
  223. engine, err := s.initRouter()
  224. if err != nil {
  225. return err
  226. }
  227. certFile, err := s.settingService.GetSubCertFile()
  228. if err != nil {
  229. return err
  230. }
  231. keyFile, err := s.settingService.GetSubKeyFile()
  232. if err != nil {
  233. return err
  234. }
  235. listen, err := s.settingService.GetSubListen()
  236. if err != nil {
  237. return err
  238. }
  239. port, err := s.settingService.GetSubPort()
  240. if err != nil {
  241. return err
  242. }
  243. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  244. listener, err := net.Listen("tcp", listenAddr)
  245. if err != nil {
  246. return err
  247. }
  248. if certFile != "" || keyFile != "" {
  249. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  250. if err == nil {
  251. c := &tls.Config{
  252. Certificates: []tls.Certificate{cert},
  253. }
  254. listener = network.NewAutoHttpsListener(listener)
  255. listener = tls.NewListener(listener, c)
  256. logger.Info("Sub server running HTTPS on", listener.Addr())
  257. } else {
  258. logger.Error("Error loading certificates:", err)
  259. logger.Info("Sub server running HTTP on", listener.Addr())
  260. }
  261. } else {
  262. logger.Info("Sub server running HTTP on", listener.Addr())
  263. }
  264. s.listener = listener
  265. s.httpServer = &http.Server{
  266. Handler: engine,
  267. // The subscription server is the most exposed (public) listener; without
  268. // these a few slow-header connections exhaust it (Slowloris). Mirrors the
  269. // panel server timeouts in internal/web/web.go.
  270. ReadHeaderTimeout: 5 * time.Second,
  271. ReadTimeout: 30 * time.Second,
  272. WriteTimeout: 30 * time.Second,
  273. IdleTimeout: 120 * time.Second,
  274. }
  275. go func() {
  276. s.httpServer.Serve(listener)
  277. }()
  278. return nil
  279. }
  280. // Stop gracefully shuts down the subscription server and closes the listener.
  281. func (s *Server) Stop() error {
  282. s.cancel()
  283. var err1 error
  284. var err2 error
  285. if s.httpServer != nil {
  286. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  287. defer shutdownCancel()
  288. err1 = s.httpServer.Shutdown(shutdownCtx)
  289. }
  290. if s.listener != nil {
  291. err2 = s.listener.Close()
  292. }
  293. return common.Combine(err1, err2)
  294. }
  295. // GetCtx returns the server's context for cancellation and deadline management.
  296. func (s *Server) GetCtx() context.Context {
  297. return s.ctx
  298. }