controller.go 28 KB

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