external_subscription.go 4.8 KB

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