client.go 8.7 KB

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