request_builder.go 12 KB

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