controller.go 23 KB

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