controller.go 14 KB

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