response_handler.go 6.4 KB

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