1
0

xray_setting.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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 "changeIp":
  184. resp, err = a.WarpService.ChangeWarpIP()
  185. if err == nil {
  186. a.XrayService.SetToNeedRestart()
  187. // Restart the auto-update clock so a scheduled rotation
  188. // doesn't fire right after this manual one.
  189. err = a.SettingService.SetWarpLastUpdate(time.Now().Unix())
  190. }
  191. case "license":
  192. license := c.PostForm("license")
  193. resp, err = a.WarpService.SetWarpLicense(license)
  194. case "interval":
  195. interval, convErr := strconv.Atoi(c.PostForm("interval"))
  196. if convErr != nil || interval < 0 {
  197. err = common.NewError("invalid warp update interval")
  198. } else if err = a.SettingService.SetWarpUpdateInterval(interval); err == nil && interval > 0 {
  199. // Count the interval from now rather than from epoch 0,
  200. // otherwise the job would rotate on its next tick.
  201. err = a.SettingService.SetWarpLastUpdate(time.Now().Unix())
  202. }
  203. }
  204. jsonObj(c, resp, err)
  205. }
  206. // nord handles NordVPN-related operations based on the action parameter.
  207. func (a *XraySettingController) nord(c *gin.Context) {
  208. action := c.Param("action")
  209. var resp string
  210. var err error
  211. switch action {
  212. case "countries":
  213. resp, err = a.NordService.GetCountries()
  214. case "servers":
  215. countryId := c.PostForm("countryId")
  216. resp, err = a.NordService.GetServers(countryId)
  217. case "reg":
  218. token := c.PostForm("token")
  219. resp, err = a.NordService.GetCredentials(token)
  220. case "setKey":
  221. key := c.PostForm("key")
  222. resp, err = a.NordService.SetKey(key)
  223. case "data":
  224. resp, err = a.NordService.GetNordData()
  225. case "del":
  226. err = a.NordService.DelNordData()
  227. }
  228. jsonObj(c, resp, err)
  229. }
  230. func (a *XraySettingController) pia(c *gin.Context) {
  231. action := c.Param("action")
  232. var resp any
  233. var err error
  234. switch action {
  235. case "countries":
  236. resp, err = a.PiaService.GetCountries()
  237. case "servers":
  238. resp, err = a.PiaService.GetServers(c.PostForm("countryCode"))
  239. case "reg":
  240. resp, err = a.PiaService.Login(c.PostForm("username"), c.PostForm("password"))
  241. case "data":
  242. resp, err = a.PiaService.GetPiaData()
  243. case "del":
  244. err = a.PiaService.DelPiaData()
  245. case "addKey":
  246. resp, err = a.PiaService.AddKey(c.PostForm("hostname"))
  247. default:
  248. jsonMsg(c, "unknown action", common.NewError("unknown action"))
  249. return
  250. }
  251. if err != nil {
  252. var pe *piaprotocol.Error
  253. if errors.As(err, &pe) && pe != nil {
  254. jsonObj(c, nil, common.NewError(pe.Message))
  255. return
  256. }
  257. jsonObj(c, nil, err)
  258. return
  259. }
  260. jsonObj(c, resp, nil)
  261. }
  262. // getOutboundsTraffic retrieves the traffic statistics for outbounds.
  263. func (a *XraySettingController) getOutboundsTraffic(c *gin.Context) {
  264. outboundsTraffic, err := a.OutboundService.GetOutboundsTraffic()
  265. if err != nil {
  266. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.getOutboundTrafficError"), err)
  267. return
  268. }
  269. jsonObj(c, outboundsTraffic, nil)
  270. }
  271. // resetOutboundsTraffic resets the traffic statistics for the specified outbound tag.
  272. func (a *XraySettingController) resetOutboundsTraffic(c *gin.Context) {
  273. tag := c.PostForm("tag")
  274. err := a.OutboundService.ResetOutboundTraffic(tag)
  275. if err != nil {
  276. jsonMsg(c, I18nWeb(c, "pages.settings.toasts.resetOutboundTrafficError"), err)
  277. return
  278. }
  279. jsonObj(c, "", nil)
  280. }
  281. // testOutbound tests an outbound configuration and returns the delay/response time.
  282. // Optional form "allOutbounds": JSON array of all outbounds; used to resolve sockopt.dialerProxy dependencies.
  283. // Optional form "mode": "tcp" for a fast dial-only probe, "real" for the cold
  284. // full-request delay, anything else (default) for a full HTTP probe through a temp xray instance.
  285. func (a *XraySettingController) testOutbound(c *gin.Context) {
  286. outboundJSON := c.PostForm("outbound")
  287. allOutboundsJSON := c.PostForm("allOutbounds")
  288. mode := c.PostForm("mode")
  289. if outboundJSON == "" {
  290. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("outbound parameter is required"))
  291. return
  292. }
  293. // Load the test URL from server settings to prevent SSRF via user-controlled URLs
  294. testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
  295. testURL, err := service.SanitizePublicHTTPURL(testURL, false)
  296. if err != nil {
  297. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  298. return
  299. }
  300. result, err := a.OutboundService.TestOutbound(outboundJSON, testURL, allOutboundsJSON, mode)
  301. if err != nil {
  302. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  303. return
  304. }
  305. jsonObj(c, result, nil)
  306. }
  307. // testOutbounds tests a batch of outbound configurations through one shared
  308. // temp xray instance and returns an array of results in input order.
  309. // Form "outbounds": JSON array of outbound configs (required).
  310. // Optional form "allOutbounds": JSON array of all outbounds; used to resolve sockopt.dialerProxy dependencies.
  311. // Optional form "mode": "tcp" for fast dial-only probes, "real" for the cold
  312. // full-request delay, anything else (default) for real HTTP requests routed through each outbound.
  313. func (a *XraySettingController) testOutbounds(c *gin.Context) {
  314. outboundsJSON := c.PostForm("outbounds")
  315. allOutboundsJSON := c.PostForm("allOutbounds")
  316. mode := c.PostForm("mode")
  317. if outboundsJSON == "" {
  318. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("outbounds parameter is required"))
  319. return
  320. }
  321. // Load the test URL from server settings to prevent SSRF via user-controlled URLs
  322. testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
  323. testURL, err := service.SanitizePublicHTTPURL(testURL, false)
  324. if err != nil {
  325. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  326. return
  327. }
  328. results, err := a.OutboundService.TestOutbounds(outboundsJSON, testURL, allOutboundsJSON, mode)
  329. if err != nil {
  330. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  331. return
  332. }
  333. jsonObj(c, results, nil)
  334. }
  335. // balancerStatus reports the live state (override + strategy picks) of the
  336. // balancer tags given as a comma-separated "tags" form field.
  337. func (a *XraySettingController) balancerStatus(c *gin.Context) {
  338. raw := c.PostForm("tags")
  339. var tags []string
  340. for tag := range strings.SplitSeq(raw, ",") {
  341. if tag = strings.TrimSpace(tag); tag != "" {
  342. tags = append(tags, tag)
  343. }
  344. }
  345. statuses, err := a.XrayService.GetBalancersStatus(tags)
  346. if err != nil {
  347. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  348. return
  349. }
  350. byTag := make(map[string]service.BalancerStatus, len(statuses))
  351. for _, status := range statuses {
  352. byTag[status.Tag] = status
  353. }
  354. jsonObj(c, byTag, nil)
  355. }
  356. // balancerOverride forces a balancer to a specific outbound tag; an empty
  357. // "target" clears the override.
  358. func (a *XraySettingController) balancerOverride(c *gin.Context) {
  359. tag := c.PostForm("tag")
  360. if tag == "" {
  361. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("tag is required"))
  362. return
  363. }
  364. target := c.PostForm("target")
  365. if err := a.XrayService.OverrideBalancer(tag, target); err != nil {
  366. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  367. return
  368. }
  369. jsonObj(c, "", nil)
  370. }
  371. // routeTest asks the running core which outbound it would route a synthetic
  372. // connection to.
  373. func (a *XraySettingController) routeTest(c *gin.Context) {
  374. port := 0
  375. if portStr := c.PostForm("port"); portStr != "" {
  376. parsed, err := strconv.Atoi(portStr)
  377. if err != nil || parsed < 0 || parsed > 65535 {
  378. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("invalid port"))
  379. return
  380. }
  381. port = parsed
  382. }
  383. req := xray.RouteTestRequest{
  384. InboundTag: c.PostForm("inboundTag"),
  385. Domain: c.PostForm("domain"),
  386. IP: c.PostForm("ip"),
  387. Port: port,
  388. Network: c.PostForm("network"),
  389. Protocol: c.PostForm("protocol"),
  390. Email: c.PostForm("email"),
  391. }
  392. if req.Domain == "" && req.IP == "" {
  393. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("domain or ip is required"))
  394. return
  395. }
  396. result, err := a.XrayService.TestRoute(req)
  397. if err != nil {
  398. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  399. return
  400. }
  401. jsonObj(c, result, nil)
  402. }
  403. // maxGeodataTokens bounds one validation request; a routing rule listing more
  404. // categories than this is not something the panel needs to answer for.
  405. const maxGeodataTokens = 500
  406. // geodataFiles lists the geo databases Xray resolves geosite:/geoip: tokens
  407. // against, including ones that failed to parse.
  408. func (a *XraySettingController) geodataFiles(c *gin.Context) {
  409. files, err := a.GeodataService.Files()
  410. if err != nil {
  411. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  412. return
  413. }
  414. jsonObj(c, files, nil)
  415. }
  416. // geodataCategories returns one page of a database's categories.
  417. func (a *XraySettingController) geodataCategories(c *gin.Context) {
  418. offset, limit := geodataPaging(c)
  419. page, err := a.GeodataService.Categories(c.Query("file"), c.Query("q"), offset, limit)
  420. if err != nil {
  421. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  422. return
  423. }
  424. jsonObj(c, page, nil)
  425. }
  426. // geodataEntries returns one page of the domains or CIDRs inside a category.
  427. func (a *XraySettingController) geodataEntries(c *gin.Context) {
  428. code := c.Query("code")
  429. if code == "" {
  430. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("code is required"))
  431. return
  432. }
  433. offset, limit := geodataPaging(c)
  434. page, err := a.GeodataService.Entries(c.Query("file"), code, c.Query("q"), offset, limit)
  435. if err != nil {
  436. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
  437. return
  438. }
  439. jsonObj(c, page, nil)
  440. }
  441. // geodataValidate reports which routing tokens do not resolve against the
  442. // databases on disk.
  443. func (a *XraySettingController) geodataValidate(c *gin.Context) {
  444. // Split with a bound rather than splitting first: a 10 MB body of commas
  445. // would otherwise allocate millions of strings before the limit is checked.
  446. tokens := strings.SplitN(c.PostForm("tokens"), ",", maxGeodataTokens+1)
  447. if len(tokens) > maxGeodataTokens {
  448. jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewErrorf("too many tokens: over %d", maxGeodataTokens))
  449. return
  450. }
  451. jsonObj(c, a.GeodataService.Validate(c.PostForm("kind") == "ip", tokens), nil)
  452. }
  453. func geodataPaging(c *gin.Context) (int, int) {
  454. offset, err := strconv.Atoi(c.Query("offset"))
  455. if err != nil {
  456. offset = 0
  457. }
  458. limit, err := strconv.Atoi(c.Query("limit"))
  459. if err != nil {
  460. limit = 0
  461. }
  462. return offset, limit
  463. }
  464. // --- Outbound Subscription handlers ---
  465. func (a *XraySettingController) listOutboundSubs(c *gin.Context) {
  466. list, err := a.OutboundSubscriptionService.List()
  467. if err != nil {
  468. jsonMsg(c, "Failed to list outbound subscriptions", err)
  469. return
  470. }
  471. jsonObj(c, list, nil)
  472. }
  473. func (a *XraySettingController) createOutboundSub(c *gin.Context) {
  474. remark := c.PostForm("remark")
  475. rawURL := c.PostForm("url")
  476. prefix := c.PostForm("tagPrefix")
  477. userAgent := c.PostForm("userAgent")
  478. enabled := c.PostForm("enabled") != "false"
  479. allowPrivate := c.PostForm("allowPrivate") == "true"
  480. allowInsecure := c.PostForm("allowInsecure") == "true"
  481. prepend := c.PostForm("prepend") == "true"
  482. intervalStr := c.PostForm("updateInterval")
  483. interval := 600
  484. if intervalStr != "" {
  485. if v, err := parseIntSafe(intervalStr); err == nil && v > 0 {
  486. interval = v
  487. }
  488. }
  489. sub, err := a.OutboundSubscriptionService.Create(remark, rawURL, prefix, userAgent, enabled, interval, allowPrivate, prepend, allowInsecure)
  490. if err != nil {
  491. jsonMsg(c, "Failed to create outbound subscription", err)
  492. return
  493. }
  494. jsonObj(c, sub, nil)
  495. }
  496. func (a *XraySettingController) updateOutboundSub(c *gin.Context) {
  497. id := c.Param("id")
  498. var subID int
  499. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  500. jsonMsg(c, "Invalid id", err)
  501. return
  502. }
  503. remark := c.PostForm("remark")
  504. rawURL := c.PostForm("url")
  505. prefix := c.PostForm("tagPrefix")
  506. userAgent := c.PostForm("userAgent")
  507. enabled := c.PostForm("enabled") != "false"
  508. allowPrivate := c.PostForm("allowPrivate") == "true"
  509. allowInsecure := c.PostForm("allowInsecure") == "true"
  510. prepend := c.PostForm("prepend") == "true"
  511. intervalStr := c.PostForm("updateInterval")
  512. interval := 600
  513. if intervalStr != "" {
  514. if v, err := parseIntSafe(intervalStr); err == nil && v > 0 {
  515. interval = v
  516. }
  517. }
  518. if err := a.OutboundSubscriptionService.Update(subID, remark, rawURL, prefix, userAgent, enabled, interval, allowPrivate, prepend, allowInsecure); err != nil {
  519. jsonMsg(c, "Failed to update outbound subscription", err)
  520. return
  521. }
  522. jsonObj(c, "", nil)
  523. }
  524. func (a *XraySettingController) deleteOutboundSub(c *gin.Context) {
  525. id := c.Param("id")
  526. var subID int
  527. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  528. jsonMsg(c, "Invalid id", err)
  529. return
  530. }
  531. if err := a.OutboundSubscriptionService.Delete(subID); err != nil {
  532. jsonMsg(c, "Failed to delete outbound subscription", err)
  533. return
  534. }
  535. // Signal that xray should drop this subscription's outbounds on next reload.
  536. a.XrayService.SetToNeedRestart()
  537. jsonObj(c, "", nil)
  538. }
  539. func (a *XraySettingController) refreshOutboundSub(c *gin.Context) {
  540. id := c.Param("id")
  541. var subID int
  542. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  543. jsonMsg(c, "Invalid id", err)
  544. return
  545. }
  546. obs, err := a.OutboundSubscriptionService.Refresh(subID)
  547. if err != nil {
  548. jsonMsg(c, "Refresh failed", err)
  549. return
  550. }
  551. // Signal that xray should pick up the new outbounds on next restart/reload
  552. a.XrayService.SetToNeedRestart()
  553. jsonObj(c, obs, nil)
  554. }
  555. func (a *XraySettingController) moveOutboundSub(c *gin.Context) {
  556. id := c.Param("id")
  557. var subID int
  558. if _, err := fmt.Sscanf(id, "%d", &subID); err != nil {
  559. jsonMsg(c, "Invalid id", err)
  560. return
  561. }
  562. up := c.PostForm("dir") == "up"
  563. if err := a.OutboundSubscriptionService.Move(subID, up); err != nil {
  564. jsonMsg(c, "Failed to reorder outbound subscription", err)
  565. return
  566. }
  567. // Order affects the merged outbounds, so xray needs a reload.
  568. a.XrayService.SetToNeedRestart()
  569. jsonObj(c, "", nil)
  570. }
  571. // parseOutboundSubURL is a preview endpoint: it fetches + parses the provided
  572. // URL but does not persist anything. Useful for the "add subscription" flow
  573. // so the user can see the resulting outbounds (and assigned tags) before saving.
  574. func (a *XraySettingController) parseOutboundSubURL(c *gin.Context) {
  575. rawURL := c.PostForm("url")
  576. if rawURL == "" {
  577. jsonMsg(c, "url is required", common.NewError("missing url"))
  578. return
  579. }
  580. allowPrivate := c.PostForm("allowPrivate") == "true"
  581. allowInsecure := c.PostForm("allowInsecure") == "true"
  582. userAgent := c.PostForm("userAgent")
  583. // Use a throw-away service instance; it only needs the settingService for proxy.
  584. svc := service.OutboundSubscriptionService{}
  585. // We don't have a direct "fetch once" that returns without storing, so we
  586. // temporarily create a disabled row, refresh it, then delete. Cleaner would
  587. // be to expose a pure ParseURL on the service, but this keeps the surface small.
  588. tmp, err := svc.Create("preview", rawURL, "", userAgent, false, 600, allowPrivate, false, allowInsecure)
  589. if err != nil {
  590. jsonMsg(c, "Failed to preview subscription", err)
  591. return
  592. }
  593. obs, err := svc.Refresh(tmp.Id)
  594. // best-effort cleanup
  595. _ = svc.Delete(tmp.Id)
  596. if err != nil {
  597. jsonMsg(c, "Failed to fetch/parse subscription", err)
  598. return
  599. }
  600. jsonObj(c, obs, nil)
  601. }
  602. func parseIntSafe(s string) (int, error) {
  603. var v int
  604. _, err := fmt.Sscanf(s, "%d", &v)
  605. return v, err
  606. }