| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"crypto/tls" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"net/http" |
| 9 |
"net/url" |
| 10 |
"os" |
| 11 |
"path" |
| 12 |
"strings" |
| 13 |
"time" |
| 14 |
|
| 15 |
"crypto/x509" |
| 16 |
|
| 17 |
"github.com/pkg/errors" |
| 18 |
"github.com/sirupsen/logrus" |
| 19 |
) |
| 20 |
|
| 21 |
var _ WriteStore = &RemoteHTTP{} |
| 22 |
|
| 23 |
// RemoteHTTPBase is the base object for a remote, HTTP-based chunk or index stores. |
| 24 |
type RemoteHTTPBase struct { |
| 25 |
location *url.URL |
| 26 |
client *http.Client |
| 27 |
opt StoreOptions |
| 28 |
converters Converters |
| 29 |
|
| 30 |
// Chunk file extension, derived from the converters at construction |
| 31 |
extension string |
| 32 |
} |
| 33 |
|
| 34 |
// RemoteHTTP is a remote casync store accessed via HTTP. |
| 35 |
type RemoteHTTP struct { |
| 36 |
*RemoteHTTPBase |
| 37 |
} |
| 38 |
|
| 39 |
type GetReaderForRequestBody func() io.Reader |
| 40 |
|
| 41 |
// NewRemoteHTTPStoreBase initializes a base object for HTTP index or chunk stores. |
| 42 |
func NewRemoteHTTPStoreBase(location *url.URL, opt StoreOptions) (*RemoteHTTPBase, error) { |
| 43 |
if location.Scheme != "http" && location.Scheme != "https" { |
| 44 |
return nil, fmt.Errorf("unsupported scheme %s, expected http or https", location.Scheme) |
| 45 |
} |
| 46 |
// Make sure we have a trailing / on the path |
| 47 |
if !strings.HasSuffix(location.Path, "/") { |
| 48 |
location.Path = location.Path + "/" |
| 49 |
} |
| 50 |
|
| 51 |
// Build a TLS client config |
| 52 |
tlsConfig := &tls.Config{InsecureSkipVerify: opt.TrustInsecure} |
| 53 |
|
| 54 |
// Add client key/cert if provided |
| 55 |
if opt.ClientCert != "" && opt.ClientKey != "" { |
| 56 |
certificate, err := tls.LoadX509KeyPair(opt.ClientCert, opt.ClientKey) |
| 57 |
if err != nil { |
| 58 |
return nil, fmt.Errorf("failed to load client certificate from %s", opt.ClientCert) |
| 59 |
} |
| 60 |
tlsConfig.Certificates = []tls.Certificate{certificate} |
| 61 |
} |
| 62 |
|
| 63 |
// Load custom CA set if provided |
| 64 |
if opt.CACert != "" { |
| 65 |
certPool := x509.NewCertPool() |
| 66 |
b, err := os.ReadFile(opt.CACert) |
| 67 |
if err != nil { |
| 68 |
return nil, err |
| 69 |
} |
| 70 |
if ok := certPool.AppendCertsFromPEM(b); !ok { |
| 71 |
return nil, errors.New("no CA certificates found in ca-cert file") |
| 72 |
} |
| 73 |
tlsConfig.RootCAs = certPool |
| 74 |
} |
| 75 |
|
| 76 |
tr := &http.Transport{ |
| 77 |
Proxy: http.ProxyFromEnvironment, |
| 78 |
DisableCompression: true, |
| 79 |
MaxIdleConnsPerHost: opt.N, |
| 80 |
IdleConnTimeout: 60 * time.Second, |
| 81 |
TLSClientConfig: tlsConfig, |
| 82 |
ForceAttemptHTTP2: true, |
| 83 |
} |
| 84 |
|
| 85 |
// If no timeout was given in config (set to 0), then use 1 minute. If timeout is negative, use 0 to |
| 86 |
// set an infinite timeout. |
| 87 |
timeout := opt.Timeout |
| 88 |
if timeout == 0 { |
| 89 |
timeout = time.Minute |
| 90 |
} else if timeout < 0 { |
| 91 |
timeout = 0 |
| 92 |
} |
| 93 |
client := &http.Client{Transport: tr, Timeout: timeout} |
| 94 |
|
| 95 |
converters, err := opt.StorageConverters() |
| 96 |
if err != nil { |
| 97 |
return nil, err |
| 98 |
} |
| 99 |
return &RemoteHTTPBase{location: location, client: client, opt: opt, converters: converters, extension: converters.storageExtension()}, nil |
| 100 |
} |
| 101 |
|
| 102 |
func (r *RemoteHTTPBase) String() string { |
| 103 |
return r.location.String() |
| 104 |
} |
| 105 |
|
| 106 |
// Close the HTTP store. NOP operation but needed to implement the interface. |
| 107 |
func (r *RemoteHTTPBase) Close() error { return nil } |
| 108 |
|
| 109 |
// Send a single HTTP request. |
| 110 |
func (r *RemoteHTTPBase) IssueHttpRequest(method string, u *url.URL, getReader GetReaderForRequestBody, attempt int) (int, []byte, error) { |
| 111 |
|
| 112 |
var ( |
| 113 |
resp *http.Response |
| 114 |
log = Log.WithFields(logrus.Fields{ |
| 115 |
"method": method, |
| 116 |
"url": u.String(), |
| 117 |
"attempt": attempt, |
| 118 |
}) |
| 119 |
) |
| 120 |
|
| 121 |
req, err := http.NewRequest(method, u.String(), getReader()) |
| 122 |
if err != nil { |
| 123 |
log.Debug("unable to create new request") |
| 124 |
return 0, nil, err |
| 125 |
} |
| 126 |
if r.opt.HTTPAuth != "" { |
| 127 |
req.Header.Set("Authorization", r.opt.HTTPAuth) |
| 128 |
} |
| 129 |
if r.opt.HTTPCookie != "" { |
| 130 |
req.Header.Set("Cookie", r.opt.HTTPCookie) |
| 131 |
} |
| 132 |
|
| 133 |
log.Debug("sending request") |
| 134 |
resp, err = r.client.Do(req) |
| 135 |
if err != nil { |
| 136 |
log.WithError(err).Error("error while sending request") |
| 137 |
return 0, nil, errors.Wrap(err, u.String()) |
| 138 |
} |
| 139 |
|
| 140 |
defer resp.Body.Close() |
| 141 |
|
| 142 |
b, err := io.ReadAll(resp.Body) |
| 143 |
if err != nil { |
| 144 |
log.WithError(err).Error("error while reading response") |
| 145 |
return 0, nil, errors.Wrap(err, u.String()) |
| 146 |
} |
| 147 |
|
| 148 |
log.WithField("statusCode", resp.StatusCode).Debug("response received") |
| 149 |
return resp.StatusCode, b, nil |
| 150 |
} |
| 151 |
|
| 152 |
// Send a single HTTP request, retrying if a retryable error has occurred. |
| 153 |
func (r *RemoteHTTPBase) IssueRetryableHttpRequest(method string, u *url.URL, getReader GetReaderForRequestBody) (int, []byte, error) { |
| 154 |
|
| 155 |
var ( |
| 156 |
attempt int |
| 157 |
log = Log.WithFields(logrus.Fields{ |
| 158 |
"method": method, |
| 159 |
"url": u.String(), |
| 160 |
}) |
| 161 |
) |
| 162 |
|
| 163 |
retry: |
| 164 |
attempt++ |
| 165 |
statusCode, responseBody, err := r.IssueHttpRequest(method, u, getReader, attempt) |
| 166 |
|
| 167 |
if (err != nil) || (statusCode >= 500 && statusCode < 600) { |
| 168 |
if attempt >= r.opt.ErrorRetry { |
| 169 |
log.WithField("attempt", attempt).Debug("failed, giving up") |
| 170 |
// Return the last response as-is. In the server-error case err is |
| 171 |
// nil and the callers report the actual status code and body. |
| 172 |
return statusCode, responseBody, err |
| 173 |
} else { |
| 174 |
log.WithField("attempt", attempt).WithField("delay", attempt).Debug("waiting, then retrying") |
| 175 |
time.Sleep(time.Duration(attempt) * r.opt.ErrorRetryBaseInterval) |
| 176 |
goto retry |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
return statusCode, responseBody, nil |
| 181 |
} |
| 182 |
|
| 183 |
// GetObject reads and returns an object in the form of []byte from the store |
| 184 |
func (r *RemoteHTTPBase) GetObject(name string) ([]byte, error) { |
| 185 |
u, _ := r.location.Parse(name) |
| 186 |
statusCode, responseBody, err := r.IssueRetryableHttpRequest("GET", u, func() io.Reader { return nil }) |
| 187 |
if err != nil { |
| 188 |
return nil, err |
| 189 |
} |
| 190 |
switch statusCode { |
| 191 |
case 200: // expected |
| 192 |
return responseBody, nil |
| 193 |
case 404: |
| 194 |
return nil, NoSuchObject{name} |
| 195 |
default: |
| 196 |
return nil, fmt.Errorf("unexpected status code %d from %s", statusCode, name) |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
// StoreObject stores an object to the store. |
| 201 |
func (r *RemoteHTTPBase) StoreObject(name string, getReader GetReaderForRequestBody) error { |
| 202 |
u, _ := r.location.Parse(name) |
| 203 |
statusCode, responseBody, err := r.IssueRetryableHttpRequest("PUT", u, getReader) |
| 204 |
if err != nil { |
| 205 |
return err |
| 206 |
} |
| 207 |
if statusCode != 200 && statusCode != 201 { |
| 208 |
return errors.New(string(responseBody)) |
| 209 |
} |
| 210 |
return nil |
| 211 |
} |
| 212 |
|
| 213 |
// NewRemoteHTTPStore initializes a new store that pulls chunks via HTTP(S) from |
| 214 |
// a remote web server. n defines the size of idle connections allowed. |
| 215 |
func NewRemoteHTTPStore(location *url.URL, opt StoreOptions) (*RemoteHTTP, error) { |
| 216 |
b, err := NewRemoteHTTPStoreBase(location, opt) |
| 217 |
if err != nil { |
| 218 |
return nil, err |
| 219 |
} |
| 220 |
return &RemoteHTTP{b}, nil |
| 221 |
} |
| 222 |
|
| 223 |
// GetChunk reads and returns one chunk from the store |
| 224 |
func (r *RemoteHTTP) GetChunk(id ChunkID) (*Chunk, error) { |
| 225 |
p := r.nameFromID(id) |
| 226 |
b, err := r.GetObject(p) |
| 227 |
if err != nil { |
| 228 |
// The base returns NoSuchObject, but it has to be ChunkMissing for routers to work |
| 229 |
if _, ok := err.(NoSuchObject); ok { |
| 230 |
return nil, ChunkMissing{id} |
| 231 |
} |
| 232 |
return nil, err |
| 233 |
} |
| 234 |
return NewChunkFromStorage(id, b, r.converters, r.opt.SkipVerify) |
| 235 |
} |
| 236 |
|
| 237 |
// HasChunk returns true if the chunk is in the store |
| 238 |
func (r *RemoteHTTP) HasChunk(id ChunkID) (bool, error) { |
| 239 |
p := r.nameFromID(id) |
| 240 |
u, _ := r.location.Parse(p) |
| 241 |
|
| 242 |
statusCode, _, err := r.IssueRetryableHttpRequest("HEAD", u, func() io.Reader { return nil }) |
| 243 |
if err != nil { |
| 244 |
return false, err |
| 245 |
} |
| 246 |
switch statusCode { |
| 247 |
case 200: |
| 248 |
return true, nil |
| 249 |
case 404: |
| 250 |
return false, nil |
| 251 |
default: |
| 252 |
return false, fmt.Errorf("unexpected status code: %d", statusCode) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// StoreChunk adds a new chunk to the store |
| 257 |
func (r *RemoteHTTP) StoreChunk(chunk *Chunk) error { |
| 258 |
p := r.nameFromID(chunk.ID()) |
| 259 |
b, err := chunk.Storage(r.converters) |
| 260 |
if err != nil { |
| 261 |
return err |
| 262 |
} |
| 263 |
return r.StoreObject(p, func() io.Reader { return bytes.NewReader(b) }) |
| 264 |
} |
| 265 |
|
| 266 |
func (r *RemoteHTTP) nameFromID(id ChunkID) string { |
| 267 |
sID := id.String() |
| 268 |
name := path.Join(sID[0:4], sID) + r.extension |
| 269 |
return name |
| 270 |
} |