controller.go 14 KB

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