controller.go 31 KB

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