1
0

controller.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. if a.jsonEnabled {
  259. gJson := g.Group(a.subJsonPath)
  260. gJson.GET(":subid", a.subJsons)
  261. gJson.HEAD(":subid", a.subJsons)
  262. }
  263. if a.clashEnabled {
  264. gClash := g.Group(a.subClashPath)
  265. gClash.GET(":subid", a.subClashs)
  266. gClash.HEAD(":subid", a.subClashs)
  267. if sameSubscriptionPath(a.subClashPath, subMihomoPath) {
  268. // The configured Clash path already provides the full Mihomo profile.
  269. } else if owner := a.configuredSubscriptionPathOwner(subMihomoPath); owner != "" {
  270. logger.Warningf("Mihomo subscription alias %q is unavailable because it conflicts with the configured %s path", subMihomoPath, owner)
  271. } else {
  272. gMihomo := g.Group(subMihomoPath)
  273. gMihomo.GET(":subid", a.subClashs)
  274. gMihomo.HEAD(":subid", a.subClashs)
  275. }
  276. if owner := a.configuredSubscriptionPathOwner(subClashLegacyPath); owner != "" {
  277. logger.Warningf("Legacy Clash subscription alias %q is unavailable because it conflicts with the configured %s path", subClashLegacyPath, owner)
  278. } else {
  279. gLegacy := g.Group(subClashLegacyPath)
  280. gLegacy.GET(":subid", a.subClashLegacy)
  281. gLegacy.HEAD(":subid", a.subClashLegacy)
  282. }
  283. }
  284. }
  285. func sameSubscriptionPath(left, right string) bool {
  286. return strings.Trim(left, "/") == strings.Trim(right, "/")
  287. }
  288. func (a *SUBController) configuredSubscriptionPathOwner(candidate string) string {
  289. if sameSubscriptionPath(candidate, a.subPath) {
  290. return "raw subscription"
  291. }
  292. if a.jsonEnabled && sameSubscriptionPath(candidate, a.subJsonPath) {
  293. return "JSON subscription"
  294. }
  295. if a.clashEnabled && sameSubscriptionPath(candidate, a.subClashPath) {
  296. return "Clash subscription"
  297. }
  298. return ""
  299. }
  300. // maybeServeSubPage renders the HTML info page when the request comes from a
  301. // browser (Accept: text/html) or explicitly asks for it (?html=1 or ?view=html).
  302. // It reports whether the request was handled. The remark template's per-client
  303. // info is for the content a client app imports — the raw subscription body. A
  304. // browser viewing the HTML info page gets clean, name-only remarks (usage is
  305. // shown in the page summary).
  306. func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
  307. accept := c.GetHeader("Accept")
  308. wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
  309. if !wantsHTML {
  310. return false
  311. }
  312. page, ok := a.buildSubPageData(c)
  313. if !ok {
  314. return true
  315. }
  316. a.serveSubPage(c, page.BasePath, page)
  317. return true
  318. }
  319. func (a *SUBController) maybeServeSubInfo(c *gin.Context) bool {
  320. if !strings.EqualFold(c.Query("format"), "info") {
  321. return false
  322. }
  323. page, ok := a.buildSubPageData(c)
  324. if !ok {
  325. return true
  326. }
  327. info := a.subPageContext(page)
  328. delete(info, "links")
  329. info["emails"] = dedupeEmails(page.Emails)
  330. setNoCacheHeaders(c)
  331. c.JSON(http.StatusOK, info)
  332. return true
  333. }
  334. func (a *SUBController) buildSubPageData(c *gin.Context) (PageData, bool) {
  335. subId := c.Param("subid")
  336. _, host, _, hostHeader := a.subService.ResolveRequest(c)
  337. subReq := a.subService.ForRequest(host)
  338. subReq.subscriptionBody = false
  339. subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
  340. if err != nil || subs == nil {
  341. writeSubError(c, err)
  342. return PageData{}, false
  343. }
  344. subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
  345. if !a.jsonEnabled {
  346. subJsonURL = ""
  347. }
  348. if !a.clashEnabled {
  349. subClashURL = ""
  350. }
  351. basePath, exists := c.Get("base_path")
  352. if !exists {
  353. basePath = "/"
  354. }
  355. basePathStr := basePath.(string)
  356. metadata := a.metadataForSubRequest(func() *SubService { return subReq }, subId, "")
  357. page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, metadata.Title, metadata.SupportURL)
  358. page.SubAnnounce = metadata.Announce
  359. return page, true
  360. }
  361. func dedupeEmails(emails []string) []string {
  362. out := make([]string, 0, len(emails))
  363. seen := make(map[string]struct{}, len(emails))
  364. for _, email := range emails {
  365. if email == "" {
  366. continue
  367. }
  368. if _, dup := seen[email]; dup {
  369. continue
  370. }
  371. seen[email] = struct{}{}
  372. out = append(out, email)
  373. }
  374. return out
  375. }
  376. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  377. func (a *SUBController) subs(c *gin.Context) {
  378. userAgent := c.GetHeader("User-Agent")
  379. if a.maybeServeSubInfo(c) {
  380. logSubscriptionRoute(userAgent, "info")
  381. return
  382. }
  383. if a.maybeServeSubPage(c) {
  384. logSubscriptionRoute(userAgent, "html")
  385. return
  386. }
  387. if !a.enforceHwid(c) {
  388. return
  389. }
  390. if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) && a.serveClashBody(c, false, false) {
  391. a.recordSubscriptionFetch(c)
  392. logSubscriptionRoute(userAgent, "clash")
  393. return
  394. }
  395. if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) {
  396. a.recordSubscriptionFetch(c)
  397. logSubscriptionRoute(userAgent, "json")
  398. return
  399. }
  400. logSubscriptionRoute(userAgent, "raw")
  401. subId := c.Param("subid")
  402. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  403. subReq := a.subService.ForRequest(host)
  404. subReq.subscriptionBody = true
  405. subs, _, _, traffic, err := subReq.getSubs(subId)
  406. if err != nil || subs == nil {
  407. writeSubError(c, err)
  408. } else {
  409. var result strings.Builder
  410. for _, sub := range subs {
  411. result.WriteString(sub)
  412. result.WriteString("\n")
  413. }
  414. // Add headers
  415. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  416. profileURL := fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  417. metadata := a.metadataForSubRequest(func() *SubService { return subReq }, subId, profileURL)
  418. a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  419. if a.subIncyEnableRouting && a.subIncyRoutingRules != "" {
  420. incyRules, _, err := resolveIncyRoutingSource(a.subIncyRoutingRules)
  421. if err == nil && strings.TrimSpace(incyRules) != "" {
  422. result.WriteString(incyRules)
  423. result.WriteString("\n")
  424. }
  425. }
  426. if a.subEncrypt {
  427. c.String(200, base64.StdEncoding.EncodeToString([]byte(result.String())))
  428. } else {
  429. c.String(200, result.String())
  430. }
  431. a.recordSubscriptionFetch(c)
  432. }
  433. }
  434. func (a *SUBController) recordSubscriptionFetch(c *gin.Context) {
  435. if c.Request == nil || c.Request.Method != http.MethodGet || c.Writer.Status() != http.StatusOK {
  436. return
  437. }
  438. if err := a.subService.RecordSubscriptionFetch(c.Param("subid")); err != nil {
  439. logger.Warning("Failed to record subscription fetch:", err)
  440. }
  441. }
  442. func shouldAutoServeClash(autoDetect, clashEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  443. return shouldAutoServeFormat(autoDetect, clashEnabled, wantsHTML, userAgent, userAgentRegex)
  444. }
  445. func shouldAutoServeJson(autoDetect, jsonEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  446. return shouldAutoServeFormat(autoDetect, jsonEnabled, wantsHTML, userAgent, userAgentRegex)
  447. }
  448. func shouldAutoServeFormat(autoDetect, formatEnabled, wantsHTML bool, userAgent string, userAgentRegex *regexp.Regexp) bool {
  449. if !autoDetect || !formatEnabled || wantsHTML || userAgentRegex == nil {
  450. return false
  451. }
  452. return userAgentRegex.MatchString(userAgent)
  453. }
  454. func logSubscriptionRoute(userAgent, branch string) {
  455. logger.Debugf("Subscription request routed: branch=%s user_agent=%q", branch, sanitizeUserAgentForLog(userAgent))
  456. }
  457. func sanitizeUserAgentForLog(userAgent string) string {
  458. clean := strings.Map(func(r rune) rune {
  459. if unicode.IsControl(r) {
  460. return ' '
  461. }
  462. return r
  463. }, userAgent)
  464. runes := []rune(clean)
  465. if len(runes) > 512 {
  466. return string(runes[:512])
  467. }
  468. return clean
  469. }
  470. func compileUserAgentRegex(name, pattern, defaultPattern string) *regexp.Regexp {
  471. pattern = strings.TrimSpace(pattern)
  472. if pattern == "" {
  473. pattern = strings.TrimSpace(defaultPattern)
  474. }
  475. if pattern == "" {
  476. return nil
  477. }
  478. compiled, err := regexp.Compile(pattern)
  479. if err == nil {
  480. return compiled
  481. }
  482. logger.Warningf("Invalid %s User-Agent regex %q; falling back to default %q: %v", name, pattern, defaultPattern, err)
  483. if strings.TrimSpace(defaultPattern) == "" {
  484. return nil
  485. }
  486. return regexp.MustCompile(defaultPattern)
  487. }
  488. // serveSubPage renders internal/web/dist/subpage.html for the current subscription
  489. // request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
  490. // we inject that here, along with window.X_UI_BASE_PATH so the
  491. // page's static asset references resolve correctly when the panel runs
  492. // behind a URL prefix.
  493. func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
  494. var body []byte
  495. if diskBody, diskErr := os.ReadFile("internal/web/dist/subpage.html"); diskErr == nil {
  496. body = diskBody
  497. } else {
  498. readBody, err := fs.ReadFile(distFS, "dist/subpage.html")
  499. if err != nil {
  500. c.String(http.StatusInternalServerError, "missing embedded subpage")
  501. return
  502. }
  503. body = readBody
  504. }
  505. // Vite emits absolute asset URLs (`/assets/...`); when the panel is
  506. // installed under a custom URL prefix, rewrite them so the bundle
  507. // loads from `<basePath>assets/...` where the static handler is
  508. // actually mounted.
  509. if basePath != "/" && basePath != "" {
  510. body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
  511. body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
  512. }
  513. subData := a.subPageContext(page)
  514. // When an admin has configured a custom subscription theme, render it
  515. // instead of the default SPA. We render into a buffer first so a template
  516. // that fails mid-execution can't leave a partially-written (corrupt)
  517. // response — on any error we log and fall through to the default page.
  518. if themeDir, _ := a.settingService.GetSubThemeDir(); themeDir != "" {
  519. if tmpl, err := a.loadSubTemplate(themeDir); err != nil {
  520. logger.Error("sub: custom template parse failed, using default page:", err)
  521. } else if tmpl == nil {
  522. logger.Warning("sub: subThemeDir set but no usable template found, using default page:", themeDir)
  523. } else {
  524. var buf bytes.Buffer
  525. if execErr := tmpl.Execute(&buf, subData); execErr != nil {
  526. logger.Error("sub: custom template execution failed, using default page:", execErr)
  527. } else {
  528. setNoCacheHeaders(c)
  529. c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
  530. return
  531. }
  532. }
  533. }
  534. subDataJSON, err := json.Marshal(subData)
  535. if err != nil {
  536. subDataJSON = []byte("{}")
  537. }
  538. // Defense-in-depth string-escape for the basePath embed — admin-
  539. // controlled but cheap to harden.
  540. jsEscape := strings.NewReplacer(
  541. `\`, `\\`,
  542. `"`, `\"`,
  543. "\n", `\n`,
  544. "\r", `\r`,
  545. "<", `<`,
  546. ">", `>`,
  547. "&", `&`,
  548. )
  549. escapedBase := jsEscape.Replace(basePath)
  550. inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
  551. `window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
  552. out := bytes.Replace(body, []byte("</head>"), inject, 1)
  553. setNoCacheHeaders(c)
  554. c.Data(http.StatusOK, "text/html; charset=utf-8", out)
  555. }
  556. // subPageContext builds the shared view-model map: the template context for
  557. // custom sub themes, the window.__SUB_PAGE_DATA__ payload the SPA reads, and
  558. // (without links) the ?format=info JSON body. The panel's "Calendar Type"
  559. // setting decides whether dates render Gregorian or Jalali — surfaced here so
  560. // consumers match the rest of the panel without a round-trip.
  561. func (a *SUBController) subPageContext(page PageData) map[string]any {
  562. datepicker, _ := a.settingService.GetDatepicker()
  563. if datepicker == "" {
  564. datepicker = "gregorian"
  565. }
  566. return map[string]any{
  567. "sId": page.SId,
  568. "enabled": page.Enabled,
  569. "isOnline": page.IsOnline,
  570. "download": page.Download,
  571. "upload": page.Upload,
  572. "total": page.Total,
  573. "used": page.Used,
  574. "remained": page.Remained,
  575. "expire": page.Expire,
  576. "lastOnline": page.LastOnline,
  577. "downloadByte": page.DownloadByte,
  578. "uploadByte": page.UploadByte,
  579. "totalByte": page.TotalByte,
  580. "subUrl": page.SubUrl,
  581. "subJsonUrl": page.SubJsonUrl,
  582. "subClashUrl": page.SubClashUrl,
  583. "subTitle": page.SubTitle,
  584. "subSupportUrl": page.SubSupportUrl,
  585. "links": page.Result,
  586. "emails": page.Emails,
  587. "datepicker": datepicker,
  588. "announce": page.SubAnnounce,
  589. }
  590. }
  591. func (a *SUBController) enforceHwid(c *gin.Context) bool {
  592. result, err := a.clientService.EnforceHwidForSubID(c.Param("subid"), service.HwidRequest{
  593. Hwid: c.GetHeader("X-HWID"),
  594. UserAgent: c.GetHeader("User-Agent"),
  595. DeviceOS: c.GetHeader("X-Device-OS"),
  596. OsVersion: c.GetHeader("X-Ver-OS"),
  597. DeviceModel: c.GetHeader("X-Device-Model"),
  598. })
  599. if err != nil {
  600. writeSubError(c, err)
  601. return false
  602. }
  603. applyHwidHeaders(c, result)
  604. if !result.Allowed {
  605. c.Status(http.StatusNotFound)
  606. return false
  607. }
  608. return true
  609. }
  610. func applyHwidHeaders(c *gin.Context, result service.HwidGateResult) {
  611. if result.Active {
  612. c.Header("X-Hwid-Active", "true")
  613. }
  614. if result.NotSupported {
  615. c.Header("X-Hwid-Not-Supported", "true")
  616. }
  617. if result.LimitReached {
  618. c.Header("X-Hwid-Limit", "true")
  619. }
  620. if result.MaxDevicesReached {
  621. c.Header("X-Hwid-Max-Devices-Reached", "true")
  622. }
  623. }
  624. // setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
  625. // clients and browsers always fetch fresh traffic/expiry data.
  626. func setNoCacheHeaders(c *gin.Context) {
  627. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  628. c.Header("Pragma", "no-cache")
  629. c.Header("Expires", "0")
  630. }
  631. // loadSubTemplate returns the parsed custom subscription template located in
  632. // themeDir, preferring sub.html over index.html. Parsed templates are cached and
  633. // only re-parsed when the underlying file's modification time changes, so admin
  634. // edits are picked up without paying a disk read + HTML parse on every request.
  635. //
  636. // It returns (nil, nil) when themeDir is not a usable directory or contains no
  637. // template file — the caller should fall back to the default page. A non-nil
  638. // error means a template file exists but failed to parse.
  639. func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, error) {
  640. info, err := os.Stat(themeDir)
  641. if err != nil || !info.IsDir() {
  642. return nil, nil
  643. }
  644. templatePath := filepath.Join(themeDir, "index.html")
  645. if _, err := os.Stat(filepath.Join(themeDir, "sub.html")); err == nil {
  646. templatePath = filepath.Join(themeDir, "sub.html")
  647. }
  648. fi, err := os.Stat(templatePath)
  649. if err != nil {
  650. return nil, nil
  651. }
  652. modTime := fi.ModTime()
  653. a.subTemplateMu.RLock()
  654. cached := a.subTemplateCache[templatePath]
  655. a.subTemplateMu.RUnlock()
  656. if cached != nil && cached.modTime.Equal(modTime) {
  657. return cached.tmpl, nil
  658. }
  659. tmpl, err := template.ParseFiles(templatePath)
  660. if err != nil {
  661. return nil, err
  662. }
  663. a.subTemplateMu.Lock()
  664. a.subTemplateCache[templatePath] = &cachedSubTemplate{tmpl: tmpl, modTime: modTime}
  665. a.subTemplateMu.Unlock()
  666. return tmpl, nil
  667. }
  668. // subJsons handles HTTP requests for JSON subscription configurations. The
  669. // device limit is enforced on every body route, ?view=raw included (#GHSA-7ww3).
  670. func (a *SUBController) subJsons(c *gin.Context) {
  671. if strings.EqualFold(c.Query("view"), "raw") {
  672. if !a.enforceHwid(c) {
  673. return
  674. }
  675. if !a.serveJsonBody(c, a.jsonAlwaysArray, "application/json; charset=utf-8", true) {
  676. writeSubError(c, nil)
  677. }
  678. a.recordSubscriptionFetch(c)
  679. return
  680. }
  681. if a.maybeServeSubPage(c) {
  682. return
  683. }
  684. if !a.enforceHwid(c) {
  685. return
  686. }
  687. a.serveJson(c, a.jsonAlwaysArray, "text/plain; charset=utf-8")
  688. }
  689. func (a *SUBController) serveJson(c *gin.Context, alwaysReturnArray bool, contentType string) {
  690. if !a.serveJsonBody(c, alwaysReturnArray, contentType, false) {
  691. writeSubError(c, nil)
  692. }
  693. a.recordSubscriptionFetch(c)
  694. }
  695. func (a *SUBController) serveJsonBody(c *gin.Context, alwaysReturnArray bool, contentType string, rawDownload bool) bool {
  696. subId := c.Param("subid")
  697. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  698. jsonSub, header, err := a.subJsonService.GetJson(subId, host, alwaysReturnArray)
  699. if err != nil {
  700. writeSubError(c, err)
  701. return true
  702. }
  703. if len(jsonSub) == 0 && header == "" {
  704. return false
  705. }
  706. profileURL := fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  707. var subReq *SubService
  708. metadata := a.metadataForSubRequest(func() *SubService {
  709. if subReq == nil {
  710. subReq = a.subService.ForRequest(host)
  711. }
  712. return subReq
  713. }, subId, profileURL)
  714. a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  715. if rawDownload {
  716. c.Writer.Header().Set("Content-Disposition", `attachment; filename="subscription.json"`)
  717. }
  718. c.Data(200, contentType, []byte(jsonSub))
  719. return true
  720. }
  721. func (a *SUBController) subClashs(c *gin.Context) {
  722. a.subClash(c, false)
  723. }
  724. func (a *SUBController) subClashLegacy(c *gin.Context) {
  725. a.subClash(c, true)
  726. }
  727. func (a *SUBController) subClash(c *gin.Context, legacy bool) {
  728. if strings.EqualFold(c.Query("view"), "raw") {
  729. if !a.enforceHwid(c) {
  730. return
  731. }
  732. if !a.serveClashBody(c, true, legacy) {
  733. writeSubError(c, nil)
  734. }
  735. a.recordSubscriptionFetch(c)
  736. return
  737. }
  738. if a.maybeServeSubPage(c) {
  739. return
  740. }
  741. if !a.enforceHwid(c) {
  742. return
  743. }
  744. if !a.serveClashBody(c, false, legacy) {
  745. writeSubError(c, nil)
  746. }
  747. a.recordSubscriptionFetch(c)
  748. }
  749. func (a *SUBController) serveClashBody(c *gin.Context, rawDownload bool, legacy bool) bool {
  750. subId := c.Param("subid")
  751. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  752. var clashSub, header string
  753. var err error
  754. if legacy {
  755. clashSub, header, err = a.subClashService.GetClashLegacy(subId, host)
  756. } else {
  757. clashSub, header, err = a.subClashService.GetClash(subId, host)
  758. }
  759. if err != nil {
  760. if errors.Is(err, errNoLegacyClashProxies) {
  761. c.String(http.StatusUnprocessableEntity, err.Error())
  762. return true
  763. }
  764. writeSubError(c, err)
  765. return true
  766. }
  767. if len(clashSub) == 0 && header == "" {
  768. return false
  769. }
  770. profileURL := fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  771. var subReq *SubService
  772. metadata := a.metadataForSubRequest(func() *SubService {
  773. if subReq == nil {
  774. subReq = a.subService.ForRequest(host)
  775. }
  776. return subReq
  777. }, subId, profileURL)
  778. a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings)
  779. if rawDownload {
  780. c.Writer.Header().Set("Content-Disposition", `attachment; filename="subscription.yaml"`)
  781. } else if metadata.Title != "" {
  782. // Clash clients commonly use Content-Disposition to choose the imported profile name.
  783. c.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename*=UTF-8''%s`, url.PathEscape(metadata.Title)))
  784. }
  785. c.Data(200, "application/yaml; charset=utf-8", []byte(clashSub))
  786. return true
  787. }
  788. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  789. func (a *SUBController) ApplyCommonHeaders(
  790. c *gin.Context,
  791. header,
  792. updateInterval,
  793. profileTitle string,
  794. profileSupportUrl string,
  795. profileUrl string,
  796. profileAnnounce string,
  797. profileEnableRouting bool,
  798. profileRoutingRules string,
  799. profileHideSettings bool,
  800. ) {
  801. c.Writer.Header().Set("Subscription-Userinfo", header)
  802. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  803. // Basics
  804. if profileTitle != "" {
  805. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  806. }
  807. if profileSupportUrl != "" {
  808. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  809. }
  810. if profileUrl != "" {
  811. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  812. }
  813. if profileAnnounce != "" {
  814. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  815. }
  816. rules, remote, routingErr := resolveRoutingSource(remoteRoutingHapp, profileRoutingRules)
  817. if strings.TrimSpace(profileRoutingRules) == "" {
  818. // Happ/INCY fetch the geo files the baked JSON rules reference through
  819. // this header, so a blank Happ setting falls back to the JSON profile.
  820. rules, remote, routingErr = jsonRoutingHeaderSource(a.subJsonRoutingRules), false, nil
  821. }
  822. // The off values undo a previously pushed setting, so they ride the same
  823. // opt-in as every other Happ header rather than reaching every Happ client.
  824. happManaged := a.happConfig.AutoDetect && c.Request != nil && IsHappClient(c.GetHeader("User-Agent"))
  825. if profileEnableRouting {
  826. c.Writer.Header().Set("Routing-Enable", "true")
  827. } else if happManaged {
  828. c.Writer.Header().Set("Routing-Enable", "0")
  829. }
  830. if (routingErr == nil || !remote) && strings.TrimSpace(rules) != "" {
  831. c.Writer.Header().Set("Routing", rules)
  832. }
  833. if profileHideSettings {
  834. c.Writer.Header().Set("Hide-Settings", "1")
  835. } else if happManaged {
  836. c.Writer.Header().Set("Hide-Settings", "0")
  837. }
  838. ApplyHappHeaders(c, a.happConfig, happManaged)
  839. }