1
0

sub.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. subClashAutoDetect, err := s.settingService.GetSubClashAutoDetect()
  76. if err != nil {
  77. subClashAutoDetect = false
  78. }
  79. subJsonAutoDetect, err := s.settingService.GetSubJsonAutoDetect()
  80. if err != nil {
  81. subJsonAutoDetect = false
  82. }
  83. subJsonAlwaysArray, err := s.settingService.GetSubJsonAlwaysArray()
  84. if err != nil {
  85. subJsonAlwaysArray = false
  86. }
  87. subJsonUserAgentRegex, err := s.settingService.GetSubJsonUserAgentRegex()
  88. if err != nil {
  89. subJsonUserAgentRegex = service.DefaultSubJsonUserAgentRegex
  90. }
  91. subClashUserAgentRegex, err := s.settingService.GetSubClashUserAgentRegex()
  92. if err != nil {
  93. subClashUserAgentRegex = service.DefaultSubClashUserAgentRegex
  94. }
  95. // Set base_path based on LinksPath for template rendering
  96. // Ensure LinksPath ends with "/" for proper asset URL generation
  97. basePath := LinksPath
  98. if basePath != "/" && !strings.HasSuffix(basePath, "/") {
  99. basePath += "/"
  100. }
  101. // logger.Debug("sub: Setting base_path to:", basePath)
  102. engine.Use(func(c *gin.Context) {
  103. c.Set("base_path", basePath)
  104. })
  105. Encrypt, err := s.settingService.GetSubEncrypt()
  106. if err != nil {
  107. return nil, err
  108. }
  109. RemarkTemplate, err := s.settingService.GetRemarkTemplate()
  110. if err != nil {
  111. RemarkTemplate = ""
  112. }
  113. SubUpdates, err := s.settingService.GetSubUpdates()
  114. if err != nil {
  115. SubUpdates = "10"
  116. }
  117. SubJsonMux, err := s.settingService.GetSubJsonMux()
  118. if err != nil {
  119. SubJsonMux = ""
  120. }
  121. SubJsonRules, err := s.settingService.GetSubJsonRules()
  122. if err != nil {
  123. SubJsonRules = ""
  124. }
  125. SubJsonRoutingRules, err := s.settingService.GetSubJsonRoutingRules()
  126. if err != nil {
  127. SubJsonRoutingRules = ""
  128. }
  129. SubJsonDns, err := s.settingService.GetSubJsonDns()
  130. if err != nil {
  131. SubJsonDns = ""
  132. }
  133. SubJsonFinalMask, err := s.settingService.GetSubJsonFinalMask()
  134. if err != nil {
  135. SubJsonFinalMask = ""
  136. }
  137. SubJsonObservatory, err := s.settingService.GetSubJsonObservatory()
  138. if err != nil {
  139. SubJsonObservatory = ""
  140. }
  141. SubClashEnableRouting, err := s.settingService.GetSubClashEnableRouting()
  142. if err != nil {
  143. SubClashEnableRouting = false
  144. }
  145. SubClashRules, err := s.settingService.GetSubClashRules()
  146. if err != nil {
  147. SubClashRules = ""
  148. }
  149. SubTitle, err := s.settingService.GetSubTitle()
  150. if err != nil {
  151. SubTitle = ""
  152. }
  153. SubSupportUrl, err := s.settingService.GetSubSupportUrl()
  154. if err != nil {
  155. SubSupportUrl = ""
  156. }
  157. SubProfileUrl, err := s.settingService.GetSubProfileUrl()
  158. if err != nil {
  159. SubProfileUrl = ""
  160. }
  161. SubProfileMode, err := s.settingService.GetSubProfileMode()
  162. if err != nil {
  163. SubProfileMode = service.SubProfileModeNone
  164. }
  165. SubAnnounce, err := s.settingService.GetSubAnnounce()
  166. if err != nil {
  167. SubAnnounce = ""
  168. }
  169. SubEnableRouting, err := s.settingService.GetSubEnableRouting()
  170. if err != nil {
  171. return nil, err
  172. }
  173. SubRoutingRules, err := s.settingService.GetSubRoutingRules()
  174. if err != nil {
  175. SubRoutingRules = ""
  176. }
  177. SubHideSettings, err := s.settingService.GetSubHideSettings()
  178. if err != nil {
  179. SubHideSettings = false
  180. }
  181. SubIncyEnableRouting, err := s.settingService.GetSubIncyEnableRouting()
  182. if err != nil {
  183. SubIncyEnableRouting = false
  184. }
  185. SubIncyRoutingRules, err := s.settingService.GetSubIncyRoutingRules()
  186. if err != nil {
  187. SubIncyRoutingRules = ""
  188. }
  189. happCfg := HappConfig{}
  190. happCfg.AutoDetect, _ = s.settingService.GetSubHappAutoDetect()
  191. happCfg.ProviderId, _ = s.settingService.GetSubHappProviderId()
  192. happCfg.NewUrl, _ = s.settingService.GetSubHappNewUrl()
  193. happCfg.FallbackUrl, _ = s.settingService.GetSubHappFallbackUrl()
  194. happCfg.SubInfoColor, _ = s.settingService.GetSubHappSubInfoColor()
  195. happCfg.SubInfoText, _ = s.settingService.GetSubHappSubInfoText()
  196. happCfg.SubInfoButtonText, _ = s.settingService.GetSubHappSubInfoButtonText()
  197. happCfg.SubInfoButtonLink, _ = s.settingService.GetSubHappSubInfoButtonLink()
  198. happCfg.SubExpire, _ = s.settingService.GetSubHappSubExpire()
  199. happCfg.SubExpireButtonLink, _ = s.settingService.GetSubHappSubExpireButtonLink()
  200. happCfg.NotificationExpire, _ = s.settingService.GetSubHappNotificationExpire()
  201. happCfg.NoLimit, _ = s.settingService.GetSubHappNoLimit()
  202. happCfg.AlwaysHwid, _ = s.settingService.GetSubHappAlwaysHwid()
  203. happCfg.TunMode, _ = s.settingService.GetSubHappTunMode()
  204. happCfg.TunType, _ = s.settingService.GetSubHappTunType()
  205. happCfg.ExcludeRoutes, _ = s.settingService.GetSubHappExcludeRoutes()
  206. happCfg.ExcludeApns, _ = s.settingService.GetSubHappExcludeApns()
  207. happCfg.ColorProfile, _ = s.settingService.GetSubHappColorProfile()
  208. happCfg.PingType, _ = s.settingService.GetSubHappPingType()
  209. happCfg.AutoConnect, _ = s.settingService.GetSubHappAutoConnect()
  210. happCfg.AutoConnectType, _ = s.settingService.GetSubHappAutoConnectType()
  211. happCfg.PerAppMode, _ = s.settingService.GetSubHappPerAppMode()
  212. happCfg.PerAppList, _ = s.settingService.GetSubHappPerAppList()
  213. happCfg.LocalProxyAuth, _ = s.settingService.GetSubHappLocalProxyAuth()
  214. incyCfg := IncyConfig{}
  215. incyCfg.AutoDetect, _ = s.settingService.GetSubIncyAppAutoDetect()
  216. incyCfg.ProfileDescription, _ = s.settingService.GetSubIncyProfileDescription()
  217. incyCfg.SortOrder, _ = s.settingService.GetSubIncySortOrder()
  218. incyCfg.SupportEmail, _ = s.settingService.GetSubIncySupportEmail()
  219. incyCfg.AnnounceUrl, _ = s.settingService.GetSubIncyAnnounceUrl()
  220. incyCfg.PremiumUrl, _ = s.settingService.GetSubIncyPremiumUrl()
  221. incyCfg.BannerText, _ = s.settingService.GetSubIncyBannerText()
  222. incyCfg.BannerButtonText, _ = s.settingService.GetSubIncyBannerButtonText()
  223. incyCfg.BannerButtonUrl, _ = s.settingService.GetSubIncyBannerButtonUrl()
  224. incyCfg.BannerBgColor, _ = s.settingService.GetSubIncyBannerBgColor()
  225. incyCfg.BannerButtonColor, _ = s.settingService.GetSubIncyBannerButtonColor()
  226. incyCfg.HideUrl, _ = s.settingService.GetSubIncyHideUrl()
  227. incyCfg.HideCheck, _ = s.settingService.GetSubIncyHideCheck()
  228. incyCfg.NoLimitEnabled, _ = s.settingService.GetSubIncyNoLimitEnabled()
  229. incyCfg.PerAppProxyEnable, _ = s.settingService.GetSubIncyPerAppEnable()
  230. incyCfg.PerAppProxyMode, _ = s.settingService.GetSubIncyPerAppMode()
  231. incyCfg.PerAppProxyList, _ = s.settingService.GetSubIncyPerAppList()
  232. incyCfg.FragmentationEnable, _ = s.settingService.GetSubIncyFragmentationEnable()
  233. incyCfg.FragmentationLength, _ = s.settingService.GetSubIncyFragmentLength()
  234. incyCfg.FragmentationInterval, _ = s.settingService.GetSubIncyFragmentInterval()
  235. incyCfg.FragmentationPackets, _ = s.settingService.GetSubIncyFragmentPackets()
  236. incyCfg.NoisesEnable, _ = s.settingService.GetSubIncyNoisesEnable()
  237. incyCfg.NoisesType, _ = s.settingService.GetSubIncyNoisesType()
  238. incyCfg.NoisesPacket, _ = s.settingService.GetSubIncyNoisesPacket()
  239. incyCfg.NoisesDelay, _ = s.settingService.GetSubIncyNoisesDelay()
  240. incyCfg.ServerAddressResolveEnable, _ = s.settingService.GetSubIncyResolveEnable()
  241. incyCfg.ServerAddressResolveDnsDomain, _ = s.settingService.GetSubIncyResolveDnsDomain()
  242. incyCfg.ServerAddressResolveDnsIp, _ = s.settingService.GetSubIncyResolveDnsIp()
  243. // set per-request localizer from headers/cookies
  244. engine.Use(locale.LocalizerMiddleware())
  245. // Mount the Vite-built dist/assets/ so the subscription page's JS/CSS
  246. // bundles load from `/assets/...`. Also mount the same FS under the
  247. // subscription path prefix (LinksPath + "assets") so reverse proxies
  248. // running the panel under a URI prefix can resolve those URLs too.
  249. // Note: LinksPath always starts and ends with "/" (validated in settings).
  250. var linksPathForAssets string
  251. if LinksPath == "/" {
  252. linksPathForAssets = "/assets"
  253. } else {
  254. linksPathForAssets = strings.TrimRight(LinksPath, "/") + "/assets"
  255. }
  256. var assetsFS http.FileSystem
  257. if _, err := os.Stat("internal/web/dist/assets"); err == nil {
  258. assetsFS = http.FS(os.DirFS("internal/web/dist/assets"))
  259. } else if subFS, err := fs.Sub(distFS, "dist/assets"); err == nil {
  260. assetsFS = http.FS(subFS)
  261. } else {
  262. logger.Error("sub: failed to mount embedded dist assets:", err)
  263. }
  264. if assetsFS != nil {
  265. engine.StaticFS("/assets", assetsFS)
  266. if linksPathForAssets != "/assets" {
  267. engine.StaticFS(linksPathForAssets, assetsFS)
  268. }
  269. // Browser may resolve subpage assets relative to the request URL —
  270. // /sub/<basePath>/<subId>/assets/... — so route those to the same FS.
  271. if LinksPath != "/" {
  272. engine.Use(func(c *gin.Context) {
  273. path := c.Request.URL.Path
  274. pathPrefix := strings.TrimRight(LinksPath, "/") + "/"
  275. if strings.HasPrefix(path, pathPrefix) && strings.Contains(path, "/assets/") {
  276. _, after, ok := strings.Cut(path, "/assets/")
  277. if ok {
  278. assetPath := after // +8 to skip "/assets/"
  279. if assetPath != "" {
  280. c.FileFromFS(assetPath, assetsFS)
  281. c.Abort()
  282. return
  283. }
  284. }
  285. }
  286. c.Next()
  287. })
  288. }
  289. }
  290. g := engine.Group("/")
  291. s.sub = NewSUBController(g,
  292. WithSUBPath(LinksPath),
  293. WithSUBJsonPath(JsonPath),
  294. WithSUBClashPath(ClashPath),
  295. WithSUBClashAutoDetect(subClashAutoDetect),
  296. WithSUBClashUserAgentRegex(subClashUserAgentRegex),
  297. WithSUBJsonAutoDetect(subJsonAutoDetect),
  298. WithSUBJsonUserAgentRegex(subJsonUserAgentRegex),
  299. WithSUBJsonAlwaysArray(subJsonAlwaysArray),
  300. WithSUBJsonEnabled(subJsonEnable),
  301. WithSUBClashEnabled(subClashEnable),
  302. WithSUBEncryption(Encrypt),
  303. WithSUBRemarkTemplate(RemarkTemplate),
  304. WithSUBUpdateInterval(SubUpdates),
  305. WithSUBJsonMux(SubJsonMux),
  306. WithSUBJsonRules(SubJsonRules),
  307. WithSUBJsonRoutingRules(SubJsonRoutingRules),
  308. WithSUBJsonDns(SubJsonDns),
  309. WithSUBJsonFinalMask(SubJsonFinalMask),
  310. WithSUBJsonObservatory(SubJsonObservatory),
  311. WithSUBClashEnableRouting(SubClashEnableRouting),
  312. WithSUBClashRules(SubClashRules),
  313. WithSUBTitle(SubTitle),
  314. WithSUBSupportURL(SubSupportUrl),
  315. WithSUBProfileURL(SubProfileUrl),
  316. WithSUBProfileMode(SubProfileMode),
  317. WithSUBAnnounce(SubAnnounce),
  318. WithSUBEnableRouting(SubEnableRouting),
  319. WithSUBRoutingRules(SubRoutingRules),
  320. WithSUBHideSettings(SubHideSettings),
  321. WithSUBHappConfig(happCfg),
  322. WithSUBIncyConfig(incyCfg),
  323. WithSUBIncyEnableRouting(SubIncyEnableRouting),
  324. WithSUBIncyRoutingRules(SubIncyRoutingRules),
  325. )
  326. return engine, nil
  327. }
  328. // Start initializes and starts the subscription server with configured settings.
  329. func (s *Server) Start() (err error) {
  330. // This is an anonymous function, no function name
  331. defer func() {
  332. if err != nil {
  333. _ = s.Stop()
  334. }
  335. }()
  336. subEnable, err := s.settingService.GetSubEnable()
  337. if err != nil {
  338. return err
  339. }
  340. if !subEnable {
  341. return nil
  342. }
  343. engine, err := s.initRouter()
  344. if err != nil {
  345. return err
  346. }
  347. certFile, err := s.settingService.GetSubCertFile()
  348. if err != nil {
  349. return err
  350. }
  351. keyFile, err := s.settingService.GetSubKeyFile()
  352. if err != nil {
  353. return err
  354. }
  355. listen, err := s.settingService.GetSubListen()
  356. if err != nil {
  357. return err
  358. }
  359. port, err := s.settingService.GetSubPort()
  360. if err != nil {
  361. return err
  362. }
  363. listenAddr := net.JoinHostPort(listen, strconv.Itoa(port))
  364. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", listenAddr)
  365. if err != nil {
  366. return err
  367. }
  368. if certFile != "" || keyFile != "" {
  369. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  370. if err == nil {
  371. c := &tls.Config{
  372. Certificates: []tls.Certificate{cert},
  373. }
  374. listener = network.NewAutoHttpsListener(listener)
  375. listener = tls.NewListener(listener, c)
  376. logger.Info("Sub server running HTTPS on", listener.Addr())
  377. } else {
  378. logger.Error("Error loading certificates:", err)
  379. logger.Info("Sub server running HTTP on", listener.Addr())
  380. }
  381. } else {
  382. logger.Info("Sub server running HTTP on", listener.Addr())
  383. }
  384. s.listener = listener
  385. s.httpServer = &http.Server{
  386. Handler: engine,
  387. // The subscription server is the most exposed (public) listener; without
  388. // these a few slow-header connections exhaust it (Slowloris). Mirrors the
  389. // panel server timeouts in internal/web/web.go.
  390. ReadHeaderTimeout: 5 * time.Second,
  391. ReadTimeout: 30 * time.Second,
  392. WriteTimeout: 30 * time.Second,
  393. IdleTimeout: 120 * time.Second,
  394. }
  395. go network.ServeHTTP(s.httpServer, listener, "Subscription server")
  396. return nil
  397. }
  398. // Stop gracefully shuts down the subscription server and closes the listener.
  399. func (s *Server) Stop() error {
  400. s.cancel()
  401. var err1 error
  402. var err2 error
  403. if s.httpServer != nil {
  404. shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
  405. defer shutdownCancel()
  406. err1 = s.httpServer.Shutdown(shutdownCtx)
  407. }
  408. if s.listener != nil {
  409. err2 = s.listener.Close()
  410. }
  411. return common.Combine(err1, err2)
  412. }
  413. // GetCtx returns the server's context for cancellation and deadline management.
  414. func (s *Server) GetCtx() context.Context {
  415. return s.ctx
  416. }