response_handler.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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) IsRedirect() bool {
  76. return r.httpResponse != nil &&
  77. (r.httpResponse.StatusCode == http.StatusMovedPermanently ||
  78. r.httpResponse.StatusCode == http.StatusFound ||
  79. r.httpResponse.StatusCode == http.StatusSeeOther ||
  80. r.httpResponse.StatusCode == http.StatusTemporaryRedirect ||
  81. r.httpResponse.StatusCode == http.StatusPermanentRedirect)
  82. }
  83. func (r *ResponseHandler) Close() {
  84. if r.httpResponse != nil && r.httpResponse.Body != nil && r.clientErr == nil {
  85. r.httpResponse.Body.Close()
  86. }
  87. }
  88. func (r *ResponseHandler) getReader(maxBodySize int64) io.ReadCloser {
  89. contentEncoding := strings.ToLower(r.httpResponse.Header.Get("Content-Encoding"))
  90. slog.Debug("Request response",
  91. slog.String("effective_url", r.EffectiveURL()),
  92. slog.String("content_length", r.httpResponse.Header.Get("Content-Length")),
  93. slog.String("content_encoding", contentEncoding),
  94. slog.String("content_type", r.httpResponse.Header.Get("Content-Type")),
  95. )
  96. reader := r.httpResponse.Body
  97. switch contentEncoding {
  98. case "br":
  99. reader = NewBrotliReadCloser(r.httpResponse.Body)
  100. case "gzip":
  101. reader = NewGzipReadCloser(r.httpResponse.Body)
  102. }
  103. return http.MaxBytesReader(nil, reader, maxBodySize)
  104. }
  105. func (r *ResponseHandler) Body(maxBodySize int64) io.ReadCloser {
  106. return r.getReader(maxBodySize)
  107. }
  108. func (r *ResponseHandler) ReadBody(maxBodySize int64) ([]byte, *locale.LocalizedErrorWrapper) {
  109. limitedReader := r.getReader(maxBodySize)
  110. buffer, err := io.ReadAll(limitedReader)
  111. if err != nil && err != io.EOF {
  112. if err, ok := err.(*http.MaxBytesError); ok {
  113. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: response body too large: %d bytes", err.Limit), "error.http_response_too_large")
  114. }
  115. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unable to read response body: %w", err), "error.http_body_read", err)
  116. }
  117. if len(buffer) == 0 {
  118. return nil, locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: empty response body"), "error.http_empty_response_body")
  119. }
  120. return buffer, nil
  121. }
  122. func (r *ResponseHandler) LocalizedError() *locale.LocalizedErrorWrapper {
  123. if r.clientErr != nil {
  124. switch {
  125. case isSSLError(r.clientErr):
  126. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.tls_error", r.clientErr)
  127. case isNetworkError(r.clientErr):
  128. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.network_operation", r.clientErr)
  129. case os.IsTimeout(r.clientErr):
  130. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.network_timeout", r.clientErr)
  131. case errors.Is(r.clientErr, io.EOF):
  132. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.http_empty_response")
  133. default:
  134. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: %w", r.clientErr), "error.http_client_error", r.clientErr)
  135. }
  136. }
  137. switch r.httpResponse.StatusCode {
  138. case http.StatusUnauthorized:
  139. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: access unauthorized (401 status code)"), "error.http_not_authorized")
  140. case http.StatusForbidden:
  141. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: access forbidden (403 status code)"), "error.http_forbidden")
  142. case http.StatusTooManyRequests:
  143. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: too many requests (429 status code)"), "error.http_too_many_requests")
  144. case http.StatusNotFound, http.StatusGone:
  145. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: resource not found (%d status code)", r.httpResponse.StatusCode), "error.http_resource_not_found")
  146. case http.StatusInternalServerError:
  147. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: remote server error (%d status code)", r.httpResponse.StatusCode), "error.http_internal_server_error")
  148. case http.StatusBadGateway:
  149. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: bad gateway (%d status code)", r.httpResponse.StatusCode), "error.http_bad_gateway")
  150. case http.StatusServiceUnavailable:
  151. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: service unavailable (%d status code)", r.httpResponse.StatusCode), "error.http_service_unavailable")
  152. case http.StatusGatewayTimeout:
  153. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: gateway timeout (%d status code)", r.httpResponse.StatusCode), "error.http_gateway_timeout")
  154. }
  155. if r.httpResponse.StatusCode >= 400 {
  156. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: unexpected status code (%d status code)", r.httpResponse.StatusCode), "error.http_unexpected_status_code", r.httpResponse.StatusCode)
  157. }
  158. if r.httpResponse.StatusCode != 304 {
  159. // Content-Length = -1 when no Content-Length header is sent.
  160. if r.httpResponse.ContentLength == 0 {
  161. return locale.NewLocalizedErrorWrapper(fmt.Errorf("fetcher: empty response body"), "error.http_empty_response_body")
  162. }
  163. }
  164. return nil
  165. }
  166. func isNetworkError(err error) bool {
  167. if _, ok := err.(*url.Error); ok {
  168. return true
  169. }
  170. if err == io.EOF {
  171. return true
  172. }
  173. var opErr *net.OpError
  174. if ok := errors.As(err, &opErr); ok {
  175. return true
  176. }
  177. return false
  178. }
  179. func isSSLError(err error) bool {
  180. var certErr x509.UnknownAuthorityError
  181. if errors.As(err, &certErr) {
  182. return true
  183. }
  184. var hostErr x509.HostnameError
  185. if errors.As(err, &hostErr) {
  186. return true
  187. }
  188. var algErr x509.InsecureAlgorithmError
  189. return errors.As(err, &algErr)
  190. }