outbound_subscription.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. package service
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/link"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  20. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  21. )
  22. // filterOutboundsRejectedByCore drops outbounds the vendored xray-core config
  23. // loader refuses to build — since v26.7.11 that includes unencrypted
  24. // vless/trojan outbounds to public addresses — because one such outbound in
  25. // the merged config would keep the whole core from starting. When the running
  26. // core predates that rejection, unencrypted outbounds are kept, mirroring
  27. // CheckXrayConfig's version gate.
  28. func filterOutboundsRejectedByCore(label string, outbounds []any) ([]any, []string) {
  29. coreVersion := "Unknown"
  30. if process := currentXrayProcess(); process != nil {
  31. coreVersion = process.GetXrayVersion()
  32. }
  33. kept := make([]any, 0, len(outbounds))
  34. var dropped []string
  35. for _, ob := range outbounds {
  36. raw, err := json.Marshal(ob)
  37. if err == nil {
  38. if buildErr := xray.ValidateOutboundConfig(raw); buildErr != nil && !shouldSkipLegacyUnencryptedOutboundRejection(coreVersion, buildErr) {
  39. tag := ""
  40. if m, ok := ob.(map[string]any); ok {
  41. tag, _ = m["tag"].(string)
  42. }
  43. logger.Warningf("%s: dropping outbound %q rejected by xray-core: %v", label, tag, buildErr)
  44. dropped = append(dropped, fmt.Sprintf("%s: %v", tag, buildErr))
  45. continue
  46. }
  47. }
  48. kept = append(kept, ob)
  49. }
  50. return kept, dropped
  51. }
  52. // maxOutboundSubscriptionBytes caps a single outbound subscription response.
  53. // It is larger than the 2 MiB user-facing subscription cap because an outbound
  54. // subscription may aggregate many upstream outbounds into one document.
  55. const maxOutboundSubscriptionBytes int64 = 8 << 20
  56. var errOutboundSubscriptionBodyTooLarge = errors.New("outbound subscription response body exceeds size limit")
  57. func readBoundedOutboundSubscriptionBody(r io.Reader) ([]byte, error) {
  58. body, err := io.ReadAll(io.LimitReader(r, maxOutboundSubscriptionBytes+1))
  59. if err != nil {
  60. return nil, err
  61. }
  62. if int64(len(body)) > maxOutboundSubscriptionBytes {
  63. return nil, fmt.Errorf("%w (limit: %d bytes)", errOutboundSubscriptionBodyTooLarge, maxOutboundSubscriptionBytes)
  64. }
  65. return body, nil
  66. }
  67. // OutboundSubscriptionService manages remote outbound subscriptions.
  68. type OutboundSubscriptionService struct {
  69. settingService SettingService
  70. }
  71. // NewOutboundSubscriptionService returns a service for managing outbound subscriptions.
  72. func NewOutboundSubscriptionService() *OutboundSubscriptionService {
  73. return &OutboundSubscriptionService{}
  74. }
  75. // List returns all subscriptions (newest first).
  76. func (s *OutboundSubscriptionService) List() ([]*model.OutboundSubscription, error) {
  77. db := database.GetDB()
  78. var subs []*model.OutboundSubscription
  79. if err := db.Model(&model.OutboundSubscription{}).Order("priority asc, id asc").Find(&subs).Error; err != nil {
  80. return nil, err
  81. }
  82. for _, sub := range subs {
  83. sub.OutboundCount = countOutbounds(sub.LastFetchedOutbounds)
  84. // Don't ship the heavy raw blobs to the list view.
  85. sub.LastFetchedOutbounds = ""
  86. sub.LinkIdentities = ""
  87. }
  88. return subs, nil
  89. }
  90. // countOutbounds returns the number of outbounds in a stored LastFetchedOutbounds
  91. // JSON array (0 for empty/invalid).
  92. func countOutbounds(raw string) int {
  93. if strings.TrimSpace(raw) == "" {
  94. return 0
  95. }
  96. var arr []any
  97. if json.Unmarshal([]byte(raw), &arr) != nil {
  98. return 0
  99. }
  100. return len(arr)
  101. }
  102. // Get returns a single subscription by id.
  103. func (s *OutboundSubscriptionService) Get(id int) (*model.OutboundSubscription, error) {
  104. db := database.GetDB()
  105. var sub model.OutboundSubscription
  106. if err := db.First(&sub, id).Error; err != nil {
  107. return nil, err
  108. }
  109. return &sub, nil
  110. }
  111. // Create persists a new subscription. It does not fetch immediately; the caller
  112. // can call Refresh on the returned id if desired.
  113. var defaultPrefixRe = regexp.MustCompile(`^sub(\d+)-$`)
  114. // defaultPrefixNumber returns the smallest positive integer N that is not already
  115. // in use as a "subN-" tag prefix among the given subscriptions. This is used to
  116. // auto-name a subscription's outbounds when the user leaves the prefix blank, so
  117. // deleting a subscription frees its number for reuse instead of letting the
  118. // number grow forever with the auto-increment DB id. A subscription with a blank
  119. // prefix reserves its own id (it falls back to id-based "sub<id>-" tags).
  120. func defaultPrefixNumber(subs []*model.OutboundSubscription, excludeId int) int {
  121. used := map[int]bool{}
  122. for _, sub := range subs {
  123. if sub.Id == excludeId {
  124. continue
  125. }
  126. if sub.TagPrefix == "" {
  127. used[sub.Id] = true
  128. continue
  129. }
  130. if m := defaultPrefixRe.FindStringSubmatch(sub.TagPrefix); m != nil {
  131. if n, err := strconv.Atoi(m[1]); err == nil {
  132. used[n] = true
  133. }
  134. }
  135. }
  136. n := 1
  137. for used[n] {
  138. n++
  139. }
  140. return n
  141. }
  142. // nextDefaultSubPrefix builds the default "subN-" prefix for a new/edited
  143. // subscription, picking the smallest free N (excludeId skips a subscription's
  144. // own current prefix when editing).
  145. func (s *OutboundSubscriptionService) nextDefaultSubPrefix(excludeId int) (string, error) {
  146. var subs []*model.OutboundSubscription
  147. if err := database.GetDB().Find(&subs).Error; err != nil {
  148. return "", err
  149. }
  150. return fmt.Sprintf("sub%d-", defaultPrefixNumber(subs, excludeId)), nil
  151. }
  152. func (s *OutboundSubscriptionService) Create(remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend, allowInsecure bool) (*model.OutboundSubscription, error) {
  153. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  154. if err != nil {
  155. return nil, common.NewError("invalid subscription URL:", err)
  156. }
  157. if cleanURL == "" {
  158. return nil, common.NewError("subscription URL is required")
  159. }
  160. if updateInterval <= 0 {
  161. updateInterval = 600
  162. }
  163. prefix := strings.TrimSpace(tagPrefix)
  164. if prefix == "" {
  165. prefix, err = s.nextDefaultSubPrefix(0)
  166. if err != nil {
  167. return nil, err
  168. }
  169. }
  170. // New subscriptions go to the end of the priority order.
  171. var count int64
  172. if err := database.GetDB().Model(&model.OutboundSubscription{}).Count(&count).Error; err != nil {
  173. return nil, err
  174. }
  175. sub := &model.OutboundSubscription{
  176. Remark: strings.TrimSpace(remark),
  177. Url: cleanURL,
  178. Enabled: enabled,
  179. AllowPrivate: allowPrivate,
  180. AllowInsecure: allowInsecure,
  181. Prepend: prepend,
  182. Priority: int(count),
  183. TagPrefix: prefix,
  184. UpdateInterval: updateInterval,
  185. }
  186. if err := database.GetDB().Create(sub).Error; err != nil {
  187. return nil, err
  188. }
  189. return sub, nil
  190. }
  191. // Update updates editable fields.
  192. func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend, allowInsecure bool) error {
  193. sub, err := s.Get(id)
  194. if err != nil {
  195. return err
  196. }
  197. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  198. if err != nil {
  199. return common.NewError("invalid subscription URL:", err)
  200. }
  201. if cleanURL == "" {
  202. return common.NewError("subscription URL is required")
  203. }
  204. if updateInterval <= 0 {
  205. updateInterval = 600
  206. }
  207. prefix := strings.TrimSpace(tagPrefix)
  208. if prefix == "" {
  209. prefix, err = s.nextDefaultSubPrefix(sub.Id)
  210. if err != nil {
  211. return err
  212. }
  213. }
  214. sub.Remark = strings.TrimSpace(remark)
  215. sub.Url = cleanURL
  216. sub.Enabled = enabled
  217. sub.AllowPrivate = allowPrivate
  218. sub.AllowInsecure = allowInsecure
  219. sub.Prepend = prepend
  220. sub.TagPrefix = prefix
  221. sub.UpdateInterval = updateInterval
  222. return database.GetDB().Save(sub).Error
  223. }
  224. // Delete removes a subscription.
  225. func (s *OutboundSubscriptionService) Delete(id int) error {
  226. return database.GetDB().Delete(&model.OutboundSubscription{}, id).Error
  227. }
  228. // GetLastOutbounds returns the last successfully fetched outbounds for a subscription
  229. // (as raw interface slice ready for JSON merge). Returns nil slice when none.
  230. func (s *OutboundSubscriptionService) GetLastOutbounds(id int) ([]any, error) {
  231. sub, err := s.Get(id)
  232. if err != nil {
  233. return nil, err
  234. }
  235. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  236. return nil, nil
  237. }
  238. var arr []any
  239. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  240. return nil, err
  241. }
  242. return arr, nil
  243. }
  244. // Refresh fetches the subscription URL, parses the links, assigns stable tags,
  245. // persists the results, and returns the generated outbounds.
  246. func (s *OutboundSubscriptionService) Refresh(id int) ([]any, error) {
  247. sub, err := s.Get(id)
  248. if err != nil {
  249. return nil, err
  250. }
  251. outbounds, err := s.fetchAndStore(sub)
  252. return outbounds, err
  253. }
  254. // RefreshAllEnabled fetches every enabled subscription whose due time has passed
  255. // (lastUpdated + updateInterval <= now). It returns the number of subscriptions
  256. // that were actually refreshed.
  257. func (s *OutboundSubscriptionService) RefreshAllEnabled() (int, error) {
  258. db := database.GetDB()
  259. var subs []*model.OutboundSubscription
  260. if err := db.Where("enabled = ?", true).Find(&subs).Error; err != nil {
  261. return 0, err
  262. }
  263. now := time.Now().Unix()
  264. refreshed := 0
  265. for _, sub := range subs {
  266. due := sub.LastUpdated + int64(sub.UpdateInterval)
  267. if sub.LastUpdated == 0 || due <= now {
  268. if _, err := s.fetchAndStore(sub); err != nil {
  269. logger.Warningf("outbound sub %d (%s) refresh failed: %v", sub.Id, sub.Remark, err)
  270. // continue with others
  271. } else {
  272. refreshed++
  273. }
  274. }
  275. }
  276. return refreshed, nil
  277. }
  278. // subscriptionFetchClient builds the HTTP client used to fetch a subscription.
  279. // A configured panel egress proxy dials the loopback SOCKS bridge (xray handles
  280. // the real egress), so its localhost dial must not be SSRF-blocked. A direct
  281. // fetch dials the target itself and re-resolves the hostname at dial time, so it
  282. // goes through the SSRF-guarded dialer, which resolves, checks and dials the same
  283. // IP atomically — closing the DNS-rebinding gap left by validating the hostname
  284. // separately from the dial.
  285. func (s *OutboundSubscriptionService) subscriptionFetchClient(timeout time.Duration, allowInsecure bool) *http.Client {
  286. var client *http.Client
  287. if s.settingService.PanelEgressProxyURL() != "" {
  288. client = s.settingService.NewProxiedHTTPClient(timeout)
  289. } else {
  290. client = &http.Client{
  291. Timeout: timeout,
  292. Transport: &http.Transport{DialContext: netsafe.SSRFGuardedDialContext},
  293. }
  294. }
  295. if allowInsecure {
  296. if tr, ok := client.Transport.(*http.Transport); ok && tr != nil {
  297. cloned := tr.Clone()
  298. if cloned.TLSClientConfig == nil {
  299. cloned.TLSClientConfig = &tls.Config{}
  300. }
  301. cloned.TLSClientConfig.InsecureSkipVerify = true
  302. client.Transport = cloned
  303. }
  304. }
  305. return client
  306. }
  307. // fetchAndStore does the actual network + parse + stability + persist work.
  308. func (s *OutboundSubscriptionService) fetchAndStore(sub *model.OutboundSubscription) ([]any, error) {
  309. // Re-sanitize on every fetch (handles legacy rows + defense in depth against
  310. // any direct DB tampering). Private targets are blocked unless this
  311. // subscription was explicitly created with AllowPrivate.
  312. cleanURL, err := SanitizePublicHTTPURL(sub.Url, sub.AllowPrivate)
  313. if err != nil {
  314. s.recordError(sub, err)
  315. return nil, err
  316. }
  317. if cleanURL == "" {
  318. return nil, common.NewError("subscription has no valid URL")
  319. }
  320. sub.Url = cleanURL // persist the cleaned version
  321. client := s.subscriptionFetchClient(30*time.Second, sub.AllowInsecure)
  322. // Re-validate every redirect hop: the initial host is checked above, but a
  323. // redirect could still point at a private/internal address (SSRF). Cap the
  324. // redirect chain as well.
  325. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  326. if len(via) >= 10 {
  327. return fmt.Errorf("stopped after 10 redirects")
  328. }
  329. if sub.AllowPrivate {
  330. return nil
  331. }
  332. ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
  333. defer cancel()
  334. return rejectPrivateHost(ctx, req.URL.Hostname())
  335. }
  336. reqCtx := netsafe.ContextWithAllowPrivate(context.Background(), sub.AllowPrivate)
  337. req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, sub.Url, nil)
  338. if err != nil {
  339. s.recordError(sub, err)
  340. return nil, err
  341. }
  342. req.Header.Set("User-Agent", "3x-ui-outbound-sub/1.0")
  343. resp, err := client.Do(req)
  344. if err != nil {
  345. s.recordError(sub, err)
  346. return nil, err
  347. }
  348. defer resp.Body.Close()
  349. if resp.StatusCode != http.StatusOK {
  350. err := fmt.Errorf("http %d", resp.StatusCode)
  351. s.recordError(sub, err)
  352. return nil, err
  353. }
  354. body, err := readBoundedOutboundSubscriptionBody(resp.Body)
  355. if err != nil {
  356. s.recordError(sub, err)
  357. return nil, err
  358. }
  359. parsed, identities, err := link.ParseSubscriptionBody(body)
  360. if err != nil {
  361. s.recordError(sub, err)
  362. return nil, err
  363. }
  364. // Load previous identities -> tags for stability
  365. prev := map[string]string{}
  366. if strings.TrimSpace(sub.LinkIdentities) != "" {
  367. _ = json.Unmarshal([]byte(sub.LinkIdentities), &prev)
  368. }
  369. // Also load previous outbounds so we can reuse tags even for identities we
  370. // temporarily lost (defensive).
  371. prevTagByIndex := map[int]string{}
  372. if strings.TrimSpace(sub.LastFetchedOutbounds) != "" {
  373. var prevObs []any
  374. if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &prevObs) == nil {
  375. for i, o := range prevObs {
  376. if m, ok := o.(map[string]any); ok {
  377. if tag, _ := m["tag"].(string); tag != "" {
  378. prevTagByIndex[i] = tag
  379. }
  380. }
  381. }
  382. }
  383. }
  384. // Assign tags with stability (identity reuse, positional fallback, then a
  385. // fresh allocation), keeping tags unique within this batch. Extracted into a
  386. // pure function so it can be unit-tested without network/DB. Tags are written
  387. // back into the parsed outbounds in place.
  388. assigned := assignStableTags(parsed, identities, prev, prevTagByIndex, sub.Id, sub.TagPrefix)
  389. // Persist identities for next time
  390. newIdent := map[string]string{}
  391. for i, id := range identities {
  392. newIdent[id] = assigned[i]
  393. }
  394. identJSON, _ := json.Marshal(newIdent)
  395. asAny := make([]any, len(parsed))
  396. for i := range parsed {
  397. asAny[i] = map[string]any(parsed[i])
  398. }
  399. kept, droppedByCore := filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), asAny)
  400. // Persist the outbounds (as compact JSON array)
  401. obsJSON, _ := json.Marshal(kept)
  402. sub.LastFetchedOutbounds = string(obsJSON)
  403. sub.LinkIdentities = string(identJSON)
  404. sub.LastUpdated = time.Now().Unix()
  405. sub.LastError = ""
  406. if len(droppedByCore) > 0 {
  407. sub.LastError = fmt.Sprintf("dropped %d outbound(s) the xray core rejects: %s", len(droppedByCore), droppedByCore[0])
  408. }
  409. if err := database.GetDB().Save(sub).Error; err != nil {
  410. return nil, err
  411. }
  412. return kept, nil
  413. }
  414. func (s *OutboundSubscriptionService) recordError(sub *model.OutboundSubscription, err error) {
  415. sub.LastError = err.Error()
  416. _ = database.GetDB().Model(sub).Update("last_error", sub.LastError).Error
  417. }
  418. // assignStableTags assigns a tag to each parsed outbound, preferring stability:
  419. // 1. reuse the tag previously mapped to the link's identity (prev),
  420. // 2. else reuse the tag at the same position from the last fetch (prevTagByIndex),
  421. // 3. else allocate a fresh tag from the prefix + remark (link.SuggestTag).
  422. //
  423. // Tags are kept unique within the batch by appending "-N" on collision, and are
  424. // written back into parsed[i]["tag"]. The returned slice holds the assigned tags
  425. // in order. When tagPrefix is empty a "sub<subID>-" prefix is used for fresh tags.
  426. func assignStableTags(parsed []link.Outbound, identities []string, prev map[string]string, prevTagByIndex map[int]string, subID int, tagPrefix string) []string {
  427. used := map[string]bool{} // uniqueness within this refresh batch
  428. assigned := make([]string, len(parsed))
  429. for i := range parsed {
  430. id := ""
  431. if i < len(identities) {
  432. id = identities[i]
  433. }
  434. candidate := ""
  435. if old, ok := prev[id]; ok && old != "" {
  436. candidate = old
  437. }
  438. if candidate == "" {
  439. // try to reuse by rough positional match from previous fetch (best effort)
  440. if old, ok := prevTagByIndex[i]; ok && old != "" {
  441. candidate = old
  442. }
  443. }
  444. if candidate == "" {
  445. // fresh allocation
  446. prefix := tagPrefix
  447. if prefix == "" {
  448. prefix = fmt.Sprintf("sub%d-", subID)
  449. }
  450. remark := ""
  451. if m, ok := parsed[i]["tag"].(string); ok {
  452. remark = m
  453. }
  454. candidate = link.SuggestTag(prefix, remark, i)
  455. }
  456. // ensure local uniqueness inside this batch
  457. final := candidate
  458. for k := 1; used[final]; k++ {
  459. final = fmt.Sprintf("%s-%d", candidate, k)
  460. }
  461. used[final] = true
  462. assigned[i] = final
  463. // write back the tag into the outbound
  464. parsed[i]["tag"] = final
  465. }
  466. return assigned
  467. }
  468. // AllActiveOutbounds returns the concatenation of the last-fetched outbounds
  469. // for every enabled subscription. This is the set that should be merged into
  470. // the final Xray config. Order: subscription creation order (by id asc) so
  471. // that later subscriptions can shadow earlier ones if the admin uses colliding
  472. // prefixes (last writer wins inside xray, but we try to keep tags unique).
  473. func (s *OutboundSubscriptionService) AllActiveOutbounds() ([]any, error) {
  474. prepend, appendList, err := s.activeOutboundsSplit()
  475. if err != nil {
  476. return nil, err
  477. }
  478. return append(prepend, appendList...), nil
  479. }
  480. // activeOutboundsSplit returns the active subscription outbounds split into those
  481. // that should be placed BEFORE the manual template outbounds (Prepend) and those
  482. // placed AFTER. Within each group, subscriptions are ordered by Priority (then id)
  483. // so the admin can control the merged order.
  484. func (s *OutboundSubscriptionService) activeOutboundsSplit() (prepend []any, appendList []any, err error) {
  485. db := database.GetDB()
  486. var subs []*model.OutboundSubscription
  487. if err := db.Where("enabled = ?", true).Order("priority asc, id asc").Find(&subs).Error; err != nil {
  488. return nil, nil, err
  489. }
  490. for _, sub := range subs {
  491. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  492. continue
  493. }
  494. var arr []any
  495. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  496. logger.Warningf("outbound sub %d has corrupt LastFetchedOutbounds: %v", sub.Id, err)
  497. continue
  498. }
  499. arr, _ = filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), arr)
  500. if sub.Prepend {
  501. prepend = append(prepend, arr...)
  502. } else {
  503. appendList = append(appendList, arr...)
  504. }
  505. }
  506. return prepend, appendList, nil
  507. }
  508. // Move shifts a subscription one step up or down in the priority order and
  509. // re-normalizes all priorities to a 0..n-1 sequence.
  510. func (s *OutboundSubscriptionService) Move(id int, up bool) error {
  511. db := database.GetDB()
  512. var subs []*model.OutboundSubscription
  513. if err := db.Order("priority asc, id asc").Find(&subs).Error; err != nil {
  514. return err
  515. }
  516. idx := -1
  517. for i, sub := range subs {
  518. if sub.Id == id {
  519. idx = i
  520. break
  521. }
  522. }
  523. if idx == -1 {
  524. return common.NewError("subscription not found")
  525. }
  526. swap := idx + 1
  527. if up {
  528. swap = idx - 1
  529. }
  530. if swap < 0 || swap >= len(subs) {
  531. return nil // already at the edge
  532. }
  533. subs[idx], subs[swap] = subs[swap], subs[idx]
  534. for i, sub := range subs {
  535. if sub.Priority != i {
  536. if err := db.Model(sub).Update("priority", i).Error; err != nil {
  537. return err
  538. }
  539. }
  540. }
  541. return nil
  542. }
  543. // AllActiveOutboundTags returns only the tags of active subscription outbounds.
  544. // Useful for populating balancer / routing selectors without shipping full objects.
  545. func (s *OutboundSubscriptionService) AllActiveOutboundTags() ([]string, error) {
  546. obs, err := s.AllActiveOutbounds()
  547. if err != nil {
  548. return nil, err
  549. }
  550. tags := make([]string, 0, len(obs))
  551. for _, o := range obs {
  552. if m, ok := o.(map[string]any); ok {
  553. if t, _ := m["tag"].(string); t != "" {
  554. tags = append(tags, t)
  555. }
  556. }
  557. }
  558. return tags, nil
  559. }
  560. /*
  561. Tag stability strategy (important for balancers and routing rules)
  562. When a subscription is refreshed we try very hard to keep the *same* tag for the
  563. same logical outbound so that existing balancers and routing rules keep working.
  564. How we do it:
  565. - On every successful parse we compute a stable "identity" for each link
  566. (the core of the URI with the remark fragment removed, or for vmess the inner
  567. JSON without the "ps" field).
  568. - We persist a map identity -> tag in the LinkIdentities column.
  569. - On the next refresh, if we see the same identity again we reuse the previous tag,
  570. even if the remark changed or minor parameters moved.
  571. - Only when we have never seen the identity before do we allocate a fresh tag
  572. using the user-supplied TagPrefix + slug(remark) (or an index fallback).
  573. - Within one refresh we still deduplicate with -N suffixes.
  574. Consequences for balancers / routing:
  575. - If you use an *exact* tag in a balancer selector or a routing rule, that
  576. specific server will continue to be used after refreshes (as long as the
  577. provider still returns a link that produces the same identity).
  578. - If you use a *prefix/wildcard* selector (e.g. "hk-*", "sg-.*"), then any
  579. *new* servers that the subscription later returns will automatically be
  580. eligible for that balancer on the next Xray reload — this is the recommended
  581. way to "subscribe to a pool".
  582. - When a server disappears from the subscription, its tag simply stops
  583. existing in the final outbounds array. The balancer will have fewer
  584. candidates. If you configured a `fallbackTag` on the balancer, Xray will use
  585. it. Otherwise connections that would have used the missing member may fail
  586. or be routed by the next rule.
  587. - If the provider rotates credentials/UUIDs/hosts for a server, the identity
  588. changes → we treat it as a brand new outbound and give it a new tag. Any
  589. balancer/rule that referenced the *old* tag will no longer see it. This is
  590. an inherent limitation of subscription-based outbounds.
  591. We deliberately do *not* mutate the saved xrayTemplateConfig. Subscription
  592. outbounds are always injected at runtime in GetXrayConfig.
  593. */