2018-01-12 17:30:54 +01:00
|
|
|
// Package fshttp contains the common http parts of the config, Transport and Client
|
|
|
|
package fshttp
|
2016-09-10 20:17:43 +02:00
|
|
|
|
|
|
|
import (
|
2016-11-02 16:53:43 +01:00
|
|
|
"bytes"
|
2018-04-06 20:13:27 +02:00
|
|
|
"context"
|
2016-09-10 20:17:43 +02:00
|
|
|
"crypto/tls"
|
2019-02-11 14:09:32 +01:00
|
|
|
"crypto/x509"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
2016-09-10 20:17:43 +02:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2019-01-11 18:35:29 +01:00
|
|
|
"net/http/cookiejar"
|
2016-09-10 20:17:43 +02:00
|
|
|
"net/http/httputil"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2017-07-13 06:11:24 +02:00
|
|
|
|
2019-07-28 19:47:38 +02:00
|
|
|
"github.com/rclone/rclone/fs"
|
2020-06-05 13:15:07 +02:00
|
|
|
"github.com/rclone/rclone/lib/structs"
|
2019-01-11 18:35:29 +01:00
|
|
|
"golang.org/x/net/publicsuffix"
|
2017-07-13 06:11:24 +02:00
|
|
|
"golang.org/x/time/rate"
|
2016-09-10 20:17:43 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
separatorReq = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
|
|
|
|
separatorResp = "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2019-01-11 18:35:29 +01:00
|
|
|
transport http.RoundTripper
|
2019-03-08 21:33:22 +01:00
|
|
|
noTransport = new(sync.Once)
|
2019-01-11 18:35:29 +01:00
|
|
|
tpsBucket *rate.Limiter // for limiting number of http transactions per second
|
|
|
|
cookieJar, _ = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
2016-09-10 20:17:43 +02:00
|
|
|
)
|
|
|
|
|
2018-01-12 17:30:54 +01:00
|
|
|
// StartHTTPTokenBucket starts the token bucket if necessary
|
2020-11-05 12:33:32 +01:00
|
|
|
func StartHTTPTokenBucket(ctx context.Context) {
|
|
|
|
if fs.GetConfig(ctx).TPSLimit > 0 {
|
|
|
|
tpsBurst := fs.GetConfig(ctx).TPSLimitBurst
|
2017-07-13 06:11:24 +02:00
|
|
|
if tpsBurst < 1 {
|
|
|
|
tpsBurst = 1
|
|
|
|
}
|
2020-11-05 12:33:32 +01:00
|
|
|
tpsBucket = rate.NewLimiter(rate.Limit(fs.GetConfig(ctx).TPSLimit), tpsBurst)
|
|
|
|
fs.Infof(nil, "Starting HTTP transaction limiter: max %g transactions/s with burst %d", fs.GetConfig(ctx).TPSLimit, tpsBurst)
|
2017-07-13 06:11:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-10 20:17:43 +02:00
|
|
|
// A net.Conn that sets a deadline for every Read or Write operation
|
|
|
|
type timeoutConn struct {
|
|
|
|
net.Conn
|
2018-05-05 12:33:01 +02:00
|
|
|
timeout time.Duration
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// create a timeoutConn using the timeout
|
2018-02-14 13:27:56 +01:00
|
|
|
func newTimeoutConn(conn net.Conn, timeout time.Duration) (c *timeoutConn, err error) {
|
|
|
|
c = &timeoutConn{
|
2016-09-10 20:17:43 +02:00
|
|
|
Conn: conn,
|
|
|
|
timeout: timeout,
|
|
|
|
}
|
2018-02-14 13:27:56 +01:00
|
|
|
err = c.nudgeDeadline()
|
|
|
|
return
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
2016-10-05 12:59:47 +02:00
|
|
|
// Nudge the deadline for an idle timeout on by c.timeout if non-zero
|
|
|
|
func (c *timeoutConn) nudgeDeadline() (err error) {
|
|
|
|
if c.timeout == 0 {
|
|
|
|
return nil
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
2016-10-05 12:59:47 +02:00
|
|
|
when := time.Now().Add(c.timeout)
|
|
|
|
return c.Conn.SetDeadline(when)
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
2016-10-05 12:59:47 +02:00
|
|
|
// readOrWrite bytes doing idle timeouts
|
|
|
|
func (c *timeoutConn) readOrWrite(f func([]byte) (int, error), b []byte) (n int, err error) {
|
|
|
|
n, err = f(b)
|
2018-02-14 13:27:56 +01:00
|
|
|
// Don't nudge if no bytes or an error
|
|
|
|
if n == 0 || err != nil {
|
|
|
|
return
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
2018-02-14 13:27:56 +01:00
|
|
|
// Nudge the deadline on successful Read or Write
|
|
|
|
err = c.nudgeDeadline()
|
|
|
|
return
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
2016-10-05 12:59:47 +02:00
|
|
|
// Read bytes doing idle timeouts
|
|
|
|
func (c *timeoutConn) Read(b []byte) (n int, err error) {
|
|
|
|
return c.readOrWrite(c.Conn.Read, b)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write bytes doing idle timeouts
|
|
|
|
func (c *timeoutConn) Write(b []byte) (n int, err error) {
|
|
|
|
return c.readOrWrite(c.Conn.Write, b)
|
|
|
|
}
|
|
|
|
|
2018-04-06 21:33:51 +02:00
|
|
|
// dial with context and timeouts
|
|
|
|
func dialContextTimeout(ctx context.Context, network, address string, ci *fs.ConfigInfo) (net.Conn, error) {
|
|
|
|
dialer := NewDialer(ci)
|
|
|
|
c, err := dialer.DialContext(ctx, network, address)
|
|
|
|
if err != nil {
|
|
|
|
return c, err
|
|
|
|
}
|
|
|
|
return newTimeoutConn(c, ci.Timeout)
|
|
|
|
}
|
|
|
|
|
2019-03-08 21:33:22 +01:00
|
|
|
// ResetTransport resets the existing transport, allowing it to take new settings.
|
|
|
|
// Should only be used for testing.
|
|
|
|
func ResetTransport() {
|
|
|
|
noTransport = new(sync.Once)
|
|
|
|
}
|
|
|
|
|
2019-10-16 12:21:26 +02:00
|
|
|
// NewTransportCustom returns an http.RoundTripper with the correct timeouts.
|
|
|
|
// The customize function is called if set to give the caller an opportunity to
|
|
|
|
// customize any defaults in the Transport.
|
|
|
|
func NewTransportCustom(ci *fs.ConfigInfo, customize func(*http.Transport)) http.RoundTripper {
|
|
|
|
// Start with a sensible set of defaults then override.
|
|
|
|
// This also means we get new stuff when it gets added to go
|
|
|
|
t := new(http.Transport)
|
2020-06-05 13:15:07 +02:00
|
|
|
structs.SetDefaults(t, http.DefaultTransport.(*http.Transport))
|
2019-10-16 12:21:26 +02:00
|
|
|
t.Proxy = http.ProxyFromEnvironment
|
|
|
|
t.MaxIdleConnsPerHost = 2 * (ci.Checkers + ci.Transfers + 1)
|
|
|
|
t.MaxIdleConns = 2 * t.MaxIdleConnsPerHost
|
|
|
|
t.TLSHandshakeTimeout = ci.ConnectTimeout
|
|
|
|
t.ResponseHeaderTimeout = ci.Timeout
|
|
|
|
|
|
|
|
// TLS Config
|
|
|
|
t.TLSClientConfig = &tls.Config{
|
|
|
|
InsecureSkipVerify: ci.InsecureSkipVerify,
|
|
|
|
}
|
2019-02-11 14:09:32 +01:00
|
|
|
|
2019-10-16 12:21:26 +02:00
|
|
|
// Load client certs
|
|
|
|
if ci.ClientCert != "" || ci.ClientKey != "" {
|
|
|
|
if ci.ClientCert == "" || ci.ClientKey == "" {
|
|
|
|
log.Fatalf("Both --client-cert and --client-key must be set")
|
2019-02-11 14:09:32 +01:00
|
|
|
}
|
2019-10-16 12:21:26 +02:00
|
|
|
cert, err := tls.LoadX509KeyPair(ci.ClientCert, ci.ClientKey)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to load --client-cert/--client-key pair: %v", err)
|
2019-02-11 14:09:32 +01:00
|
|
|
}
|
2019-10-16 12:21:26 +02:00
|
|
|
t.TLSClientConfig.Certificates = []tls.Certificate{cert}
|
|
|
|
t.TLSClientConfig.BuildNameToCertificate()
|
|
|
|
}
|
2019-02-11 14:09:32 +01:00
|
|
|
|
2019-10-16 12:21:26 +02:00
|
|
|
// Load CA cert
|
|
|
|
if ci.CaCert != "" {
|
|
|
|
caCert, err := ioutil.ReadFile(ci.CaCert)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Failed to read --ca-cert: %v", err)
|
|
|
|
}
|
|
|
|
caCertPool := x509.NewCertPool()
|
|
|
|
ok := caCertPool.AppendCertsFromPEM(caCert)
|
|
|
|
if !ok {
|
|
|
|
log.Fatalf("Failed to add certificates from --ca-cert")
|
2018-04-06 21:33:51 +02:00
|
|
|
}
|
2019-10-16 12:21:26 +02:00
|
|
|
t.TLSClientConfig.RootCAs = caCertPool
|
|
|
|
}
|
|
|
|
|
|
|
|
t.DisableCompression = ci.NoGzip
|
|
|
|
t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
|
|
return dialContextTimeout(ctx, network, addr, ci)
|
|
|
|
}
|
|
|
|
t.IdleConnTimeout = 60 * time.Second
|
2020-01-09 15:00:46 +01:00
|
|
|
t.ExpectContinueTimeout = ci.ExpectContinueTimeout
|
2019-10-16 12:21:26 +02:00
|
|
|
|
2020-01-21 17:34:29 +01:00
|
|
|
if ci.Dump&(fs.DumpHeaders|fs.DumpBodies|fs.DumpAuth|fs.DumpRequests|fs.DumpResponses) != 0 {
|
|
|
|
fs.Debugf(nil, "You have specified to dump information. Please be noted that the "+
|
|
|
|
"Accept-Encoding as shown may not be correct in the request and the response may not show "+
|
|
|
|
"Content-Encoding if the go standard libraries auto gzip encoding was in effect. In this case"+
|
|
|
|
" the body of the request will be gunzipped before showing it.")
|
|
|
|
}
|
|
|
|
|
2019-10-16 12:21:26 +02:00
|
|
|
// customize the transport if required
|
|
|
|
if customize != nil {
|
|
|
|
customize(t)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wrap that http.Transport in our own transport
|
|
|
|
return newTransport(ci, t)
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewTransport returns an http.RoundTripper with the correct timeouts
|
|
|
|
func NewTransport(ci *fs.ConfigInfo) http.RoundTripper {
|
|
|
|
(*noTransport).Do(func() {
|
|
|
|
transport = NewTransportCustom(ci, nil)
|
2016-09-10 20:17:43 +02:00
|
|
|
})
|
|
|
|
return transport
|
|
|
|
}
|
|
|
|
|
2018-01-12 17:30:54 +01:00
|
|
|
// NewClient returns an http.Client with the correct timeouts
|
|
|
|
func NewClient(ci *fs.ConfigInfo) *http.Client {
|
2019-10-16 12:21:26 +02:00
|
|
|
client := &http.Client{
|
2018-01-12 17:30:54 +01:00
|
|
|
Transport: NewTransport(ci),
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
2019-01-11 18:35:29 +01:00
|
|
|
if ci.Cookie {
|
2019-10-16 12:21:26 +02:00
|
|
|
client.Jar = cookieJar
|
2019-01-11 18:35:29 +01:00
|
|
|
}
|
2019-10-16 12:21:26 +02:00
|
|
|
return client
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
2020-05-20 12:39:20 +02:00
|
|
|
// Transport is our http Transport which wraps an http.Transport
|
2016-09-10 20:17:43 +02:00
|
|
|
// * Sets the User Agent
|
|
|
|
// * Does logging
|
|
|
|
type Transport struct {
|
|
|
|
*http.Transport
|
2018-01-12 17:30:54 +01:00
|
|
|
dump fs.DumpFlags
|
2017-11-24 10:07:56 +01:00
|
|
|
filterRequest func(req *http.Request)
|
2018-01-12 17:30:54 +01:00
|
|
|
userAgent string
|
2020-04-23 16:24:21 +02:00
|
|
|
headers []*fs.HTTPOption
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
|
2018-01-12 17:30:54 +01:00
|
|
|
// newTransport wraps the http.Transport passed in and logs all
|
2016-09-10 20:17:43 +02:00
|
|
|
// roundtrips including the body if logBody is set.
|
2018-01-12 17:30:54 +01:00
|
|
|
func newTransport(ci *fs.ConfigInfo, transport *http.Transport) *Transport {
|
2016-09-10 20:17:43 +02:00
|
|
|
return &Transport{
|
|
|
|
Transport: transport,
|
2018-01-12 17:30:54 +01:00
|
|
|
dump: ci.Dump,
|
|
|
|
userAgent: ci.UserAgent,
|
2020-04-23 16:24:21 +02:00
|
|
|
headers: ci.Headers,
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-24 10:07:56 +01:00
|
|
|
// SetRequestFilter sets a filter to be used on each request
|
|
|
|
func (t *Transport) SetRequestFilter(f func(req *http.Request)) {
|
|
|
|
t.filterRequest = f
|
|
|
|
}
|
|
|
|
|
2016-10-30 20:16:27 +01:00
|
|
|
// A mutex to protect this map
|
|
|
|
var checkedHostMu sync.RWMutex
|
|
|
|
|
2016-10-08 15:00:50 +02:00
|
|
|
// A map of servers we have checked for time
|
|
|
|
var checkedHost = make(map[string]struct{}, 1)
|
|
|
|
|
|
|
|
// Check the server time is the same as ours, once for each server
|
|
|
|
func checkServerTime(req *http.Request, resp *http.Response) {
|
|
|
|
host := req.URL.Host
|
|
|
|
if req.Host != "" {
|
|
|
|
host = req.Host
|
|
|
|
}
|
2016-10-30 20:16:27 +01:00
|
|
|
checkedHostMu.RLock()
|
|
|
|
_, ok := checkedHost[host]
|
|
|
|
checkedHostMu.RUnlock()
|
|
|
|
if ok {
|
2016-10-08 15:00:50 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
dateString := resp.Header.Get("Date")
|
|
|
|
if dateString == "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
date, err := http.ParseTime(dateString)
|
|
|
|
if err != nil {
|
2018-01-12 17:30:54 +01:00
|
|
|
fs.Debugf(nil, "Couldn't parse Date: from server %s: %q: %v", host, dateString, err)
|
2016-10-08 15:00:50 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
dt := time.Since(date)
|
|
|
|
const window = 5 * 60 * time.Second
|
|
|
|
if dt > window || dt < -window {
|
2018-01-12 17:30:54 +01:00
|
|
|
fs.Logf(nil, "Time may be set wrong - time from %q is %v different from this computer", host, dt)
|
2016-10-08 15:00:50 +02:00
|
|
|
}
|
2016-10-30 20:16:27 +01:00
|
|
|
checkedHostMu.Lock()
|
2016-10-08 15:00:50 +02:00
|
|
|
checkedHost[host] = struct{}{}
|
2016-10-30 20:16:27 +01:00
|
|
|
checkedHostMu.Unlock()
|
2016-10-08 15:00:50 +02:00
|
|
|
}
|
|
|
|
|
2017-11-21 13:14:52 +01:00
|
|
|
// cleanAuth gets rid of one authBuf header within the first 4k
|
|
|
|
func cleanAuth(buf, authBuf []byte) []byte {
|
2016-11-02 16:53:43 +01:00
|
|
|
// Find how much buffer to check
|
|
|
|
n := 4096
|
|
|
|
if len(buf) < n {
|
|
|
|
n = len(buf)
|
|
|
|
}
|
|
|
|
// See if there is an Authorization: header
|
|
|
|
i := bytes.Index(buf[:n], authBuf)
|
|
|
|
if i < 0 {
|
|
|
|
return buf
|
|
|
|
}
|
|
|
|
i += len(authBuf)
|
|
|
|
// Overwrite the next 4 chars with 'X'
|
|
|
|
for j := 0; i < len(buf) && j < 4; j++ {
|
|
|
|
if buf[i] == '\n' {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
buf[i] = 'X'
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
// Snip out to the next '\n'
|
|
|
|
j := bytes.IndexByte(buf[i:], '\n')
|
|
|
|
if j < 0 {
|
|
|
|
return buf[:i]
|
|
|
|
}
|
|
|
|
n = copy(buf[i:], buf[i+j:])
|
|
|
|
return buf[:i+n]
|
|
|
|
}
|
|
|
|
|
2017-11-21 13:14:52 +01:00
|
|
|
var authBufs = [][]byte{
|
|
|
|
[]byte("Authorization: "),
|
|
|
|
[]byte("X-Auth-Token: "),
|
|
|
|
}
|
|
|
|
|
|
|
|
// cleanAuths gets rid of all the possible Auth headers
|
|
|
|
func cleanAuths(buf []byte) []byte {
|
|
|
|
for _, authBuf := range authBufs {
|
|
|
|
buf = cleanAuth(buf, authBuf)
|
|
|
|
}
|
|
|
|
return buf
|
|
|
|
}
|
|
|
|
|
2016-09-10 20:17:43 +02:00
|
|
|
// RoundTrip implements the RoundTripper interface.
|
|
|
|
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
|
2017-07-13 06:11:24 +02:00
|
|
|
// Get transactions per second token first if limiting
|
|
|
|
if tpsBucket != nil {
|
2018-04-06 20:04:31 +02:00
|
|
|
tbErr := tpsBucket.Wait(req.Context())
|
2019-10-29 17:25:13 +01:00
|
|
|
if tbErr != nil && tbErr != context.Canceled {
|
2019-10-27 12:08:05 +01:00
|
|
|
fs.Errorf(nil, "HTTP token bucket error: %v", tbErr)
|
2017-07-13 06:11:24 +02:00
|
|
|
}
|
|
|
|
}
|
2016-09-10 20:17:43 +02:00
|
|
|
// Force user agent
|
2018-01-12 17:30:54 +01:00
|
|
|
req.Header.Set("User-Agent", t.userAgent)
|
2020-04-23 16:24:21 +02:00
|
|
|
// Set user defined headers
|
|
|
|
for _, option := range t.headers {
|
|
|
|
req.Header.Set(option.Key, option.Value)
|
|
|
|
}
|
2017-11-24 10:07:56 +01:00
|
|
|
// Filter the request if required
|
|
|
|
if t.filterRequest != nil {
|
|
|
|
t.filterRequest(req)
|
|
|
|
}
|
2017-02-09 12:01:20 +01:00
|
|
|
// Logf request
|
2018-01-12 17:30:54 +01:00
|
|
|
if t.dump&(fs.DumpHeaders|fs.DumpBodies|fs.DumpAuth|fs.DumpRequests|fs.DumpResponses) != 0 {
|
|
|
|
buf, _ := httputil.DumpRequestOut(req, t.dump&(fs.DumpBodies|fs.DumpRequests) != 0)
|
|
|
|
if t.dump&fs.DumpAuth == 0 {
|
2017-11-21 13:14:52 +01:00
|
|
|
buf = cleanAuths(buf)
|
2016-11-02 16:53:43 +01:00
|
|
|
}
|
2018-01-12 17:30:54 +01:00
|
|
|
fs.Debugf(nil, "%s", separatorReq)
|
|
|
|
fs.Debugf(nil, "%s (req %p)", "HTTP REQUEST", req)
|
|
|
|
fs.Debugf(nil, "%s", string(buf))
|
|
|
|
fs.Debugf(nil, "%s", separatorReq)
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
|
|
|
// Do round trip
|
|
|
|
resp, err = t.Transport.RoundTrip(req)
|
2017-02-09 12:01:20 +01:00
|
|
|
// Logf response
|
2018-01-12 17:30:54 +01:00
|
|
|
if t.dump&(fs.DumpHeaders|fs.DumpBodies|fs.DumpAuth|fs.DumpRequests|fs.DumpResponses) != 0 {
|
|
|
|
fs.Debugf(nil, "%s", separatorResp)
|
|
|
|
fs.Debugf(nil, "%s (req %p)", "HTTP RESPONSE", req)
|
2016-09-10 20:17:43 +02:00
|
|
|
if err != nil {
|
2018-01-12 17:30:54 +01:00
|
|
|
fs.Debugf(nil, "Error: %v", err)
|
2016-09-10 20:17:43 +02:00
|
|
|
} else {
|
2018-01-12 17:30:54 +01:00
|
|
|
buf, _ := httputil.DumpResponse(resp, t.dump&(fs.DumpBodies|fs.DumpResponses) != 0)
|
|
|
|
fs.Debugf(nil, "%s", string(buf))
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
2018-01-12 17:30:54 +01:00
|
|
|
fs.Debugf(nil, "%s", separatorResp)
|
2016-09-10 20:17:43 +02:00
|
|
|
}
|
2016-10-08 15:00:50 +02:00
|
|
|
if err == nil {
|
|
|
|
checkServerTime(req, resp)
|
|
|
|
}
|
2016-09-10 20:17:43 +02:00
|
|
|
return resp, err
|
|
|
|
}
|
2017-07-23 17:10:23 +02:00
|
|
|
|
|
|
|
// NewDialer creates a net.Dialer structure with Timeout, Keepalive
|
|
|
|
// and LocalAddr set from rclone flags.
|
2018-01-12 17:30:54 +01:00
|
|
|
func NewDialer(ci *fs.ConfigInfo) *net.Dialer {
|
2017-07-23 17:10:23 +02:00
|
|
|
dialer := &net.Dialer{
|
|
|
|
Timeout: ci.ConnectTimeout,
|
|
|
|
KeepAlive: 30 * time.Second,
|
|
|
|
}
|
|
|
|
if ci.BindAddr != nil {
|
|
|
|
dialer.LocalAddr = &net.TCPAddr{IP: ci.BindAddr}
|
|
|
|
}
|
|
|
|
return dialer
|
|
|
|
}
|