client.go 8.8 KB

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