subController.go 10.0 KB

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