response_handler.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. )
  19. type ResponseHandler struct {
  20. httpResponse *http.Response
  21. clientErr error
  22. }
  23. func NewResponseHandler(httpResponse *http.Response, clientErr error) *ResponseHandler {
  24. return &ResponseHandler{httpResponse: httpResponse, clientErr: clientErr}
  25. }
  26. func (r *ResponseHandler) EffectiveURL() string {
  27. return r.httpResponse.Request.URL.String()
  28. }
  29. func (r *ResponseHandler) ContentType() string {
  30. return r.httpResponse.Header.Get("Content-Type")
  31. }
  32. func (r *ResponseHandler) LastModified() string {
  33. // Ignore caching headers for feeds that do not want any cache.
  34. if r.httpResponse.Header.Get("Expires") == "0" {
  35. return ""
  36. }
  37. return r.httpResponse.Header.Get("Last-Modified")
  38. }
  39. func (r *ResponseHandler) ETag() string {
  40. // Ignore caching headers for feeds that do not want any cache.
  41. if r.httpResponse.Header.Get("Expires") == "0" {
  42. return ""
  43. }
  44. return r.httpResponse.Header.Get("ETag")
  45. }
  46. func (r *ResponseHandler) ParseRetryDelay() int {
  47. retryAfterHeaderValue := r.httpResponse.Header.Get("Retry-After")
  48. if retryAfterHeaderValue != "" {
  49. // First, try to parse as an integer (number of seconds)
  50. if seconds, err := strconv.Atoi(retryAfterHeaderValue); err == nil {
  51. return seconds
  52. }
  53. // If not an integer, try to parse as an HTTP-date
  54. if t, err := time.Parse(time.RFC1123, retryAfterHeaderValue); err == nil {
  55. return int(time.Until(t).Seconds())
  56. }
  57. }
  58. return 0
  59. }
  60. func (r *ResponseHandler) IsRateLimited() bool {
  61. return r.httpResponse != nil && r.httpResponse.StatusCode == http.StatusTooManyRequests
  62. }
  63. func (r *ResponseHandler) IsModified(lastEtagValue, lastModifiedValue string) bool {
  64. if r.httpResponse.StatusCode == http.StatusNotModified {
  65. return false
  66. }
  67. if r.ETag() != "" {
  68. return r.ETag() != lastEtagValue
  69. }
  70. if r.LastModified() != "" {
  71. return r.LastModified() != lastModifiedValue
  72. }
  73. return true
  74. }
  75. func (r *ResponseHandler) Close() {
  76. if r.httpResponse != nil && r.httpResponse.Body != nil && r.clientErr == nil {
  77. r.httpResponse.Body.Close()
  78. }
  79. }
  80. func (r *ResponseHandler) getReader(maxBodySize int64) io.ReadCloser {
  81. contentEncoding := strings.ToLower(r.httpResponse.Header.Get("Content-Encoding"))
  82. slog.Debug("Request response",
  83. slog.String("effective_url", r.EffectiveURL()),
  84. slog.String("content_length", r.httpResponse.Header.Get("Content-Length")),
  85. slog.String("content_encoding", contentEncoding),
  86. slog.String("content_type", r.httpResponse.Header.Get("Content-Type")),
  87. )
  88. reader := r.httpResponse.Body
  89. switch contentEncoding {
  90. case "br":
  91. reader = NewBrotliReadCloser(r.httpResponse.Body)
  92. case "gzip":
  93. reader = NewGzipReadCloser(r.httpResponse.Body)
  94. }
  95. return http.MaxBytesReader(nil, reader, maxBodySize)
  96. }
  97. func (r *ResponseHandler) Body(maxBodySize int64) io.ReadCloser {
  98. return r.getReader(maxBodySize)
  99. }
  100. func (r *ResponseHandler) ReadBody(maxBodySize int64) ([]byte, *locale.LocalizedErrorWrapper) {
  101. limitedReader := r.getReader(maxBodySize)
  102. buffer, err := io.ReadAll(limitedReader)
  103. if err != nil && err != io.EOF {
  104. if err, ok := err.(*http.MaxBytesError); ok {
  105. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: response body too large: %d bytes", err.Limit), "error.http_response_too_large")
  106. }
  107. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unable to read response body: %w", err), "error.http_body_read", err)
  108. }
  109. if len(buffer) == 0 {
  110. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: empty response body"), "error.http_empty_response_body")
  111. }
  112. return buffer, nil
  113. }
  114. func (r *ResponseHandler) LocalizedError() *locale.LocalizedErrorWrapper {
  115. if r.clientErr != nil {
  116. switch {
  117. case isSSLError(r.clientErr):
  118. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.tls_error", r.clientErr)
  119. case isNetworkError(r.clientErr):
  120. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.network_operation", r.clientErr)
  121. case os.IsTimeout(r.clientErr):
  122. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.network_timeout", r.clientErr)
  123. case errors.Is(r.clientErr, io.EOF):
  124. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.http_empty_response")
  125. default:
  126. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.http_client_error", r.clientErr)
  127. }
  128. }
  129. switch r.httpResponse.StatusCode {
  130. case http.StatusUnauthorized:
  131. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: access unauthorized (401 status code)"), "error.http_not_authorized")
  132. case http.StatusForbidden:
  133. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: access forbidden (403 status code)"), "error.http_forbidden")
  134. case http.StatusTooManyRequests:
  135. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: too many requests (429 status code)"), "error.http_too_many_requests")
  136. case http.StatusNotFound, http.StatusGone:
  137. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: resource not found (%d status code)", r.httpResponse.StatusCode), "error.http_resource_not_found")
  138. case http.StatusInternalServerError:
  139. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: remote server error (%d status code)", r.httpResponse.StatusCode), "error.http_internal_server_error")
  140. case http.StatusBadGateway:
  141. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: bad gateway (%d status code)", r.httpResponse.StatusCode), "error.http_bad_gateway")
  142. case http.StatusServiceUnavailable:
  143. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: service unavailable (%d status code)", r.httpResponse.StatusCode), "error.http_service_unavailable")
  144. case http.StatusGatewayTimeout:
  145. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: gateway timeout (%d status code)", r.httpResponse.StatusCode), "error.http_gateway_timeout")
  146. }
  147. if r.httpResponse.StatusCode >= 400 {
  148. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unexpected status code (%d status code)", r.httpResponse.StatusCode), "error.http_unexpected_status_code", r.httpResponse.StatusCode)
  149. }
  150. if r.httpResponse.StatusCode != 304 {
  151. // Content-Length = -1 when no Content-Length header is sent.
  152. if r.httpResponse.ContentLength == 0 {
  153. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: empty response body"), "error.http_empty_response_body")
  154. }
  155. }
  156. return nil
  157. }
  158. func isNetworkError(err error) bool {
  159. if _, ok := err.(*url.Error); ok {
  160. return true
  161. }
  162. if err == io.EOF {
  163. return true
  164. }
  165. var opErr *net.OpError
  166. if ok := errors.As(err, &opErr); ok {
  167. return true
  168. }
  169. return false
  170. }
  171. func isSSLError(err error) bool {
  172. var certErr x509.UnknownAuthorityError
  173. if errors.As(err, &certErr) {
  174. return true
  175. }
  176. var hostErr x509.HostnameError
  177. if errors.As(err, &hostErr) {
  178. return true
  179. }
  180. var algErr x509.InsecureAlgorithmError
  181. return errors.As(err, &algErr)
  182. }