controller.go 31 KB

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