controller.go 31 KB

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