aboutsummaryrefslogtreecommitdiff
path: root/internal/http/client/client.go
blob: de7c9d48b07418b431f91092d1bb036dc74dd4f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package client // import "miniflux.app/v2/internal/http/client"

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"

	"miniflux.app/v2/internal/config"
	"miniflux.app/v2/internal/errors"
	"miniflux.app/v2/internal/logger"
	"miniflux.app/v2/internal/timer"
)

const (
	defaultHTTPClientTimeout     = 20
	defaultHTTPClientMaxBodySize = 15 * 1024 * 1024
)

var (
	errInvalidCertificate = "Invalid SSL certificate (original error: %q)"
	errNetworkOperation   = "This website is unreachable (original error: %q)"
	errRequestTimeout     = "Website unreachable, the request timed out after %d seconds"
)

// Client builds and executes HTTP requests.
type Client struct {
	inputURL string

	requestEtagHeader          string
	requestLastModifiedHeader  string
	requestAuthorizationHeader string
	requestUsername            string
	requestPassword            string
	requestUserAgent           string
	requestCookie              string
	customHeaders              map[string]string
	useProxy                   bool
	doNotFollowRedirects       bool

	ClientTimeout               int
	ClientMaxBodySize           int64
	ClientProxyURL              string
	AllowSelfSignedCertificates bool
}

// New initializes a new HTTP client.
func New(url string) *Client {
	return &Client{
		inputURL:          url,
		ClientTimeout:     defaultHTTPClientTimeout,
		ClientMaxBodySize: defaultHTTPClientMaxBodySize,
	}
}

// NewClientWithConfig initializes a new HTTP client with application config options.
func NewClientWithConfig(url string, opts *config.Options) *Client {
	return &Client{
		inputURL:          url,
		requestUserAgent:  opts.HTTPClientUserAgent(),
		ClientTimeout:     opts.HTTPClientTimeout(),
		ClientMaxBodySize: opts.HTTPClientMaxBodySize(),
		ClientProxyURL:    opts.HTTPClientProxy(),
	}
}

func (c *Client) String() string {
	etagHeader := c.requestEtagHeader
	if c.requestEtagHeader == "" {
		etagHeader = "None"
	}

	lastModifiedHeader := c.requestLastModifiedHeader
	if c.requestLastModifiedHeader == "" {
		lastModifiedHeader = "None"
	}

	return fmt.Sprintf(
		`InputURL=%q ETag=%s LastMod=%s Auth=%v UserAgent=%q Verify=%v`,
		c.inputURL,
		etagHeader,
		lastModifiedHeader,
		c.requestAuthorizationHeader != "" || (c.requestUsername != "" && c.requestPassword != ""),
		c.requestUserAgent,
		!c.AllowSelfSignedCertificates,
	)
}

// WithCredentials defines the username/password for HTTP Basic authentication.
func (c *Client) WithCredentials(username, password string) *Client {
	if username != "" && password != "" {
		c.requestUsername = username
		c.requestPassword = password
	}
	return c
}

// WithAuthorization defines the authorization HTTP header value.
func (c *Client) WithAuthorization(authorization string) *Client {
	c.requestAuthorizationHeader = authorization
	return c
}

// WithCustomHeaders defines custom HTTP headers.
func (c *Client) WithCustomHeaders(customHeaders map[string]string) *Client {
	c.customHeaders = customHeaders
	return c
}

// WithCacheHeaders defines caching headers.
func (c *Client) WithCacheHeaders(etagHeader, lastModifiedHeader string) *Client {
	c.requestEtagHeader = etagHeader
	c.requestLastModifiedHeader = lastModifiedHeader
	return c
}

// WithProxy enables proxy for the current HTTP request.
func (c *Client) WithProxy() *Client {
	c.useProxy = true
	return c
}

// WithoutRedirects disables HTTP redirects.
func (c *Client) WithoutRedirects() *Client {
	c.doNotFollowRedirects = true
	return c
}

// WithUserAgent defines the User-Agent header to use for HTTP requests.
func (c *Client) WithUserAgent(userAgent string) *Client {
	if userAgent != "" {
		c.requestUserAgent = userAgent
	}
	return c
}

// WithCookie defines the Cookies to use for HTTP requests.
func (c *Client) WithCookie(cookie string) *Client {
	if cookie != "" {
		c.requestCookie = cookie
	}
	return c
}

// Get performs a GET HTTP request.
func (c *Client) Get() (*Response, error) {
	request, err := c.buildRequest(http.MethodGet, nil)
	if err != nil {
		return nil, err
	}

	return c.executeRequest(request)
}

// PostForm performs a POST HTTP request with form encoded values.
func (c *Client) PostForm(values url.Values) (*Response, error) {
	request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
	if err != nil {
		return nil, err
	}

	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	return c.executeRequest(request)
}

