client.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package client // import "miniflux.app/http/client"
  4. import (
  5. "bytes"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/http"
  13. "net/url"
  14. "strings"
  15. "time"
  16. "miniflux.app/config"
  17. "miniflux.app/errors"
  18. "miniflux.app/logger"
  19. "miniflux.app/timer"
  20. )
  21. const (
  22. defaultHTTPClientTimeout = 20
  23. defaultHTTPClientMaxBodySize = 15 * 1024 * 1024
  24. )
  25. var (
  26. errInvalidCertificate = "Invalid SSL certificate (original error: %q)"
  27. errNetworkOperation = "This website is unreachable (original error: %q)"
  28. errRequestTimeout = "Website unreachable, the request timed out after %d seconds"
  29. )
  30. // Client builds and executes HTTP requests.
  31. type Client struct {
  32. inputURL string
  33. requestEtagHeader string
  34. requestLastModifiedHeader string
  35. requestAuthorizationHeader string
  36. requestUsername string
  37. requestPassword string
  38. requestUserAgent string
  39. requestCookie string
  40. customHeaders map[string]string
  41. useProxy bool
  42. doNotFollowRedirects bool
  43. ClientTimeout int
  44. ClientMaxBodySize int64
  45. ClientProxyURL string
  46. AllowSelfSignedCertificates bool
  47. }
  48. // New initializes a new HTTP client.
  49. func New(url string) *Client {
  50. return &Client{
  51. inputURL: url,
  52. ClientTimeout: defaultHTTPClientTimeout,
  53. ClientMaxBodySize: defaultHTTPClientMaxBodySize,
  54. }
  55. }
  56. // NewClientWithConfig initializes a new HTTP client with application config options.
  57. func NewClientWithConfig(url string, opts *config.Options) *Client {
  58. return &Client{
  59. inputURL: url,
  60. requestUserAgent: opts.HTTPClientUserAgent(),
  61. ClientTimeout: opts.HTTPClientTimeout(),
  62. ClientMaxBodySize: opts.HTTPClientMaxBodySize(),
  63. ClientProxyURL: opts.HTTPClientProxy(),
  64. }
  65. }
  66. func (c *Client) String() string {
  67. etagHeader := c.requestEtagHeader
  68. if c.requestEtagHeader == "" {
  69. etagHeader = "None"
  70. }
  71. lastModifiedHeader := c.requestLastModifiedHeader
  72. if c.requestLastModifiedHeader == "" {
  73. lastModifiedHeader = "None"
  74. }
  75. return fmt.Sprintf(
  76. `InputURL=%q ETag=%s LastMod=%s Auth=%v UserAgent=%q Verify=%v`,
  77. c.inputURL,
  78. etagHeader,
  79. lastModifiedHeader,
  80. c.requestAuthorizationHeader != "" || (c.requestUsername != "" && c.requestPassword != ""),
  81. c.requestUserAgent,
  82. !c.AllowSelfSignedCertificates,
  83. )
  84. }
  85. // WithCredentials defines the username/password for HTTP Basic authentication.
  86. func (c *Client) WithCredentials(username, password string) *Client {
  87. if username != "" && password != "" {
  88. c.requestUsername = username
  89. c.requestPassword = password
  90. }
  91. return c
  92. }
  93. // WithAuthorization defines the authorization HTTP header value.
  94. func (c *Client) WithAuthorization(authorization string) *Client {
  95. c.requestAuthorizationHeader = authorization
  96. return c
  97. }
  98. // WithCustomHeaders defines custom HTTP headers.
  99. func (c *Client) WithCustomHeaders(customHeaders map[string]string) *Client {
  100. c.customHeaders = customHeaders
  101. return c
  102. }
  103. // WithCacheHeaders defines caching headers.
  104. func (c *Client) WithCacheHeaders(etagHeader, lastModifiedHeader string) *Client {
  105. c.requestEtagHeader = etagHeader
  106. c.requestLastModifiedHeader = lastModifiedHeader
  107. return c
  108. }
  109. // WithProxy enables proxy for the current HTTP request.
  110. func (c *Client) WithProxy() *Client {
  111. c.useProxy = true
  112. return c
  113. }
  114. // WithoutRedirects disables HTTP redirects.
  115. func (c *Client) WithoutRedirects() *Client {
  116. c.doNotFollowRedirects = true
  117. return c
  118. }
  119. // WithUserAgent defines the User-Agent header to use for HTTP requests.
  120. func (c *Client) WithUserAgent(userAgent string) *Client {
  121. if userAgent != "" {
  122. c.requestUserAgent = userAgent
  123. }
  124. return c
  125. }
  126. // WithCookie defines the Cookies to use for HTTP requests.
  127. func (c *Client) WithCookie(cookie string) *Client {
  128. if cookie != "" {
  129. c.requestCookie = cookie
  130. }
  131. return c
  132. }
  133. // Get performs a GET HTTP request.
  134. func (c *Client) Get() (*Response, error) {
  135. request, err := c.buildRequest(http.MethodGet, nil)
  136. if err != nil {
  137. return nil, err
  138. }
  139. return c.executeRequest(request)
  140. }
  141. // PostForm performs a POST HTTP request with form encoded values.
  142. func (c *Client) PostForm(values url.Values) (*Response, error) {
  143. request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
  144. if err != nil {
  145. return nil, err
  146. }
  147. request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  148. return c.executeRequest(request)
  149. }
  150. // PostJSON performs a POST HTTP request with a JSON payload.
  151. func (c *Client) PostJSON(data interface{}) (*Response, error) {
  152. b, err := json.Marshal(data)
  153. if err != nil {
  154. return nil, err
  155. }
  156. request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
  157. if err != nil {
  158. return nil, err
  159. }
  160. request.Header.Add("Content-Type", "application/json")
  161. return c.executeRequest(request)
  162. }
  163. // PatchJSON performs a Patch HTTP request with a JSON payload.
  164. func (c *Client) PatchJSON(data interface{}) (*Response, error) {
  165. b, err := json.Marshal(data)
  166. if err != nil {
  167. return nil, err
  168. }
  169. request, err := c.buildRequest(http.MethodPatch, bytes.NewReader(b))
  170. if err != nil {
  171. return nil, err
  172. }
  173. request.Header.Add("Content-Type", "application/json")
  174. return c.executeRequest(request)
  175. }
  176. func (c *Client) executeRequest(request *http.Request) (*Response, error) {
  177. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] inputURL=%s", c.inputURL))
  178. logger.Debug("[HttpClient:Before] Method=%s %s",
  179. request.Method,
  180. c.String(),
  181. )
  182. client := c.buildClient()
  183. resp, err := client.Do(request)
  184. if resp != nil {
  185. defer resp.Body.Close()
  186. }
  187. if err != nil {
  188. if uerr, ok := err.(*url.Error); ok {
  189. switch uerr.Err.(type) {
  190. case x509.CertificateInvalidError, x509.HostnameError:
  191. err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
  192. case *net.OpError:
  193. err = errors.NewLocalizedError(errNetworkOperation, uerr.Err)
  194. case net.Error:
  195. nerr := uerr.Err.(net.Error)
  196. if nerr.Timeout() {
  197. err = errors.NewLocalizedError(errRequestTimeout, c.ClientTimeout)
  198. }
  199. }
  200. }
  201. return nil, err
  202. }
  203. if resp.ContentLength > c.ClientMaxBodySize {
  204. return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
  205. }
  206. buf, err := io.ReadAll(resp.Body)
  207. if err != nil {
  208. return nil, fmt.Errorf("client: error while reading body %v", err)
  209. }
  210. response := &Response{
  211. Body: bytes.NewReader(buf),
  212. StatusCode: resp.StatusCode,
  213. EffectiveURL: resp.Request.URL.String(),
  214. LastModified: resp.Header.Get("Last-Modified"),
  215. ETag: resp.Header.Get("ETag"),
  216. Expires: resp.Header.Get("Expires"),
  217. ContentType: resp.Header.Get("Content-Type"),
  218. ContentLength: resp.ContentLength,
  219. }
  220. logger.Debug("[HttpClient:After] Method=%s %s; Response => %s",
  221. request.Method,
  222. c.String(),
  223. response,
  224. )
  225. // Ignore caching headers for feeds that do not want any cache.
  226. if resp.Header.Get("Expires") == "0" {
  227. logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
  228. response.ETag = ""
  229. response.LastModified = ""
  230. }
  231. return response, err
  232. }
  233. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  234. request, err := http.NewRequest(method, c.inputURL, body)
  235. if err != nil {
  236. return nil, err
  237. }
  238. request.Header = c.buildHeaders()
  239. if c.requestUsername != "" && c.requestPassword != "" {
  240. request.SetBasicAuth(c.requestUsername, c.requestPassword)
  241. }
  242. return request, nil
  243. }
  244. func (c *Client) buildClient() http.Client {
  245. client := http.Client{
  246. Timeout: time.Duration(c.ClientTimeout) * time.Second,
  247. }
  248. transport := &http.Transport{
  249. Proxy: http.ProxyFromEnvironment,
  250. DialContext: (&net.Dialer{
  251. // Default is 30s.
  252. Timeout: 10 * time.Second,
  253. // Default is 30s.
  254. KeepAlive: 15 * time.Second,
  255. }).DialContext,
  256. // Default is 100.
  257. MaxIdleConns: 50,
  258. // Default is 90s.
  259. IdleConnTimeout: 10 * time.Second,
  260. }
  261. if c.AllowSelfSignedCertificates {
  262. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  263. }
  264. if c.doNotFollowRedirects {
  265. client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  266. return http.ErrUseLastResponse
  267. }
  268. }
  269. if c.useProxy && c.ClientProxyURL != "" {
  270. proxyURL, err := url.Parse(c.ClientProxyURL)
  271. if err != nil {
  272. logger.Error("[HttpClient] Proxy URL error: %v", err)
  273. } else {
  274. logger.Debug("[HttpClient] Use proxy: %s", proxyURL)
  275. transport.Proxy = http.ProxyURL(proxyURL)
  276. }
  277. }
  278. client.Transport = transport
  279. return client
  280. }
  281. func (c *Client) buildHeaders() http.Header {
  282. headers := make(http.Header)
  283. headers.Add("Accept", "*/*")
  284. if c.requestUserAgent != "" {
  285. headers.Add("User-Agent", c.requestUserAgent)
  286. }
  287. if c.requestEtagHeader != "" {
  288. headers.Add("If-None-Match", c.requestEtagHeader)
  289. }
  290. if c.requestLastModifiedHeader != "" {
  291. headers.Add("If-Modified-Since", c.requestLastModifiedHeader)
  292. }
  293. if c.requestAuthorizationHeader != "" {
  294. headers.Add("Authorization", c.requestAuthorizationHeader)
  295. }
  296. if c.requestCookie != "" {
  297. headers.Add("Cookie", c.requestCookie)
  298. }
  299. for key, value := range c.customHeaders {
  300. headers.Add(key, value)
  301. }
  302. headers.Add("Connection", "close")
  303. return headers
  304. }