request_builder.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. "context"
  6. "crypto/tls"
  7. "encoding/base64"
  8. "errors"
  9. "fmt"
  10. "log/slog"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "slices"
  15. "strings"
  16. "syscall"
  17. "time"
  18. "miniflux.app/v2/internal/config"
  19. "miniflux.app/v2/internal/proxyrotator"
  20. "miniflux.app/v2/internal/urllib"
  21. "golang.org/x/net/http/httpproxy"
  22. )
  23. const (
  24. defaultHTTPClientTimeout = 20 * time.Second
  25. defaultAcceptHeader = "application/xml,application/atom+xml,application/rss+xml,application/rdf+xml,application/feed+json,text/html,*/*;q=0.9"
  26. )
  27. var (
  28. ErrHostnameResolution = errors.New("fetcher: unable to resolve request hostname")
  29. ErrPrivateNetworkHost = errors.New("fetcher: refusing to access private network host")
  30. )
  31. type RequestBuilder struct {
  32. headers http.Header
  33. clientProxyURL *url.URL
  34. clientTimeout time.Duration
  35. useClientProxy bool
  36. withoutRedirects bool
  37. ignoreTLSErrors bool
  38. disableHTTP2 bool
  39. disableCompression bool
  40. proxyRotator *proxyrotator.ProxyRotator
  41. feedProxyURL string
  42. }
  43. func NewRequestBuilder() *RequestBuilder {
  44. return &RequestBuilder{
  45. headers: make(http.Header),
  46. clientTimeout: defaultHTTPClientTimeout,
  47. }
  48. }
  49. // Clone returns an independent copy of the builder. Mutating the copy (for
  50. // example to disable redirects for a single request) leaves the original
  51. // untouched.
  52. func (r *RequestBuilder) Clone() *RequestBuilder {
  53. clone := *r
  54. clone.headers = r.headers.Clone()
  55. return &clone
  56. }
  57. func (r *RequestBuilder) WithHeader(key, value string) *RequestBuilder {
  58. r.headers.Set(key, value)
  59. return r
  60. }
  61. func (r *RequestBuilder) WithETag(etag string) *RequestBuilder {
  62. if etag != "" {
  63. r.headers.Set("If-None-Match", etag)
  64. }
  65. return r
  66. }
  67. func (r *RequestBuilder) WithLastModified(lastModified string) *RequestBuilder {
  68. if lastModified != "" {
  69. r.headers.Set("If-Modified-Since", lastModified)
  70. }
  71. return r
  72. }
  73. func (r *RequestBuilder) WithUserAgent(userAgent string, defaultUserAgent string) *RequestBuilder {
  74. if userAgent != "" {
  75. r.headers.Set("User-Agent", userAgent)
  76. } else {
  77. r.headers.Set("User-Agent", defaultUserAgent)
  78. }
  79. return r
  80. }
  81. func (r *RequestBuilder) WithCookie(cookie string) *RequestBuilder {
  82. if cookie != "" {
  83. r.headers.Set("Cookie", cookie)
  84. }
  85. return r
  86. }
  87. func (r *RequestBuilder) WithUsernameAndPassword(username, password string) *RequestBuilder {
  88. if username != "" && password != "" {
  89. r.headers.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
  90. }
  91. return r
  92. }
  93. func (r *RequestBuilder) WithProxyRotator(proxyRotator *proxyrotator.ProxyRotator) *RequestBuilder {
  94. r.proxyRotator = proxyRotator
  95. return r
  96. }
  97. func (r *RequestBuilder) WithCustomApplicationProxyURL(proxyURL *url.URL) *RequestBuilder {
  98. r.clientProxyURL = proxyURL
  99. return r
  100. }
  101. func (r *RequestBuilder) UseCustomApplicationProxyURL(value bool) *RequestBuilder {
  102. r.useClientProxy = value
  103. return r
  104. }
  105. func (r *RequestBuilder) WithCustomFeedProxyURL(proxyURL string) *RequestBuilder {
  106. r.feedProxyURL = proxyURL
  107. return r
  108. }
  109. func (r *RequestBuilder) WithTimeout(timeout time.Duration) *RequestBuilder {
  110. r.clientTimeout = timeout
  111. return r
  112. }
  113. func (r *RequestBuilder) WithoutRedirects() *RequestBuilder {
  114. r.withoutRedirects = true
  115. return r
  116. }
  117. func (r *RequestBuilder) DisableHTTP2(value bool) *RequestBuilder {
  118. r.disableHTTP2 = value
  119. return r
  120. }
  121. func (r *RequestBuilder) IgnoreTLSErrors(value bool) *RequestBuilder {
  122. r.ignoreTLSErrors = value
  123. return r
  124. }
  125. func (r *RequestBuilder) WithoutCompression() *RequestBuilder {
  126. r.disableCompression = true
  127. return r
  128. }
  129. func (r *RequestBuilder) ExecuteRequest(requestURL string) (*http.Response, error) {
  130. var clientProxyURL *url.URL
  131. switch {
  132. case r.feedProxyURL != "":
  133. var err error
  134. clientProxyURL, err = url.Parse(r.feedProxyURL)
  135. if err != nil {
  136. return nil, fmt.Errorf(`fetcher: invalid feed proxy URL %q: %w`, r.feedProxyURL, err)
  137. }
  138. case r.useClientProxy && r.clientProxyURL != nil:
  139. clientProxyURL = r.clientProxyURL
  140. case r.proxyRotator != nil && r.proxyRotator.HasProxies():
  141. clientProxyURL = r.proxyRotator.GetNextProxy()
  142. }
  143. directDialer := &net.Dialer{
  144. Timeout: 10 * time.Second, // Default is 30s.
  145. KeepAlive: 15 * time.Second, // Default is 30s.
  146. }
  147. proxyDialer := &net.Dialer{
  148. Timeout: 10 * time.Second, // Default is 30s.
  149. KeepAlive: 15 * time.Second, // Default is 30s.
  150. }
  151. // http.ProxyFromEnvironment caches the environment on first use and needs a
  152. // request that does not exist yet here, so read the variables directly. This
  153. // keeps routing and the private-network exemption below in agreement.
  154. envProxyFunc := httpproxy.FromEnvironment().ProxyFunc()
  155. proxyDialAddress := normalizeProxyDialAddress(clientProxyURL)
  156. if clientProxyURL == nil {
  157. if parsedRequestURL, err := url.Parse(requestURL); err == nil {
  158. if envProxyURL, err := envProxyFunc(parsedRequestURL); err == nil {
  159. proxyDialAddress = normalizeProxyDialAddress(envProxyURL)
  160. }
  161. }
  162. }
  163. // Perform the private-network check inside the dialer's Control callback,
  164. // which fires after DNS resolution but before the TCP connection is made.
  165. // This eliminates TOCTOU / DNS-rebinding vulnerabilities: the resolved IP
  166. // that is checked is exactly the IP that will be connected to.
  167. allowPrivateNetworks := config.Opts == nil || config.Opts.FetcherAllowPrivateNetworks()
  168. if !allowPrivateNetworks {
  169. directDialer.Control = func(network, address string, c syscall.RawConn) error {
  170. host, _, err := net.SplitHostPort(address)
  171. if err != nil {
  172. return err
  173. }
  174. ip := net.ParseIP(host)
  175. if urllib.IsNonPublicIP(ip) {
  176. return fmt.Errorf("%w %q", ErrPrivateNetworkHost, host)
  177. }
  178. return nil
  179. }
  180. }
  181. transport := &http.Transport{
  182. Proxy: func(req *http.Request) (*url.URL, error) {
  183. return envProxyFunc(req.URL)
  184. },
  185. // Setting `DialContext` disables HTTP/2, this option forces the transport to try HTTP/2 regardless.
  186. ForceAttemptHTTP2: true,
  187. MaxIdleConns: 50, // Default is 100.
  188. IdleConnTimeout: 10 * time.Second, // Default is 90s.
  189. }
  190. transport.DialContext = directDialer.DialContext
  191. if !allowPrivateNetworks && proxyDialAddress != "" {
  192. // Explicitly configured proxies are a trusted hop. Keep the private-network
  193. // check for direct requests and redirects, but allow the connection to the proxy itself.
  194. transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  195. if normalizeDialAddress(addr) == proxyDialAddress {
  196. return proxyDialer.DialContext(ctx, network, addr)
  197. }
  198. return directDialer.DialContext(ctx, network, addr)
  199. }
  200. }
  201. if r.ignoreTLSErrors {
  202. // Add insecure ciphers if we are ignoring TLS errors. This allows to connect to badly configured servers anyway
  203. ciphers := slices.Concat(tls.CipherSuites(), tls.InsecureCipherSuites())
  204. cipherSuites := make([]uint16, 0, len(ciphers))
  205. for _, cipher := range ciphers {
  206. cipherSuites = append(cipherSuites, cipher.ID)
  207. }
  208. transport.TLSClientConfig = &tls.Config{
  209. CipherSuites: cipherSuites,
  210. InsecureSkipVerify: true,
  211. }
  212. }
  213. if r.disableHTTP2 {
  214. transport.ForceAttemptHTTP2 = false
  215. // https://pkg.go.dev/net/http#hdr-HTTP_2
  216. // 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.
  217. transport.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
  218. }
  219. var clientProxyURLRedacted string
  220. if clientProxyURL != nil {
  221. transport.Proxy = http.ProxyURL(clientProxyURL)
  222. clientProxyURLRedacted = clientProxyURL.Redacted()
  223. }
  224. client := &http.Client{
  225. Timeout: r.clientTimeout,
  226. }
  227. if r.withoutRedirects {
  228. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  229. return http.ErrUseLastResponse
  230. }
  231. }
  232. client.Transport = transport
  233. req, err := http.NewRequest("GET", requestURL, nil)
  234. if err != nil {
  235. return nil, err
  236. }
  237. req.Header = r.headers
  238. if r.disableCompression {
  239. req.Header.Set("Accept-Encoding", "identity")
  240. } else {
  241. req.Header.Set("Accept-Encoding", "br,gzip")
  242. }
  243. // Set default Accept header if not already set.
  244. // Note that for the media proxy requests, we need to forward the browser Accept header.
  245. if req.Header.Get("Accept") == "" {
  246. req.Header.Set("Accept", defaultAcceptHeader)
  247. }
  248. req.Header.Set("Connection", "close")
  249. slog.Debug("Making outgoing request", slog.Group("request",
  250. slog.String("method", req.Method),
  251. slog.String("url", req.URL.String()),
  252. slog.Any("headers", req.Header),
  253. slog.Bool("without_redirects", r.withoutRedirects),
  254. slog.Bool("use_app_client_proxy", r.useClientProxy),
  255. slog.String("client_proxy_url", clientProxyURLRedacted),
  256. slog.Bool("ignore_tls_errors", r.ignoreTLSErrors),
  257. slog.Bool("disable_http2", r.disableHTTP2),
  258. ))
  259. return client.Do(req)
  260. }
  261. func normalizeDialAddress(addr string) string {
  262. host, port, err := net.SplitHostPort(addr)
  263. if err != nil {
  264. return ""
  265. }
  266. return net.JoinHostPort(strings.ToLower(host), port)
  267. }
  268. func normalizeProxyDialAddress(proxyURL *url.URL) string {
  269. if proxyURL == nil {
  270. return ""
  271. }
  272. port := proxyURL.Port()
  273. if port == "" {
  274. switch strings.ToLower(proxyURL.Scheme) {
  275. case "", "http":
  276. port = "80"
  277. case "https":
  278. port = "443"
  279. case "socks5", "socks5h":
  280. port = "1080"
  281. default:
  282. return ""
  283. }
  284. }
  285. return net.JoinHostPort(strings.ToLower(proxyURL.Hostname()), port)
  286. }