request_builder.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "slices"
  13. "time"
  14. "miniflux.app/v2/internal/botauth"
  15. "miniflux.app/v2/internal/proxyrotator"
  16. )
  17. const (
  18. defaultHTTPClientTimeout = 20 * time.Second
  19. defaultAcceptHeader = "application/xml, application/atom+xml, application/rss+xml, application/rdf+xml, application/feed+json, text/html, */*;q=0.9"
  20. )
  21. type RequestBuilder struct {
  22. headers http.Header
  23. clientProxyURL *url.URL
  24. clientTimeout time.Duration
  25. useClientProxy bool
  26. withoutRedirects bool
  27. ignoreTLSErrors bool
  28. disableHTTP2 bool
  29. disableCompression bool
  30. proxyRotator *proxyrotator.ProxyRotator
  31. feedProxyURL string
  32. }
  33. func NewRequestBuilder() *RequestBuilder {
  34. return &RequestBuilder{
  35. headers: make(http.Header),
  36. clientTimeout: defaultHTTPClientTimeout,
  37. }
  38. }
  39. func (r *RequestBuilder) WithHeader(key, value string) *RequestBuilder {
  40. r.headers.Set(key, value)
  41. return r
  42. }
  43. func (r *RequestBuilder) WithETag(etag string) *RequestBuilder {
  44. if etag != "" {
  45. r.headers.Set("If-None-Match", etag)
  46. }
  47. return r
  48. }
  49. func (r *RequestBuilder) WithLastModified(lastModified string) *RequestBuilder {
  50. if lastModified != "" {
  51. r.headers.Set("If-Modified-Since", lastModified)
  52. }
  53. return r
  54. }
  55. func (r *RequestBuilder) WithUserAgent(userAgent string, defaultUserAgent string) *RequestBuilder {
  56. if userAgent != "" {
  57. r.headers.Set("User-Agent", userAgent)
  58. } else {
  59. r.headers.Set("User-Agent", defaultUserAgent)
  60. }
  61. return r
  62. }
  63. func (r *RequestBuilder) WithCookie(cookie string) *RequestBuilder {
  64. if cookie != "" {
  65. r.headers.Set("Cookie", cookie)
  66. }
  67. return r
  68. }
  69. func (r *RequestBuilder) WithUsernameAndPassword(username, password string) *RequestBuilder {
  70. if username != "" && password != "" {
  71. r.headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
  72. }
  73. return r
  74. }
  75. func (r *RequestBuilder) WithProxyRotator(proxyRotator *proxyrotator.ProxyRotator) *RequestBuilder {
  76. r.proxyRotator = proxyRotator
  77. return r
  78. }
  79. func (r *RequestBuilder) WithCustomApplicationProxyURL(proxyURL *url.URL) *RequestBuilder {
  80. r.clientProxyURL = proxyURL
  81. return r
  82. }
  83. func (r *RequestBuilder) UseCustomApplicationProxyURL(value bool) *RequestBuilder {
  84. r.useClientProxy = value
  85. return r
  86. }
  87. func (r *RequestBuilder) WithCustomFeedProxyURL(proxyURL string) *RequestBuilder {
  88. r.feedProxyURL = proxyURL
  89. return r
  90. }
  91. func (r *RequestBuilder) WithTimeout(timeout time.Duration) *RequestBuilder {
  92. r.clientTimeout = timeout
  93. return r
  94. }
  95. func (r *RequestBuilder) WithoutRedirects() *RequestBuilder {
  96. r.withoutRedirects = true
  97. return r
  98. }
  99. func (r *RequestBuilder) DisableHTTP2(value bool) *RequestBuilder {
  100. r.disableHTTP2 = value
  101. return r
  102. }
  103. func (r *RequestBuilder) IgnoreTLSErrors(value bool) *RequestBuilder {
  104. r.ignoreTLSErrors = value
  105. return r
  106. }
  107. func (r *RequestBuilder) WithoutCompression() *RequestBuilder {
  108. r.disableCompression = true
  109. return r
  110. }
  111. func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, error) {
  112. transport := &http.Transport{
  113. Proxy: http.ProxyFromEnvironment,
  114. // Setting `DialContext` disables HTTP/2, this option forces the transport to try HTTP/2 regardless.
  115. ForceAttemptHTTP2: true,
  116. DialContext: (&net.Dialer{
  117. Timeout: 10 * time.Second, // Default is 30s.
  118. KeepAlive: 15 * time.Second, // Default is 30s.
  119. }).DialContext,
  120. MaxIdleConns: 50, // Default is 100.
  121. IdleConnTimeout: 10 * time.Second, // Default is 90s.
  122. }
  123. if r.ignoreTLSErrors {
  124. // Add insecure ciphers if we are ignoring TLS errors. This allows to connect to badly configured servers anyway
  125. ciphers := slices.Concat(tls.CipherSuites(), tls.InsecureCipherSuites())
  126. cipherSuites := make([]uint16, 0, len(ciphers))
  127. for _, cipher := range ciphers {
  128. cipherSuites = append(cipherSuites, cipher.ID)
  129. }
  130. transport.TLSClientConfig = &tls.Config{
  131. CipherSuites: cipherSuites,
  132. InsecureSkipVerify: true,
  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: r.clientTimeout,
  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. if r.disableCompression {
  174. req.Header.Set("Accept-Encoding", "identity")
  175. } else {
  176. req.Header.Set("Accept-Encoding", "br, gzip")
  177. }
  178. // Set default Accept header if not already set.
  179. // Note that for the media proxy requests, we need to forward the browser Accept header.
  180. if req.Header.Get("Accept") == "" {
  181. req.Header.Set("Accept", defaultAcceptHeader)
  182. }
  183. if botauth.GlobalInstance != nil {
  184. botauth.GlobalInstance.SignRequest(req)
  185. }
  186. req.Header.Set("Connection", "close")
  187. slog.Debug("Making outgoing request", slog.Group("request",
  188. slog.String("method", req.Method),
  189. slog.String("url", req.URL.String()),
  190. slog.Any("headers", req.Header),
  191. slog.Bool("without_redirects", r.withoutRedirects),
  192. slog.Bool("use_app_client_proxy", r.useClientProxy),
  193. slog.String("client_proxy_url", clientProxyURLRedacted),
  194. slog.Bool("ignore_tls_errors", r.ignoreTLSErrors),
  195. slog.Bool("disable_http2", r.disableHTTP2),
  196. ))
  197. return client.Do(req)
  198. }