controller.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. package sub
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "html/template"
  8. "io/fs"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path/filepath"
  13. "regexp"
  14. "strings"
  15. "sync"
  16. "time"
  17. "unicode"
  18. "github.com/gin-gonic/gin"
  19. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  20. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  21. )
  22. // writeSubError translates a service-layer result into an HTTP response.
  23. // A nil error with no rows means the subId doesn't match anything (deleted
  24. // client, never-existed id) and becomes 404. A real error becomes 500. No
  25. // body — VPN clients only look at the status.
  26. func writeSubError(c *gin.Context, err error) {
  27. if err == nil {
  28. c.Status(http.StatusNotFound)
  29. return
  30. }
  31. c.Status(http.StatusInternalServerError)
  32. }
  33. // cachedSubTemplate holds a parsed custom subscription template together with
  34. // the modification time of the file it was parsed from, so the cache can be
  35. // invalidated when an admin edits the template on disk.
  36. type cachedSubTemplate struct {
  37. tmpl *template.Template
  38. modTime time.Time
  39. }
  40. // SUBController handles HTTP requests for subscription links and JSON configurations.
  41. type SUBController struct {
  42. subTitle string
  43. subSupportUrl string
  44. subProfileUrl string
  45. subAnnounce string
  46. subEnableRouting bool
  47. subRoutingRules string
  48. subHideSettings bool
  49. subIncyEnableRouting bool
  50. subIncyRoutingRules string
  51. subPath string
  52. subJsonPath string
  53. subClashPath string
  54. subClashAutoDetect bool
  55. clashUserAgent *regexp.Regexp
  56. jsonAutoDetect bool
  57. jsonUserAgent *regexp.Regexp
  58. jsonAlwaysArray bool
  59. jsonEnabled bool
  60. clashEnabled bool
  61. subEncrypt bool
  62. updateInterval string
  63. subService *SubService
  64. subJsonService *SubJsonService
  65. subClashService *SubClashService
  66. settingService service.SettingService
  67. subTemplateMu sync.RWMutex
  68. subTemplateCache map[string]*cachedSubTemplate
  69. }
  70. type subControllerConfig struct {
  71. subPath string
  72. subJsonPath string
  73. subClashPath string
  74. subClashAutoDetect bool
  75. subClashUserAgentRegex string
  76. subJsonAutoDetect bool
  77. subJsonUserAgentRegex string
  78. subJsonAlwaysArray bool
  79. subJsonEnabled bool
  80. subClashEnabled bool
  81. subEncrypt bool
  82. remarkTemplate string
  83. updateInterval string
  84. subJsonMux string
  85. subJsonRules string
  86. subJsonFinalMask string
  87. subClashEnableRouting bool
  88. subClashRules string
  89. subTitle string
  90. subSupportURL string
  91. subProfileURL string
  92. subAnnounce string
  93. subEnableRouting bool
  94. subRoutingRules string
  95. subHideSettings bool
  96. subIncyEnableRouting bool
  97. subIncyRoutingRules string
  98. }
  99. type SUBControllerOption func(*subControllerConfig)
  100. func WithSUBPath(value string) SUBControllerOption {
  101. return func(config *subControllerConfig) { config.subPath = value }
  102. }
  103. func WithSUBJsonPath(value string) SUBControllerOption {
  104. return func(config *subControllerConfig) { config.subJsonPath = value }
  105. }
  106. func WithSUBClashPath(value string) SUBControllerOption {
  107. return func(config *subControllerConfig) { config.subClashPath = value }
  108. }
  109. func WithSUBClashAutoDetect(value bool) SUBControllerOption {
  110. return func(config *subControllerConfig) { config.subClashAutoDetect = value }
  111. }
  112. func WithSUBClashUserAgentRegex(value string) SUBControllerOption {
  113. return func(config *subControllerConfig) { config.subClashUserAgentRegex = value }
  114. }
  115. func WithSUBJsonAutoDetect(value bool) SUBControllerOption {
  116. return func(config *subControllerConfig) { config.subJsonAutoDetect = value }
  117. }
  118. func WithSUBJsonUserAgentRegex(value string) SUBControllerOption {
  119. return func(config *subControllerConfig) { config.subJsonUserAgentRegex = value }
  120. }
  121. func WithSUBJsonAlwaysArray(value bool) SUBControllerOption {
  122. return func(config *subControllerConfig) { config.subJsonAlwaysArray = value }
  123. }
  124. func WithSUBJsonEnabled(value bool) SUBControllerOption {
  125. return func(config *subControllerConfig) { config.subJsonEnabled = value }
  126. }
  127. func WithSUBClashEnabled(value bool) SUBControllerOption {
  128. return func(config *subControllerConfig) { config.subClashEnabled = value }
  129. }
  130. func WithSUBEncryption(value bool) SUBControllerOption {
  131. return func(config *subControllerConfig) { config.subEncrypt = value }
  132. }
  133. func WithSUBRemarkTemplate(value string) SUBControllerOption {
  134. return func(config *subControllerConfig) { config.remarkTemplate = value }
  135. }
  136. func WithSUBUpdateInterval(value string) SUBControllerOption {
  137. return func(config *subControllerConfig) { config.updateInterval = value }
  138. }
  139. func WithSUBJsonMux(value string) SUBControllerOption {
  140. return func(config *subControllerConfig) { config.subJsonMux = value }
  141. }
  142. func WithSUBJsonRules(value string) SUBControllerOption {
  143. return func(config *subControllerConfig) { config.subJsonRules = value }
  144. }
  145. func WithSUBJsonFinalMask(value string) SUBControllerOption {
  146. return func(config *subControllerConfig) { config.subJsonFinalMask = value }
  147. }
  148. func WithSUBClashEnableRouting(value bool) SUBControllerOption {
  149. return func(config *subControllerConfig) { config.subClashEnableRouting = value }
  150. }
  151. func WithSUBClashRules(value string) SUBControllerOption {
  152. return func(config *subControllerConfig) { config.subClashRules = value }
  153. }
  154. func WithSUBTitle(value string) SUBControllerOption {
  155. return func(config *subControllerConfig) { config.subTitle = value }
  156. }
  157. func WithSUBSupportURL(value string) SUBControllerOption {
  158. return func(config *subControllerConfig) { config.subSupportURL = value }
  159. }
  160. func WithSUBProfileURL(value string) SUBControllerOption {
  161. return func(config *subControllerConfig) { config.subProfileURL = value }
  162. }
  163. func WithSUBAnnounce(value string) SUBControllerOption {
  164. return func(config *subControllerConfig) { config.subAnnounce = value }
  165. }
  166. func WithSUBEnableRouting(value bool) SUBControllerOption {
  167. return func(config *subControllerConfig) { config.subEnableRouting = value }
  168. }
  169. func WithSUBRoutingRules(value string) SUBControllerOption {
  170. return func(config *subControllerConfig) { config.subRoutingRules = value }
  171. }
  172. func WithSUBHideSettings(value bool) SUBControllerOption {
  173. return func(config *subControllerConfig) { config.subHideSettings = value }
  174. }
  175. func WithSUBIncyEnableRouting(value bool) SUBControllerOption {
  176. return func(config *subControllerConfig) { config.subIncyEnableRouting = value }
  177. }
  178. func WithSUBIncyRoutingRules(value string) SUBControllerOption {
  179. return func(config *subControllerConfig) { config.subIncyRoutingRules = value }
  180. }
  181. func defaultSUBControllerConfig() subControllerConfig {
  182. return subControllerConfig{
  183. subPath: "/sub/",
  184. subJsonPath: "/json/",
  185. subClashPath: "/clash/",
  186. subEncrypt: true,
  187. remarkTemplate: service.DefaultRemarkTemplate,
  188. updateInterval: "12",
  189. }
  190. }
  191. // NewSUBController creates a new subscription controller with the given configuration.
  192. func NewSUBController(g *gin.RouterGroup, options ...SUBControllerOption) *SUBController {
  193. config := defaultSUBControllerConfig()
  194. for _, option := range options {
  195. option(&config)
  196. }
  197. sub := NewSubService(config.remarkTemplate)
  198. a := &SUBController{
  199. subTitle: config.subTitle,
  200. subSupportUrl: config.subSupportURL,
  201. subProfileUrl: config.subProfileURL,
  202. subAnnounce: config.subAnnounce,
  203. subEnableRouting: config.subEnableRouting,
  204. subRoutingRules: config.subRoutingRules,
  205. subHideSettings: config.subHideSettings,
  206. subIncyEnableRouting: config.subIncyEnableRouting,
  207. subIncyRoutingRules: config.subIncyRoutingRules,
  208. subPath: config.subPath,
  209. subJsonPath: config.subJsonPath,
  210. subClashPath: config.subClashPath,
  211. subClashAutoDetect: config.subClashAutoDetect,
  212. clashUserAgent: compileUserAgentRegex("Clash/Mihomo", config.subClashUserAgentRegex, service.DefaultSubClashUserAgentRegex),
  213. jsonAutoDetect: config.subJsonAutoDetect,
  214. jsonUserAgent: compileUserAgentRegex("Xray JSON", config.subJsonUserAgentRegex, service.DefaultSubJsonUserAgentRegex),
  215. jsonAlwaysArray: config.subJsonAlwaysArray,
  216. jsonEnabled: config.subJsonEnabled,
  217. clashEnabled: config.subClashEnabled,
  218. subEncrypt: config.subEncrypt,
  219. updateInterval: config.updateInterval,
  220. subService: sub,
  221. subJsonService: NewSubJsonService(config.subJsonMux, config.subJsonRules, config.subJsonFinalMask, sub),
  222. subClashService: NewSubClashService(config.subClashEnableRouting, config.subClashRules, sub),
  223. subTemplateCache: map[string]*cachedSubTemplate{},
  224. }
  225. a.initRouter(g)
  226. return a
  227. }
  228. // initRouter registers HTTP routes for subscription links and JSON endpoints
  229. // on the provided router group.
  230. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  231. gLink := g.Group(a.subPath)
  232. gLink.GET(":subid", a.subs)
  233. gLink.HEAD(":subid", a.subs)
  234. if a.jsonEnabled {
  235. gJson := g.Group(a.subJsonPath)
  236. gJson.GET(":subid", a.subJsons)
  237. gJson.HEAD(":subid", a.subJsons)
  238. }
  239. if a.clashEnabled {
  240. gClash := g.Group(a.subClashPath)
  241. gClash.GET(":subid", a.subClashs)
  242. gClash.HEAD(":subid", a.subClashs)
  243. }
  244. }
  245. // maybeServeSubPage renders the HTML info page when the request comes from a
  246. // browser (Accept: text/html) or explicitly asks for it (?html=1 or ?view=html).
  247. // It reports whether the request was handled. The remark template's per-client
  248. // info is for the content a client app imports — the raw subscription body. A
  249. // browser viewing the HTML info page gets clean, name-only remarks (usage is
  250. // shown in the page summary).
  251. func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
  252. accept := c.GetHeader("Accept")
  253. wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
  254. if !wantsHTML {
  255. return false
  256. }
  257. page, ok := a.buildSubPageData(c)
  258. if !ok {
  259. return true
  260. }
  261. a.serveSubPage(c, page.BasePath, page)
  262. return true
  263. }
  264. func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool {
  265. if !strings.EqualFold(c.Query("format"), "info") {
  266. return false
  267. }
  268. page, ok := a.buildSubPageData(c)
  269. if !ok {
  270. return true
  271. }
  272. info := a.subPageContext(page)
  273. delete(info, "links")
  274. info["emails"] = dedupeEmails(page.Emails)
  275. setNoCacheHeaders(c)
  276. c.JSON(http.StatusOK, info)
  277. return true
  278. }
  279. func (a *SUBController) buildSubPageData(c *gin.Context) (PageData, bool) {
  280. subId := c.Param("subid")
  281. _, host, _, hostHeader := a.subService.ResolveRequest(c)
  282. subReq := a.subService.ForRequest(host)
  283. subReq.subscriptionBody = false
  284. subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
  285. if err != nil || len(subs) == 0 {
  286. writeSubError(c, err)
  287. return PageData{}, false
  288. }
  289. subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
  290. if !a.jsonEnabled {
  291. subJsonURL = ""
  292. }
  293. if !a.clashEnabled {
  294. subClashURL = ""
  295. }
  296. basePath, exists := c.Get("base_path")
  297. if !exists {
  298. basePath = "/"
  299. }
  300. basePathStr := basePath.(string)
  301. page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
  302. return page, true
  303. }
  304. func dedupeEmails(emails []string) []string {
  305. out := make([]string, 0, len(emails))
  306. seen := make(map[string]struct{}, len(emails))
  307. for _, email := range emails {
  308. if email == "" {
  309. continue
  310. }
  311. if _, dup := seen[email]; dup {
  312. continue
  313. }
  314. seen[email] = struct{}{}
  315. out = append(out, email)
  316. }
  317. return out
  318. }
  319. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  320. func (a *SUBController) subs(c *gin.Context) {
  321. userAgent := c.GetHeader("User-Agent")
  322. if a.maybeServeSubInfo(c) {
  323. logSubscriptionRoute(userAgent, "info")
  324. return
  325. }
  326. if a.maybeServeSubPage(c) {
  327. logSubscriptionRoute(userAgent, "html")
  328. return
  329. }
  330. if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) && a.serveClashBody(c, false) {
  331. logSubscriptionRoute(userAgent, "clash")
  332. return
  333. }
  334. if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) {
  335. logSubscriptionRoute(userAgent, "json")
  336. return
  337. }
  338. logSubscriptionRoute(userAgent, "raw")
  339. subId := c.Param("subid")
  340. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  341. subReq := a.subService.ForRequest(host)
  342. subReq.subscriptionBody = true
  343. subs, _, _, traffic, err := subReq.getSubs(subId)
  344. if err != nil || len(subs) == 0 {
  345. writeSubError(c, err)
  346. } else {
  347. var result strings.Builder
  348. for _, sub := range subs {
  349. result.WriteString(sub)
  350. result.WriteString("\n")
  351. }
  352. // Add headers
  353. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  354. profileUrl := a.subProfileUrl
  355. if profileUrl == "" {
  356. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  357. }
  358. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  359. if a.subIncyEnableRouting && a.subIncyRoutingRules != "" {
  360. result.WriteString(a.subIncyRoutingRules)
  361. result.WriteString("\n")
  362. }
  363. if a.subEncrypt {
  364. c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
  365. } else {
  366. c.String(200, result.String())
  367. }
  368. }
  369. }
  370. func shouldAutoServeClash(autoDetect, clashEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  371. return shouldAutoServeFormat(autoDetect, clashEnabled, wantsHTML, userAgent, userAgentRegex)
  372. }
  373. func shouldAutoServeJson(autoDetect, jsonEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  374. return shouldAutoServeFormat(autoDetect, jsonEnabled, wantsHTML, userAgent, userAgentRegex)
  375. }
  376. func shouldAutoServeFormat(autoDetect, formatEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  377. if !autoDetect || !formatEnabled || wantsHTML || userAgentRegex == nil {
  378. return false
  379. }
  380. return userAgentRegex.MatchString(userAgent)
  381. }
  382. func logSubscriptionRoute(userAgent, branch string) {
  383. logger.Debugf("Subscription request routed: branch=%s user_agent=%q", branch, sanitizeUserAgentForLog(userAgent))
  384. }
  385. func sanitizeUserAgentForLog(userAgent string) string {
  386. clean := strings.Map(func(r rune) rune {
  387. if unicode.IsControl(r) {
  388. return ' '
  389. }
  390. return r
  391. }, userAgent)
  392. runes := []rune(clean)
  393. if len(runes) > 512 {
  394. return string(runes[:512])
  395. }
  396. return clean
  397. }
  398. func compileUserAgentRegex(name, pattern, defaultPattern string) *regexp.Regexp {
  399. pattern = strings.TrimSpace(pattern)
  400. if pattern == "" {
  401. pattern = strings.TrimSpace(defaultPattern)
  402. }
  403. if pattern == "" {
  404. return nil
  405. }
  406. compiled, err := regexp.Compile(pattern)
  407. if err == nil {
  408. return compiled
  409. }
  410. logger.Warningf("Invalid %s User-Agent regex %q; falling back to default %q: %v", name, pattern, defaultPattern, err)
  411. if strings.TrimSpace(defaultPattern) == "" {
  412. return nil
  413. }
  414. return regexp.MustCompile(defaultPattern)
  415. }
  416. // serveSubPage renders internal/web/dist/subpage.html for the current subscription
  417. // request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
  418. // we inject that here, along with window.X_UI_BASE_PATH so the
  419. // page's static asset references resolve correctly when the panel runs
  420. // behind a URL prefix.
  421. func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
  422. var body []byte
  423. if diskBody, diskErr := os.ReadFile("internal/web/dist/subpage.html"); diskErr == nil {
  424. body = diskBody
  425. } else {
  426. readBody, err := fs.ReadFile(distFS, "dist/subpage.html")
  427. if err != nil {
  428. c.String(http.StatusInternalServerError, "missing embedded subpage")
  429. return
  430. }
  431. body = readBody
  432. }
  433. // Vite emits absolute asset URLs (`/assets/...`); when the panel is
  434. // installed under a custom URL prefix, rewrite them so the bundle
  435. // loads from `<basePath>assets/...` where the static handler is
  436. // actually mounted.
  437. if basePath != "/" && basePath != "" {
  438. body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
  439. body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
  440. }
  441. subData := a.subPageContext(page)
  442. // When an admin has configured a custom subscription theme, render it
  443. // instead of the default SPA. We render into a buffer first so a template
  444. // that fails mid-execution can't leave a partially-written (corrupt)
  445. // response — on any error we log and fall through to the default page.
  446. if themeDir, _ := a.settingService.GetSubThemeDir(); themeDir != "" {
  447. if tmpl, err := a.loadSubTemplate(themeDir); err != nil {
  448. logger.Error("sub: custom template parse failed, using default page:", err)
  449. } else if tmpl == nil {
  450. logger.Warning("sub: subThemeDir set but no usable template found, using default page:", themeDir)
  451. } else {
  452. var buf bytes.Buffer
  453. if execErr := tmpl.Execute(&buf, subData); execErr != nil {
  454. logger.Error("sub: custom template execution failed, using default page:", execErr)
  455. } else {
  456. setNoCacheHeaders(c)
  457. c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
  458. return
  459. }
  460. }
  461. }
  462. subDataJSON, err := json.Marshal(subData)
  463. if err != nil {
  464. subDataJSON = []byte("{}")
  465. }
  466. // Defense-in-depth string-escape for the basePath embed — admin-
  467. // controlled but cheap to harden.
  468. jsEscape := strings.NewReplacer(
  469. `\`, `\\`,
  470. `"`, `\"`,
  471. "\n", `\n`,
  472. "\r", `\r`,
  473. "<", `<`,
  474. ">", `>`,
  475. "&", `&`,
  476. )
  477. escapedBase := jsEscape.Replace(basePath)
  478. inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
  479. `window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
  480. out := bytes.Replace(body, []byte("</head>"), inject, 1)
  481. setNoCacheHeaders(c)
  482. c.Data(http.StatusOK, "text/html; charset=utf-8", out)
  483. }
  484. // subPageContext builds the shared view-model map: the template context for
  485. // custom sub themes, the window.__SUB_PAGE_DATA__ payload the SPA reads, and
  486. // (without links) the ?format=info JSON body. The panel's "Calendar Type"
  487. // setting decides whether dates render Gregorian or Jalali — surfaced here so
  488. // consumers match the rest of the panel without a round-trip.
  489. func (a *SUBController) subPageContext(page PageData) map[string]any {
  490. datepicker, _ := a.settingService.GetDatepicker()
  491. if datepicker == "" {
  492. datepicker = "gregorian"
  493. }
  494. return map[string]any{
  495. "sId": page.SId,
  496. "enabled": page.Enabled,
  497. "isOnline": page.IsOnline,
  498. "download": page.Download,
  499. "upload": page.Upload,
  500. "total": page.Total,
  501. "used": page.Used,
  502. "remained": page.Remained,
  503. "expire": page.Expire,
  504. "lastOnline": page.LastOnline,
  505. "downloadByte": page.DownloadByte,
  506. "uploadByte": page.UploadByte,
  507. "totalByte": page.TotalByte,
  508. "subUrl": page.SubUrl,
  509. "subJsonUrl": page.SubJsonUrl,
  510. "subClashUrl": page.SubClashUrl,
  511. "subTitle": page.SubTitle,
  512. "subSupportUrl": page.SubSupportUrl,
  513. "links": page.Result,
  514. "emails": page.Emails,
  515. "datepicker": datepicker,
  516. "announce": a.subAnnounce,
  517. }
  518. }
  519. // setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
  520. // clients and browsers always fetch fresh traffic/expiry data.
  521. func setNoCacheHeaders(c *gin.Context) {
  522. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  523. c.Header("Pragma", "no-cache")
  524. c.Header("Expires", "0")
  525. }
  526. // loadSubTemplate returns the parsed custom subscription template located in
  527. // themeDir, preferring sub.html over index.html. Parsed templates are cached and
  528. // only re-parsed when the underlying file's modification time changes, so admin
  529. // edits are picked up without paying a disk read + HTML parse on every request.
  530. //
  531. // It returns (nil, nil) when themeDir is not a usable directory or contains no
  532. // template file — the caller should fall back to the default page. A non-nil
  533. // error means a template file exists but failed to parse.
  534. func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, error) {
  535. info, err := os.Stat(themeDir)
  536. if err != nil || !info.IsDir() {
  537. return nil, nil
  538. }
  539. templatePath := filepath.Join(themeDir, "index.html")
  540. if _, err := os.Stat(filepath.Join(themeDir, "sub.html")); err == nil {
  541. templatePath = filepath.Join(themeDir, "sub.html")
  542. }
  543. fi, err := os.Stat(templatePath)
  544. if err != nil {
  545. return nil, nil
  546. }
  547. modTime := fi.ModTime()
  548. a.subTemplateMu.RLock()
  549. cached := a.subTemplateCache[templatePath]
  550. a.subTemplateMu.RUnlock()
  551. if cached != nil && cached.modTime.Equal(modTime) {
  552. return cached.tmpl, nil
  553. }
  554. tmpl, err := template.ParseFiles(templatePath)
  555. if err != nil {
  556. return nil, err
  557. }
  558. a.subTemplateMu.Lock()
  559. a.subTemplateCache[templatePath] = &cachedSubTemplate{tmpl: tmpl, modTime: modTime}
  560. a.subTemplateMu.Unlock()
  561. return tmpl, nil
  562. }
  563. // subJsons handles HTTP requests for JSON subscription configurations.
  564. func (a *SUBController) subJsons(c *gin.Context) {
  565. if strings.EqualFold(c.Query("view"), "raw") {
  566. if !a.serveJsonBody(c, a.jsonAlwaysArray, "application/json; charset=utf-8", true) {
  567. writeSubError(c, nil)
  568. }
  569. return
  570. }
  571. if a.maybeServeSubPage(c) {
  572. return
  573. }
  574. a.serveJson(c, a.jsonAlwaysArray, "text/plain; charset=utf-8")
  575. }
  576. func (a *SUBController) serveJson(c *gin.Context, alwaysReturnArray bool, contentType string) {
  577. if !a.serveJsonBody(c, alwaysReturnArray, contentType, false) {
  578. writeSubError(c, nil)
  579. }
  580. }
  581. func (a *SUBController) serveJsonBody(c *gin.Context, alwaysReturnArray bool, contentType string, rawDownload bool) bool {
  582. subId := c.Param("subid")
  583. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  584. jsonSub, header, err := a.subJsonService.GetJson(subId, host, alwaysReturnArray)
  585. if err != nil {
  586. writeSubError(c, err)
  587. return true
  588. }
  589. if len(jsonSub) == 0 {
  590. return false
  591. }
  592. profileUrl := a.subProfileUrl
  593. if profileUrl == "" {
  594. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  595. }
  596. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  597. if rawDownload {
  598. c.Writer.Header().Set("Content-Disposition", `attachment; filename="subscription.json"`)
  599. }
  600. c.Data(200, contentType, []byte(jsonSub))
  601. return true
  602. }
  603. func (a *SUBController) subClashs(c *gin.Context) {
  604. if strings.EqualFold(c.Query("view"), "raw") {
  605. if !a.serveClashBody(c, true) {
  606. writeSubError(c, nil)
  607. }
  608. return
  609. }
  610. if a.maybeServeSubPage(c) {
  611. return
  612. }
  613. if !a.serveClashBody(c, false) {
  614. writeSubError(c, nil)
  615. }
  616. }
  617. func (a *SUBController) serveClashBody(c *gin.Context, rawDownload bool) bool {
  618. subId := c.Param("subid")
  619. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  620. clashSub, header, err := a.subClashService.GetClash(subId, host)
  621. if err != nil {
  622. writeSubError(c, err)
  623. return true
  624. }
  625. if len(clashSub) == 0 {
  626. return false
  627. }
  628. profileUrl := a.subProfileUrl
  629. if profileUrl == "" {
  630. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  631. }
  632. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  633. if rawDownload {
  634. c.Writer.Header().Set("Content-Disposition", `attachment; filename="subscription.yaml"`)
  635. } else if a.subTitle != "" {
  636. // Clash clients commonly use Content-Disposition to choose the imported profile name.
  637. c.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename*=UTF-8''%s`, url.PathEscape(a.subTitle)))
  638. }
  639. c.Data(200, "application/yaml; charset=utf-8", []byte(clashSub))
  640. return true
  641. }
  642. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  643. func (a *SUBController) ApplyCommonHeaders(
  644. c *gin.Context,
  645. header,
  646. updateInterval,
  647. profileTitle string,
  648. profileSupportUrl string,
  649. profileUrl string,
  650. profileAnnounce string,
  651. profileEnableRouting bool,
  652. profileRoutingRules string,
  653. profileHideSettings bool,
  654. ) {
  655. c.Writer.Header().Set("Subscription-Userinfo", header)
  656. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  657. // Basics
  658. if profileTitle != "" {
  659. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  660. }
  661. if profileSupportUrl != "" {
  662. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  663. }
  664. if profileUrl != "" {
  665. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  666. }
  667. if profileAnnounce != "" {
  668. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  669. }
  670. // Advanced (Happ)
  671. if profileEnableRouting {
  672. c.Writer.Header().Set("Routing-Enable", "true")
  673. }
  674. if profileRoutingRules != "" {
  675. c.Writer.Header().Set("Routing", profileRoutingRules)
  676. }
  677. if profileHideSettings {
  678. c.Writer.Header().Set("Hide-Settings", "1")
  679. }
  680. }