request_builder.go 12 KB

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