response_handler.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fetcher // import "miniflux.app/v2/internal/reader/fetcher"
  4. import (
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "log/slog"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "miniflux.app/v2/internal/locale"
  18. "miniflux.app/v2/internal/urllib"
  19. )
  20. type ResponseHandler struct {
  21. httpResponse *http.Response
  22. clientErr error
  23. }
  24. func NewResponseHandler(httpResponse *http.Response, clientErr error) *ResponseHandler {
  25. return &ResponseHandler{httpResponse: httpResponse, clientErr: clientErr}
  26. }
  27. func (r *ResponseHandler) EffectiveURL() string {
  28. return r.httpResponse.Request.URL.String()
  29. }
  30. func (r *ResponseHandler) ContentType() string {
  31. return r.httpResponse.Header.Get("Content-Type")
  32. }
  33. func (r *ResponseHandler) LastModified() string {
  34. // Ignore caching headers for feeds that do not want any cache.
  35. if r.httpResponse.Header.Get("Expires") == "0" {
  36. return ""
  37. }
  38. return r.httpResponse.Header.Get("Last-Modified")
  39. }
  40. func (r *ResponseHandler) ETag() string {
  41. // Ignore caching headers for feeds that do not want any cache.
  42. if r.httpResponse.Header.Get("Expires") == "0" {
  43. return ""
  44. }
  45. return r.httpResponse.Header.Get("ETag")
  46. }
  47. func (r *ResponseHandler) Expires() time.Duration {
  48. expiresHeaderValue := r.httpResponse.Header.Get("Expires")
  49. if expiresHeaderValue != "" {
  50. t, err := time.Parse(time.RFC1123, expiresHeaderValue)
  51. if err == nil {
  52. // This rounds up to the next minute by rounding down and just adding a minute.
  53. return time.Until(t).Truncate(time.Minute) + time.Minute
  54. }
  55. }
  56. return 0
  57. }
  58. func (r *ResponseHandler) CacheControlMaxAge() time.Duration {
  59. cacheControlHeaderValue := r.httpResponse.Header.Get("Cache-Control")
  60. if cacheControlHeaderValue != "" {
  61. for directive := range strings.SplitSeq(cacheControlHeaderValue, ",") {
  62. if after, ok := strings.CutPrefix(strings.TrimSpace(directive), "max-age="); ok {
  63. if maxAge, err := strconv.Atoi(after); err == nil {
  64. return time.Duration(maxAge) * time.Second
  65. }
  66. }
  67. }
  68. }
  69. return 0
  70. }
  71. func (r *ResponseHandler) ParseRetryDelay() time.Duration {
  72. retryAfterHeaderValue := r.httpResponse.Header.Get("Retry-After")
  73. if retryAfterHeaderValue != "" {
  74. // First, try to parse as an integer (number of seconds)
  75. if seconds, err := strconv.Atoi(retryAfterHeaderValue); err == nil {
  76. return time.Duration(seconds) * time.Second
  77. }
  78. // If not an integer, try to parse as an HTTP-date
  79. if t, err := time.Parse(time.RFC1123, retryAfterHeaderValue); err == nil {
  80. return time.Until(t).Truncate(time.Second)
  81. }
  82. }
  83. return 0
  84. }
  85. func (r *ResponseHandler) IsRateLimited() bool {
  86. return r.httpResponse != nil && r.httpResponse.StatusCode == http.StatusTooManyRequests
  87. }
  88. func (r *ResponseHandler) IsModified(lastEtagValue, lastModifiedValue string) bool {
  89. if r.httpResponse.StatusCode == http.StatusNotModified {
  90. return false
  91. }
  92. if r.ETag() != "" {
  93. return r.ETag() != lastEtagValue
  94. }
  95. if r.LastModified() != "" {
  96. return r.LastModified() != lastModifiedValue
  97. }
  98. return true
  99. }
  100. func (r *ResponseHandler) IsRedirect() bool {
  101. return r.httpResponse != nil &&
  102. (r.httpResponse.StatusCode == http.StatusMovedPermanently ||
  103. r.httpResponse.StatusCode == http.StatusFound ||
  104. r.httpResponse.StatusCode == http.StatusSeeOther ||
  105. r.httpResponse.StatusCode == http.StatusTemporaryRedirect ||
  106. r.httpResponse.StatusCode == http.StatusPermanentRedirect)
  107. }
  108. func (r *ResponseHandler) Close() {
  109. if r.httpResponse != nil && r.httpResponse.Body != nil {
  110. r.httpResponse.Body.Close()
  111. }
  112. }
  113. func (r *ResponseHandler) getReader(maxBodySize int64) io.ReadCloser {
  114. contentEncoding := strings.ToLower(r.httpResponse.Header.Get("Content-Encoding"))
  115. slog.Debug("Request response",
  116. slog.String("effective_url", urllib.RedactedURL(r.EffectiveURL())),
  117. slog.String("content_length", r.httpResponse.Header.Get("Content-Length")),
  118. slog.String("content_encoding", contentEncoding),
  119. slog.String("content_type", r.httpResponse.Header.Get("Content-Type")),
  120. )
  121. reader := r.httpResponse.Body
  122. switch contentEncoding {
  123. case "br":
  124. reader = NewBrotliReadCloser(reader)
  125. case "gzip":
  126. reader = NewGzipReadCloser(reader)
  127. }
  128. return http.MaxBytesReader(nil, reader, maxBodySize)
  129. }
  130. func (r *ResponseHandler) Body(maxBodySize int64) io.ReadCloser {
  131. return r.getReader(maxBodySize)
  132. }
  133. func (r *ResponseHandler) ReadBody(maxBodySize int64) ([]byte, *locale.LocalizedErrorWrapper) {
  134. limitedReader := r.getReader(maxBodySize)
  135. buffer, err := io.ReadAll(limitedReader)
  136. if err != nil && err != io.EOF {
  137. if err, ok := err.(*http.MaxBytesError); ok {
  138. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: response body too large: %d bytes", err.Limit), "error.http_response_too_large")
  139. }
  140. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unable to read response body: %w", err), "error.http_body_read", err)
  141. }
  142. if len(buffer) == 0 {
  143. return nil, locale.NewLocalizedErrorWrapper(errors.New("fetcher: empty response body"), "error.http_empty_response_body")
  144. }
  145. return buffer, nil
  146. }
  147. func (r *ResponseHandler) LocalizedError() *locale.LocalizedErrorWrapper {
  148. if r.clientErr != nil {
  149. err := fmt.Errorf("fetcher: %w", r.clientErr)
  150. switch {
  151. case isSSLError(r.clientErr):
  152. return locale.NewLocalizedErrorWrapper(err, "error.tls_error", r.clientErr)
  153. case isNetworkError(r.clientErr):
  154. return locale.NewLocalizedErrorWrapper(err, "error.network_operation", r.clientErr)
  155. case os.IsTimeout(r.clientErr):
  156. return locale.NewLocalizedErrorWrapper(err, "error.network_timeout", r.clientErr)
  157. case errors.Is(r.clientErr, io.EOF):
  158. return locale.NewLocalizedErrorWrapper(err, "error.http_empty_response")
  159. default:
  160. return locale.NewLocalizedErrorWrapper(err, "error.http_client_error", r.clientErr)
  161. }
  162. }
  163. if r.isCloudflareChallenge() {
  164. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: blocked by Cloudflare challenge (%d status code)", r.httpResponse.StatusCode), "error.http_cloudflare_challenge")
  165. }
  166. switch r.httpResponse.StatusCode {
  167. case http.StatusUnauthorized:
  168. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: access unauthorized (401 status code)"), "error.http_not_authorized")
  169. case http.StatusForbidden:
  170. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: access forbidden (403 status code)"), "error.http_forbidden")
  171. case http.StatusTooManyRequests:
  172. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: too many requests (429 status code)"), "error.http_too_many_requests")
  173. case http.StatusNotFound:
  174. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: resource not found (404 status code)"), "error.http_resource_not_found")
  175. case http.StatusGone:
  176. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: resource not found (410 status code)"), "error.http_resource_not_found")
  177. case http.StatusInternalServerError:
  178. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: remote server error (500 status code)"), "error.http_internal_server_error")
  179. case http.StatusBadGateway:
  180. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: bad gateway (502 status code)"), "error.http_bad_gateway")
  181. case http.StatusServiceUnavailable:
  182. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: service unavailable (503 status code)"), "error.http_service_unavailable")
  183. case http.StatusGatewayTimeout:
  184. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: gateway timeout (504 status code)"), "error.http_gateway_timeout")
  185. }
  186. if r.httpResponse.StatusCode >= 400 {
  187. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unexpected status code (%d status code)", r.httpResponse.StatusCode), "error.http_unexpected_status_code", r.httpResponse.StatusCode)
  188. }
  189. if r.httpResponse.StatusCode != 304 {
  190. // Content-Length = -1 when no Content-Length header is sent.
  191. if r.httpResponse.ContentLength == 0 {
  192. return locale.NewLocalizedErrorWrapper(errors.New("fetcher: empty response body"), "error.http_empty_response_body")
  193. }
  194. }
  195. return nil
  196. }
  197. // isCloudflareChallenge reports whether the response looks like a Cloudflare
  198. // bot/captcha interstitial rather than a genuine error from the origin. It
  199. // relies on response headers only (no body read) to keep the check cheap and
  200. // to run before ReadBody is called.
  201. func (r *ResponseHandler) isCloudflareChallenge() bool {
  202. if r.httpResponse == nil {
  203. return false
  204. }
  205. return r.httpResponse.StatusCode == http.StatusForbidden &&
  206. strings.EqualFold(r.httpResponse.Header.Get("cf-mitigated"), "challenge") &&
  207. strings.HasPrefix(strings.ToLower(r.ContentType()), "text/html")
  208. }
  209. func isNetworkError(err error) bool {
  210. if _, ok := errors.AsType[*url.Error](err); ok {
  211. return true
  212. }
  213. if errors.Is(err, io.EOF) {
  214. return true
  215. }
  216. if _, ok := errors.AsType[*net.OpError](err); ok {
  217. return true
  218. }
  219. return false
  220. }
  221. func isSSLError(err error) bool {
  222. if _, ok := errors.AsType[x509.UnknownAuthorityError](err); ok {
  223. return true
  224. }
  225. if _, ok := errors.AsType[x509.HostnameError](err); ok {
  226. return true
  227. }
  228. if _, ok := errors.AsType[x509.InsecureAlgorithmError](err); ok {
  229. return true
  230. }
  231. return false
  232. }