client.go 9.0 KB

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