controller.go 23 KB

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