request_builder.go 9.9 KB

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