controller.go 32 KB

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