1
0

controller.go 14 KB

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