1
0

xray_setting.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  9. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/service/integration"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/service/outbound"
  12. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // XraySettingController handles Xray configuration and settings operations.
  16. type XraySettingController struct {
  17. XraySettingService service.XraySettingService
  18. SettingService service.SettingService
  19. InboundService service.InboundService
  20. OutboundService outbound.OutboundService
  21. XrayService service.XrayService
  22. WarpService integration.WarpService
  23. NordService integration.NordService
  24. OutboundSubscriptionService service.OutboundSubscriptionService
  25. GeodataService service.GeodataService
  26. }
  27. // NewXraySettingController creates a new XraySettingController and initializes its routes.
  28. func NewXraySettingController(g *gin.RouterGroup) *XraySettingController {
  29. a := &XraySettingController{}
  30. a.initRouter(g)
  31. return a
  32. }
  33. // initRouter sets up the routes for Xray settings management.
  34. func (a *XraySettingController) initRouter(g *gin.RouterGroup) {
  35. g = g.Group("/xray")
  36. g.GET("/getDefaultJsonConfig", a.getDefaultXrayConfig)
  37. g.GET("/getOutboundsTraffic", a.getOutboundsTraffic)
  38. g.GET("/getXrayResult", a.getXrayResult)
  39. g.POST("/", a.getXraySetting)
  40. g.POST("/warp/:action", a.warp)
  41. g.POST("/nord/:action", a.nord)
  42. g.POST("/update", a.updateSetting)
  43. g.POST("/resetOutboundsTraffic", a.resetOutboundsTraffic)
  44. g.POST("/testOutbound", a.testOutbound)
  45. g.POST("/testOutbounds", a.testOutbounds)
  46. g.POST("/balancerStatus", a.balancerStatus)
  47. g.POST("/balancerOverride", a.balancerOverride)
  48. g.POST("/routeTest", a.routeTest)
  49. g.GET("/geodata/files", a.geodataFiles)
  50. g.GET("/geodata/categories", a.geodataCategories)
  51. g.GET("/geodata/entries", a.geodataEntries)
  52. g.POST("/geodata/validate", a.geodataValidate)
  53. // Outbound subscription (remote outbound lists)
  54. g.GET("/outbound-subs", a.listOutboundSubs)
  55. g.POST("/outbound-subs", a.createOutboundSub)
  56. g.POST("/outbound-subs/:id/refresh", a.refreshOutboundSub)
  57. g.POST("/outbound-subs/:id/move", a.moveOutboundSub)
  58. g.POST("/outbound-subs/:id", a.updateOutboundSub)
  59. g.DELETE("/outbound-subs/:id", a.deleteOutboundSub)
  60. g.POST("/outbound-subs/:id/del", a.deleteOutboundSub) // POST alias for clients that can't send DELETE
  61. g.POST("/outbound-subs/parse", a.parseOutboundSubURL) // preview without saving
  62. }
  63. // getXraySetting retrieves the Xray configuration template, inbound tags, and outbound test URL.
  64. func (a *XraySettingController) getXraySetting(c *gin.Context) {
  65. xraySetting, err := a.SettingService.GetXrayConfigTemplate()
  66. if err != nil {
  67. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  68. return
  69. }
  70. // Older versions of this handler embedded the raw DB value as
  71. // `xraySetting` in the response without checking if the value
  72. // already had that wrapper shape. When the frontend saved it
  73. // back through the textarea verbatim, the wrapper got persisted
  74. // and every subsequent save nested another layer, which is what
  75. // eventually produced the blank Xray Settings page in #4059.
  76. // Strip any such wrapper here, and heal the DB if we found one so
  77. // the next read is O(1) instead of climbing the same pile again.
  78. if unwrapped := service.UnwrapXrayTemplateConfig(xraySetting); unwrapped != xraySetting {
  79. if saveErr := a.XraySettingService.SaveXraySetting(unwrapped); saveErr == nil {
  80. xraySetting = unwrapped
  81. } else {
  82. // Don't fail the read — just serve the unwrapped value
  83. // and leave the DB healing for a later save.
  84. xraySetting = unwrapped
  85. }
  86. }
  87. inboundTags, err := a.InboundService.GetInboundTags()
  88. if err != nil {
  89. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  90. return
  91. }
  92. clientReverseTags, err := a.InboundService.GetClientReverseTags()
  93. if err != nil {
  94. clientReverseTags = "[]"
  95. }
  96. outboundTestUrl, _ := a.SettingService.GetXrayOutboundTestUrl()
  97. if outboundTestUrl == "" {
  98. outboundTestUrl = "https://www.google.com/generate_204"
  99. }
  100. xrayResponse := map[string]any{
  101. "xraySetting": json.RawMessage(xraySetting),
  102. "inboundTags": json.RawMessage(inboundTags),
  103. "clientReverseTags": json.RawMessage(clientReverseTags),
  104. "outboundTestUrl": outboundTestUrl,
  105. }
  106. // Surface subscription outbounds (and their tags) so the frontend can:
  107. // - show them as read-only items in the Outbounds tab
  108. // - let users pick them in balancers and routing rules
  109. // These are not part of the editable template; they are injected at runtime.
  110. if subObs, err := a.OutboundSubscriptionService.AllActiveOutbounds(); err == nil && len(subObs) > 0 {
  111. xrayResponse["subscriptionOutbounds"] = subObs
  112. }
  113. if subTags, err := a.OutboundSubscriptionService.AllActiveOutboundTags(); err == nil && len(subTags) > 0 {
  114. xrayResponse["subscriptionOutboundTags"] = subTags
  115. }
  116. result, err := json.Marshal(xrayResponse)
  117. if err != nil {
  118. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  119. return
  120. }
  121. jsonObj(c, string(result), nil)
  122. }
  123. // updateSetting updates the Xray configuration settings and applies them to
  124. // the running core right away — through the gRPC API when only inbounds,
  125. // outbounds or routing rules changed, with a process restart otherwise.
  126. func (a *XraySettingController) updateSetting(c *gin.Context) {
  127. xraySetting := c.PostForm("xraySetting")
  128. if err := a.XraySettingService.SaveXraySetting(xraySetting); err != nil {
  129. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  130. return
  131. }
  132. outboundTestUrl := c.PostForm("outboundTestUrl")
  133. if outboundTestUrl == "" {
  134. outboundTestUrl = "https://www.google.com/generate_204"
  135. }
  136. if err := a.SettingService.SetXrayOutboundTestUrl(outboundTestUrl); err != nil {
  137. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  138. return
  139. }
  140. // Only reconcile a running core; a manually stopped xray stays stopped.
  141. if a.XrayService.IsXrayRunning() {
  142. if err := a.XrayService.RestartXray(false); err != nil {
  143. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
  144. return
  145. }
  146. }
  147. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), nil)
  148. }
  149. // getDefaultXrayConfig retrieves the default Xray configuration.
  150. func (a *XraySettingController) getDefaultXrayConfig(c *gin.Context) {
  151. defaultJsonConfig, err := a.SettingService.GetDefaultXrayConfig()
  152. if err != nil {
  153. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getSettings"), err)
  154. return
  155. }
  156. jsonObj(c, defaultJsonConfig, nil)
  157. }
  158. // getXrayResult retrieves the current Xray service result.
  159. func (a *XraySettingController) getXrayResult(c *gin.Context) {
  160. jsonObj(c, a.XrayService.GetXrayResult(), nil)
  161. }
  162. // warp handles Warp-related operations based on the action parameter.
  163. func (a *XraySettingController) warp(c *gin.Context) {
  164. action := c.Param("action")
  165. var resp string
  166. var err error
  167. switch action {
  168. case "data":
  169. resp, err = a.WarpService.GetWarpData()
  170. case "del":
  171. err = a.WarpService.DelWarpData()
  172. case "config":
  173. resp, err = a.WarpService.GetWarpConfig()
  174. case "reg":
  175. skey := c.PostForm("privateKey")
  176. pkey := c.PostForm("publicKey")
  177. resp, err = a.WarpService.RegWarp(skey, pkey)
  178. case "changeIp":
  179. resp, err = a.WarpService.ChangeWarpIP()
  180. if err == nil {
  181. a.XrayService.SetToNeedRestart()
  182. // Restart the auto-update clock so a scheduled rotation
  183. // doesn't fire right after this manual one.
  184. err = a.SettingService.SetWarpLastUpdate(time.Now().Unix())
  185. }
  186. case "license":
  187. license := c.PostForm("license")
  188. resp, err = a.WarpService.SetWarpLicense(license)
  189. case "interval":
  190. interval, convErr := strconv.Atoi(c.PostForm("interval"))
  191. if convErr != nil || interval < 0 {
  192. err = common.NewError("invalid warp update interval")
  193. } else if err = a.SettingService.SetWarpUpdateInterval(interval); err == nil && interval > 0 {
  194. // Count the interval from now rather than from epoch 0,
  195. // otherwise the job would rotate on its next tick.
  196. err = a.SettingService.SetWarpLastUpdate(time.Now().Unix())
  197. }
  198. }
  199. jsonObj(c, resp, err)
  200. }
  201. // nord handles NordVPN-related operations based on the action parameter.
  202. func (a *XraySettingController) nord(c *gin.Context) {
  203. action := c.Param("action")
  204. var resp string
  205. var err error
  206. switch action {
  207. case "countries":
  208. resp, err = a.NordService.GetCountries()
  209. case "servers":
  210. countryId := c.PostForm("countryId")
  211. resp, err = a.NordService.GetServers(countryId)
  212. case "reg":
  213. token := c.PostForm("token")
  214. resp, err = a.NordService.GetCredentials(token)
  215. case "setKey":
  216. key := c.PostForm("key")
  217. resp, err = a.NordService.SetKey(key)
  218. case "data":
  219. resp, err = a.NordService.GetNordData()
  220. case "del":
  221. err = a.NordService.DelNordData()
  222. }
  223. jsonObj(c, resp, err)
  224. }
  225. // getOutboundsTraffic retrieves the traffic statistics for outbounds.
  226. func (a *XraySettingController) getOutboundsTraffic(c *gin.Context) {
  227. outboundsTraffic, err := a.OutboundService.GetOutboundsTraffic()
  228. if err != nil {
  229. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getOutboundTrafficError"), err)
  230. return
  231. }
  232. jsonObj(c, outboundsTraffic, nil)
  233. }
  234. // resetOutboundsTraffic resets the traffic statistics for the specified outbound tag.
  235. func (a *XraySettingController) resetOutboundsTraffic(c *gin.Context) {
  236. tag := c.PostForm("tag")
  237. err := a.OutboundService.ResetOutboundTraffic(tag)
  238. if err != nil {
  239. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.resetOutboundTrafficError"), err)
  240. return
  241. }
  242. jsonObj(c, "", nil)
  243. }
  244. // testOutbound tests an outbound configuration and returns the delay/response time.
  245. // Optional form "allOutbounds": JSON array of all outbounds; used to resolve sockopt.dialerProxy dependencies.
  246. // Optional form "mode": "tcp" for a fast dial-only probe, "real" for the cold
  247. // full-request delay, anything else (default) for a full HTTP probe through a temp xray instance.
  248. func (a *XraySettingController) testOutbound(c *gin.Context) {
  249. outboundJSON := c.PostForm("outbound")
  250. allOutboundsJSON := c.PostForm("allOutbounds")
  251. mode := c.PostForm("mode")
  252. if outboundJSON == "" {
  253. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("outbound parameter is required"))
  254. return
  255. }
  256. // Load the test URL from server settings to prevent SSRF via user-controlled URLs
  257. testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
  258. testURL, err := service.SanitizePublicHTTPURL(testURL, false)
  259. if err != nil {
  260. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  261. return
  262. }
  263. result, err := a.OutboundService.TestOutbound(outboundJSON, testURL, allOutboundsJSON, mode)
  264. if err != nil {
  265. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  266. return
  267. }
  268. jsonObj(c, result, nil)
  269. }
  270. // testOutbounds tests a batch of outbound configurations through one shared
  271. // temp xray instance and returns an array of results in input order.
  272. // Form "outbounds": JSON array of outbound configs (required).
  273. // Optional form "allOutbounds": JSON array of all outbounds; used to resolve sockopt.dialerProxy dependencies.
  274. // Optional form "mode": "tcp" for fast dial-only probes, "real" for the cold
  275. // full-request delay, anything else (default) for real HTTP requests routed through each outbound.
  276. func (a *XraySettingController) testOutbounds(c *gin.Context) {
  277. outboundsJSON := c.PostForm("outbounds")
  278. allOutboundsJSON := c.PostForm("allOutbounds")
  279. mode := c.PostForm("mode")
  280. if outboundsJSON == "" {
  281. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("outbounds parameter is required"))
  282. return
  283. }
  284. // Load the test URL from server settings to prevent SSRF via user-controlled URLs
  285. testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
  286. testURL, err := service.SanitizePublicHTTPURL(testURL, false)
  287. if err != nil {
  288. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  289. return
  290. }
  291. results, err := a.OutboundService.TestOutbounds(outboundsJSON, testURL, allOutboundsJSON, mode)
  292. if err != nil {
  293. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  294. return
  295. }
  296. jsonObj(c, results, nil)
  297. }
  298. // balancerStatus reports the live state (override + strategy picks) of the
  299. // balancer tags given as a comma-separated "tags" form field.
  300. func (a *XraySettingController) balancerStatus(c *gin.Context) {
  301. raw := c.PostForm("tags")
  302. var tags []string
  303. for tag := range strings.SplitSeq(raw, ",") {
  304. if tag = strings.TrimSpace(tag); tag != "" {
  305. tags = append(tags, tag)
  306. }
  307. }
  308. statuses, err := a.XrayService.GetBalancersStatus(tags)
  309. if err != nil {
  310. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  311. return
  312. }
  313. byTag := make(map[string]service.BalancerStatus, len(statuses))
  314. for _, status := range statuses {
  315. byTag[status.Tag] = status
  316. }
  317. jsonObj(c, byTag, nil)
  318. }
  319. // balancerOverride forces a balancer to a specific outbound tag; an empty
  320. // "target" clears the override.
  321. func (a *XraySettingController) balancerOverride(c *gin.Context) {
  322. tag := c.PostForm("tag")
  323. if tag == "" {
  324. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("tag is required"))
  325. return
  326. }
  327. target := c.PostForm("target")
  328. if err := a.XrayService.OverrideBalancer(tag, target); err != nil {
  329. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  330. return
  331. }
  332. jsonObj(c, "", nil)
  333. }
  334. // routeTest asks the running core which outbound it would route a synthetic
  335. // connection to.
  336. func (a *XraySettingController) routeTest(c *gin.Context) {
  337. port := 0
  338. if portStr := c.PostForm("port"); portStr != "" {
  339. parsed, err := strconv.Atoi(portStr)
  340. if err != nil || parsed < 0 || parsed > 65535 {
  341. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("invalid port"))
  342. return
  343. }
  344. port = parsed
  345. }
  346. req := xray.RouteTestRequest{
  347. InboundTag: c.PostForm("inboundTag"),
  348. Domain: c.PostForm("domain"),
  349. IP: c.PostForm("ip"),
  350. Port: port,
  351. Network: c.PostForm("network"),
  352. Protocol: c.PostForm("protocol"),
  353. Email: c.PostForm("email"),
  354. }
  355. if req.Domain == "" && req.IP == "" {
  356. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("domain or ip is required"))
  357. return
  358. }
  359. result, err := a.XrayService.TestRoute(req)
  360. if err != nil {
  361. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  362. return
  363. }
  364. jsonObj(c, result, nil)
  365. }
  366. // maxGeodataTokens bounds one validation request; a routing rule listing more
  367. // categories than this is not something the panel needs to answer for.
  368. const maxGeodataTokens = 500
  369. // geodataFiles lists the geo databases Xray resolves geosite:/geoip: tokens
  370. // against, including ones that failed to parse.
  371. func (a *XraySettingController) geodataFiles(c *gin.Context) {
  372. files, err := a.GeodataService.Files()
  373. if err != nil {
  374. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  375. return
  376. }
  377. jsonObj(c, files, nil)
  378. }
  379. // geodataCategories returns one page of a database's categories.
  380. func (a *XraySettingController) geodataCategories(c *gin.Context) {
  381. offset, limit := geodataPaging(c)
  382. page, err := a.GeodataService.Categories(c.Query("file"), c.Query("q"), offset, limit)
  383. if err != nil {
  384. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  385. return
  386. }
  387. jsonObj(c, page, nil)
  388. }
  389. // geodataEntries returns one page of the domains or CIDRs inside a category.
  390. func (a *XraySettingController) geodataEntries(c *gin.Context) {
  391. code := c.Query("code")
  392. if code == "" {
  393. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("code is required"))
  394. return
  395. }
  396. offset, limit := geodataPaging(c)
  397. page, err := a.GeodataService.Entries(c.Query("file"), code, c.Query("q"), offset, limit)
  398. if err != nil {
  399. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  400. return
  401. }
  402. jsonObj(c, page, nil)
  403. }
  404. // geodataValidate reports which routing tokens do not resolve against the
  405. // databases on disk.
  406. func (a *XraySettingController) geodataValidate(c *gin.Context) {
  407. // Split with a bound rather than splitting first: a 10 MB body of commas
  408. // would otherwise allocate millions of strings before the limit is checked.
  409. tokens := strings.SplitN(c.PostForm("tokens"), ",", maxGeodataTokens+1)
  410. if len(tokens) > maxGeodataTokens {
  411. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewErrorf("too many tokens: over %d", maxGeodataTokens))
  412. return
  413. }
  414. jsonObj(c, a.GeodataService.Validate(c.PostForm("kind") == "ip", tokens), nil)
  415. }
  416. func geodataPaging(c *gin.Context) (int, int) {
  417. offset, err := strconv.Atoi(c.Query("offset"))
  418. if err != nil {
  419. offset = 0
  420. }
  421. limit, err := strconv.Atoi(c.Query("limit"))
  422. if err != nil {
  423. limit = 0
  424. }
  425. return offset, limit
  426. }
  427. // --- Outbound Subscription handlers ---
  428. func (a *XraySettingController) listOutboundSubs(c *gin.Context) {
  429. list, err := a.OutboundSubscriptionService.List()
  430. if err != nil {
  431. jsonMsg(c, "Failed to list outbound subscriptions", err)
  432. return
  433. }
  434. jsonObj(c, list, nil)
  435. }
  436. func (a *XraySettingController) createOutboundSub(c *gin.Context) {
  437. remark := c.PostForm("remark")
  438. rawURL := c.PostForm("url")
  439. prefix := c.PostForm("tagPrefix")
  440. enabled := c.PostForm("enabled") != "false"
  441. allowPrivate := c.PostForm("allowPrivate") == "true"
  442. allowInsecure := c.PostForm("allowInsecure") == "true"
  443. prepend := c.PostForm("prepend") == "true"
  444. intervalStr := c.PostForm("updateInterval")
  445. interval := 600
  446. if intervalStr != "" {
  447. if v, err := parseIntSafe(intervalStr); err == nil && v > 0 {
  448. interval = v
  449. }
  450. }
  451. sub, err := a.OutboundSubscriptionService.Create(remark, rawURL, prefix, enabled, interval, allowPrivate, prepend, allowInsecure)
  452. if err != nil {
  453. jsonMsg(c, "Failed to create outbound subscription", err)
  454. return
  455. }
  456. jsonObj(c, sub, nil)
  457. }
  458. func (a *XraySettingController) updateOutboundSub(c *gin.Context) {
  459. id := c.Param("id")
  460. var subID int
  461. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  462. jsonMsg(c, "Invalid id", err)
  463. return
  464. }
  465. remark := c.PostForm("remark")
  466. rawURL := c.PostForm("url")
  467. prefix := c.PostForm("tagPrefix")
  468. enabled := c.PostForm("enabled") != "false"
  469. allowPrivate := c.PostForm("allowPrivate") == "true"
  470. allowInsecure := c.PostForm("allowInsecure") == "true"
  471. prepend := c.PostForm("prepend") == "true"
  472. intervalStr := c.PostForm("updateInterval")
  473. interval := 600
  474. if intervalStr != "" {
  475. if v, err := parseIntSafe(intervalStr); err == nil && v > 0 {
  476. interval = v
  477. }
  478. }
  479. if err := a.OutboundSubscriptionService.Update(subID, remark, rawURL, prefix, enabled, interval, allowPrivate, prepend, allowInsecure); err != nil {
  480. jsonMsg(c, "Failed to update outbound subscription", err)
  481. return
  482. }
  483. jsonObj(c, "", nil)
  484. }
  485. func (a *XraySettingController) deleteOutboundSub(c *gin.Context) {
  486. id := c.Param("id")
  487. var subID int
  488. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  489. jsonMsg(c, "Invalid id", err)
  490. return
  491. }
  492. if err := a.OutboundSubscriptionService.Delete(subID); err != nil {
  493. jsonMsg(c, "Failed to delete outbound subscription", err)
  494. return
  495. }
  496. // Signal that xray should drop this subscription's outbounds on next reload.
  497. a.XrayService.SetToNeedRestart()
  498. jsonObj(c, "", nil)
  499. }
  500. func (a *XraySettingController) refreshOutboundSub(c *gin.Context) {
  501. id := c.Param("id")
  502. var subID int
  503. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  504. jsonMsg(c, "Invalid id", err)
  505. return
  506. }
  507. obs, err := a.OutboundSubscriptionService.Refresh(subID)
  508. if err != nil {
  509. jsonMsg(c, "Refresh failed", err)
  510. return
  511. }
  512. // Signal that xray should pick up the new outbounds on next restart/reload
  513. a.XrayService.SetToNeedRestart()
  514. jsonObj(c, obs, nil)
  515. }
  516. func (a *XraySettingController) moveOutboundSub(c *gin.Context) {
  517. id := c.Param("id")
  518. var subID int
  519. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  520. jsonMsg(c, "Invalid id", err)
  521. return
  522. }
  523. up := c.PostForm("dir") == "up"
  524. if err := a.OutboundSubscriptionService.Move(subID, up); err != nil {
  525. jsonMsg(c, "Failed to reorder outbound subscription", err)
  526. return
  527. }
  528. // Order affects the merged outbounds, so xray needs a reload.
  529. a.XrayService.SetToNeedRestart()
  530. jsonObj(c, "", nil)
  531. }
  532. // parseOutboundSubURL is a preview endpoint: it fetches + parses the provided
  533. // URL but does not persist anything. Useful for the "add subscription" flow
  534. // so the user can see the resulting outbounds (and assigned tags) before saving.
  535. func (a *XraySettingController) parseOutboundSubURL(c *gin.Context) {
  536. rawURL := c.PostForm("url")
  537. if rawURL == "" {
  538. jsonMsg(c, "url is required", common.NewError("missing url"))
  539. return
  540. }
  541. allowPrivate := c.PostForm("allowPrivate") == "true"
  542. allowInsecure := c.PostForm("allowInsecure") == "true"
  543. // Use a throw-away service instance; it only needs the settingService for proxy.
  544. svc := service.OutboundSubscriptionService{}
  545. // We don't have a direct "fetch once" that returns without storing, so we
  546. // temporarily create a disabled row, refresh it, then delete. Cleaner would
  547. // be to expose a pure ParseURL on the service, but this keeps the surface small.
  548. tmp, err := svc.Create("preview", rawURL, "", false, 600, allowPrivate, false, allowInsecure)
  549. if err != nil {
  550. jsonMsg(c, "Failed to preview subscription", err)
  551. return
  552. }
  553. obs, err := svc.Refresh(tmp.Id)
  554. // best-effort cleanup
  555. _ = svc.Delete(tmp.Id)
  556. if err != nil {
  557. jsonMsg(c, "Failed to fetch/parse subscription", err)
  558. return
  559. }
  560. jsonObj(c, obs, nil)
  561. }
  562. func parseIntSafe(s string) (int, error) {
  563. var v int
  564. _, err := fmt.Sscanf(s, "%d", &v)
  565. return v, err
  566. }