1
0

subController.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package sub
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "html/template"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/gin-gonic/gin"
  17. "github.com/mhsanaei/3x-ui/v3/logger"
  18. "github.com/mhsanaei/3x-ui/v3/web/service"
  19. )
  20. // writeSubError translates a service-layer result into an HTTP response.
  21. // A nil error with no rows means the subId doesn't match anything (deleted
  22. // client, never-existed id) and becomes 404. A real error becomes 500. No
  23. // body — VPN clients only look at the status.
  24. func writeSubError(c *gin.Context, err error) {
  25. if err == nil {
  26. c.Status(http.StatusNotFound)
  27. return
  28. }
  29. c.Status(http.StatusInternalServerError)
  30. }
  31. // cachedSubTemplate holds a parsed custom subscription template together with
  32. // the modification time of the file it was parsed from, so the cache can be
  33. // invalidated when an admin edits the template on disk.
  34. type cachedSubTemplate struct {
  35. tmpl *template.Template
  36. modTime time.Time
  37. }
  38. // SUBController handles HTTP requests for subscription links and JSON configurations.
  39. type SUBController struct {
  40. subTitle string
  41. subSupportUrl string
  42. subProfileUrl string
  43. subAnnounce string
  44. subEnableRouting bool
  45. subRoutingRules string
  46. subPath string
  47. subJsonPath string
  48. subClashPath string
  49. jsonEnabled bool
  50. clashEnabled bool
  51. subEncrypt bool
  52. updateInterval string
  53. subService *SubService
  54. subJsonService *SubJsonService
  55. subClashService *SubClashService
  56. settingService service.SettingService
  57. subTemplateMu sync.RWMutex
  58. subTemplateCache map[string]*cachedSubTemplate
  59. }
  60. // NewSUBController creates a new subscription controller with the given configuration.
  61. func NewSUBController(
  62. g *gin.RouterGroup,
  63. subPath string,
  64. jsonPath string,
  65. clashPath string,
  66. jsonEnabled bool,
  67. clashEnabled bool,
  68. encrypt bool,
  69. showInfo bool,
  70. rModel string,
  71. update string,
  72. jsonMux string,
  73. jsonRules string,
  74. jsonFinalMask string,
  75. clashEnableRouting bool,
  76. clashRules string,
  77. subTitle string,
  78. subSupportUrl string,
  79. subProfileUrl string,
  80. subAnnounce string,
  81. subEnableRouting bool,
  82. subRoutingRules string,
  83. ) *SUBController {
  84. sub := NewSubService(showInfo, rModel)
  85. a := &SUBController{
  86. subTitle: subTitle,
  87. subSupportUrl: subSupportUrl,
  88. subProfileUrl: subProfileUrl,
  89. subAnnounce: subAnnounce,
  90. subEnableRouting: subEnableRouting,
  91. subRoutingRules: subRoutingRules,
  92. subPath: subPath,
  93. subJsonPath: jsonPath,
  94. subClashPath: clashPath,
  95. jsonEnabled: jsonEnabled,
  96. clashEnabled: clashEnabled,
  97. subEncrypt: encrypt,
  98. updateInterval: update,
  99. subService: sub,
  100. subJsonService: NewSubJsonService(jsonMux, jsonRules, jsonFinalMask, sub),
  101. subClashService: NewSubClashService(clashEnableRouting, clashRules, sub),
  102. subTemplateCache: map[string]*cachedSubTemplate{},
  103. }
  104. a.initRouter(g)
  105. return a
  106. }
  107. // initRouter registers HTTP routes for subscription links and JSON endpoints
  108. // on the provided router group.
  109. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  110. gLink := g.Group(a.subPath)
  111. gLink.GET(":subid", a.subs)
  112. gLink.HEAD(":subid", a.subs)
  113. if a.jsonEnabled {
  114. gJson := g.Group(a.subJsonPath)
  115. gJson.GET(":subid", a.subJsons)
  116. gJson.HEAD(":subid", a.subJsons)
  117. }
  118. if a.clashEnabled {
  119. gClash := g.Group(a.subClashPath)
  120. gClash.GET(":subid", a.subClashs)
  121. gClash.HEAD(":subid", a.subClashs)
  122. }
  123. }
  124. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  125. func (a *SUBController) subs(c *gin.Context) {
  126. subId := c.Param("subid")
  127. scheme, host, hostWithPort, hostHeader := a.subService.ResolveRequest(c)
  128. subs, emails, lastOnline, traffic, err := a.subService.GetSubs(subId, host)
  129. if err != nil || len(subs) == 0 {
  130. writeSubError(c, err)
  131. } else {
  132. result := ""
  133. for _, sub := range subs {
  134. result += sub + "\n"
  135. }
  136. // If the request expects HTML (e.g., browser) or explicitly asked (?html=1 or ?view=html), render the info page here
  137. accept := c.GetHeader("Accept")
  138. if strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html") {
  139. subURL, subJsonURL, subClashURL := a.subService.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
  140. if !a.jsonEnabled {
  141. subJsonURL = ""
  142. }
  143. if !a.clashEnabled {
  144. subClashURL = ""
  145. }
  146. basePath, exists := c.Get("base_path")
  147. if !exists {
  148. basePath = "/"
  149. }
  150. basePathStr := basePath.(string)
  151. page := a.subService.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
  152. a.serveSubPage(c, basePathStr, page)
  153. return
  154. }
  155. // Add headers
  156. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  157. profileUrl := a.subProfileUrl
  158. if profileUrl == "" {
  159. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  160. }
  161. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  162. if a.subEncrypt {
  163. c.String(200, base64.StdEncoding.EncodeToString([]byte(result)))
  164. } else {
  165. c.String(200, result)
  166. }
  167. }
  168. }
  169. // serveSubPage renders web/dist/subpage.html for the current subscription
  170. // request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
  171. // we inject that here, along with window.X_UI_BASE_PATH so the
  172. // page's static asset references resolve correctly when the panel runs
  173. // behind a URL prefix.
  174. func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
  175. var body []byte
  176. if diskBody, diskErr := os.ReadFile("web/dist/subpage.html"); diskErr == nil {
  177. body = diskBody
  178. } else {
  179. readBody, err := distFS.ReadFile("dist/subpage.html")
  180. if err != nil {
  181. c.String(http.StatusInternalServerError, "missing embedded subpage")
  182. return
  183. }
  184. body = readBody
  185. }
  186. // Vite emits absolute asset URLs (`/assets/...`); when the panel is
  187. // installed under a custom URL prefix, rewrite them so the bundle
  188. // loads from `<basePath>assets/...` where the static handler is
  189. // actually mounted.
  190. if basePath != "/" && basePath != "" {
  191. body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
  192. body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
  193. }
  194. // JSON-marshal the view-model so the SPA can read it as a plain
  195. // The panel's "Calendar Type" setting decides whether the SubPage
  196. // renders dates in Gregorian or Jalali — surface it here so the SPA
  197. // can match the rest of the panel without a round-trip.
  198. datepicker, _ := a.settingService.GetDatepicker()
  199. if datepicker == "" {
  200. datepicker = "gregorian"
  201. }
  202. subData := map[string]any{
  203. "sId": page.SId,
  204. "enabled": page.Enabled,
  205. "download": page.Download,
  206. "upload": page.Upload,
  207. "total": page.Total,
  208. "used": page.Used,
  209. "remained": page.Remained,
  210. "expire": page.Expire,
  211. "lastOnline": page.LastOnline,
  212. "downloadByte": page.DownloadByte,
  213. "uploadByte": page.UploadByte,
  214. "totalByte": page.TotalByte,
  215. "subUrl": page.SubUrl,
  216. "subJsonUrl": page.SubJsonUrl,
  217. "subClashUrl": page.SubClashUrl,
  218. "subTitle": page.SubTitle,
  219. "subSupportUrl": page.SubSupportUrl,
  220. "links": page.Result,
  221. "emails": page.Emails,
  222. "datepicker": datepicker,
  223. }
  224. // When an admin has configured a custom subscription theme, render it
  225. // instead of the default SPA. We render into a buffer first so a template
  226. // that fails mid-execution can't leave a partially-written (corrupt)
  227. // response — on any error we log and fall through to the default page.
  228. if themeDir, _ := a.settingService.GetSubThemeDir(); themeDir != "" {
  229. if tmpl, err := a.loadSubTemplate(themeDir); err != nil {
  230. logger.Error("sub: custom template parse failed, using default page:", err)
  231. } else if tmpl == nil {
  232. logger.Warning("sub: subThemeDir set but no usable template found, using default page:", themeDir)
  233. } else {
  234. var buf bytes.Buffer
  235. if execErr := tmpl.Execute(&buf, subData); execErr != nil {
  236. logger.Error("sub: custom template execution failed, using default page:", execErr)
  237. } else {
  238. setNoCacheHeaders(c)
  239. c.Data(http.StatusOK, "text/html; charset=utf-8", buf.Bytes())
  240. return
  241. }
  242. }
  243. }
  244. subDataJSON, err := json.Marshal(subData)
  245. if err != nil {
  246. subDataJSON = []byte("{}")
  247. }
  248. // Defense-in-depth string-escape for the basePath embed — admin-
  249. // controlled but cheap to harden.
  250. jsEscape := strings.NewReplacer(
  251. `\`, `\\`,
  252. `"`, `\"`,
  253. "\n", `\n`,
  254. "\r", `\r`,
  255. "<", `<`,
  256. ">", `>`,
  257. "&", `&`,
  258. )
  259. escapedBase := jsEscape.Replace(basePath)
  260. inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
  261. `window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
  262. out := bytes.Replace(body, []byte("</head>"), inject, 1)
  263. setNoCacheHeaders(c)
  264. c.Data(http.StatusOK, "text/html; charset=utf-8", out)
  265. }
  266. // setNoCacheHeaders marks a subscription page response as non-cacheable so VPN
  267. // clients and browsers always fetch fresh traffic/expiry data.
  268. func setNoCacheHeaders(c *gin.Context) {
  269. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  270. c.Header("Pragma", "no-cache")
  271. c.Header("Expires", "0")
  272. }
  273. // loadSubTemplate returns the parsed custom subscription template located in
  274. // themeDir, preferring sub.html over index.html. Parsed templates are cached and
  275. // only re-parsed when the underlying file's modification time changes, so admin
  276. // edits are picked up without paying a disk read + HTML parse on every request.
  277. //
  278. // It returns (nil, nil) when themeDir is not a usable directory or contains no
  279. // template file — the caller should fall back to the default page. A non-nil
  280. // error means a template file exists but failed to parse.
  281. func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, error) {
  282. info, err := os.Stat(themeDir)
  283. if err != nil || !info.IsDir() {
  284. return nil, nil
  285. }
  286. templatePath := filepath.Join(themeDir, "index.html")
  287. if _, err := os.Stat(filepath.Join(themeDir, "sub.html")); err == nil {
  288. templatePath = filepath.Join(themeDir, "sub.html")
  289. }
  290. fi, err := os.Stat(templatePath)
  291. if err != nil {
  292. return nil, nil
  293. }
  294. modTime := fi.ModTime()
  295. a.subTemplateMu.RLock()
  296. cached := a.subTemplateCache[templatePath]
  297. a.subTemplateMu.RUnlock()
  298. if cached != nil && cached.modTime.Equal(modTime) {
  299. return cached.tmpl, nil
  300. }
  301. tmpl, err := template.ParseFiles(templatePath)
  302. if err != nil {
  303. return nil, err
  304. }
  305. a.subTemplateMu.Lock()
  306. a.subTemplateCache[templatePath] = &cachedSubTemplate{tmpl: tmpl, modTime: modTime}
  307. a.subTemplateMu.Unlock()
  308. return tmpl, nil
  309. }
  310. // subJsons handles HTTP requests for JSON subscription configurations.
  311. func (a *SUBController) subJsons(c *gin.Context) {
  312. subId := c.Param("subid")
  313. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  314. jsonSub, header, err := a.subJsonService.GetJson(subId, host)
  315. if err != nil || len(jsonSub) == 0 {
  316. writeSubError(c, err)
  317. } else {
  318. profileUrl := a.subProfileUrl
  319. if profileUrl == "" {
  320. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  321. }
  322. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  323. c.String(200, jsonSub)
  324. }
  325. }
  326. func (a *SUBController) subClashs(c *gin.Context) {
  327. subId := c.Param("subid")
  328. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  329. clashSub, header, err := a.subClashService.GetClash(subId, host)
  330. if err != nil || len(clashSub) == 0 {
  331. writeSubError(c, err)
  332. } else {
  333. profileUrl := a.subProfileUrl
  334. if profileUrl == "" {
  335. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  336. }
  337. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  338. if a.subTitle != "" {
  339. // Clash clients commonly use Content-Disposition to choose the imported profile name.
  340. c.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename*=UTF-8''%s`, url.PathEscape(a.subTitle)))
  341. }
  342. c.Data(200, "application/yaml; charset=utf-8", []byte(clashSub))
  343. }
  344. }
  345. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  346. func (a *SUBController) ApplyCommonHeaders(
  347. c *gin.Context,
  348. header,
  349. updateInterval,
  350. profileTitle string,
  351. profileSupportUrl string,
  352. profileUrl string,
  353. profileAnnounce string,
  354. profileEnableRouting bool,
  355. profileRoutingRules string,
  356. ) {
  357. c.Writer.Header().Set("Subscription-Userinfo", header)
  358. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  359. //Basics
  360. if profileTitle != "" {
  361. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  362. }
  363. if profileSupportUrl != "" {
  364. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  365. }
  366. if profileUrl != "" {
  367. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  368. }
  369. if profileAnnounce != "" {
  370. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  371. }
  372. //Advanced (Happ)
  373. c.Writer.Header().Set("Routing-Enable", strconv.FormatBool(profileEnableRouting))
  374. if profileRoutingRules != "" {
  375. c.Writer.Header().Set("Routing", profileRoutingRules)
  376. }
  377. }