// PostJSON performs a POST HTTP request with a JSON payload.
func (c *Client) PostJSON(data interface{}) (*Response, error) {
	b, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
	if err != nil {
		return nil, err
	}

	request.Header.Add("Content-Type", "application/json")
	return c.executeRequest(request)
}

// PatchJSON performs a Patch HTTP request with a JSON payload.
func (c *Client) PatchJSON(data interface{}) (*Response, error) {
	b, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}

	request, err := c.buildRequest(http.MethodPatch, bytes.NewReader(b))
	if err != nil {
		return nil, err
	}

	request.Header.Add("Content-Type", "application/json")
	return c.executeRequest(request)
}

func (c *Client) executeRequest(request *http.Request) (*Response, error) {
	defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] inputURL=%s", c.inputURL))

	logger.Debug("[HttpClient:Before] Method=%s %s",
		request.Method,
		c.String(),
	)

	client := c.buildClient()
	resp, err := client.Do(request)
	if resp != nil {
		defer resp.Body.Close()
	}

	if err != nil {
		if uerr, ok := err.(*url.Error); ok {
			switch uerr.Err.(type) {
			case x509.CertificateInvalidError, x509.HostnameError:
				err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
			case *net.OpError:
				err = errors.NewLocalizedError(errNetworkOperation, uerr.Err)
			case net.Error:
				nerr := uerr.Err.(net.Error)
				if nerr.Timeout() {
					err = errors.NewLocalizedError(errRequestTimeout, c.ClientTimeout)
				}
			}
		}

		return nil, err
	}

	if resp.ContentLength > c.ClientMaxBodySize {
		return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
	}

	buf, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("client: error while reading body %v", err)
	}

	response := &Response{
		Body:          bytes.NewReader(buf),
		StatusCode:    resp.StatusCode,
		EffectiveURL:  resp.Request.URL.String(),
		LastModified:  resp.Header.Get("Last-Modified"),
		ETag:          resp.Header.Get("ETag"),
		Expires:       resp.Header.Get("Expires"),
		ContentType:   resp.Header.Get("Content-Type"),
		ContentLength: resp.ContentLength,
	}

	logger.Debug("[HttpClient:After] Method=%s %s; Response => %s",
		request.Method,
		c.String(),
		response,
	)

	// Ignore caching headers for feeds that do not want any cache.
	if resp.Header.Get("Expires") == "0" {
		logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
		response.ETag = ""
		response.LastModified = ""
	}

	return response, err
}

func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
	request, err := http.NewRequest(method, c.inputURL, body)
	if err != nil {
		return nil, err
	}

	request.Header = c.buildHeaders()

	if c.requestUsername != "" && c.requestPassword != "" {
		request.SetBasicAuth(c.requestUsername, c.requestPassword)
	}

	return request, nil
}

func (c *Client) buildClient() http.Client {
	client := http.Client{
		Timeout: time.Duration(c.ClientTimeout) * time.Second,
	}

	transport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			// Default is 30s.
			Timeout: 10 * time.Second,

			// Default is 30s.
			KeepAlive: 15 * time.Second,
		}).DialContext,

		// Default is 100.
		MaxIdleConns: 50,

		// Default is 90s.
		IdleConnTimeout: 10 * time.Second,
	}

	if c.AllowSelfSignedCertificates {
		transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
	}

	if c.doNotFollowRedirects {
		client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		}
	}

	if c.useProxy && c.ClientProxyURL != "" {
		proxyURL, err := url.Parse(c.ClientProxyURL)
		if err != nil {
			logger.Error("[HttpClient] Proxy URL error: %v", err)
		} else {
			logger.Debug("[HttpClient] Use proxy: %s", proxyURL)
			transport.Proxy = http.ProxyURL(proxyURL)
		}
	}

	client.Transport = transport

	return client
}

func (c *Client) buildHeaders() http.Header {
	headers := make(http.Header)
	headers.Add("Accept", "*/*")

	if c.requestUserAgent != "" {
		headers.Add("User-Agent", c.requestUserAgent)
	}

	if c.requestEtagHeader != "" {
		headers.Add("If-None-Match", c.requestEtagHeader)
	}

	if c.requestLastModifiedHeader != "" {
		headers.Add("If-Modified-Since", c.requestLastModifiedHeader)
	}

	if c.requestAuthorizationHeader != "" {
		headers.Add("Authorization", c.requestAuthorizationHeader)
	}

	if c.requestCookie != "" {
		headers.Add("Cookie", c.requestCookie)
	}

	for key, value := range c.customHeaders {
		headers.Add(key, value)
	}

	headers.Add("Connection", "close")
	return headers
}