xray_setting.go 22 KB

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