controller.go 14 KB

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