1
0

controller.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. package sub
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "html/template"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "strconv"
  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. subId := c.Param("subid")
  258. _, host, _, hostHeader := a.subService.ResolveRequest(c)
  259. subReq := a.subService.ForRequest(host)
  260. subReq.subscriptionBody = false
  261. subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
  262. if err != nil || len(subs) == 0 {
  263. writeSubError(c, err)
  264. return true
  265. }
  266. subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
  267. if !a.jsonEnabled {
  268. subJsonURL = ""
  269. }
  270. if !a.clashEnabled {
  271. subClashURL = ""
  272. }
  273. basePath, exists := c.Get("base_path")
  274. if !exists {
  275. basePath = "/"
  276. }
  277. basePathStr := basePath.(string)
  278. page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
  279. a.serveSubPage(c, basePathStr, page)
  280. return true
  281. }
  282. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  283. func (a *SUBController) subs(c *gin.Context) {
  284. userAgent := c.GetHeader("User-Agent")
  285. if a.maybeServeSubPage(c) {
  286. logSubscriptionRoute(userAgent, "html")
  287. return
  288. }
  289. if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) {
  290. logSubscriptionRoute(userAgent, "clash")
  291. a.subClashs(c)
  292. return
  293. }
  294. if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) {
  295. logSubscriptionRoute(userAgent, "json")
  296. a.serveJson(c, true, "application/json; charset=utf-8")
  297. return
  298. }
  299. logSubscriptionRoute(userAgent, "raw")
  300. subId := c.Param("subid")
  301. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  302. subReq := a.subService.ForRequest(host)
  303. subReq.subscriptionBody = true
  304. subs, _, _, traffic, err := subReq.getSubs(subId)
  305. if err != nil || len(subs) == 0 {
  306. writeSubError(c, err)
  307. } else {
  308. var result strings.Builder
  309. for _, sub := range subs {
  310. result.WriteString(sub)
  311. result.WriteString("\n")
  312. }
  313. // Add headers
  314. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  315. profileUrl := a.subProfileUrl
  316. if profileUrl == "" {
  317. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  318. }
  319. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  320. if a.subIncyEnableRouting && a.subIncyRoutingRules != "" {
  321. result.WriteString(a.subIncyRoutingRules)
  322. result.WriteString("\n")
  323. }
  324. if a.subEncrypt {
  325. c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
  326. } else {
  327. c.String(200, result.String())
  328. }
  329. }
  330. }
  331. func shouldAutoServeClash(autoDetect, clashEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  332. return shouldAutoServeFormat(autoDetect, clashEnabled, wantsHTML, userAgent, userAgentRegex)
  333. }
  334. func shouldAutoServeJson(autoDetect, jsonEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  335. return shouldAutoServeFormat(autoDetect, jsonEnabled, wantsHTML, userAgent, userAgentRegex)
  336. }
  337. func shouldAutoServeFormat(autoDetect, formatEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  338. if !autoDetect || !formatEnabled || wantsHTML || userAgentRegex == nil {
  339. return false
  340. }
  341. return userAgentRegex.MatchString(userAgent)
  342. }
  343. func logSubscriptionRoute(userAgent, branch string) {
  344. logger.Debugf("Subscription request routed: branch=%s user_agent=%q", branch, sanitizeUserAgentForLog(userAgent))
  345. }
  346. func sanitizeUserAgentForLog(userAgent string) string {
  347. clean := strings.Map(func(r rune) rune {
  348. if unicode.IsControl(r) {
  349. return ' '
  350. }
  351. return r
  352. }, userAgent)
  353. runes := []rune(clean)
  354. if len(runes) > 512 {
  355. return string(runes[:512])
  356. }
  357. return clean
  358. }
  359. func compileUserAgentRegex(name, pattern, defaultPattern string) *regexp.Regexp {
  360. pattern = strings.TrimSpace(pattern)
  361. if pattern == "" {
  362. pattern = strings.TrimSpace(defaultPattern)
  363. }
  364. if pattern == "" {
  365. return nil
  366. }
  367. compiled, err := regexp.Compile(pattern)
  368. if err == nil {
  369. return compiled
  370. }
  371. logger.Warningf("Invalid %s User-Agent regex %q; falling back to default %q: %v", name, pattern, defaultPattern, err)
  372. if strings.TrimSpace(defaultPattern) == "" {
  373. return nil
  374. }
  375. return regexp.MustCompile(defaultPattern)
  376. }
  377. // serveSubPage renders internal/web/dist/subpage.html for the current subscription
  378. // request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
  379. // we inject that here, along with window.X_UI_BASE_PATH so the
  380. // page's static asset references resolve correctly when the panel runs
  381. // behind a URL prefix.
  382. func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
  383. var body []byte
  384. if diskBody, diskErr := os.ReadFile("internal/web/dist/subpage.html"); diskErr == nil {
  385. body = diskBody
  386. } else {
  387. readBody, err := distFS.ReadFile("dist/subpage.html")
  388. if err != nil {
  389. c.String(http.StatusInternalServerError, "missing embedded subpage")
  390. return
  391. }
  392. body = readBody
  393. }
  394. // Vite emits absolute asset URLs (`/assets/...`); when the panel is
  395. // installed under a custom URL prefix, rewrite them so the bundle
  396. // loads from `<basePath>assets/...` where the static handler is
  397. // actually mounted.
  398. if basePath != "/" && basePath != "" {
  399. body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
  400. body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
  401. }
  402. // JSON-marshal the view-model so the SPA can read it as a plain
  403. // The panel's "Calendar Type" setting decides whether the SubPage
  404. // renders dates in Gregorian or Jalali — surface it here so the SPA
  405. // can match the rest of the panel without a round-trip.
  406. datepicker, _ := a.settingService.GetDatepicker()
  407. if datepicker == "" {
  408. datepicker = "gregorian"
  409. }
  410. subData := map[string]any{
  411. "sId": page.SId,
  412. "enabled": page.Enabled,
  413. "download": page.Download,
  414. "upload": page.Upload,
  415. "total": page.Total,
  416. "used": page.Used,
  417. "remained": page.Remained,
  418. "expire": page.Expire,
  419. "lastOnline": page.LastOnline,
  420. "downloadByte": page.DownloadByte,
  421. "uploadByte": page.UploadByte,
  422. "totalByte": page.TotalByte,
  423. "subUrl": page.SubUrl,
  424. "subJsonUrl": page.SubJsonUrl,
  425. "subClashUrl": page.SubClashUrl,
  426. "subTitle": page.SubTitle,
  427. "subSupportUrl": page.SubSupportUrl,
  428. "links": page.Result,
  429. "emails": page.Emails,
  430. "datepicker": datepicker,
  431. "announce": a.subAnnounce,
  432. }
  433. // When an admin has configured a custom subscription theme, render it
  434. // instead of the default SPA. We render into a buffer first so a template
  435. // that fails mid-execution can't leave a partially-written (corrupt)
  436. // response — on any error we log and fall through to the default page.
  437. if themeDir, _ := a.settingService.GetSubThemeDir(); themeDir != "" {
  438. if tmpl, err := a.loadSubTemplate(themeDir); err != nil {
  439. logger.Error("sub: custom template parse failed, using default page:", err)
  440. } else if tmpl == nil {
  441. logger.Warning("sub: subThemeDir set but no usable template found, using default page:", themeDir)
  442. } else {
  443. var buf bytes.Buffer
  444. if execErr := tmpl.Execute(&buf, subData); execErr != nil {
  445. logger.Error("sub: custom template execution failed, using default page:", execErr)
  446. } else {
  447. setNoCacheHeaders(c)
  448. c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
  449. return
  450. }
  451. }
  452. }
  453. subDataJSON, err := json.Marshal(subData)
  454. if err != nil {
  455. subDataJSON = []byte("{}")
  456. }
  457. // Defense-in-depth string-escape for the basePath embed — admin-
  458. // controlled but cheap to harden.
  459. jsEscape := strings.NewReplacer(
  460. `\`, `\\`,
  461. `"`, `\"`,
  462. "\n", `\n`,
  463. "\r", `\r`,
  464. "<", `<`,
  465. ">", `>`,
  466. "&", `&`,
  467. )
  468. escapedBase := jsEscape.Replace(basePath)
  469. inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
  470. `window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
  471. out := bytes.Replace(body, []byte("</head>"), inject, 1)
  472. setNoCacheHeaders(c)
  473. c.Data(http.StatusOK, "text/html; charset=utf-8", out)
  474. }
  475. // setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
  476. // clients and browsers always fetch fresh traffic/expiry data.
  477. func setNoCacheHeaders(c *gin.Context) {
  478. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  479. c.Header("Pragma", "no-cache")
  480. c.Header("Expires", "0")
  481. }
  482. // loadSubTemplate returns the parsed custom subscription template located in
  483. // themeDir, preferring sub.html over index.html. Parsed templates are cached and
  484. // only re-parsed when the underlying file's modification time changes, so admin
  485. // edits are picked up without paying a disk read + HTML parse on every request.
  486. //
  487. // It returns (nil, nil) when themeDir is not a usable directory or contains no
  488. // template file — the caller should fall back to the default page. A non-nil
  489. // error means a template file exists but failed to parse.
  490. func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, error) {
  491. info, err := os.Stat(themeDir)
  492. if err != nil || !info.IsDir() {
  493. return nil, nil
  494. }
  495. templatePath := filepath.Join(themeDir, "index.html")
  496. if _, err := os.Stat(filepath.Join(themeDir, "sub.html")); err == nil {
  497. templatePath = filepath.Join(themeDir, "sub.html")
  498. }
  499. fi, err := os.Stat(templatePath)
  500. if err != nil {
  501. return nil, nil
  502. }
  503. modTime := fi.ModTime()
  504. a.subTemplateMu.RLock()
  505. cached := a.subTemplateCache[templatePath]
  506. a.subTemplateMu.RUnlock()
  507. if cached != nil && cached.modTime.Equal(modTime) {
  508. return cached.tmpl, nil
  509. }
  510. tmpl, err := template.ParseFiles(templatePath)
  511. if err != nil {
  512. return nil, err
  513. }
  514. a.subTemplateMu.Lock()
  515. a.subTemplateCache[templatePath] = &cachedSubTemplate{tmpl: tmpl, modTime: modTime}
  516. a.subTemplateMu.Unlock()
  517. return tmpl, nil
  518. }
  519. // subJsons handles HTTP requests for JSON subscription configurations.
  520. func (a *SUBController) subJsons(c *gin.Context) {
  521. if a.maybeServeSubPage(c) {
  522. return
  523. }
  524. a.serveJson(c, a.jsonAlwaysArray, "text/plain; charset=utf-8")
  525. }
  526. func (a *SUBController) serveJson(c *gin.Context, alwaysReturnArray bool, contentType string) {
  527. subId := c.Param("subid")
  528. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  529. jsonSub, header, err := a.subJsonService.GetJson(subId, host, alwaysReturnArray)
  530. if err != nil || len(jsonSub) == 0 {
  531. writeSubError(c, err)
  532. } else {
  533. profileUrl := a.subProfileUrl
  534. if profileUrl == "" {
  535. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  536. }
  537. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  538. c.Data(200, contentType, []byte(jsonSub))
  539. }
  540. }
  541. func (a *SUBController) subClashs(c *gin.Context) {
  542. if a.maybeServeSubPage(c) {
  543. return
  544. }
  545. subId := c.Param("subid")
  546. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  547. clashSub, header, err := a.subClashService.GetClash(subId, host)
  548. if err != nil || len(clashSub) == 0 {
  549. writeSubError(c, err)
  550. } else {
  551. profileUrl := a.subProfileUrl
  552. if profileUrl == "" {
  553. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  554. }
  555. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  556. if a.subTitle != "" {
  557. // Clash clients commonly use Content-Disposition to choose the imported profile name.
  558. c.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename*=UTF-8''%s`, url.PathEscape(a.subTitle)))
  559. }
  560. c.Data(200, "application/yaml; charset=utf-8", []byte(clashSub))
  561. }
  562. }
  563. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  564. func (a *SUBController) ApplyCommonHeaders(
  565. c *gin.Context,
  566. header,
  567. updateInterval,
  568. profileTitle string,
  569. profileSupportUrl string,
  570. profileUrl string,
  571. profileAnnounce string,
  572. profileEnableRouting bool,
  573. profileRoutingRules string,
  574. profileHideSettings bool,
  575. ) {
  576. c.Writer.Header().Set("Subscription-Userinfo", header)
  577. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  578. // Basics
  579. if profileTitle != "" {
  580. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  581. }
  582. if profileSupportUrl != "" {
  583. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  584. }
  585. if profileUrl != "" {
  586. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  587. }
  588. if profileAnnounce != "" {
  589. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  590. }
  591. // Advanced (Happ)
  592. c.Writer.Header().Set("Routing-Enable", strconv.FormatBool(profileEnableRouting))
  593. if profileRoutingRules != "" {
  594. c.Writer.Header().Set("Routing", profileRoutingRules)
  595. }
  596. if profileHideSettings {
  597. c.Writer.Header().Set("Hide-Settings", "1")
  598. }
  599. }