external_subscription.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. package sub
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. )
  14. // External subscription fetching: a "subscription" external link is a remote
  15. // URL whose body is a (often base64-encoded) newline list of share links. We
  16. // fetch it on demand, cache the decoded links briefly, and bound the request
  17. // with a short timeout so a slow/dead provider can't stall a client's sub.
  18. const (
  19. subscriptionCacheTTL = 5 * time.Minute
  20. subscriptionMaxBytes = 2 << 20 // 2 MiB
  21. subscriptionCacheCapacity = 256
  22. )
  23. var subscriptionHTTPClient = &http.Client{Timeout: 6 * time.Second}
  24. type subscriptionCacheEntry struct {
  25. links []string
  26. fetchedAt time.Time
  27. }
  28. type subscriptionFetch struct {
  29. done chan struct{}
  30. links []string
  31. }
  32. var subscriptionCache = struct {
  33. sync.Mutex
  34. m map[string]subscriptionCacheEntry
  35. inflight map[string]*subscriptionFetch
  36. }{
  37. m: make(map[string]subscriptionCacheEntry),
  38. inflight: make(map[string]*subscriptionFetch),
  39. }
  40. // subscriptionFetchResult reports whether this caller performed the network
  41. // fetch, so only it records status and cache hits stay read-only.
  42. type subscriptionFetchResult struct {
  43. links []string
  44. fetched bool
  45. err error
  46. }
  47. // fetchSubscriptionLinks returns the share links contained in a remote
  48. // subscription URL, using a short-lived cache. On any failure it returns the
  49. // last cached value (if present) or nil — never an error, so the rest of the
  50. // client's subscription still renders.
  51. func fetchSubscriptionLinks(rawURL string) subscriptionFetchResult {
  52. rawURL = strings.TrimSpace(rawURL)
  53. if rawURL == "" {
  54. return subscriptionFetchResult{}
  55. }
  56. subscriptionCache.Lock()
  57. cached, ok := subscriptionCache.m[rawURL]
  58. if ok && time.Since(cached.fetchedAt) < subscriptionCacheTTL {
  59. subscriptionCache.Unlock()
  60. return subscriptionFetchResult{links: cached.links}
  61. }
  62. if fetch, waiting := subscriptionCache.inflight[rawURL]; waiting {
  63. subscriptionCache.Unlock()
  64. <-fetch.done
  65. return subscriptionFetchResult{links: fetch.links}
  66. }
  67. fetch := &subscriptionFetch{done: make(chan struct{})}
  68. subscriptionCache.inflight[rawURL] = fetch
  69. subscriptionCache.Unlock()
  70. defer func() {
  71. subscriptionCache.Lock()
  72. close(fetch.done)
  73. delete(subscriptionCache.inflight, rawURL)
  74. subscriptionCache.Unlock()
  75. }()
  76. links, err := doFetchSubscriptionLinks(rawURL)
  77. if err != nil {
  78. if ok {
  79. fetch.links = cached.links
  80. }
  81. return subscriptionFetchResult{links: fetch.links, fetched: true, err: err}
  82. }
  83. subscriptionCache.Lock()
  84. subscriptionCache.m[rawURL] = subscriptionCacheEntry{links: links, fetchedAt: time.Now()}
  85. trimSubscriptionCacheLocked(rawURL)
  86. subscriptionCache.Unlock()
  87. fetch.links = links
  88. return subscriptionFetchResult{links: links, fetched: true}
  89. }
  90. func trimSubscriptionCacheLocked(keep string) {
  91. for len(subscriptionCache.m) > subscriptionCacheCapacity {
  92. var oldestURL string
  93. var oldest time.Time
  94. for rawURL, entry := range subscriptionCache.m {
  95. if rawURL == keep {
  96. continue
  97. }
  98. if oldestURL == "" || entry.fetchedAt.Before(oldest) {
  99. oldestURL = rawURL
  100. oldest = entry.fetchedAt
  101. }
  102. }
  103. if oldestURL == "" {
  104. return
  105. }
  106. delete(subscriptionCache.m, oldestURL)
  107. }
  108. }
  109. // recordExternalSubscriptionFetch stamps status on every row holding this URL,
  110. // keyed by value because row ids churn on save and the cache is per URL.
  111. func recordExternalSubscriptionFetch(rawURL string, fetchErr error) {
  112. rawURL = strings.TrimSpace(rawURL)
  113. if rawURL == "" {
  114. return
  115. }
  116. lastFetchError := ""
  117. if fetchErr != nil {
  118. lastFetchError = fetchErr.Error()
  119. }
  120. if err := database.GetDB().
  121. Model(&model.ClientExternalLink{}).
  122. Where("kind = ? AND value = ?", model.ExternalLinkKindSubscription, rawURL).
  123. Updates(map[string]any{
  124. "last_fetch_at": time.Now().UnixMilli(),
  125. "last_fetch_error": lastFetchError,
  126. }).Error; err != nil {
  127. logger.Warningf("sub: recording fetch status for external subscription %q: %v", rawURL, err)
  128. }
  129. }
  130. func doFetchSubscriptionLinks(rawURL string) ([]string, error) {
  131. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil)
  132. if err != nil {
  133. return nil, err
  134. }
  135. // Some providers gate the link body on a known client User-Agent.
  136. req.Header.Set("User-Agent", "v2rayNG/1.8.5")
  137. resp, err := subscriptionHTTPClient.Do(req)
  138. if err != nil {
  139. return nil, err
  140. }
  141. defer resp.Body.Close()
  142. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  143. return nil, errBadStatus
  144. }
  145. body, err := io.ReadAll(io.LimitReader(resp.Body, subscriptionMaxBytes+1))
  146. if err != nil {
  147. return nil, err
  148. }
  149. if len(body) > subscriptionMaxBytes {
  150. return nil, errSubscriptionBodyTooLarge
  151. }
  152. return decodeSubscriptionBody(body), nil
  153. }
  154. var (
  155. errBadStatus = &subError{"non-2xx subscription response"}
  156. errSubscriptionBodyTooLarge = &subError{"subscription response body exceeds size limit"}
  157. )
  158. type subError struct{ msg string }
  159. func (e *subError) Error() string { return e.msg }
  160. // decodeSubscriptionBody handles the common base64-encoded newline list as well
  161. // as a plain-text body, returning only the lines that look like share links.
  162. func decodeSubscriptionBody(body []byte) []string {
  163. text := strings.TrimSpace(string(body))
  164. if text == "" {
  165. return nil
  166. }
  167. if decoded, ok := tryDecodeBase64Body(text); ok {
  168. text = strings.TrimSpace(decoded)
  169. }
  170. lines := strings.FieldsFunc(text, func(r rune) bool { return r == '\n' || r == '\r' })
  171. out := make([]string, 0, len(lines))
  172. for _, ln := range lines {
  173. ln = strings.TrimSpace(ln)
  174. if ln == "" || strings.HasPrefix(ln, "#") {
  175. continue
  176. }
  177. if strings.Contains(ln, "://") {
  178. out = append(out, ln)
  179. }
  180. }
  181. return out
  182. }
  183. func tryDecodeBase64Body(s string) (string, bool) {
  184. clean := strings.Map(func(r rune) rune {
  185. switch r {
  186. case ' ', '\n', '\r', '\t':
  187. return -1
  188. }
  189. return r
  190. }, s)
  191. if b, err := base64.StdEncoding.DecodeString(padBase64Sub(clean)); err == nil {
  192. return string(b), true
  193. }
  194. if b, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(clean, "=")); err == nil {
  195. return string(b), true
  196. }
  197. return "", false
  198. }