subController.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package sub
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "github.com/mhsanaei/3x-ui/v3/web/service"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // writeSubError translates a service-layer result into an HTTP response.
  16. // A nil error with no rows means the subId doesn't match anything (deleted
  17. // client, never-existed id) and becomes 404. A real error becomes 500. No
  18. // body — VPN clients only look at the status.
  19. func writeSubError(c *gin.Context, err error) {
  20. if err == nil {
  21. c.Status(http.StatusNotFound)
  22. return
  23. }
  24. c.Status(http.StatusInternalServerError)
  25. }
  26. // SUBController handles HTTP requests for subscription links and JSON configurations.
  27. type SUBController struct {
  28. subTitle string
  29. subSupportUrl string
  30. subProfileUrl string
  31. subAnnounce string
  32. subEnableRouting bool
  33. subRoutingRules string
  34. subPath string
  35. subJsonPath string
  36. subClashPath string
  37. jsonEnabled bool
  38. clashEnabled bool
  39. subEncrypt bool
  40. updateInterval string
  41. subService *SubService
  42. subJsonService *SubJsonService
  43. subClashService *SubClashService
  44. settingService service.SettingService
  45. }
  46. // NewSUBController creates a new subscription controller with the given configuration.
  47. func NewSUBController(
  48. g *gin.RouterGroup,
  49. subPath string,
  50. jsonPath string,
  51. clashPath string,
  52. jsonEnabled bool,
  53. clashEnabled bool,
  54. encrypt bool,
  55. showInfo bool,
  56. rModel string,
  57. update string,
  58. jsonMux string,
  59. jsonRules string,
  60. jsonFinalMask string,
  61. clashEnableRouting bool,
  62. clashRules string,
  63. subTitle string,
  64. subSupportUrl string,
  65. subProfileUrl string,
  66. subAnnounce string,
  67. subEnableRouting bool,
  68. subRoutingRules string,
  69. ) *SUBController {
  70. sub := NewSubService(showInfo, rModel)
  71. a := &SUBController{
  72. subTitle: subTitle,
  73. subSupportUrl: subSupportUrl,
  74. subProfileUrl: subProfileUrl,
  75. subAnnounce: subAnnounce,
  76. subEnableRouting: subEnableRouting,
  77. subRoutingRules: subRoutingRules,
  78. subPath: subPath,
  79. subJsonPath: jsonPath,
  80. subClashPath: clashPath,
  81. jsonEnabled: jsonEnabled,
  82. clashEnabled: clashEnabled,
  83. subEncrypt: encrypt,
  84. updateInterval: update,
  85. subService: sub,
  86. subJsonService: NewSubJsonService(jsonMux, jsonRules, jsonFinalMask, sub),
  87. subClashService: NewSubClashService(clashEnableRouting, clashRules, sub),
  88. }
  89. a.initRouter(g)
  90. return a
  91. }
  92. // initRouter registers HTTP routes for subscription links and JSON endpoints
  93. // on the provided router group.
  94. func (a *SUBController) initRouter(g *gin.RouterGroup) {
  95. gLink := g.Group(a.subPath)
  96. gLink.GET(":subid", a.subs)
  97. gLink.HEAD(":subid", a.subs)
  98. if a.jsonEnabled {
  99. gJson := g.Group(a.subJsonPath)
  100. gJson.GET(":subid", a.subJsons)
  101. gJson.HEAD(":subid", a.subJsons)
  102. }
  103. if a.clashEnabled {
  104. gClash := g.Group(a.subClashPath)
  105. gClash.GET(":subid", a.subClashs)
  106. gClash.HEAD(":subid", a.subClashs)
  107. }
  108. }
  109. // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
  110. func (a *SUBController) subs(c *gin.Context) {
  111. subId := c.Param("subid")
  112. scheme, host, hostWithPort, hostHeader := a.subService.ResolveRequest(c)
  113. subs, emails, lastOnline, traffic, err := a.subService.GetSubs(subId, host)
  114. if err != nil || len(subs) == 0 {
  115. writeSubError(c, err)
  116. } else {
  117. result := ""
  118. for _, sub := range subs {
  119. result += sub + "\n"
  120. }
  121. // If the request expects HTML (e.g., browser) or explicitly asked (?html=1 or ?view=html), render the info page here
  122. accept := c.GetHeader("Accept")
  123. if strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html") {
  124. subURL, subJsonURL, subClashURL := a.subService.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
  125. if !a.jsonEnabled {
  126. subJsonURL = ""
  127. }
  128. if !a.clashEnabled {
  129. subClashURL = ""
  130. }
  131. basePath, exists := c.Get("base_path")
  132. if !exists {
  133. basePath = "/"
  134. }
  135. basePathStr := basePath.(string)
  136. page := a.subService.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
  137. a.serveSubPage(c, basePathStr, page)
  138. return
  139. }
  140. // Add headers
  141. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  142. profileUrl := a.subProfileUrl
  143. if profileUrl == "" {
  144. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  145. }
  146. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  147. if a.subEncrypt {
  148. c.String(200, base64.StdEncoding.EncodeToString([]byte(result)))
  149. } else {
  150. c.String(200, result)
  151. }
  152. }
  153. }
  154. // serveSubPage renders web/dist/subpage.html for the current subscription
  155. // request. The Vite-built SPA reads window.__SUB_PAGE_DATA__ on mount —
  156. // we inject that here, along with window.X_UI_BASE_PATH so the
  157. // page's static asset references resolve correctly when the panel runs
  158. // behind a URL prefix.
  159. func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageData) {
  160. var body []byte
  161. if diskBody, diskErr := os.ReadFile("web/dist/subpage.html"); diskErr == nil {
  162. body = diskBody
  163. } else {
  164. readBody, err := distFS.ReadFile("dist/subpage.html")
  165. if err != nil {
  166. c.String(http.StatusInternalServerError, "missing embedded subpage")
  167. return
  168. }
  169. body = readBody
  170. }
  171. // Vite emits absolute asset URLs (`/assets/...`); when the panel is
  172. // installed under a custom URL prefix, rewrite them so the bundle
  173. // loads from `<basePath>assets/...` where the static handler is
  174. // actually mounted.
  175. if basePath != "/" && basePath != "" {
  176. body = bytes.ReplaceAll(body, []byte(`src="/assets/`), []byte(`src="`+basePath+`assets/`))
  177. body = bytes.ReplaceAll(body, []byte(`href="/assets/`), []byte(`href="`+basePath+`assets/`))
  178. }
  179. // JSON-marshal the view-model so the SPA can read it as a plain
  180. // The panel's "Calendar Type" setting decides whether the SubPage
  181. // renders dates in Gregorian or Jalali — surface it here so the SPA
  182. // can match the rest of the panel without a round-trip.
  183. datepicker, _ := a.settingService.GetDatepicker()
  184. if datepicker == "" {
  185. datepicker = "gregorian"
  186. }
  187. subData := map[string]any{
  188. "sId": page.SId,
  189. "enabled": page.Enabled,
  190. "download": page.Download,
  191. "upload": page.Upload,
  192. "total": page.Total,
  193. "used": page.Used,
  194. "remained": page.Remained,
  195. "expire": page.Expire,
  196. "lastOnline": page.LastOnline,
  197. "downloadByte": page.DownloadByte,
  198. "uploadByte": page.UploadByte,
  199. "totalByte": page.TotalByte,
  200. "subUrl": page.SubUrl,
  201. "subJsonUrl": page.SubJsonUrl,
  202. "subClashUrl": page.SubClashUrl,
  203. "links": page.Result,
  204. "emails": page.Emails,
  205. "datepicker": datepicker,
  206. }
  207. subDataJSON, err := json.Marshal(subData)
  208. if err != nil {
  209. subDataJSON = []byte("{}")
  210. }
  211. // Defense-in-depth string-escape for the basePath embed — admin-
  212. // controlled but cheap to harden.
  213. jsEscape := strings.NewReplacer(
  214. `\`, `\\`,
  215. `"`, `\"`,
  216. "\n", `\n`,
  217. "\r", `\r`,
  218. "<", `<`,
  219. ">", `>`,
  220. "&", `&`,
  221. )
  222. escapedBase := jsEscape.Replace(basePath)
  223. inject := []byte(`<script>window.X_UI_BASE_PATH="` + escapedBase + `";` +
  224. `window.__SUB_PAGE_DATA__=` + string(subDataJSON) + `;</script></head>`)
  225. out := bytes.Replace(body, []byte("</head>"), inject, 1)
  226. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  227. c.Header("Pragma", "no-cache")
  228. c.Header("Expires", "0")
  229. c.Data(http.StatusOK, "text/html; charset=utf-8", out)
  230. }
  231. // subJsons handles HTTP requests for JSON subscription configurations.
  232. func (a *SUBController) subJsons(c *gin.Context) {
  233. subId := c.Param("subid")
  234. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  235. jsonSub, header, err := a.subJsonService.GetJson(subId, host)
  236. if err != nil || len(jsonSub) == 0 {
  237. writeSubError(c, err)
  238. } else {
  239. profileUrl := a.subProfileUrl
  240. if profileUrl == "" {
  241. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  242. }
  243. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  244. c.String(200, jsonSub)
  245. }
  246. }
  247. func (a *SUBController) subClashs(c *gin.Context) {
  248. subId := c.Param("subid")
  249. scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
  250. clashSub, header, err := a.subClashService.GetClash(subId, host)
  251. if err != nil || len(clashSub) == 0 {
  252. writeSubError(c, err)
  253. } else {
  254. profileUrl := a.subProfileUrl
  255. if profileUrl == "" {
  256. profileUrl = fmt.Sprintf("%s://%s%s", scheme, hostWithPort, c.Request.RequestURI)
  257. }
  258. a.ApplyCommonHeaders(c, header, a.updateInterval, a.subTitle, a.subSupportUrl, profileUrl, a.subAnnounce, a.subEnableRouting, a.subRoutingRules)
  259. if a.subTitle != "" {
  260. // Clash clients commonly use Content-Disposition to choose the imported profile name.
  261. c.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename*=UTF-8''%s`, url.PathEscape(a.subTitle)))
  262. }
  263. c.Data(200, "application/yaml; charset=utf-8", []byte(clashSub))
  264. }
  265. }
  266. // ApplyCommonHeaders sets common HTTP headers for subscription responses including user info, update interval, and profile title.
  267. func (a *SUBController) ApplyCommonHeaders(
  268. c *gin.Context,
  269. header,
  270. updateInterval,
  271. profileTitle string,
  272. profileSupportUrl string,
  273. profileUrl string,
  274. profileAnnounce string,
  275. profileEnableRouting bool,
  276. profileRoutingRules string,
  277. ) {
  278. c.Writer.Header().Set("Subscription-Userinfo", header)
  279. c.Writer.Header().Set("Profile-Update-Interval", updateInterval)
  280. //Basics
  281. if profileTitle != "" {
  282. c.Writer.Header().Set("Profile-Title", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileTitle)))
  283. }
  284. if profileSupportUrl != "" {
  285. c.Writer.Header().Set("Support-Url", profileSupportUrl)
  286. }
  287. if profileUrl != "" {
  288. c.Writer.Header().Set("Profile-Web-Page-Url", profileUrl)
  289. }
  290. if profileAnnounce != "" {
  291. c.Writer.Header().Set("Announce", "base64:"+base64.StdEncoding.EncodeToString([]byte(profileAnnounce)))
  292. }
  293. //Advanced (Happ)
  294. c.Writer.Header().Set("Routing-Enable", strconv.FormatBool(profileEnableRouting))
  295. if profileRoutingRules != "" {
  296. c.Writer.Header().Set("Routing", profileRoutingRules)
  297. }
  298. }