controller.go 31 KB

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