outbound_subscription.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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 p != nil {
  31. coreVersion = p.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 {
  146. var subs []*model.OutboundSubscription
  147. _ = database.GetDB().Find(&subs).Error
  148. return fmt.Sprintf("sub%d-", defaultPrefixNumber(subs, excludeId))
  149. }
  150. func (s *OutboundSubscriptionService) Create(remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend, allowInsecure bool) (*model.OutboundSubscription, error) {
  151. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  152. if err != nil {
  153. return nil, common.NewError("invalid subscription URL:", err)
  154. }
  155. if cleanURL == "" {
  156. return nil, common.NewError("subscription URL is required")
  157. }
  158. if updateInterval <= 0 {
  159. updateInterval = 600
  160. }
  161. prefix := strings.TrimSpace(tagPrefix)
  162. if prefix == "" {
  163. prefix = s.nextDefaultSubPrefix(0)
  164. }
  165. // New subscriptions go to the end of the priority order.
  166. var count int64
  167. database.GetDB().Model(&model.OutboundSubscription{}).Count(&count)
  168. sub := &model.OutboundSubscription{
  169. Remark: strings.TrimSpace(remark),
  170. Url: cleanURL,
  171. Enabled: enabled,
  172. AllowPrivate: allowPrivate,
  173. AllowInsecure: allowInsecure,
  174. Prepend: prepend,
  175. Priority: int(count),
  176. TagPrefix: prefix,
  177. UpdateInterval: updateInterval,
  178. }
  179. if err := database.GetDB().Create(sub).Error; err != nil {
  180. return nil, err
  181. }
  182. return sub, nil
  183. }
  184. // Update updates editable fields.
  185. func (s *OutboundSubscriptionService) Update(id int, remark, rawURL, tagPrefix string, enabled bool, updateInterval int, allowPrivate, prepend, allowInsecure bool) error {
  186. sub, err := s.Get(id)
  187. if err != nil {
  188. return err
  189. }
  190. cleanURL, err := SanitizePublicHTTPURL(rawURL, allowPrivate)
  191. if err != nil {
  192. return common.NewError("invalid subscription URL:", err)
  193. }
  194. if cleanURL == "" {
  195. return common.NewError("subscription URL is required")
  196. }
  197. if updateInterval <= 0 {
  198. updateInterval = 600
  199. }
  200. prefix := strings.TrimSpace(tagPrefix)
  201. if prefix == "" {
  202. prefix = s.nextDefaultSubPrefix(sub.Id)
  203. }
  204. sub.Remark = strings.TrimSpace(remark)
  205. sub.Url = cleanURL
  206. sub.Enabled = enabled
  207. sub.AllowPrivate = allowPrivate
  208. sub.AllowInsecure = allowInsecure
  209. sub.Prepend = prepend
  210. sub.TagPrefix = prefix
  211. sub.UpdateInterval = updateInterval
  212. return database.GetDB().Save(sub).Error
  213. }
  214. // Delete removes a subscription.
  215. func (s *OutboundSubscriptionService) Delete(id int) error {
  216. return database.GetDB().Delete(&model.OutboundSubscription{}, id).Error
  217. }
  218. // GetLastOutbounds returns the last successfully fetched outbounds for a subscription
  219. // (as raw interface slice ready for JSON merge). Returns nil slice when none.
  220. func (s *OutboundSubscriptionService) GetLastOutbounds(id int) ([]any, error) {
  221. sub, err := s.Get(id)
  222. if err != nil {
  223. return nil, err
  224. }
  225. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  226. return nil, nil
  227. }
  228. var arr []any
  229. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  230. return nil, err
  231. }
  232. return arr, nil
  233. }
  234. // Refresh fetches the subscription URL, parses the links, assigns stable tags,
  235. // persists the results, and returns the generated outbounds.
  236. func (s *OutboundSubscriptionService) Refresh(id int) ([]any, error) {
  237. sub, err := s.Get(id)
  238. if err != nil {
  239. return nil, err
  240. }
  241. outbounds, err := s.fetchAndStore(sub)
  242. return outbounds, err
  243. }
  244. // RefreshAllEnabled fetches every enabled subscription whose due time has passed
  245. // (lastUpdated + updateInterval <= now). It returns the number of subscriptions
  246. // that were actually refreshed.
  247. func (s *OutboundSubscriptionService) RefreshAllEnabled() (int, error) {
  248. db := database.GetDB()
  249. var subs []*model.OutboundSubscription
  250. if err := db.Where("enabled = ?", true).Find(&subs).Error; err != nil {
  251. return 0, err
  252. }
  253. now := time.Now().Unix()
  254. refreshed := 0
  255. for _, sub := range subs {
  256. due := sub.LastUpdated + int64(sub.UpdateInterval)
  257. if sub.LastUpdated == 0 || due <= now {
  258. if _, err := s.fetchAndStore(sub); err != nil {
  259. logger.Warningf("outbound sub %d (%s) refresh failed: %v", sub.Id, sub.Remark, err)
  260. // continue with others
  261. } else {
  262. refreshed++
  263. }
  264. }
  265. }
  266. return refreshed, nil
  267. }
  268. // subscriptionFetchClient builds the HTTP client used to fetch a subscription.
  269. // A configured panel egress proxy dials the loopback SOCKS bridge (xray handles
  270. // the real egress), so its localhost dial must not be SSRF-blocked. A direct
  271. // fetch dials the target itself and re-resolves the hostname at dial time, so it
  272. // goes through the SSRF-guarded dialer, which resolves, checks and dials the same
  273. // IP atomically — closing the DNS-rebinding gap left by validating the hostname
  274. // separately from the dial.
  275. func (s *OutboundSubscriptionService) subscriptionFetchClient(timeout time.Duration, allowInsecure bool) *http.Client {
  276. var client *http.Client
  277. if s.settingService.PanelEgressProxyURL() != "" {
  278. client = s.settingService.NewProxiedHTTPClient(timeout)
  279. } else {
  280. client = &http.Client{
  281. Timeout: timeout,
  282. Transport: &http.Transport{DialContext: netsafe.SSRFGuardedDialContext},
  283. }
  284. }
  285. if allowInsecure {
  286. if tr, ok := client.Transport.(*http.Transport); ok && tr != nil {
  287. cloned := tr.Clone()
  288. if cloned.TLSClientConfig == nil {
  289. cloned.TLSClientConfig = &tls.Config{}
  290. }
  291. cloned.TLSClientConfig.InsecureSkipVerify = true
  292. client.Transport = cloned
  293. }
  294. }
  295. return client
  296. }
  297. // fetchAndStore does the actual network + parse + stability + persist work.
  298. func (s *OutboundSubscriptionService) fetchAndStore(sub *model.OutboundSubscription) ([]any, error) {
  299. // Re-sanitize on every fetch (handles legacy rows + defense in depth against
  300. // any direct DB tampering). Private targets are blocked unless this
  301. // subscription was explicitly created with AllowPrivate.
  302. cleanURL, err := SanitizePublicHTTPURL(sub.Url, sub.AllowPrivate)
  303. if err != nil {
  304. s.recordError(sub, err)
  305. return nil, err
  306. }
  307. if cleanURL == "" {
  308. return nil, common.NewError("subscription has no valid URL")
  309. }
  310. sub.Url = cleanURL // persist the cleaned version
  311. client := s.subscriptionFetchClient(30*time.Second, sub.AllowInsecure)
  312. // Re-validate every redirect hop: the initial host is checked above, but a
  313. // redirect could still point at a private/internal address (SSRF). Cap the
  314. // redirect chain as well.
  315. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  316. if len(via) >= 10 {
  317. return fmt.Errorf("stopped after 10 redirects")
  318. }
  319. if sub.AllowPrivate {
  320. return nil
  321. }
  322. ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
  323. defer cancel()
  324. return rejectPrivateHost(ctx, req.URL.Hostname())
  325. }
  326. reqCtx := netsafe.ContextWithAllowPrivate(context.Background(), sub.AllowPrivate)
  327. req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, sub.Url, nil)
  328. if err != nil {
  329. s.recordError(sub, err)
  330. return nil, err
  331. }
  332. req.Header.Set("User-Agent", "3x-ui-outbound-sub/1.0")
  333. resp, err := client.Do(req)
  334. if err != nil {
  335. s.recordError(sub, err)
  336. return nil, err
  337. }
  338. defer resp.Body.Close()
  339. if resp.StatusCode != http.StatusOK {
  340. err := fmt.Errorf("http %d", resp.StatusCode)
  341. s.recordError(sub, err)
  342. return nil, err
  343. }
  344. body, err := readBoundedOutboundSubscriptionBody(resp.Body)
  345. if err != nil {
  346. s.recordError(sub, err)
  347. return nil, err
  348. }
  349. parsed, identities, err := link.ParseSubscriptionBody(body)
  350. if err != nil {
  351. s.recordError(sub, err)
  352. return nil, err
  353. }
  354. // Load previous identities -> tags for stability
  355. prev := map[string]string{}
  356. if strings.TrimSpace(sub.LinkIdentities) != "" {
  357. _ = json.Unmarshal([]byte(sub.LinkIdentities), &prev)
  358. }
  359. // Also load previous outbounds so we can reuse tags even for identities we
  360. // temporarily lost (defensive).
  361. prevTagByIndex := map[int]string{}
  362. if strings.TrimSpace(sub.LastFetchedOutbounds) != "" {
  363. var prevObs []any
  364. if json.Unmarshal([]byte(sub.LastFetchedOutbounds), &prevObs) == nil {
  365. for i, o := range prevObs {
  366. if m, ok := o.(map[string]any); ok {
  367. if tag, _ := m["tag"].(string); tag != "" {
  368. prevTagByIndex[i] = tag
  369. }
  370. }
  371. }
  372. }
  373. }
  374. // Assign tags with stability (identity reuse, positional fallback, then a
  375. // fresh allocation), keeping tags unique within this batch. Extracted into a
  376. // pure function so it can be unit-tested without network/DB. Tags are written
  377. // back into the parsed outbounds in place.
  378. assigned := assignStableTags(parsed, identities, prev, prevTagByIndex, sub.Id, sub.TagPrefix)
  379. // Persist identities for next time
  380. newIdent := map[string]string{}
  381. for i, id := range identities {
  382. newIdent[id] = assigned[i]
  383. }
  384. identJSON, _ := json.Marshal(newIdent)
  385. asAny := make([]any, len(parsed))
  386. for i := range parsed {
  387. asAny[i] = map[string]any(parsed[i])
  388. }
  389. kept, droppedByCore := filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), asAny)
  390. // Persist the outbounds (as compact JSON array)
  391. obsJSON, _ := json.Marshal(kept)
  392. sub.LastFetchedOutbounds = string(obsJSON)
  393. sub.LinkIdentities = string(identJSON)
  394. sub.LastUpdated = time.Now().Unix()
  395. sub.LastError = ""
  396. if len(droppedByCore) > 0 {
  397. sub.LastError = fmt.Sprintf("dropped %d outbound(s) the xray core rejects: %s", len(droppedByCore), droppedByCore[0])
  398. }
  399. if err := database.GetDB().Save(sub).Error; err != nil {
  400. return nil, err
  401. }
  402. return kept, nil
  403. }
  404. func (s *OutboundSubscriptionService) recordError(sub *model.OutboundSubscription, err error) {
  405. sub.LastError = err.Error()
  406. _ = database.GetDB().Model(sub).Update("last_error", sub.LastError).Error
  407. }
  408. // assignStableTags assigns a tag to each parsed outbound, preferring stability:
  409. // 1. reuse the tag previously mapped to the link's identity (prev),
  410. // 2. else reuse the tag at the same position from the last fetch (prevTagByIndex),
  411. // 3. else allocate a fresh tag from the prefix + remark (link.SuggestTag).
  412. //
  413. // Tags are kept unique within the batch by appending "-N" on collision, and are
  414. // written back into parsed[i]["tag"]. The returned slice holds the assigned tags
  415. // in order. When tagPrefix is empty a "sub<subID>-" prefix is used for fresh tags.
  416. func assignStableTags(parsed []link.Outbound, identities []string, prev map[string]string, prevTagByIndex map[int]string, subID int, tagPrefix string) []string {
  417. used := map[string]bool{} // uniqueness within this refresh batch
  418. assigned := make([]string, len(parsed))
  419. for i := range parsed {
  420. id := ""
  421. if i < len(identities) {
  422. id = identities[i]
  423. }
  424. candidate := ""
  425. if old, ok := prev[id]; ok && old != "" {
  426. candidate = old
  427. }
  428. if candidate == "" {
  429. // try to reuse by rough positional match from previous fetch (best effort)
  430. if old, ok := prevTagByIndex[i]; ok && old != "" {
  431. candidate = old
  432. }
  433. }
  434. if candidate == "" {
  435. // fresh allocation
  436. prefix := tagPrefix
  437. if prefix == "" {
  438. prefix = fmt.Sprintf("sub%d-", subID)
  439. }
  440. remark := ""
  441. if m, ok := parsed[i]["tag"].(string); ok {
  442. remark = m
  443. }
  444. candidate = link.SuggestTag(prefix, remark, i)
  445. }
  446. // ensure local uniqueness inside this batch
  447. final := candidate
  448. for k := 1; used[final]; k++ {
  449. final = fmt.Sprintf("%s-%d", candidate, k)
  450. }
  451. used[final] = true
  452. assigned[i] = final
  453. // write back the tag into the outbound
  454. parsed[i]["tag"] = final
  455. }
  456. return assigned
  457. }
  458. // AllActiveOutbounds returns the concatenation of the last-fetched outbounds
  459. // for every enabled subscription. This is the set that should be merged into
  460. // the final Xray config. Order: subscription creation order (by id asc) so
  461. // that later subscriptions can shadow earlier ones if the admin uses colliding
  462. // prefixes (last writer wins inside xray, but we try to keep tags unique).
  463. func (s *OutboundSubscriptionService) AllActiveOutbounds() ([]any, error) {
  464. prepend, appendList, err := s.activeOutboundsSplit()
  465. if err != nil {
  466. return nil, err
  467. }
  468. return append(prepend, appendList...), nil
  469. }
  470. // activeOutboundsSplit returns the active subscription outbounds split into those
  471. // that should be placed BEFORE the manual template outbounds (Prepend) and those
  472. // placed AFTER. Within each group, subscriptions are ordered by Priority (then id)
  473. // so the admin can control the merged order.
  474. func (s *OutboundSubscriptionService) activeOutboundsSplit() (prepend []any, appendList []any, err error) {
  475. db := database.GetDB()
  476. var subs []*model.OutboundSubscription
  477. if err := db.Where("enabled = ?", true).Order("priority asc, id asc").Find(&subs).Error; err != nil {
  478. return nil, nil, err
  479. }
  480. for _, sub := range subs {
  481. if strings.TrimSpace(sub.LastFetchedOutbounds) == "" {
  482. continue
  483. }
  484. var arr []any
  485. if err := json.Unmarshal([]byte(sub.LastFetchedOutbounds), &arr); err != nil {
  486. logger.Warningf("outbound sub %d has corrupt LastFetchedOutbounds: %v", sub.Id, err)
  487. continue
  488. }
  489. arr, _ = filterOutboundsRejectedByCore(fmt.Sprintf("outbound sub %d", sub.Id), arr)
  490. if sub.Prepend {
  491. prepend = append(prepend, arr...)
  492. } else {
  493. appendList = append(appendList, arr...)
  494. }
  495. }
  496. return prepend, appendList, nil
  497. }
  498. // Move shifts a subscription one step up or down in the priority order and
  499. // re-normalizes all priorities to a 0..n-1 sequence.
  500. func (s *OutboundSubscriptionService) Move(id int, up bool) error {
  501. db := database.GetDB()
  502. var subs []*model.OutboundSubscription
  503. if err := db.Order("priority asc, id asc").Find(&subs).Error; err != nil {
  504. return err
  505. }
  506. idx := -1
  507. for i, sub := range subs {
  508. if sub.Id == id {
  509. idx = i
  510. break
  511. }
  512. }
  513. if idx == -1 {
  514. return common.NewError("subscription not found")
  515. }
  516. swap := idx + 1
  517. if up {
  518. swap = idx - 1
  519. }
  520. if swap < 0 || swap >= len(subs) {
  521. return nil // already at the edge
  522. }
  523. subs[idx], subs[swap] = subs[swap], subs[idx]
  524. for i, sub := range subs {
  525. if sub.Priority != i {
  526. if err := db.Model(sub).Update("priority", i).Error; err != nil {
  527. return err
  528. }
  529. }
  530. }
  531. return nil
  532. }
  533. // AllActiveOutboundTags returns only the tags of active subscription outbounds.
  534. // Useful for populating balancer / routing selectors without shipping full objects.
  535. func (s *OutboundSubscriptionService) AllActiveOutboundTags() ([]string, error) {
  536. obs, err := s.AllActiveOutbounds()
  537. if err != nil {
  538. return nil, err
  539. }
  540. tags := make([]string, 0, len(obs))
  541. for _, o := range obs {
  542. if m, ok := o.(map[string]any); ok {
  543. if t, _ := m["tag"].(string); t != "" {
  544. tags = append(tags, t)
  545. }
  546. }
  547. }
  548. return tags, nil
  549. }
  550. /*
  551. Tag stability strategy (important for balancers and routing rules)
  552. When a subscription is refreshed we try very hard to keep the *same* tag for the
  553. same logical outbound so that existing balancers and routing rules keep working.
  554. How we do it:
  555. - On every successful parse we compute a stable "identity" for each link
  556. (the core of the URI with the remark fragment removed, or for vmess the inner
  557. JSON without the "ps" field).
  558. - We persist a map identity -> tag in the LinkIdentities column.
  559. - On the next refresh, if we see the same identity again we reuse the previous tag,
  560. even if the remark changed or minor parameters moved.
  561. - Only when we have never seen the identity before do we allocate a fresh tag
  562. using the user-supplied TagPrefix + slug(remark) (or an index fallback).
  563. - Within one refresh we still deduplicate with -N suffixes.
  564. Consequences for balancers / routing:
  565. - If you use an *exact* tag in a balancer selector or a routing rule, that
  566. specific server will continue to be used after refreshes (as long as the
  567. provider still returns a link that produces the same identity).
  568. - If you use a *prefix/wildcard* selector (e.g. "hk-*", "sg-.*"), then any
  569. *new* servers that the subscription later returns will automatically be
  570. eligible for that balancer on the next Xray reload — this is the recommended
  571. way to "subscribe to a pool".
  572. - When a server disappears from the subscription, its tag simply stops
  573. existing in the final outbounds array. The balancer will have fewer
  574. candidates. If you configured a `fallbackTag` on the balancer, Xray will use
  575. it. Otherwise connections that would have used the missing member may fail
  576. or be routed by the next rule.
  577. - If the provider rotates credentials/UUIDs/hosts for a server, the identity
  578. changes → we treat it as a brand new outbound and give it a new tag. Any
  579. balancer/rule that referenced the *old* tag will no longer see it. This is
  580. an inherent limitation of subscription-based outbounds.
  581. We deliberately do *not* mutate the saved xrayTemplateConfig. Subscription
  582. outbounds are always injected at runtime in GetXrayConfig.
  583. */