request_builder.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/tls"
  6. "encoding/base64"
  7. "fmt"
  8. "log/slog"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "time"
  13. "miniflux.app/v2/internal/proxyrotator"
  14. )
  15. const (
  16. defaultHTTPClientTimeout = 20
  17. defaultHTTPClientMaxBodySize = 15 * 1024 * 1024
  18. defaultAcceptHeader = "application/xml, application/atom+xml, application/rss+xml, application/rdf+xml, application/feed+json, text/html, */*;q=0.9"
  19. )
  20. type RequestBuilder struct {
  21. headers http.Header
  22. clientProxyURL *url.URL
  23. clientTimeout int
  24. useClientProxy bool
  25. withoutRedirects bool
  26. ignoreTLSErrors bool
  27. disableHTTP2 bool
  28. proxyRotator *proxyrotator.ProxyRotator
  29. feedProxyURL string
  30. }
  31. func NewRequestBuilder() *RequestBuilder {
  32. return &RequestBuilder{
  33. headers: make(http.Header),
  34. clientTimeout: defaultHTTPClientTimeout,
  35. }
  36. }
  37. func (r *RequestBuilder) WithHeader(key, value string) *RequestBuilder {
  38. r.headers.Set(key, value)
  39. return r
  40. }
  41. func (r *RequestBuilder) WithETag(etag string) *RequestBuilder {
  42. if etag != "" {
  43. r.headers.Set("If-None-Match", etag)
  44. }
  45. return r
  46. }
  47. func (r *RequestBuilder) WithLastModified(lastModified string) *RequestBuilder {
  48. if lastModified != "" {
  49. r.headers.Set("If-Modified-Since", lastModified)
  50. }
  51. return r
  52. }
  53. func (r *RequestBuilder) WithUserAgent(userAgent string, defaultUserAgent string) *RequestBuilder {
  54. if userAgent != "" {
  55. r.headers.Set("User-Agent", userAgent)
  56. } else {
  57. r.headers.Set("User-Agent", defaultUserAgent)
  58. }
  59. return r
  60. }
  61. func (r *RequestBuilder) WithCookie(cookie string) *RequestBuilder {
  62. if cookie != "" {
  63. r.headers.Set("Cookie", cookie)
  64. }
  65. return r
  66. }
  67. func (r *RequestBuilder) WithUsernameAndPassword(username, password string) *RequestBuilder {
  68. if username != "" && password != "" {
  69. r.headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
  70. }
  71. return r
  72. }
  73. func (r *RequestBuilder) WithProxyRotator(proxyRotator *proxyrotator.ProxyRotator) *RequestBuilder {
  74. r.proxyRotator = proxyRotator
  75. return r
  76. }
  77. func (r *RequestBuilder) WithCustomApplicationProxyURL(proxyURL *url.URL) *RequestBuilder {
  78. r.clientProxyURL = proxyURL
  79. return r
  80. }
  81. func (r *RequestBuilder) UseCustomApplicationProxyURL(value bool) *RequestBuilder {
  82. r.useClientProxy = value
  83. return r
  84. }
  85. func (r *RequestBuilder) WithCustomFeedProxyURL(proxyURL string) *RequestBuilder {
  86. r.feedProxyURL = proxyURL
  87. return r
  88. }
  89. func (r *RequestBuilder) WithTimeout(timeout int) *RequestBuilder {
  90. r.clientTimeout = timeout
  91. return r
  92. }
  93. func (r *RequestBuilder) WithoutRedirects() *RequestBuilder {
  94. r.withoutRedirects = true
  95. return r
  96. }
  97. func (r *RequestBuilder) DisableHTTP2(value bool) *RequestBuilder {
  98. r.disableHTTP2 = value
  99. return r
  100. }
  101. func (r *RequestBuilder) IgnoreTLSErrors(value bool) *RequestBuilder {
  102. r.ignoreTLSErrors = value
  103. return r
  104. }
  105. func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, error) {
  106. // We get the safe ciphers
  107. ciphers := tls.CipherSuites()
  108. if r.ignoreTLSErrors {
  109. // and the insecure ones if we are ignoring TLS errors. This allows to connect to badly configured servers anyway
  110. ciphers = append(ciphers, tls.InsecureCipherSuites()...)
  111. }
  112. cipherSuites := make([]uint16, 0, len(ciphers))
  113. for _, cipher := range ciphers {
  114. cipherSuites = append(cipherSuites, cipher.ID)
  115. }
  116. transport := &http.Transport{
  117. Proxy: http.ProxyFromEnvironment,
  118. // Setting `DialContext` disables HTTP/2, this option forces the transport to try HTTP/2 regardless.
  119. ForceAttemptHTTP2: true,
  120. DialContext: (&net.Dialer{
  121. // Default is 30s.
  122. Timeout: 10 * time.Second,
  123. // Default is 30s.
  124. KeepAlive: 15 * time.Second,
  125. }).DialContext,
  126. // Default is 100.
  127. MaxIdleConns: 50,
  128. // Default is 90s.
  129. IdleConnTimeout: 10 * time.Second,
  130. TLSClientConfig: &tls.Config{
  131. CipherSuites: cipherSuites,
  132. InsecureSkipVerify: r.ignoreTLSErrors,
  133. },
  134. }
  135. if r.disableHTTP2 {
  136. transport.ForceAttemptHTTP2 = false
  137. // https://pkg.go.dev/net/http#hdr-HTTP_2
  138. // Programs that must disable HTTP/2 can do so by setting [Transport.TLSNextProto] (for clients) or [Server.TLSNextProto] (for servers) to a non-nil, empty map.
  139. transport.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
  140. }
  141. var clientProxyURL *url.URL
  142. switch {
  143. case r.feedProxyURL != "":
  144. var err error
  145. clientProxyURL, err = url.Parse(r.feedProxyURL)
  146. if err != nil {
  147. return nil, fmt.Errorf(`fetcher: invalid feed proxy URL %q: %w`, r.feedProxyURL, err)
  148. }
  149. case r.useClientProxy && r.clientProxyURL != nil:
  150. clientProxyURL = r.clientProxyURL
  151. case r.proxyRotator != nil && r.proxyRotator.HasProxies():
  152. clientProxyURL = r.proxyRotator.GetNextProxy()
  153. }
  154. var clientProxyURLRedacted string
  155. if clientProxyURL != nil {
  156. transport.Proxy = http.ProxyURL(clientProxyURL)
  157. clientProxyURLRedacted = clientProxyURL.Redacted()
  158. }
  159. client := &http.Client{
  160. Timeout: time.Duration(r.clientTimeout) * time.Second,
  161. }
  162. if r.withoutRedirects {
  163. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  164. return http.ErrUseLastResponse
  165. }
  166. }
  167. client.Transport = transport
  168. req, err := http.NewRequest("GET", requestURL, nil)
  169. if err != nil {
  170. return nil, err
  171. }
  172. req.Header = r.headers
  173. req.Header.Set("Accept-Encoding", "br, gzip")
  174. req.Header.Set("Accept", defaultAcceptHeader)
  175. req.Header.Set("Connection", "close")
  176. slog.Debug("Making outgoing request", slog.Group("request",
  177. slog.String("method", req.Method),
  178. slog.String("url", req.URL.String()),
  179. slog.Any("headers", req.Header),
  180. slog.Bool("without_redirects", r.withoutRedirects),
  181. slog.Bool("use_app_client_proxy", r.useClientProxy),
  182. slog.String("client_proxy_url", clientProxyURLRedacted),
  183. slog.Bool("ignore_tls_errors", r.ignoreTLSErrors),
  184. slog.Bool("disable_http2", r.disableHTTP2),
  185. ))
  186. return client.Do(req)
  187. }