external_subscription.go 7.3 KB

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