request_builder.go 10 KB

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