Compare commits

...
47 Commits
Author SHA1 Message Date
Nick Craig-Wood d07036b92a s3: fix Alibaba OSS "Only support authorization for OSS4-HMAC-SHA256" errors
Some Alibaba Cloud OSS endpoints (dedicated regions in particular)
only accept OSS native V4 signatures (OSS4-HMAC-SHA256) and reject
the AWS style signatures rclone sends. Alibaba also require OSS V4
signatures for accounts created after March 2025 and buckets created
after September 2025.

This implements OSS V4 signing as a custom signer plugged into the
AWS SDK and enables it by default for the Alibaba provider. It can
be controlled with the new --s3-use-oss-v4-auth flag.

The signer translates the x-amz-* request headers into their x-oss-*
equivalents (including the storage class names) so that they take
part in the signature, and translates the x-oss-* response headers
back so the SDK can parse them.

See: https://forum.rclone.org/t/rclone-v1-74-4-cannot-access-alibaba-oss-endpoint-with-oss4-hmac-sha256-only/54090
2026-08-11 20:48:06 +01:00
Nick Craig-Wood 7357fb82a9 internetarchive: fix corrupted files being created when the source ends early
If the source supplied fewer bytes than its declared size, the upload
request failed but a retry could report success even though the stored
file was truncated, because the retry re-sent an already exhausted
reader.

Count the bytes actually read from the source and if they do not match
the declared size return an error.

This was found by the new FsPutShortEOF integration test.
2026-08-11 19:32:12 +01:00
Nick Craig-Wood 5d057549b9 sia: fix corrupted files being created when the source ends early
If the source supplied fewer bytes than its declared size, the upload
request failed but a retry could report success even though the stored
file was truncated, because the retry re-sent an already exhausted
reader.

Count the bytes actually read from the source and if they do not match
the declared size, remove the partially uploaded file and return an
error.

This was found by the new FsPutShortEOF integration test.
2026-08-11 19:32:12 +01:00
Nick Craig-Wood a2baa978db pikpak: fix truncated files being created when the source ends early
If the source supplied fewer bytes than its declared size, the
multipart upload was completed anyway, storing a truncated file and
reporting a successful upload.

Check the number of bytes read from the source against the declared
size before finalising and abort the upload with an error if they do
not match.

This was found by the new FsPutShortEOF integration test.
2026-08-11 19:32:12 +01:00
Nick Craig-Wood 5b7cc097e3 multipart: fix chunked uploads storing truncated objects when the source ends early
If the source supplied fewer bytes than its declared size, the
multipart upload was completed anyway, storing a truncated object and
reporting a successful upload.

Check the number of bytes read from the source against the declared
size before finalising and abort the upload with an error if they do
not match.

This affects all backends which use lib/multipart for chunked uploads:
azureblob, b2, drime, internxt, oracleobjectstorage, s3 and shade.

This was found by the new FsPutShortEOF and TestRcatSizeShortEOF
integration tests.
2026-08-11 19:32:12 +01:00
Nick Craig-Wood e1bf9405e2 filelu: fix truncated files being uploaded successfully when the source ends early
If the source supplied fewer bytes than its declared size, the
truncated file was stored and the upload reported success with the
object claiming the declared size.

Count the bytes actually read from the source and if they do not match
the declared size, remove the truncated file and return an error.

This was found by the new TestRcatSizeShortEOF integration test.
2026-08-11 19:32:12 +01:00
Nick Craig-Wood 884b28c203 azurefiles: fix zero padded files being created when the source ends early
The file is created at the declared size and the data then written
with ranged writes, so if the source supplied fewer bytes than
declared, the remainder of the file was left as zeroes and the upload
reported success.

Count the bytes actually read from the source and if they do not match
the declared size, delete the partially uploaded file (if newly
created) and return an error.

This was found by the new FsPutShortEOF and TestRcatSizeShortEOF
integration tests.
2026-08-11 19:32:12 +01:00
nielash 387b4b5e11 bisync: fix memory leak when running via the rc
Before this change, `fastCopy` created a cancellable context for the sync and
stored its cancel func on the `bisyncRun`, but only ever called it when
gracefully shutting down. On a normal run, it was never called, and until it is
cancelled, a context from `context.WithCancel` stays registered with its nearest
cancellable ancestor.

For an rc job, that ancestor is the job's own context, which the job registry
retains for `--rc-job-expire-duration`. The sync context carries bisync's
`LoggerOpt`, whose `LoggerFn` is a method value on `*bisyncRun`, so a finished
run was kept alive -- including the Path1 and Path2 listings -- for as long as the
job was.

This change fixes the issue by cancelling the sync context when `fastCopy`
returns. The cancel func is still stored on the `bisyncRun`, so a graceful
shutdown can still interrupt a sync that is in progress.
2026-08-08 20:39:49 -04:00
Nick Craig-Wood 1aa9efef17 docs: update sponsor links 2026-08-07 16:28:43 +01:00
Nick Craig-Wood 345758454c Add Edward Klesel to contributors 2026-08-07 16:28:43 +01:00
Edward Klesel e4c7aca6bd azureblob: fix Entra ID server-side copy source authentication
When using Microsoft Entra ID credentials, Azure Blob server-side copy
uses a user delegation SAS URL for the private copy source.

The SAS start time was set to the current local time. Azure Storage
validates the copy source from the service side, and small clock
differences can make that SAS appear not yet valid. The service then
returns 403 CannotVerifyCopySource with AuthenticationFailed.

Start the copy-source SAS 15 minutes in the past, matching Microsoft SAS
guidance for clock skew.
2026-08-06 17:52:42 +01:00
Nick Craig-Wood 5629f2668c overview: fix "internal error: no overview data found" on 32 bit architectures - fixes #9723
The precision field in the backend overview YAML files can hold
fs.ModTimeNotSupported (100 years in nanoseconds) which overflows int
on 32 bit platforms, making the YAML for those backends fail to parse
and causing rclone to log 18 internal errors on every invocation.

Use int64 for the precision field and add a test that parses every
embedded backend YAML file so this is caught on 32 bit test runs.
2026-08-04 19:29:21 +01:00
Nick Craig-Wood a06df7a2de protondrive: fix corrupted uploads after a retried upload error - fixes #9722
When an upload failed part way through with a retryable error (eg a
502 from the block storage servers) the pacer retried the whole upload
call with the same input stream. The stream had already been partially
consumed, so the retry re-created the upload draft and committed just
the remainder of the stream as a complete file, silently truncating
it. With restic over serve restic this corrupted the repository as the
truncated pack was reported as successfully uploaded.

This fixes it by using CallNoRetry for the upload, as the other
backends do, so retryable errors are returned wrapped in a RetryError
for the caller to retry the upload with a fresh stream.
2026-08-04 19:29:21 +01:00
Nick Craig-Wood 9b13247ba8 operations: fix silent truncation of streaming uploads whose source ends early
Uploads through RcatSize with a known size - used by rcat --size, the
rc operations/uploadfile and the serve backends, eg serve restic - did
not check the size of the uploaded object. If the source stream ended
before the declared size worth of data had been read, the truncated
object was reported as a successful upload. This could corrupt data
for callers which trust the result, eg a restic repository accessed
via serve restic (see #9722).

This adds the same size check operations.Copy performs after a copy,
respecting --ignore-size and backends which do not report sizes.
2026-08-04 19:29:21 +01:00
Nick Craig-Wood 1318962a96 docs: fix width of sponsor images on very big screens 2026-08-04 19:29:21 +01:00
Nick Craig-Wood 52b5c4d6c2 Add Anton Karpov to contributors 2026-08-04 19:29:21 +01:00
Anton Karpov 6cb4732cc3 docs: use the --dump form for the obsolete --dump-* flags
The SFTP page said `--dump-auth`, which no longer exists: it became a
value of `--dump`, so the docs asked for a flag rclone would reject.

The same line, and a line in the Swift troubleshooting section, also
used `--dump-headers` and `--dump-bodies`. Those still parse, but
SetFlags logs "--dump-headers is obsolete - please use --dump headers
instead", so the docs were steering readers onto a deprecated form.

The generated flag listings in docs/content/flags.md and
docs/content/commands/rclone.md are left alone: those flags do still
exist, so `--help` output should keep showing them.
2026-08-03 21:35:30 +01:00
Nick Craig-Wood 18fa445ffc compress: fix corrupted objects being created when the source ends early
When the source supplied fewer bytes than its declared size, the
compressed data file was stored under a name containing the declared
size while the metadata recorded the actual number of bytes read.
NewObject looks the data file up by the size in the metadata, so the
resulting object could never be read again, and the upload reported
success.

Check that the number of bytes read matches the declared size after
uploading the data and before writing the metadata, and remove the
data file and return an error if it does not.

This was found by the new FsPutShortEOF integration test.
2026-08-03 20:58:14 +01:00
Nick Craig-Wood e0701daea0 dropbox: don't retry chunked upload requests when the upload has been cancelled
The append loop retries everything once the upload session has
started, so a cancelled context error was retried through all the low
level retries with exponential backoff before the upload gave up.
2026-08-03 20:58:14 +01:00
Nick Craig-Wood bff17664ad dropbox: fix chunked uploads of truncated files never finishing - fixes #9704
A source which returned EOF before supplying as many bytes as it
declared would either commit a truncated file (if the shortfall was
within the final chunk) or loop forever appending empty chunks to the
upload session. Return an error wrapping io.ErrUnexpectedEOF instead.

Note that all dropbox uploads use the chunked upload path with the
default batch_mode of sync, so this affected uploads of every size.
2026-08-03 20:58:14 +01:00
Nick Craig-Wood 03f8582a55 fstests: check uploads terminate when the source ends before its declared size
A source reader which returns EOF before supplying as many bytes as it
declared should not cause a backend Put to hang, panic or create an
object claiming the declared size.

The layers above detect a truncated transfer by comparing sizes after
the upload, so a backend may either return an error or create a
shorter object.

See #9704
2026-08-03 20:58:14 +01:00
Nick Craig-Wood 5024425ba8 Add alliasgher to contributors 2026-08-03 20:58:14 +01:00
alliasgher ea9a64c751 smb: reuse the upload connection for SetModTime - fixes #9675
Object.Update held its connection until the deferred putConnection ran at
function exit, so the SetModTime it does at the end of every upload had to take
a second connection from the pool, dialling a whole new SMB session when the
pool was empty. With N transfers in flight the pool grew to roughly 2N sessions
for no reason.

Return the connection as soon as the file is closed. At that point the upload
has succeeded and remove() can no longer be reached, so nothing else needs it,
and SetModTime picks the same connection straight back out of the pool.
putConnection nils the pointer, so the deferred putConnection becomes a no-op
and the connection is not returned twice.
2026-08-03 17:52:23 +01:00
alliasgher 065af89635 drive: don't list trashed files when removing a directory into the trash - fixes #9681
purgeCheck listed a directory's children with includeAll set, so the Drive API
returned trashed children as well as live ones. The only thing that came of
that was the trashedFiles flag, which is used solely to decide whether to trash
the directory or delete it permanently, and when use_trash is on the directory
gets trashed either way.

That made the common case pay for nothing: after trashing N files in a
directory, removing the now empty directory paged through all N trashed entries,
about one API call and pacer delay per 1000, instead of running a single query
that returns nothing.

Ask the server to filter out trashed children when the directory is going to be
trashed anyway. Hard deletes still enumerate them, since there the distinction
decides whether the directory can be removed permanently (#1040), and
--drive-trashed-only is left alone because it deliberately lists trashed items.
2026-08-03 17:50:37 +01:00
Nick Craig-Wood 3f9d583cff gitannex: reduce subprocess launches in end to end test setup
Write the git configuration for each test's fake home directory as a
file instead of running three "git config --global" commands, and drop
the "git annex version" invocation from repository setup. This removes
four subprocess launches from each of the fifteen test cases.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood b6a82ee56c gitannex: run the end to end test functions in parallel
The subtests within each end to end test function already run in
parallel, but the three test functions themselves ran one after
another.

Marking the functions parallel lets all their subtests overlap.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood c9cd065458 gitannex: skip end to end tests under the race detector
The end to end tests exercise rclone via a separate subprocess spawned
by git-annex, and that subprocess is not built with race
instrumentation.

Running them in the race test therefore adds several minutes to CI
without providing any race coverage. The unit tests in this package
still run under the race detector.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood b3168b3ad6 gitannex: speed up the end to end tests with testremote --fast
Run the full "git annex testremote" suite for a single layout mode and
use "testremote --fast" for the rest.

The full suite repeats the same protocol operations across a matrix of
key sizes and chunk configurations, which exercises client side
git-annex behaviour rather than rclone.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood c4e82700cb gitannex: speed up the end to end tests by removing redundant checks
The migration test ran the full "git annex testremote" suite for every
layout mode after verifying the migration with "git annex fsck".

The fsck calls already prove the migrated data is accessible via the
builtin special remote, and TestEndToEnd covers the special remote
protocol with testremote, so the extra five full testremote runs
duplicated coverage at a cost of tens of seconds each on CI.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood 01d32dbde5 build: fix intermittent CI failures by raising the test timeout to 20m
The cmd/gitannex end to end tests routinely take 230-530s and on slow
CI runners the package exceeds the go test default timeout of 10m.

Raise the per-package timeout to 20m in quicktest and racequicktest to
give slow runners headroom.
2026-08-02 18:25:09 +01:00
Nick Craig-Wood c59083f3b4 Add debaditya to contributors 2026-08-02 18:25:01 +01:00
Nick Craig-Wood a15551a838 Add Loi Nguyen to contributors 2026-08-02 18:25:01 +01:00
Nick Craig-Wood 40dbc9ba22 Add am-at-enrollvb to contributors 2026-08-02 18:25:01 +01:00
Nick Craig-Wood ce8caf0daa Add SillyZir to contributors 2026-08-02 18:25:01 +01:00
Nick Craig-Wood 49e41e7f0b Add acoeur to contributors 2026-08-02 18:25:01 +01:00
Loi Nguyen 23f1dbfe50 smb: test closing failed dial connections
Followup to:

74f9f182aa smb: fix TCP connection leak when connection setup fails - #9678
2026-08-02 11:53:25 +01:00
debaditya c97ab80ca1 dropbox: fix context cancellation (e.g. --max-duration limit) not stopping in-flight requests
This switches the calls to the dropbox SDK over to use the context taking
variants. This allows context cancellation to propagate properly.

Fixes #9688
2026-08-02 11:46:27 +01:00
Loi Nguyen 1d03a77172 vfs: make poll shutdown lifecycle deterministic 2026-08-01 12:44:42 +01:00
Loi Nguyen d5275c4ebb vfs: test poll interval update lifecycle 2026-08-01 12:44:42 +01:00
Loi Nguyen f132aef295 vfs: synchronize poll updates with shutdown - fixes #9689 2026-08-01 12:44:42 +01:00
Loi Nguyen f4e231b094 drive: fetch metadata permissions concurrently - fixes #9682
Before this change permission metadata fetches were serialized by the permission cache mutex.
2026-08-01 12:36:59 +01:00
Loi Nguyen 8c8062da78 dropbox: preserve Paper export paths on lookup - fixes #9691
Direct lookups of exported Dropbox Paper files retained the
caller-visible extension before export metadata processing appended it
again. Track when metadata was resolved through an export path so the
object keeps the requested remote name while listing behavior remains
unchanged.
2026-08-01 12:33:32 +01:00
Loi Nguyen 7f6207fae2 lib/batcher: prevent commits racing shutdown - fixes #9687 2026-08-01 12:29:44 +01:00
am-at-enrollvb 5dd34275dc serve: pass the client IP address to the auth proxy - fixes #4499
The auth proxy was only given the user and their password or public
key, so a proxy program had no way to restrict logins to particular
networks, or to record where an authentication attempt came from.

The JSON sent to the program now has a client_ip key holding the bare
IP the client connected from, with the port stripped so IPv6 arrives
as 2001:db8::1 rather than [2001:db8::1]:52344. An IPv4-mapped IPv6
address is reported as plain IPv4 so that a client arriving over a
dual-stack listener still matches IPv4 networks. The key is omitted
when the client has no IP address.

The IP is also mixed into the backend cache key. That is needed as the
program is only run on a cache miss, so a client from a
non-allowlisted address presenting valid credentials within the 5
minute cache lifetime would get a cache hit and be let in without the
program being consulted at all.
2026-08-01 12:25:06 +01:00
SillyZir 7804c1b315 serve nfs: fix EIO when creating symlinks with --vfs-links
The macOS NFS client sends SETATTR after SYMLINK, which arrives as
Chmod/Chown on the link path. These opened the target with vfs.Open,
which follows symlinks - a freshly created symlink usually dangles, so
the open failed with ENOENT, surfaced to the client as NFS3ERR_IO even
though the link was created.

Add path-based VFS.Chmod and VFS.Chown mirroring VFS.Chtimes. They do
not follow symlinks (lstat semantics, matching VFS.Stat) and return
ENOSYS when the node exists, since the VFS stores neither permissions
nor ownership; serve nfs calls them and masks ENOSYS as before.

Fixes #9627
2026-08-01 12:17:20 +01:00
acoeur 060b997595 azureblob: enable on Solaris
The azure SDK didn't used to compile on Solaris, but now it does.
2026-08-01 00:41:46 +01:00
Nick Craig-Wood 39d8e83a12 Start v1.76.0-DEV development 2026-07-31 18:21:36 +01:00
67 changed files with 2036 additions and 219 deletions

No files matched your search

+6 -2
View File
@@ -93,11 +93,15 @@ test: rclone test_all
@echo "Written logs in test_all.log"
# Quick test
#
# The timeout is raised above the go test default of 10m as the
# cmd/gitannex end to end tests can take longer than that on slow CI
# runners.
quicktest:
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) ./...
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -timeout 20m ./...
racequicktest:
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -cpu=2 -race ./...
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -cpu=2 -race -timeout 20m ./...
compiletest:
RCLONE_CONFIG="/notfound" go test $(LDFLAGS) $(BUILDTAGS) -run XXX ./...
+1 -1
View File
@@ -1 +1 @@
v1.75.0
v1.76.0
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Parallel listing support for azureblob, built on the Apache Arrow
// listing format.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
package azureblob
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Package arrowlist implements the experimental "Blob Listing with Apache
// Arrow" feature on top of the released Azure azblob SDK.
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
package arrowlist
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
+4 -3
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
package azureblob
@@ -70,6 +70,7 @@ const (
defaultChunkSize = 4 * fs.Mebi
defaultAccessTier = blob.AccessTier("") // FIXME AccessTierNone
sasCopyValidity = time.Hour // how long SAS should last when doing server side copy
sasCopyStartSkew = 15 * time.Minute // how far back SAS should start to allow for clock skew
)
// setAcceptEncodingGzip is a per-call policy that sets Accept-Encoding: gzip
@@ -1827,7 +1828,7 @@ func (f *Fs) getUserDelegation(ctx context.Context) (*service.UserDelegationCred
}
// Validity window
start := time.Now().UTC()
start := time.Now().UTC().Add(-sasCopyStartSkew)
expiry := start.Add(2 * sasCopyValidity)
startStr := start.Format(time.RFC3339)
expiryStr := expiry.Format(time.RFC3339)
@@ -1876,7 +1877,7 @@ func (o *Object) getAuth(ctx context.Context, noAuth bool) (srcURL string, err e
// Build the SAS values
perms := sas.BlobPermissions{Read: true}
container, containerPath := o.split()
start := time.Now().UTC()
start := time.Now().UTC().Add(-sasCopyStartSkew)
expiry := start.Add(sasCopyValidity)
vals := sas.BlobSignatureValues{
StartTime: start,
+6 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
package azureblob
@@ -54,6 +54,11 @@ func TestBlockIDCreator(t *testing.T) {
assert.ErrorContains(t, bic2.checkID(chunkNumber, got), "random bytes")
}
func TestCopySASTimingConstants(t *testing.T) {
require.Greater(t, sasCopyStartSkew, time.Duration(0))
require.Greater(t, sasCopyValidity, sasCopyStartSkew)
}
func (f *Fs) testFeatures(t *testing.T) {
// Check first feature flags are set on this remote
enabled := f.Features().SetTier
+1 -1
View File
@@ -1,6 +1,6 @@
// Test AzureBlob filesystem interface
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
package azureblob
+1 -1
View File
@@ -1,7 +1,7 @@
// Build for azureblob for unsupported platforms to stop go complaining
// about "no buildable Go source files "
//go:build plan9 || solaris || js
//go:build plan9 || js
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
package azureblob
+18 -5
View File
@@ -696,11 +696,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
}
// Measure the size if it is unknown
if sizeUnknown {
counter = readers.NewCountingReader(in)
in = counter
}
// Count the bytes read so short reads from the source can be detected
counter = readers.NewCountingReader(in)
in = counter
// Check we have a source MD5 hash...
if hashStr, err := src.Hash(ctx, hash.MD5); err == nil && hashStr != "" {
@@ -735,6 +733,21 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
if sizeUnknown {
// Read the uploaded size - the file will be truncated to that size by updateSizeHashModTime
size = int64(counter.BytesRead())
} else if bytesRead := int64(counter.BytesRead()); bytesRead != size {
// The file was created at the declared size so a short source
// leaves the remainder padded with zeroes
if isNewlyCreated {
if _, delErr := fc.Delete(ctx, nil); delErr != nil {
fs.Errorf(o, "failed to delete partially uploaded file: %v", delErr)
}
} else if bytesRead < size {
// Truncate the file to the bytes actually received so it
// is not left padded to the declared size with zeroes
if _, resizeErr := fc.Resize(ctx, bytesRead, nil); resizeErr != nil {
fs.Errorf(o, "failed to truncate partially updated file: %v", resizeErr)
}
}
return fmt.Errorf("update: expected %d bytes in input, but got %d: %w", size, bytesRead, io.ErrUnexpectedEOF)
}
if hashUnknown {
md5Hash = hasher.Sum(nil)
+10
View File
@@ -698,6 +698,16 @@ func (f *Fs) putWithCustomFunctions(ctx context.Context, in io.Reader, src fs.Ob
return nil, err
}
// Check the source supplied the number of bytes it declared -
// compressed data is stored under a name containing the
// original size so a mismatch makes the object unreadable.
if size := src.Size(); size >= 0 && meta.Size != size {
if removeErr := dataObject.Remove(ctx); removeErr != nil {
fs.Errorf(dataObject, "Failed to remove partially transferred object: %v", removeErr)
}
return nil, fmt.Errorf("expected %d bytes in input, but got %d: %w", size, meta.Size, io.ErrUnexpectedEOF)
}
mo, err := f.putMetadata(ctx, meta, src, options, putMeta)
// meta data upload may fail. in this case we try to remove the original object
+6 -1
View File
@@ -2766,7 +2766,12 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
}
trashedFiles := false
if check {
found, err := f.list(ctx, []string{directoryID}, "", false, false, f.opt.TrashedOnly, true, func(item *drive.File) bool {
// trashedFiles is only consulted to decide between trashing and hard deleting
// below, so when the directory is going to be trashed anyway there is no reason
// to enumerate trashed children: let the server filter them out instead of
// paging through them. Hard deletes still need to see them (#1040).
includeAll := !f.opt.UseTrash || f.opt.TrashedOnly
found, err := f.list(ctx, []string{directoryID}, "", false, false, f.opt.TrashedOnly, includeAll, func(item *drive.File) bool {
if !item.Trashed {
fs.Debugf(dir, "Rmdir: contains file: %q", item.Name)
return true
+104
View File
@@ -8,10 +8,14 @@ import (
"fmt"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"strings"
stdsync "sync"
"sync/atomic"
"testing"
"time"
@@ -25,13 +29,113 @@ import (
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
func newPermissionTestFs(t *testing.T, handler http.Handler) *Fs {
t.Helper()
server := httptest.NewServer(handler)
t.Cleanup(server.Close)
service, err := drive.NewService(
context.Background(),
option.WithHTTPClient(server.Client()),
option.WithEndpoint(server.URL+"/"),
)
require.NoError(t, err)
return &Fs{
svc: service,
pacer: fs.NewPacer(context.Background(), pacer.NewGoogleDrive()),
permissionsMu: new(stdsync.Mutex),
permissions: make(map[string]*drive.Permission),
}
}
func TestInternalGetPermissionConcurrent(t *testing.T) {
const requestCount = 2
arrived := make(chan string, requestCount)
release := make(chan struct{})
var releaseOnce stdsync.Once
releaseRequests := func() {
releaseOnce.Do(func() { close(release) })
}
defer releaseRequests()
f := newPermissionTestFs(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
permissionID := path.Base(r.URL.Path)
arrived <- permissionID
<-release
w.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(w, `{"id":%q,"role":"reader","type":"user"}`, permissionID)
assert.NoError(t, err)
}))
type permissionResult struct {
permission *drive.Permission
inherited bool
err error
}
results := make(chan permissionResult, requestCount)
permissionIDs := []string{"permission-1", "permission-2"}
for _, permissionID := range permissionIDs {
go func() {
permission, inherited, err := f.getPermission(context.Background(), "file-id", permissionID, false)
results <- permissionResult{permission: permission, inherited: inherited, err: err}
}()
}
arrivedIDs := make(map[string]bool, requestCount)
timer := time.NewTimer(time.Second)
defer timer.Stop()
for len(arrivedIDs) < requestCount {
select {
case permissionID := <-arrived:
arrivedIDs[permissionID] = true
case <-timer.C:
releaseRequests()
t.Fatalf("timed out waiting for concurrent permission requests: got %d of %d", len(arrivedIDs), requestCount)
}
}
releaseRequests()
assert.Equal(t, map[string]bool{"permission-1": true, "permission-2": true}, arrivedIDs)
returnedIDs := make(map[string]bool, requestCount)
for range requestCount {
result := <-results
require.NoError(t, result.err)
require.NotNil(t, result.permission)
assert.False(t, result.inherited)
returnedIDs[result.permission.Id] = true
}
assert.Equal(t, arrivedIDs, returnedIDs)
}
func TestInternalGetPermissionCacheHit(t *testing.T) {
var requests atomic.Int32
f := newPermissionTestFs(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
permissionID := path.Base(r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(w, `{"id":%q,"role":"reader","type":"user"}`, permissionID)
assert.NoError(t, err)
}))
first, inherited, err := f.getPermission(context.Background(), "file-id", "permission-1", true)
require.NoError(t, err)
assert.False(t, inherited)
second, inherited, err := f.getPermission(context.Background(), "file-id", "permission-1", true)
require.NoError(t, err)
assert.False(t, inherited)
assert.Same(t, first, second)
assert.Equal(t, int32(1), requests.Load())
}
func TestDriveScopes(t *testing.T) {
for _, test := range []struct {
in string
+4 -2
View File
@@ -106,10 +106,10 @@ var permissionsFields = googleapi.Field(strings.Join([]string{
// getPermission returns permissions for the fileID and permissionID passed in
func (f *Fs) getPermission(ctx context.Context, fileID, permissionID string, useCache bool) (perm *drive.Permission, inherited bool, err error) {
f.permissionsMu.Lock()
defer f.permissionsMu.Unlock()
if useCache {
f.permissionsMu.Lock()
perm = f.permissions[permissionID]
f.permissionsMu.Unlock()
if perm != nil {
return perm, false, nil
}
@@ -131,7 +131,9 @@ func (f *Fs) getPermission(ctx context.Context, fileID, permissionID string, use
cleanPermission(perm)
// cache the permission
f.permissionsMu.Lock()
f.permissions[permissionID] = perm
f.permissionsMu.Unlock()
return perm, inherited, err
}
+1 -1
View File
@@ -19,7 +19,7 @@ func (f *Fs) finishBatch(ctx context.Context, items []*files.UploadSessionFinish
Entries: items,
}
err = f.pacer.Call(func() (bool, error) {
complete, err = f.srv.UploadSessionFinishBatchV2(arg)
complete, err = f.srv.UploadSessionFinishBatchV2Context(ctx, arg)
if retry, err := shouldRetryExclude(ctx, err); !retry {
return retry, err
}
+88 -68
View File
@@ -382,20 +382,20 @@ type Options struct {
// Fs represents a remote dropbox server
type Fs struct {
name string // name of this remote
root string // the path we are working on
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv files.Client // the connection to the dropbox server
svc files.Client // the connection to the dropbox server (unauthorized)
sharing sharing.Client // as above, but for generating sharing links
users users.Client // as above, but for accessing user information
team team.Client // for the Teams API
slashRoot string // root with "/" prefix, lowercase
slashRootSlash string // root with "/" prefix and postfix, lowercase
pacer *fs.Pacer // To pace the API calls
ns string // The namespace we are using or "" for none
name string // name of this remote
root string // the path we are working on
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv files.ContextClient // the connection to the dropbox server
svc files.ContextClient // the connection to the dropbox server (unauthorized)
sharing sharing.ContextClient // as above, but for generating sharing links
users users.ContextClient // as above, but for accessing user information
team team.ContextClient // for the Teams API
slashRoot string // root with "/" prefix, lowercase
slashRootSlash string // root with "/" prefix and postfix, lowercase
pacer *fs.Pacer // To pace the API calls
ns string // The namespace we are using or "" for none
batcher *batcher.Batcher[*files.UploadSessionFinishArg, *files.FileMetadata]
exportExts []exportExtension
}
@@ -577,7 +577,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
}
// NOTE: needs to be created pre-impersonation so we can look up the impersonated user
f.team = team.New(cfg)
f.team = team.NewContext(cfg)
if opt.Impersonate != "" {
user := team.UserSelectorArg{
@@ -588,7 +588,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
members := []*team.UserSelectorArg{&user}
args := team.NewMembersGetInfoArgs(members)
memberIDs, err := f.team.MembersGetInfo(args)
memberIDs, err := f.team.MembersGetInfoContext(ctx, args)
if err != nil {
return nil, fmt.Errorf("invalid dropbox team member: %q: %w", opt.Impersonate, err)
}
@@ -603,10 +603,10 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
cfg.AsAdminID = opt.ImpersonateAdmin
}
f.srv = files.New(cfg)
f.svc = files.New(ucfg)
f.sharing = sharing.New(cfg)
f.users = users.New(cfg)
f.srv = files.NewContext(cfg)
f.svc = files.NewContext(ucfg)
f.sharing = sharing.NewContext(cfg)
f.users = users.NewContext(cfg)
f.features = (&fs.Features{
CaseInsensitive: true,
ReadMimeType: false,
@@ -673,7 +673,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
// If root starts with / then use the actual root
var acc *users.FullAccount
err = f.pacer.Call(func() (bool, error) {
acc, err = f.users.GetCurrentAccount()
acc, err = f.users.GetCurrentAccountContext(ctx)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -693,7 +693,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
// See if the root is actually an object
if f.root != "" {
_, err = f.getFileMetadata(ctx, f.slashRoot)
_, _, err = f.getFileMetadata(ctx, f.slashRoot)
if err == nil {
newRoot := path.Dir(f.root)
if newRoot == "." {
@@ -728,15 +728,16 @@ func (f *Fs) setRoot(root string) {
}
type getMetadataResult struct {
entry files.IsMetadata
notFound bool
err error
entry files.IsMetadata
remoteIsExportPath bool
notFound bool
err error
}
// getMetadata gets the metadata for a file or directory
func (f *Fs) getMetadata(ctx context.Context, objPath string) (res getMetadataResult) {
res.err = f.pacer.Call(func() (bool, error) {
res.entry, res.err = f.srv.GetMetadata(&files.GetMetadataArg{
res.entry, res.err = f.srv.GetMetadataContext(ctx, &files.GetMetadataArg{
Path: f.opt.Enc.FromStandardPath(objPath),
})
return shouldRetry(ctx, res.err)
@@ -779,6 +780,7 @@ func (f *Fs) getMetadataForExt(ctx context.Context, filePath string, wantExportE
ch <- getMetadataResult{notFound: true}
return
}
res.remoteIsExportPath = true
}
// Return our real result or error
@@ -824,7 +826,7 @@ func (f *Fs) possibleMetadatas(ctx context.Context, filePath string) (ret []<-ch
}
// getFileMetadata gets the metadata for a file
func (f *Fs) getFileMetadata(ctx context.Context, filePath string) (*files.FileMetadata, error) {
func (f *Fs) getFileMetadata(ctx context.Context, filePath string) (*files.FileMetadata, bool, error) {
var res getMetadataResult
// Try all possible metadatas
@@ -833,7 +835,7 @@ func (f *Fs) getFileMetadata(ctx context.Context, filePath string) (*files.FileM
res = <-ch
if res.err != nil {
return nil, res.err
return nil, false, res.err
}
if !res.notFound {
break
@@ -841,17 +843,17 @@ func (f *Fs) getFileMetadata(ctx context.Context, filePath string) (*files.FileM
}
if res.notFound {
return nil, fs.ErrorObjectNotFound
return nil, false, fs.ErrorObjectNotFound
}
fileInfo, ok := res.entry.(*files.FileMetadata)
if !ok {
if _, ok = res.entry.(*files.FolderMetadata); ok {
return nil, fs.ErrorIsDir
return nil, false, fs.ErrorIsDir
}
return nil, fs.ErrorNotAFile
return nil, false, fs.ErrorNotAFile
}
return fileInfo, nil
return fileInfo, res.remoteIsExportPath, nil
}
// getDirMetadata gets the metadata for a directory
@@ -910,7 +912,7 @@ func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) e
Limit: 100,
}
err := f.pacer.Call(func() (bool, error) {
res, err = f.sharing.ListFolders(&arg)
res, err = f.sharing.ListFoldersContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -922,7 +924,7 @@ func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) e
Cursor: res.Cursor,
}
err := f.pacer.Call(func() (bool, error) {
res, err = f.sharing.ListFoldersContinue(&arg)
res, err = f.sharing.ListFoldersContinueContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -971,7 +973,7 @@ func (f *Fs) mountSharedFolder(ctx context.Context, id string) error {
SharedFolderId: id,
}
err := f.pacer.Call(func() (bool, error) {
_, err := f.sharing.MountFolder(&arg)
_, err := f.sharing.MountFolderContext(ctx, &arg)
return shouldRetry(ctx, err)
})
return err
@@ -988,7 +990,7 @@ func (f *Fs) listReceivedFiles(ctx context.Context, callback func(fs.DirEntry) e
Limit: 100,
}
err := f.pacer.Call(func() (bool, error) {
res, err = f.sharing.ListReceivedFiles(&arg)
res, err = f.sharing.ListReceivedFilesContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1000,7 +1002,7 @@ func (f *Fs) listReceivedFiles(ctx context.Context, callback func(fs.DirEntry) e
Cursor: res.Cursor,
}
err := f.pacer.Call(func() (bool, error) {
res, err = f.sharing.ListReceivedFilesContinue(&arg)
res, err = f.sharing.ListReceivedFilesContinueContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1107,7 +1109,7 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
arg.Path = "" // Specify root folder as empty string
}
err = f.pacer.Call(func() (bool, error) {
res, err = f.srv.ListFolder(arg)
res, err = f.srv.ListFolderContext(ctx, arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1125,7 +1127,7 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
Cursor: res.Cursor,
}
err = f.pacer.Call(func() (bool, error) {
res, err = f.srv.ListFolderContinue(&arg)
res, err = f.srv.ListFolderContinueContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1162,7 +1164,7 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
var sfMeta *sharing.SharedFolderMetadata
err = f.pacer.Call(func() (bool, error) {
var apiErr error
sfMeta, apiErr = f.sharing.GetFolderMetadata(sharing.NewGetMetadataArgs(folderInfo.SharingInfo.SharedFolderId))
sfMeta, apiErr = f.sharing.GetFolderMetadataContext(ctx, sharing.NewGetMetadataArgs(folderInfo.SharingInfo.SharedFolderId))
return shouldRetry(ctx, apiErr)
})
if err != nil {
@@ -1249,7 +1251,7 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
return cErr
}
err = f.pacer.Call(func() (bool, error) {
_, err = f.srv.CreateFolderV2(&arg2)
_, err = f.srv.CreateFolderV2Context(ctx, &arg2)
return shouldRetry(ctx, err)
})
return err
@@ -1277,7 +1279,7 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error)
}
var res *files.ListFolderResult
err = f.pacer.Call(func() (bool, error) {
res, err = f.srv.ListFolder(arg)
res, err = f.srv.ListFolderContext(ctx, arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1301,7 +1303,7 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error)
// remove it
err = f.pacer.Call(func() (bool, error) {
_, err = f.srv.DeleteV2(&files.DeleteArg{Path: encRoot})
_, err = f.srv.DeleteV2Context(ctx, &files.DeleteArg{Path: encRoot})
return shouldRetry(ctx, err)
})
return err
@@ -1360,7 +1362,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
}
var result *files.RelocationResult
err = f.pacer.Call(func() (bool, error) {
result, err = f.srv.CopyV2(&arg)
result, err = f.srv.CopyV2Context(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1421,7 +1423,7 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
var err error
var result *files.RelocationResult
err = f.pacer.Call(func() (bool, error) {
result, err = f.srv.MoveV2(&arg)
result, err = f.srv.MoveV2Context(ctx, &arg)
switch e := err.(type) {
case files.MoveV2APIError:
// There seems to be a bit of eventual consistency here which causes this to
@@ -1475,7 +1477,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
var linkRes sharing.IsSharedLinkMetadata
err = f.pacer.Call(func() (bool, error) {
linkRes, err = f.sharing.CreateSharedLinkWithSettings(&createArg)
linkRes, err = f.sharing.CreateSharedLinkWithSettingsContext(ctx, &createArg)
return shouldRetry(ctx, err)
})
@@ -1484,7 +1486,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
fs.Debugf(absPath, "can't create link with expiry, trying without")
createArg.Settings.Expires = nil
err = f.pacer.Call(func() (bool, error) {
linkRes, err = f.sharing.CreateSharedLinkWithSettings(&createArg)
linkRes, err = f.sharing.CreateSharedLinkWithSettingsContext(ctx, &createArg)
return shouldRetry(ctx, err)
})
}
@@ -1498,7 +1500,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
}
var listRes *sharing.ListSharedLinksResult
err = f.pacer.Call(func() (bool, error) {
listRes, err = f.sharing.ListSharedLinks(&listArg)
listRes, err = f.sharing.ListSharedLinksContext(ctx, &listArg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1559,7 +1561,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
},
}
err = f.pacer.Call(func() (bool, error) {
_, err = f.srv.MoveV2(&arg)
_, err = f.srv.MoveV2Context(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1573,7 +1575,7 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
var q *users.SpaceUsage
err = f.pacer.Call(func() (bool, error) {
q, err = f.users.GetSpaceUsage()
q, err = f.users.GetSpaceUsageContext(ctx)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1660,7 +1662,7 @@ func (f *Fs) changeNotifyCursor(ctx context.Context) (cursor string, err error)
arg.Path = ""
}
startCursor, err = f.srv.ListFolderGetLatestCursor(arg)
startCursor, err = f.srv.ListFolderGetLatestCursorContext(ctx, arg)
return shouldRetry(ctx, err)
})
@@ -1693,7 +1695,7 @@ func (f *Fs) changeNotifyRunner(ctx context.Context, notifyFunc func(string, fs.
Timeout: timeout,
}
res, err = f.svc.ListFolderLongpoll(&args)
res, err = f.svc.ListFolderLongpollContext(ctx, &args)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1716,7 +1718,7 @@ func (f *Fs) changeNotifyRunner(ctx context.Context, notifyFunc func(string, fs.
Cursor: cursor,
}
err = f.pacer.Call(func() (bool, error) {
changeList, err = f.srv.ListFolderContinue(&arg)
changeList, err = f.srv.ListFolderContinueContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1851,7 +1853,7 @@ func (o *Object) Size() int64 {
return o.bytes
}
func (o *Object) setMetadataForExport(info *files.FileMetadata) {
func (o *Object) setMetadataForExport(info *files.FileMetadata, remoteIsExportPath bool) {
o.bytes = -1
o.hash = ""
@@ -1872,8 +1874,10 @@ func (o *Object) setMetadataForExport(info *files.FileMetadata) {
o.exportType = exportExportable
// get rid of any paper extension, if present
o.remote = strings.TrimSuffix(o.remote, paperExtension)
// add the export extension
o.remote += "." + string(exportExt)
if !remoteIsExportPath {
// add the export extension
o.remote += "." + string(exportExt)
}
}
}
@@ -1881,19 +1885,23 @@ func (o *Object) setMetadataForExport(info *files.FileMetadata) {
//
// This isn't a complete set of metadata and has an inaccurate date
func (o *Object) setMetadataFromEntry(info *files.FileMetadata) error {
return o.setMetadataFromEntryWithExportPath(info, false)
}
func (o *Object) setMetadataFromEntryWithExportPath(info *files.FileMetadata, remoteIsExportPath bool) error {
o.id = info.Id
o.bytes = int64(info.Size)
o.modTime = time.Time(info.ClientModified)
o.hash = info.ContentHash
if !info.IsDownloadable {
o.setMetadataForExport(info)
o.setMetadataForExport(info, remoteIsExportPath)
}
return nil
}
// Reads the entry for a file from dropbox
func (o *Object) readEntry(ctx context.Context) (*files.FileMetadata, error) {
func (o *Object) readEntry(ctx context.Context) (*files.FileMetadata, bool, error) {
return o.fs.getFileMetadata(ctx, o.remotePath())
}
@@ -1903,11 +1911,11 @@ func (o *Object) readEntryAndSetMetadata(ctx context.Context) error {
if !o.modTime.IsZero() {
return nil
}
entry, err := o.readEntry(ctx)
entry, remoteIsExportPath, err := o.readEntry(ctx)
if err != nil {
return err
}
return o.setMetadataFromEntry(entry)
return o.setMetadataFromEntryWithExportPath(entry, remoteIsExportPath)
}
// Returns the remote path for the object
@@ -1961,7 +1969,7 @@ func (o *Object) export(ctx context.Context) (in io.ReadCloser, err error) {
arg := files.ExportArg{Path: o.id, ExportFormat: string(o.exportAPIFormat)}
var exportResult *files.ExportResult
err = o.fs.pacer.Call(func() (bool, error) {
exportResult, in, err = o.fs.srv.Export(&arg)
exportResult, in, err = o.fs.srv.ExportContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1983,7 +1991,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
Url: o.url,
}
err = o.fs.pacer.Call(func() (bool, error) {
_, in, err = o.fs.sharing.GetSharedLinkFile(&arg)
_, in, err = o.fs.sharing.GetSharedLinkFileContext(ctx, &arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -2003,7 +2011,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
ExtraHeaders: headers,
}
err = o.fs.pacer.Call(func() (bool, error) {
_, in, err = o.fs.srv.Download(&arg)
_, in, err = o.fs.srv.DownloadContext(ctx, &arg)
return shouldRetry(ctx, err)
})
@@ -2027,7 +2035,7 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
// start upload
var res *files.UploadSessionStartResult
err = o.fs.pacer.Call(func() (bool, error) {
res, err = o.fs.srv.UploadSessionStart(&files.UploadSessionStartArg{}, nil)
res, err = o.fs.srv.UploadSessionStartContext(ctx, &files.UploadSessionStartArg{}, nil)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -2073,7 +2081,7 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
if _, err = chunk.Seek(skip, io.SeekStart); err != nil {
return false, err
}
err = o.fs.srv.UploadSessionAppendV2(&appendArg, chunk)
err = o.fs.srv.UploadSessionAppendV2Context(ctx, &appendArg, chunk)
// after session is started, we retry everything
if err != nil {
// Check for incorrect offset error and retry with new offset
@@ -2098,11 +2106,23 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
}
}
}
// Don't waste the low level retries if the context has
// been cancelled
if fserrors.ContextError(ctx, &err) {
return false, err
}
return err != nil, err
})
if err != nil {
return nil, err
}
if size >= 0 {
// Check for sources which truncate early
expected := min(uint64(currentChunk)*uint64(chunkSize), uint64(size))
if in.BytesRead() < expected {
return nil, fmt.Errorf("expected %d bytes in input, but only read %d: %w", size, in.BytesRead(), io.ErrUnexpectedEOF)
}
}
if appendArg.Close {
break
}
@@ -2132,7 +2152,7 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
}
err = o.fs.pacer.Call(func() (bool, error) {
entry, err = o.fs.srv.UploadSessionFinish(args, nil)
entry, err = o.fs.srv.UploadSessionFinishContext(ctx, args, nil)
if retry, err := shouldRetryExclude(ctx, err); !retry {
return retry, err
}
@@ -2200,7 +2220,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
entry, err = o.uploadChunked(ctx, in, commitInfo, size)
} else {
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
entry, err = o.fs.srv.Upload(&files.UploadArg{CommitInfo: *commitInfo}, in)
entry, err = o.fs.srv.UploadContext(ctx, &files.UploadArg{CommitInfo: *commitInfo}, in)
return shouldRetry(ctx, err)
})
}
@@ -2225,7 +2245,7 @@ func (o *Object) Remove(ctx context.Context) (err error) {
return errNotSupportedInSharedMode
}
err = o.fs.pacer.Call(func() (bool, error) {
_, err = o.fs.srv.DeleteV2(&files.DeleteArg{
_, err = o.fs.srv.DeleteV2Context(ctx, &files.DeleteArg{
Path: o.fs.opt.Enc.FromStandardPath(o.remotePath()),
})
return shouldRetry(ctx, err)
+219 -1
View File
@@ -2,17 +2,86 @@ package dropbox
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/files"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/batcher"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type paperMetadataClient struct {
files.ContextClient
info *files.FileMetadata
}
func (c paperMetadataClient) GetMetadataContext(ctx context.Context, arg *files.GetMetadataArg) (files.IsMetadata, error) {
if arg.Path == "document" {
return c.info, nil
}
return nil, files.GetMetadataAPIError{
APIError: dropbox.APIError{ErrorSummary: "path/not_found/"},
EndpointError: &files.GetMetadataError{
Tagged: dropbox.Tagged{Tag: files.GetMetadataErrorPath},
Path: &files.LookupError{
Tagged: dropbox.Tagged{Tag: files.LookupErrorNotFound},
},
},
}
}
func TestInternalGetMetadataCancellation(t *testing.T) {
requestStarted := make(chan struct{})
releaseRequest := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(requestStarted)
<-releaseRequest
}))
defer server.Close()
defer close(releaseRequest)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
f := &Fs{
srv: files.NewContext(dropbox.Config{
Client: server.Client(),
URLGenerator: func(hostType string, namespace string, route string) string {
return server.URL
},
}),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(0), pacer.MaxSleep(time.Millisecond))),
}
result := make(chan getMetadataResult, 1)
go func() {
result <- f.getMetadata(ctx, "/file")
}()
select {
case <-requestStarted:
case <-time.After(time.Second):
t.Fatal("Dropbox request did not start")
}
cancel()
select {
case res := <-result:
require.ErrorIs(t, res.err, context.Canceled)
case <-time.After(time.Second):
t.Fatal("Dropbox request did not observe cancellation")
}
}
func TestInternalCheckPathLength(t *testing.T) {
rep := func(n int, r rune) (out string) {
rs := make([]rune, n)
@@ -50,6 +119,155 @@ func TestInternalCheckPathLength(t *testing.T) {
}
}
func TestPaperExportRemote(t *testing.T) {
ctx := context.Background()
info := &files.FileMetadata{
ExportInfo: &files.ExportInfo{ExportAs: "markdown"},
}
f := &Fs{
exportExts: []exportExtension{"md"},
pacer: fs.NewPacer(ctx, pacer.NewDefault()),
srv: paperMetadataClient{info: info},
}
direct, err := f.NewObject(ctx, "document.md")
require.NoError(t, err)
assert.Equal(t, "document.md", direct.Remote())
listed, err := f.newObjectWithInfo(ctx, "document.md", info)
require.NoError(t, err)
assert.Equal(t, "document.md.md", listed.Remote())
legacy, err := f.newObjectWithInfo(ctx, "document.paper", info)
require.NoError(t, err)
assert.Equal(t, "document.md", legacy.Remote())
}
// uploadSessionClient is a mock files.ContextClient which records the
// chunked upload calls made to it
type uploadSessionClient struct {
files.ContextClient
appends int // number of UploadSessionAppendV2Context calls
maxAppends int // fail the append after this many calls to stop runaway loops
bytesWritten int64 // bytes received by UploadSessionAppendV2Context
finishCalled bool // set if UploadSessionFinishContext was called
appended func() // if set, called after each successful append
}
var errTooManyAppends = errors.New("too many appends - upload looping?")
func (c *uploadSessionClient) UploadSessionStartContext(ctx context.Context, arg *files.UploadSessionStartArg, content io.Reader) (*files.UploadSessionStartResult, error) {
return &files.UploadSessionStartResult{SessionId: "session"}, nil
}
func (c *uploadSessionClient) UploadSessionAppendV2Context(ctx context.Context, arg *files.UploadSessionAppendArg, content io.Reader) error {
// the real client fails the request if the context is cancelled
if err := ctx.Err(); err != nil {
return err
}
c.appends++
if c.appends > c.maxAppends {
return errTooManyAppends
}
n, err := io.Copy(io.Discard, content)
if err != nil {
return err
}
c.bytesWritten += n
if c.appended != nil {
c.appended()
}
return nil
}
func (c *uploadSessionClient) UploadSessionFinishContext(ctx context.Context, arg *files.UploadSessionFinishArg, content io.Reader) (*files.FileMetadata, error) {
c.finishCalled = true
return &files.FileMetadata{}, nil
}
// newUploadTestFs makes an Fs with a mock srv for testing uploadChunked
func newUploadTestFs(t *testing.T, srv files.ContextClient, chunkSize fs.SizeSuffix) *Fs {
ctx := context.Background()
f := &Fs{
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(2*time.Millisecond))),
srv: srv,
}
f.opt.ChunkSize = chunkSize
batcherOptions := defaultBatcherOptions
batcherOptions.Mode = "off"
var err error
f.batcher, err = batcher.New(ctx, f, f.commitBatch, batcherOptions)
require.NoError(t, err)
return f
}
// endlessReader supplies bytes forever
type endlessReader struct{}
func (endlessReader) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'x'
}
return len(p), nil
}
func TestUploadChunkedEarlyEOF(t *testing.T) {
ctx := context.Background()
t.Run("MultiChunk", func(t *testing.T) {
// The declared size spans 4 chunks but the source ends after 1.5
client := &uploadSessionClient{maxAppends: 8}
f := newUploadTestFs(t, client, 100)
o := &Object{fs: f, remote: "test.bin"}
_, err := o.uploadChunked(ctx, strings.NewReader(strings.Repeat("a", 150)), files.NewCommitInfo("/test.bin"), 400)
require.Error(t, err)
assert.ErrorIs(t, err, io.ErrUnexpectedEOF)
assert.False(t, client.finishCalled, "must not commit a truncated upload")
})
t.Run("SingleChunk", func(t *testing.T) {
// The declared size fits in one chunk but the source ends early
client := &uploadSessionClient{maxAppends: 8}
f := newUploadTestFs(t, client, 500)
o := &Object{fs: f, remote: "test.bin"}
_, err := o.uploadChunked(ctx, strings.NewReader(strings.Repeat("a", 150)), files.NewCommitInfo("/test.bin"), 400)
require.Error(t, err)
assert.ErrorIs(t, err, io.ErrUnexpectedEOF)
assert.False(t, client.finishCalled, "must not commit a truncated upload")
})
t.Run("Complete", func(t *testing.T) {
// A source which supplies exactly the declared size uploads OK
client := &uploadSessionClient{maxAppends: 8}
f := newUploadTestFs(t, client, 100)
o := &Object{fs: f, remote: "test.bin"}
entry, err := o.uploadChunked(ctx, strings.NewReader(strings.Repeat("a", 250)), files.NewCommitInfo("/test.bin"), 250)
require.NoError(t, err)
require.NotNil(t, entry)
assert.True(t, client.finishCalled)
assert.Equal(t, int64(250), client.bytesWritten)
})
}
func TestUploadChunkedCancel(t *testing.T) {
// Cancelling the context must stop the upload even though every
// append is succeeding
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client := &uploadSessionClient{maxAppends: 8}
client.appended = func() {
if client.appends == 2 {
cancel()
}
}
f := newUploadTestFs(t, client, 100)
o := &Object{fs: f, remote: "test.bin"}
_, err := o.uploadChunked(ctx, endlessReader{}, files.NewCommitInfo("/test.bin"), -1)
require.Error(t, err)
assert.ErrorIs(t, err, context.Canceled)
assert.False(t, client.finishCalled)
}
func (f *Fs) importPaperForTest(t *testing.T) {
content := `# test doc
@@ -64,7 +282,7 @@ Lorem ipsum __dolor__ sit amet
var err error
err = f.pacer.Call(func() (bool, error) {
reader := strings.NewReader(content)
_, err = f.srv.PaperCreate(&arg, reader)
_, err = f.srv.PaperCreateContext(context.Background(), &arg, reader)
return shouldRetry(context.Background(), err)
})
require.NoError(t, err)
+12
View File
@@ -14,6 +14,7 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -141,6 +142,8 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
// Update updates the object with new data
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
size := src.Size()
counter := readers.NewCountingReader(in)
in = counter
if size <= int64(o.fs.opt.UploadCutoff) {
err := o.fs.uploadFile(ctx, in, o.remote)
@@ -155,6 +158,15 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
}
// Check the source supplied the number of bytes it declared
// otherwise a truncated file would be stored as a good upload
if size >= 0 && int64(counter.BytesRead()) != size {
if removeErr := o.Remove(ctx); removeErr != nil {
fs.Errorf(o, "Failed to remove partially transferred object: %v", removeErr)
}
return fmt.Errorf("expected %d bytes in input, but got %d: %w", size, counter.BytesRead(), io.ErrUnexpectedEOF)
}
o.size = size
o.modTime = src.ModTime(ctx)
return nil
+9 -1
View File
@@ -30,6 +30,7 @@ import (
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -854,11 +855,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
// make a PUT request at (IAS3)/encoded(:item/:path)
counter := readers.NewCountingReader(in)
var resp *http.Response
opts := rest.Opts{
Method: "PUT",
Path: "/" + url.PathEscape(path.Join(bucket, bucketPath)),
Body: in,
Body: counter,
ContentLength: &size,
ExtraHeaders: headers,
}
@@ -868,6 +870,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return o.fs.shouldRetry(resp, err)
})
// Check the source supplied the number of bytes it declared
// otherwise a truncated file would be stored as a good upload
if err == nil && size >= 0 && int64(counter.BytesRead()) != size {
err = fmt.Errorf("expected %d bytes in input, but got %d: %w", size, counter.BytesRead(), io.ErrUnexpectedEOF)
}
// we can't update/find metadata here as IA will "ingest" uploaded file(s)
// upon uploads. (you can find its progress at https://archive.org/history/ItemNameHere )
// or we have to wait for finish? (needs polling (frontend)/metadata/:item or scraping (frontend)/history/:item)
+1 -1
View File
@@ -26,7 +26,7 @@ type BackendConfig struct {
Remote string `yaml:"remote"`
Features []string `yaml:"features"`
Hashes []string `yaml:"hashes"`
Precision int `yaml:"precision"`
Precision int64 `yaml:"precision"`
}
// GetBackendConfig from docs/data/backends
+16
View File
@@ -1,8 +1,10 @@
package overview
import (
"strings"
"testing"
"github.com/rclone/rclone/docs/data/backends"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -53,3 +55,17 @@ func TestGetBackendConfig(t *testing.T) {
assert.Equal(t, expectedMemoryConfig, conf, "parsed memory.yaml should match")
}
// Check every embedded backend YAML file parses on all architectures
func TestGetBackendConfigAll(t *testing.T) {
entries, err := backends.BackendFS.ReadDir(".")
require.NoError(t, err)
require.NotEmpty(t, entries)
for _, entry := range entries {
name := strings.TrimSuffix(entry.Name(), ".yaml")
conf, err := GetBackendConfig(name)
assert.NoError(t, err, "failed to load %s", entry.Name())
assert.NotNil(t, conf)
}
}
+7
View File
@@ -128,6 +128,13 @@ func (w *pikpakChunkWriter) Upload(ctx context.Context) (err error) {
return err
}
// Check the source supplied the number of bytes it declared before
// finalising, otherwise a truncated file would be stored as a good
// upload. Returning an error here aborts the upload.
if size >= 0 && off != size {
return fmt.Errorf("multipart upload: expected %d bytes in input, but got %d: %w", size, off, io.ErrUnexpectedEOF)
}
err = w.Close(ctx)
if err != nil {
return fmt.Errorf("multipart upload: failed to finalise: %w", err)
+1 -1
View File
@@ -1114,7 +1114,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
modTime := src.ModTime(ctx)
var linkID string
var fileSystemAttrs *proton.RevisionXAttrCommon
if err = o.fs.pacer.Call(func() (bool, error) {
if err = o.fs.pacer.CallNoRetry(func() (bool, error) {
linkID, fileSystemAttrs, err = o.fs.protonDrive.UploadFileByReader(ctx, folderLinkID, leaf, modTime, in, 0)
return shouldRetry(ctx, err)
}); err != nil {
+384
View File
@@ -0,0 +1,384 @@
// OSS V4 signing (OSS4-HMAC-SHA256) for Alibaba Cloud OSS
//
// Implemented from
// https://www.alibabacloud.com/help/en/oss/developer-reference/recommend-to-use-signature-version-4
package s3
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"net"
"net/http"
"net/textproto"
"net/url"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4signer "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
const (
ossAlgorithm = "OSS4-HMAC-SHA256"
ossUnsignedPayload = "UNSIGNED-PAYLOAD"
ossAmzPrefix = "x-amz-"
ossPrefix = "x-oss-"
)
// ossV4Signer signs requests with OSS native V4 signatures
// (OSS4-HMAC-SHA256) as required by Alibaba Cloud OSS endpoints which
// don't accept AWS style signatures.
//
// Implements the HTTPSignerV4 interface.
type ossV4Signer struct {
region string // signing region for the credential scope
product string // signing product - "oss" or "oss-cloudbox"
endpointHost string // host of the endpoint to detect virtual hosted style requests
}
// newOSSV4Signer creates an OSS V4 signer from the options.
//
// The signing region is derived from the endpoint if possible,
// otherwise the region option is used.
func newOSSV4Signer(opt *Options) *ossV4Signer {
host := ossEndpointHost(opt.Endpoint)
region, product := ossRegionProduct(host)
if region == "" {
region = opt.Region
}
return &ossV4Signer{
region: region,
product: product,
endpointHost: host,
}
}
// ossEndpointHost returns the lower case host part of an endpoint
// which may or may not have a scheme, or "" if it can't be parsed.
func ossEndpointHost(endpoint string) string {
if endpoint == "" {
return ""
}
if !strings.Contains(endpoint, "://") {
endpoint = "https://" + endpoint
}
u, err := url.Parse(endpoint)
if err != nil {
return ""
}
return strings.ToLower(u.Hostname())
}
// ossRegionProduct derives the signing region and product from an OSS
// endpoint host.
//
// Standard endpoints look like oss-<region>[-internal].aliyuncs.com
// and CloudBox endpoints look like
// <cb-id>.<region>.oss-cloudbox[-internal].aliyuncs.com where the
// signing region is the CloudBox ID.
//
// It returns region == "" if the region could not be derived, eg for
// accelerate endpoints or custom domains.
func ossRegionProduct(host string) (region, product string) {
product = "oss"
labels := strings.Split(host, ".")
for _, label := range labels[1:] {
if label == "oss-cloudbox" || label == "oss-cloudbox-internal" {
return labels[0], "oss-cloudbox"
}
}
if r, ok := strings.CutPrefix(labels[0], "oss-"); ok {
r = strings.TrimSuffix(r, "-internal")
if r != "" && !strings.HasPrefix(r, "accelerate") {
region = r
}
}
return region, product
}
// ossStorageClassToOSS maps AWS style storage class names (and upper
// cased native names as produced by SetTier) to the case sensitive
// native OSS names. Native names pass through unchanged.
var ossStorageClassToOSS = map[string]string{
"STANDARD": "Standard",
"STANDARD_IA": "IA",
"GLACIER": "Archive",
"DEEP_ARCHIVE": "ColdArchive",
"ARCHIVE": "Archive",
"COLDARCHIVE": "ColdArchive",
"DEEPCOLDARCHIVE": "DeepColdArchive",
}
// ossStorageClassFromOSS maps native OSS storage class names back to
// the AWS style names the S3 compatible interface uses.
var ossStorageClassFromOSS = map[string]string{
"Standard": "STANDARD",
"IA": "STANDARD_IA",
"Archive": "GLACIER",
"ColdArchive": "DEEP_ARCHIVE",
}
// ossHeaderRename returns the x-oss-* header equivalent to the
// x-amz-* header with the given suffix (the part after "x-amz-",
// lower case). hasKey should be true if the request refers to an
// object rather than a bucket.
//
// It returns "" for headers which should be dropped because the
// signer sets the x-oss-* equivalent itself.
func ossHeaderRename(amzSuffix string, hasKey bool) string {
switch amzSuffix {
case "date", "content-sha256", "security-token":
return ""
case "acl":
// OSS uses different headers for object and bucket ACLs
if hasKey {
return "x-oss-object-acl"
}
return "x-oss-acl"
case "server-side-encryption-aws-kms-key-id":
return "x-oss-server-side-encryption-key-id"
}
return ossPrefix + amzSuffix
}
// ossTranslateRequest renames the x-amz-* headers the SDK generates
// into the x-oss-* equivalents that OSS uses so that they take part
// in the signature. OSS requires all x-oss-* headers sent to be
// signed.
func ossTranslateRequest(req *http.Request, hasKey bool) {
var keys []string
for k := range req.Header {
if strings.HasPrefix(strings.ToLower(k), ossAmzPrefix) {
keys = append(keys, k)
}
}
for _, k := range keys {
values := req.Header.Values(k)
req.Header.Del(k)
newKey := ossHeaderRename(strings.ToLower(k)[len(ossAmzPrefix):], hasKey)
if newKey == "" {
continue
}
switch newKey {
case "x-oss-copy-source":
// OSS wants the copy source to start with a "/"
for i, v := range values {
if !strings.HasPrefix(v, "/") {
values[i] = "/" + v
}
}
case "x-oss-storage-class":
// OSS uses different case sensitive storage class names
for i, v := range values {
if native, ok := ossStorageClassToOSS[v]; ok {
values[i] = native
}
}
}
for _, v := range values {
req.Header.Add(newKey, v)
}
}
}
// ossCanonicalURI returns the canonical URI for the request,
// expanding a virtual hosted style bucket in the host back to
// /bucket/key form.
func (s *ossV4Signer) ossCanonicalURI(u *url.URL) string {
path := u.EscapedPath()
if path == "" {
path = "/"
}
host := strings.ToLower(u.Host)
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if s.endpointHost != "" && strings.HasSuffix(host, "."+s.endpointHost) {
bucket := strings.TrimSuffix(host, "."+s.endpointHost)
path = "/" + bucket + path
}
return path
}
// ossCanonicalQuery returns the canonical query string for the
// request. This signs the query parameters exactly as they are sent
// on the wire except that "+" is re-encoded as %20 and the
// parameters are sorted. Parameters with an empty value are signed
// as a bare name without "=".
func ossCanonicalQuery(rawQuery string) string {
query := strings.ReplaceAll(rawQuery, "+", "%20")
type param struct{ name, value string }
var params []param
for _, part := range strings.Split(query, "&") {
if part == "" {
continue
}
name, value, _ := strings.Cut(part, "=")
params = append(params, param{name, value})
}
sort.Slice(params, func(i, j int) bool {
if params[i].name != params[j].name {
return params[i].name < params[j].name
}
return params[i].value < params[j].value
})
var b strings.Builder
for i, p := range params {
if i > 0 {
b.WriteByte('&')
}
b.WriteString(p.name)
if p.value != "" {
b.WriteByte('=')
b.WriteString(p.value)
}
}
return b.String()
}
// ossCanonicalHeaders returns the canonical headers for the request.
// OSS signs all x-oss-* headers plus content-type and content-md5.
func ossCanonicalHeaders(header http.Header) string {
var names []string
values := make(map[string]string)
for k, vs := range header {
name := strings.ToLower(k)
if name != "content-type" && name != "content-md5" && !strings.HasPrefix(name, ossPrefix) {
continue
}
trimmed := make([]string, len(vs))
for i, v := range vs {
trimmed[i] = strings.TrimSpace(v)
}
names = append(names, name)
values[name] = strings.Join(trimmed, ",")
}
sort.Strings(names)
var b strings.Builder
for _, name := range names {
b.WriteString(name)
b.WriteByte(':')
b.WriteString(values[name])
b.WriteByte('\n')
}
return b.String()
}
// ossHMAC returns the HMAC-SHA256 of value with the given key
func ossHMAC(key []byte, value string) []byte {
h := hmac.New(sha256.New, key)
_, _ = h.Write([]byte(value))
return h.Sum(nil)
}
// SignHTTP signs the request with an OSS V4 signature.
//
// It rewrites the AWS style x-amz-* headers into their x-oss-*
// equivalents before signing.
//
// Implements the HTTPSignerV4 interface.
func (s *ossV4Signer) SignHTTP(ctx context.Context, credentials aws.Credentials, req *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4signer.SignerOptions)) error {
uri := s.ossCanonicalURI(req.URL)
// an object request has a path after the /bucket/ prefix
hasKey := strings.Contains(strings.Trim(uri, "/"), "/")
ossTranslateRequest(req, hasKey)
utcTime := signingTime.UTC()
datetime := utcTime.Format("20060102T150405Z")
date := utcTime.Format("20060102")
req.Header.Set("Date", utcTime.Format(http.TimeFormat))
req.Header.Set("x-oss-date", datetime)
// OSS only supports unsigned payloads with V4 signatures
req.Header.Set("x-oss-content-sha256", ossUnsignedPayload)
if credentials.SessionToken != "" {
req.Header.Set("x-oss-security-token", credentials.SessionToken)
}
canonicalRequest := strings.Join([]string{
req.Method,
uri,
ossCanonicalQuery(req.URL.RawQuery),
ossCanonicalHeaders(req.Header),
"", // no additional signed headers
ossUnsignedPayload,
}, "\n")
hash := sha256.Sum256([]byte(canonicalRequest))
scope := date + "/" + s.region + "/" + s.product + "/aliyun_v4_request"
stringToSign := ossAlgorithm + "\n" + datetime + "\n" + scope + "\n" + hex.EncodeToString(hash[:])
key := ossHMAC([]byte("aliyun_v4"+credentials.SecretAccessKey), date)
key = ossHMAC(key, s.region)
key = ossHMAC(key, s.product)
key = ossHMAC(key, "aliyun_v4_request")
signature := hex.EncodeToString(ossHMAC(key, stringToSign))
req.Header.Set("Authorization", ossAlgorithm+" Credential="+credentials.AccessKeyID+"/"+scope+",Signature="+signature)
return nil
}
// ossTranslateResponse copies x-oss-* response headers to their
// x-amz-* equivalents so the SDK can parse them, eg for user
// metadata, version IDs and storage class.
func ossTranslateResponse(header http.Header) {
additions := make(map[string][]string)
for k, vs := range header {
suffix, ok := strings.CutPrefix(strings.ToLower(k), ossPrefix)
if !ok {
continue
}
amzKey := ossAmzPrefix + suffix
switch suffix {
case "server-side-encryption-key-id":
amzKey = "x-amz-server-side-encryption-aws-kms-key-id"
case "storage-class":
// OSS uses different case sensitive storage class names
mapped := make([]string, len(vs))
for i, v := range vs {
if aws, ok := ossStorageClassFromOSS[v]; ok {
mapped[i] = aws
} else {
mapped[i] = v
}
}
vs = mapped
}
canonical := textproto.CanonicalMIMEHeaderKey(amzKey)
if _, exists := header[canonical]; !exists {
additions[canonical] = vs
}
}
for k, vs := range additions {
header[k] = vs
}
}
// ossTransport is an http.RoundTripper which makes OSS responses
// look like S3 responses to the SDK.
type ossTransport struct {
base http.RoundTripper
}
// RoundTrip implements http.RoundTripper
func (t *ossTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if resp != nil {
ossTranslateResponse(resp.Header)
}
return resp, err
}
// ossFixupResponses returns a copy of client whose responses have
// their x-oss-* headers copied to the x-amz-* equivalents.
func ossFixupResponses(client *http.Client) *http.Client {
newClient := *client
if newClient.Transport == nil {
newClient.Transport = http.DefaultTransport
}
newClient.Transport = &ossTransport{base: newClient.Transport}
return &newClient
}
+211
View File
@@ -0,0 +1,211 @@
package s3
import (
"context"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ossV4TestRequest makes the test request used by the signing test
// vectors from the official OSS Go SDK:
// https://github.com/aliyun/alibabacloud-oss-go-sdk-v2/blob/master/oss/signer/signer_test.go
func ossV4TestRequest(t *testing.T, host string) *http.Request {
req, err := http.NewRequest("PUT", "http://"+host+"/1234%2B-/123/1.txt", nil)
require.NoError(t, err)
req.Header.Add("x-oss-head1", "value")
req.Header.Add("abc", "value")
req.Header.Add("ZAbc", "value")
req.Header.Add("XYZ", "value")
req.Header.Add("content-type", "text/plain")
values := url.Values{}
values.Add("param1", "value1")
values.Add("+param1", "value3")
values.Add("|param1", "value4")
values.Add("+param2", "")
values.Add("|param2", "")
values.Add("param2", "")
req.URL.RawQuery = values.Encode()
return req
}
func TestOSSV4SignHTTP(t *testing.T) {
signer := &ossV4Signer{
region: "cn-hangzhou",
product: "oss",
endpointHost: "oss-cn-hangzhou.aliyuncs.com",
}
req := ossV4TestRequest(t, "bucket.oss-cn-hangzhou.aliyuncs.com")
creds := aws.Credentials{AccessKeyID: "ak", SecretAccessKey: "sk"}
err := signer.SignHTTP(context.Background(), creds, req, "", "s3", "us-east-1", time.Unix(1702743657, 0))
require.NoError(t, err)
assert.Equal(t, "OSS4-HMAC-SHA256 Credential=ak/20231216/cn-hangzhou/oss/aliyun_v4_request,Signature=e21d18daa82167720f9b1047ae7e7f1ce7cb77a31e8203a7d5f4624fa0284afe", req.Header.Get("Authorization"))
assert.Equal(t, time.Unix(1702743657, 0).UTC().Format("20060102T150405Z"), req.Header.Get("x-oss-date"))
assert.Equal(t, "UNSIGNED-PAYLOAD", req.Header.Get("x-oss-content-sha256"))
}
func TestOSSV4SignHTTPToken(t *testing.T) {
signer := &ossV4Signer{
region: "cn-hangzhou",
product: "oss",
endpointHost: "oss-cn-hangzhou.aliyuncs.com",
}
req := ossV4TestRequest(t, "bucket.oss-cn-hangzhou.aliyuncs.com")
creds := aws.Credentials{AccessKeyID: "ak", SecretAccessKey: "sk", SessionToken: "token"}
err := signer.SignHTTP(context.Background(), creds, req, "", "s3", "us-east-1", time.Unix(1702784856, 0))
require.NoError(t, err)
assert.Equal(t, "OSS4-HMAC-SHA256 Credential=ak/20231217/cn-hangzhou/oss/aliyun_v4_request,Signature=b94a3f999cf85bcdc00d332fbd3734ba03e48382c36fa4d5af5df817395bd9ea", req.Header.Get("Authorization"))
assert.Equal(t, "token", req.Header.Get("x-oss-security-token"))
}
func TestOSSV4SignHTTPCloudBox(t *testing.T) {
signer := &ossV4Signer{
region: "cb-123",
product: "oss-cloudbox",
endpointHost: "cb-123.cn-hangzhou.oss-cloudbox.aliyuncs.com",
}
req := ossV4TestRequest(t, "bucket.cb-123.cn-hangzhou.oss-cloudbox.aliyuncs.com")
creds := aws.Credentials{AccessKeyID: "ak", SecretAccessKey: "sk"}
err := signer.SignHTTP(context.Background(), creds, req, "", "s3", "us-east-1", time.Unix(1702743657, 0))
require.NoError(t, err)
assert.Equal(t, "OSS4-HMAC-SHA256 Credential=ak/20231216/cb-123/oss-cloudbox/aliyun_v4_request,Signature=94ce1f12c17d148ea681030275a94449d3357f5b5b21133996eec80af3e08a43", req.Header.Get("Authorization"))
}
func TestOSSRegionProduct(t *testing.T) {
for _, test := range []struct {
host string
region string
product string
}{
{"oss-cn-hangzhou.aliyuncs.com", "cn-hangzhou", "oss"},
{"oss-cn-hangzhou-internal.aliyuncs.com", "cn-hangzhou", "oss"},
{"oss-cn-jinan-acdr-ut-1-internal.aliyuncs.com", "cn-jinan-acdr-ut-1", "oss"},
{"oss-us-east-1.aliyuncs.com", "us-east-1", "oss"},
{"oss-accelerate.aliyuncs.com", "", "oss"},
{"oss-accelerate-overseas.aliyuncs.com", "", "oss"},
{"cb-123.cn-hangzhou.oss-cloudbox.aliyuncs.com", "cb-123", "oss-cloudbox"},
{"cb-123.cn-hangzhou.oss-cloudbox-internal.aliyuncs.com", "cb-123", "oss-cloudbox"},
{"my.custom.domain.example.com", "", "oss"},
{"", "", "oss"},
} {
region, product := ossRegionProduct(test.host)
assert.Equal(t, test.region, region, test.host)
assert.Equal(t, test.product, product, test.host)
}
}
func TestOSSEndpointHost(t *testing.T) {
assert.Equal(t, "oss-cn-hangzhou.aliyuncs.com", ossEndpointHost("oss-cn-hangzhou.aliyuncs.com"))
assert.Equal(t, "oss-cn-hangzhou.aliyuncs.com", ossEndpointHost("https://oss-cn-hangzhou.aliyuncs.com"))
assert.Equal(t, "oss-cn-hangzhou.aliyuncs.com", ossEndpointHost("http://OSS-cn-hangzhou.aliyuncs.com:8080"))
assert.Equal(t, "", ossEndpointHost(""))
}
func TestOSSCanonicalURI(t *testing.T) {
signer := &ossV4Signer{endpointHost: "oss-cn-hangzhou.aliyuncs.com"}
for _, test := range []struct {
url string
want string
hasKey bool
}{
// virtual hosted style
{"https://bucket.oss-cn-hangzhou.aliyuncs.com/", "/bucket/", false},
{"https://bucket.oss-cn-hangzhou.aliyuncs.com/key", "/bucket/key", true},
{"https://bucket.oss-cn-hangzhou.aliyuncs.com/dir/key", "/bucket/dir/key", true},
{"https://bucket.oss-cn-hangzhou.aliyuncs.com", "/bucket/", false},
// path style
{"https://oss-cn-hangzhou.aliyuncs.com/", "/", false},
{"https://oss-cn-hangzhou.aliyuncs.com/bucket", "/bucket", false},
{"https://oss-cn-hangzhou.aliyuncs.com/bucket/key", "/bucket/key", true},
} {
u, err := url.Parse(test.url)
require.NoError(t, err)
uri := signer.ossCanonicalURI(u)
assert.Equal(t, test.want, uri, test.url)
hasKey := strings.Contains(strings.Trim(uri, "/"), "/")
assert.Equal(t, test.hasKey, hasKey, test.url)
}
}
func TestOSSTranslateRequest(t *testing.T) {
req, err := http.NewRequest("PUT", "https://bucket.oss-cn-hangzhou.aliyuncs.com/key", nil)
require.NoError(t, err)
req.Header.Set("X-Amz-Meta-Mtime", "1400000000.000000")
req.Header.Set("X-Amz-Copy-Source", "bucket/path/file")
req.Header.Set("X-Amz-Acl", "private")
req.Header.Set("X-Amz-Storage-Class", "GLACIER")
req.Header.Set("X-Amz-Date", "junk")
req.Header.Set("X-Amz-Content-Sha256", "junk")
req.Header.Set("X-Amz-Security-Token", "junk")
req.Header.Set("X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id", "keyid")
req.Header.Set("Content-Type", "text/plain")
ossTranslateRequest(req, true)
assert.Equal(t, "1400000000.000000", req.Header.Get("x-oss-meta-mtime"))
assert.Equal(t, "/bucket/path/file", req.Header.Get("x-oss-copy-source"))
assert.Equal(t, "private", req.Header.Get("x-oss-object-acl"))
assert.Equal(t, "Archive", req.Header.Get("x-oss-storage-class"))
assert.Equal(t, "keyid", req.Header.Get("x-oss-server-side-encryption-key-id"))
assert.Equal(t, "text/plain", req.Header.Get("Content-Type"))
for k := range req.Header {
assert.False(t, strings.HasPrefix(strings.ToLower(k), "x-amz-"), k)
}
// a copy source which already has a leading / is left alone
req.Header.Set("X-Amz-Copy-Source", "/bucket/path/file")
ossTranslateRequest(req, true)
assert.Equal(t, "/bucket/path/file", req.Header.Get("x-oss-copy-source"))
// storage class names are mapped to the native OSS names
for _, test := range []struct{ in, want string }{
{"STANDARD", "Standard"},
{"STANDARD_IA", "IA"},
{"GLACIER", "Archive"},
{"DEEP_ARCHIVE", "ColdArchive"},
{"DEEPCOLDARCHIVE", "DeepColdArchive"},
{"Standard", "Standard"},
{"IA", "IA"},
{"unknown", "unknown"},
} {
req.Header.Del("x-oss-storage-class")
req.Header.Set("X-Amz-Storage-Class", test.in)
ossTranslateRequest(req, true)
assert.Equal(t, test.want, req.Header.Get("x-oss-storage-class"), test.in)
}
// bucket level requests use x-oss-acl
req, err = http.NewRequest("PUT", "https://bucket.oss-cn-hangzhou.aliyuncs.com/", nil)
require.NoError(t, err)
req.Header.Set("X-Amz-Acl", "private")
ossTranslateRequest(req, false)
assert.Equal(t, "private", req.Header.Get("x-oss-acl"))
}
func TestOSSTranslateResponse(t *testing.T) {
header := http.Header{}
header.Set("X-Oss-Meta-Mtime", "1400000000.000000")
header.Set("X-Oss-Request-Id", "1234")
header.Set("X-Oss-Version-Id", "abcd")
header.Set("X-Oss-Storage-Class", "Standard")
header.Set("X-Oss-Server-Side-Encryption-Key-Id", "keyid")
header.Set("Etag", `"abc"`)
ossTranslateResponse(header)
assert.Equal(t, "1400000000.000000", header.Get("x-amz-meta-mtime"))
assert.Equal(t, "1234", header.Get("x-amz-request-id"))
assert.Equal(t, "abcd", header.Get("x-amz-version-id"))
assert.Equal(t, "STANDARD", header.Get("x-amz-storage-class"))
assert.Equal(t, "keyid", header.Get("x-amz-server-side-encryption-aws-kms-key-id"))
// the x-oss- headers are left in place
assert.Equal(t, "1234", header.Get("x-oss-request-id"))
// an existing x-amz- header is not overwritten
header = http.Header{}
header.Set("X-Oss-Meta-Mtime", "1")
header.Set("X-Amz-Meta-Mtime", "2")
ossTranslateResponse(header)
assert.Equal(t, "2", header.Get("x-amz-meta-mtime"))
}
+1
View File
@@ -35,3 +35,4 @@ storage_class:
bucket_acl: true
quirks:
use_multipart_etag: false # multipar ETags differ from AWS
use_oss_v4_auth: true # some endpoints only accept OSS V4 signatures
+1
View File
@@ -30,6 +30,7 @@ type Quirks struct {
MightGzip *bool `yaml:"might_gzip,omitempty"`
UseMultipartUploads *bool `yaml:"use_multipart_uploads,omitempty"`
UseUnsignedPayload *bool `yaml:"use_unsigned_payload,omitempty"`
UseOSSV4Auth *bool `yaml:"use_oss_v4_auth,omitempty"`
ListVersionsOldestFirst *bool `yaml:"list_versions_oldest_first,omitempty"`
UseXID *bool `yaml:"use_x_id,omitempty"`
SignAcceptEncoding *bool `yaml:"sign_accept_encoding,omitempty"`
+32
View File
@@ -393,6 +393,25 @@ If it is set then rclone will use v2 authentication.
Use this only if v4 signatures don't work, e.g. pre Jewel/v10 CEPH.`,
Default: false,
Advanced: true,
}, {
Name: "use_oss_v4_auth",
Help: `If true use Alibaba Cloud OSS native V4 authentication (OSS4-HMAC-SHA256).
Some Alibaba Cloud OSS endpoints (for example dedicated regions) only
accept OSS V4 signatures and reject AWS style signatures with the
error "Only support authorization for OSS4-HMAC-SHA256". Alibaba
require OSS V4 signatures for accounts created after March 2025 and
buckets created after September 2025.
This is enabled by default for the Alibaba provider.
The region for the signature is read from the endpoint if possible,
otherwise the region option is used.
Note that presigned requests (rclone link and use_presigned_request)
are still signed with AWS style signatures.`,
Default: fs.Tristate{},
Advanced: true,
}, {
Name: "use_dual_stack",
Help: `If true use AWS S3 dual-stack endpoint (IPv6 support).
@@ -1109,6 +1128,7 @@ type Options struct {
UploadConcurrency int `config:"upload_concurrency"`
ForcePathStyle bool `config:"force_path_style"`
V2Auth bool `config:"v2_auth"`
UseOSSV4Auth fs.Tristate `config:"use_oss_v4_auth"`
UseAccelerateEndpoint bool `config:"use_accelerate_endpoint"`
UseARNRegion bool `config:"use_arn_region"`
LeavePartsOnError bool `config:"leave_parts_on_error"`
@@ -1586,6 +1606,11 @@ func s3Connection(ctx context.Context, opt *Options, client *http.Client) (s3Cli
}
setQuirks(opt, provider)
useOSSV4Auth := opt.UseOSSV4Auth.Value && !opt.V2Auth && opt.Region != "other-v2-signature"
if useOSSV4Auth {
// Make OSS responses look like S3 responses
client = ossFixupResponses(client)
}
awsConfig.RetryMaxAttempts = ci.LowLevelRetries
awsConfig.HTTPClient = client
@@ -1636,6 +1661,12 @@ func s3Connection(ctx context.Context, opt *Options, client *http.Client) (s3Cli
s3Opt.HTTPSignerV4 = &v2Signer{opt: opt}
})
}
} else if useOSSV4Auth {
signer := newOSSV4Signer(opt)
fs.Debugf(nil, "Using OSS V4 auth with signing region %q", signer.region)
options = append(options, func(s3Opt *s3.Options) {
s3Opt.HTTPSignerV4 = signer
})
}
// Fixup the request if needed
@@ -1809,6 +1840,7 @@ func setQuirks(opt *Options, provider *Provider) {
opt.UploadCutoff = math.MaxInt64
}
set(&opt.UseUnsignedPayload, true, provider.Quirks.UseUnsignedPayload)
set(&opt.UseOSSV4Auth, false, provider.Quirks.UseOSSV4Auth)
set(&opt.UseXID, true, provider.Quirks.UseXID)
set(&opt.SignAcceptEncoding, true, provider.Quirks.SignAcceptEncoding)
set(&opt.ObjectLockSupported, true, provider.Quirks.ObjectLockSupported)
+11 -1
View File
@@ -24,6 +24,7 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -176,11 +177,12 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
// Update the object with the contents of the io.Reader
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
size := src.Size()
counter := readers.NewCountingReader(in)
var resp *http.Response
opts := rest.Opts{
Method: "POST",
Path: path.Join("/renter/uploadstream/", o.fs.opt.Enc.FromStandardPath(path.Join(o.fs.root, o.remote))),
Body: in,
Body: counter,
ContentLength: &size,
Parameters: url.Values{},
}
@@ -191,6 +193,14 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return o.fs.shouldRetry(resp, err)
})
// Check the source supplied the number of bytes it declared
// otherwise a truncated file would be stored as a good upload.
// The partially uploaded file is cleaned up by Put which copes
// with it appearing asynchronously after the failed upload.
if err == nil && size >= 0 && int64(counter.BytesRead()) != size {
return fmt.Errorf("expected %d bytes in input, but got %d: %w", size, counter.BytesRead(), io.ErrUnexpectedEOF)
}
if err == nil {
err = o.readMetaData(ctx)
}
+5
View File
@@ -836,6 +836,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return fmt.Errorf("Update Close failed: %w", err)
}
// Return the connection so the SetModTime below can reuse it rather than
// dialling a second one - the file is closed so remove() no longer needs
// it. This nils cn out, making the deferred putConnection a no-op.
o.fs.putConnection(&cn, nil)
// Set the modified time and also o.statResult
err = o.SetModTime(ctx, src.ModTime(ctx))
if err != nil {
+91 -1
View File
@@ -1,7 +1,97 @@
// Unit tests for internal SMB functions
package smb
import "testing"
import (
"context"
"errors"
"fmt"
"io"
"net"
"strings"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDialClosesConnectionOnSetupError(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
defer func() { require.NoError(t, listener.Close()) }()
type acceptResult struct {
conn net.Conn
err error
}
accepted := make(chan acceptResult, 1)
go func() {
conn, err := listener.Accept()
accepted <- acceptResult{conn: conn, err: err}
}()
f := &Fs{opt: Options{Pass: "invalid"}}
_, err = f.dial(context.Background(), "tcp", listener.Addr().String())
require.Error(t, err)
var result acceptResult
select {
case result = <-accepted:
case <-time.After(time.Second):
t.Fatal("timed out waiting for server to accept connection")
}
require.NoError(t, result.err)
defer func() { require.NoError(t, result.conn.Close()) }()
require.NoError(t, result.conn.SetReadDeadline(time.Now().Add(time.Second)))
buffer := make([]byte, 1)
n, err := result.conn.Read(buffer)
require.Zero(t, n)
require.ErrorIs(t, err, io.EOF)
}
// TestUploadConnectionReuse checks an upload leaves only one connection in the
// pool, ie the connection it used is available again for the SetModTime which
// follows it rather than a second one being dialled.
//
// This needs a real SMB server so it is skipped if one isn't configured.
func TestUploadConnectionReuse(t *testing.T) {
ctx := context.Background()
fstest.Initialise()
remoteName := *fstest.RemoteName
if remoteName == "" {
remoteName = "TestSMB:rclone"
}
remote, err := fs.NewFs(ctx, remoteName)
if errors.Is(err, fs.ErrorNotFoundInConfigFile) {
t.Skipf("skipping as %q is not configured", remoteName)
}
require.NoError(t, err)
f, ok := remote.(*Fs)
if !ok {
t.Skipf("skipping as %q is not an SMB remote", remoteName)
}
defer func() { require.NoError(t, f.Shutdown(ctx)) }()
// Empty the pool so the connections counted below are only the upload's
require.NoError(t, f.drainPool(ctx))
const contents = "connection reuse test"
remotePath := fmt.Sprintf("rclone-test-connection-reuse-%d.txt", time.Now().UnixNano())
src := object.NewStaticObjectInfo(remotePath, time.Now(), int64(len(contents)), true, nil, nil)
o, err := f.Put(ctx, strings.NewReader(contents), src)
require.NoError(t, err)
defer func() { require.NoError(t, o.Remove(ctx)) }()
f.poolMu.Lock()
pooled := len(f.pool)
f.poolMu.Unlock()
assert.Equal(t, 1, pooled, "upload should leave exactly one connection in the pool")
}
// TestIsPathDir tests the isPathDir function logic
func TestIsPathDir(t *testing.T) {
+16
View File
@@ -4,13 +4,29 @@ A demo proxy for rclone serve sftp/webdav/ftp, etc.
This takes the incoming user/pass and converts it into an sftp backend
running on localhost.
Logins from outside ALLOWED_NETWORKS are refused.
"""
import sys
import json
import ipaddress
ALLOWED_NETWORKS = ["127.0.0.0/8", "::1/128"]
def allowed(ip):
"""Return True if ip is in one of ALLOWED_NETWORKS."""
if ip is None:
return False
address = ipaddress.ip_address(ip)
return any(address in ipaddress.ip_network(network) for network in ALLOWED_NETWORKS)
def main():
i = json.load(sys.stdin)
# Exiting non zero refuses the login - rclone logs whatever we
# write on stderr, so say why.
if not allowed(i.get("client_ip")):
sys.exit("client_ip %s not allowed" % i.get("client_ip"))
o = {
"type": "sftp", # type of backend
"_root": "", # root of the fs
+3 -1
View File
@@ -247,7 +247,9 @@ func (b *bisyncRun) fastCopy(ctx context.Context, fsrc, fdst fs.Fs, files bilib.
b.SyncCI = fs.GetConfig(ctxCopy) // allows us to request graceful shutdown
accounting.Stats(ctxCopy).SetMaxCompletedTransfers(-1) // we need a complete list in the event of graceful shutdown
ctxCopy, b.CancelSync = context.WithCancel(ctxCopy)
ctxCopy, cancel := context.WithCancel(ctxCopy)
defer cancel()
b.CancelSync = cancel
b.testFn()
err := sync.Sync(ctxCopy, fdst, fsrc, b.opt.CreateEmptySrcDirs)
prettyprint(b.queueOpt.logger, "b.queueOpt.logger", fs.LogLevelDebug)
+33 -11
View File
@@ -18,6 +18,7 @@ import (
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/testy"
"github.com/rclone/rclone/lib/buildinfo"
"github.com/rclone/rclone/lib/israce"
)
// checkRcloneBinaryVersion runs whichever rclone is on the PATH and checks
@@ -168,14 +169,17 @@ func (e *e2eTestingContext) runInRepo(t *testing.T, command string, args ...stri
require.NoError(t, err, fmt.Sprintf("+ %s %v failed:\n%s\n", command, args, buf))
}
// createGitRepo creates an empty git repository in the ephemeral repo
// directory. It makes "global" config changes that are ultimately scoped to the
// createGitRepo creates an empty git-annex repository in the ephemeral repo
// directory. The "global" git config it writes is ultimately scoped to the
// calling test thanks to runInRepo() overriding the HOME environment variable.
func (e *e2eTestingContext) createGitRepo(t *testing.T) {
e.runInRepo(t, "git", "annex", "version")
e.runInRepo(t, "git", "config", "--global", "user.name", "User Name")
e.runInRepo(t, "git", "config", "--global", "user.email", "user@example.com")
e.runInRepo(t, "git", "config", "--global", "init.defaultBranch", "main")
gitConfig := "[user]\n" +
"\tname = User Name\n" +
"\temail = user@example.com\n" +
"[init]\n" +
"\tdefaultBranch = main\n"
require.NoError(t, os.WriteFile(
filepath.Join(e.homeDir, ".gitconfig"), []byte(gitConfig), 0600))
e.runInRepo(t, "git", "init")
e.runInRepo(t, "git", "annex", "init")
}
@@ -194,6 +198,13 @@ func skipE2eTestIfNecessary(t *testing.T) {
t.Skip("Skipping on macOS CI - tests frequently time out")
}
// The code under test runs in a separate rclone subprocess which is not
// built with race instrumentation, so running these tests under the race
// detector costs time without adding any race coverage.
if israce.Enabled {
t.Skip("Skipping because the race detector cannot observe the rclone subprocess")
}
// TODO: Support e2e tests on Windows. Need to evaluate the semantics of the
// HOME and PATH environment variables.
switch runtime.GOOS {
@@ -231,6 +242,7 @@ func skipE2eTestIfNecessary(t *testing.T) {
// parameters like repo layouts, and runtime may suffer from a combinatorial
// explosion.
func TestEndToEnd(t *testing.T) {
t.Parallel()
skipE2eTestIfNecessary(t)
for _, mode := range allLayoutModes() {
@@ -247,14 +259,25 @@ func TestEndToEnd(t *testing.T) {
"rcloneremotename=MyRcloneRemote", "rcloneprefix="+testingContext.ephemeralRepoDir,
"rclonelayout="+string(mode))
testingContext.runInRepo(t, "git", "annex", "testremote", "MyTestRemote")
// Layout modes only vary how object paths are constructed, so
// one layout mode gets the full testremote suite for depth. The
// rest use --fast, which still exercises every special remote
// protocol operation but skips the key size and chunking matrix
// that mostly tests git-annex itself.
if mode == layoutModeNodir {
testingContext.runInRepo(t, "git", "annex", "testremote", "MyTestRemote")
} else {
testingContext.runInRepo(t, "git", "annex", "testremote", "--fast", "MyTestRemote")
}
})
}
}
// For each layout mode, migrate a single remote from git-annex-remote-rclone to
// git-annex-remote-rclone-builtin and run `git annex testremote`.
// For each layout mode, migrate a single remote from git-annex-remote-rclone
// to git-annex-remote-rclone-builtin and verify that annexed files remain
// accessible.
func TestEndToEndMigration(t *testing.T) {
t.Parallel()
skipE2eTestIfNecessary(t)
if _, err := exec.LookPath("git-annex-remote-rclone"); err != nil {
@@ -303,8 +326,6 @@ func TestEndToEndMigration(t *testing.T) {
)
tc.runInRepo(t, "git", "annex", "fsck", "--from=MigratedRemote", "foo")
tc.runInRepo(t, "git", "annex", "testremote", "MigratedRemote")
})
}
}
@@ -314,6 +335,7 @@ func TestEndToEndMigration(t *testing.T) {
// remote are present on the other. Similarly, test that files deleted from one
// are removed on the other.
func TestEndToEndRepoLayoutCompat(t *testing.T) {
t.Parallel()
skipE2eTestIfNecessary(t)
if _, err := exec.LookPath("git-annex-remote-rclone"); err != nil {
+2 -2
View File
@@ -317,7 +317,7 @@ func (l *Logger) PrintResponse(sessionID string, code int, message string) {
// CheckPasswd handle auth based on configuration
func (d *driver) CheckPasswd(sctx *ftp.Context, user, pass string) (ok bool, err error) {
if d.proxy != nil {
_, _, err = d.proxy.Call(user, pass, false)
_, _, err = d.proxy.Call(user, pass, false, sctx.Sess.RemoteAddr().String())
if err != nil {
fs.Infof(nil, "proxy login failed: %v", err)
return false, nil
@@ -366,7 +366,7 @@ func (d *driver) getVFS(sctx *ftp.Context) (VFS *vfs.VFS, err error) {
if err != nil {
return nil, err
}
VFS, _, err = d.proxy.Call(user, pass, false)
VFS, _, err = d.proxy.Call(user, pass, false, sctx.Sess.RemoteAddr().String())
if err != nil {
return nil, fmt.Errorf("proxy login failed: %w", err)
}
+2 -2
View File
@@ -175,8 +175,8 @@ func (s *HTTP) getVFS(ctx context.Context) (VFS *vfs.VFS, err error) {
}
// auth does proxy authorization
func (s *HTTP) auth(user, pass string) (value any, err error) {
VFS, _, err := s.proxy.Call(user, pass, false)
func (s *HTTP) auth(r *http.Request, user, pass string) (value any, err error) {
VFS, _, err := s.proxy.Call(user, pass, false, r.RemoteAddr)
if err != nil {
return nil, err
}
+6 -19
View File
@@ -186,16 +186,7 @@ func (f *FS) Readlink(link string) (result string, err error) {
func (f *FS) Chmod(name string, mode os.FileMode) (err error) {
name = f.fullPath(name)
defer log.Trace(name, "mode=%v", mode)("err=%v", &err)
file, err := f.vfs.Open(name)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
fs.Logf(f, "Error while closing file: %e", err)
}
}()
err = file.Chmod(mode)
err = f.vfs.Chmod(name, mode)
// Mask Chmod not implemented
if err == vfs.ENOSYS {
err = nil
@@ -213,16 +204,12 @@ func (f *FS) Lchown(name string, uid, gid int) (err error) {
func (f *FS) Chown(name string, uid, gid int) (err error) {
name = f.fullPath(name)
defer log.Trace(name, "uid=%d, gid=%d", uid, gid)("err=%v", &err)
file, err := f.vfs.Open(name)
if err != nil {
return err
err = f.vfs.Chown(name, uid, gid)
// Mask Chown not implemented
if err == vfs.ENOSYS {
err = nil
}
defer func() {
if err := file.Close(); err != nil {
fs.Logf(f, "Error while closing file: %e", err)
}
}()
return file.Chown(uid, gid)
return err
}
// Chtimes changes the access time and modified time
+41
View File
@@ -0,0 +1,41 @@
//go:build unix
package nfs
import (
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Chmod/Chown arrive as plain SETATTR calls on the link path after a
// SYMLINK RPC, so they must not follow symlinks - a freshly created
// symlink usually dangles and following it would fail with ENOENT,
// which the NFS layer surfaces as an IO error. See #9627.
func TestChmodDanglingSymlink(t *testing.T) {
ctx := t.Context()
f, err := fs.NewFs(ctx, t.TempDir())
require.NoError(t, err)
opt := vfscommon.Opt
opt.Links = true
opt.CacheMode = vfscommon.CacheModeWrites
v := vfs.New(ctx, f, &opt)
defer v.Shutdown()
bfs := &FS{vfs: v}
// Create a symlink pointing at a target which doesn't exist yet
require.NoError(t, bfs.Symlink("does-not-exist", "link"))
// SETATTR after SYMLINK must not fail
assert.NoError(t, bfs.Chmod("link", 0777))
assert.NoError(t, bfs.Chown("link", 1000, 1000))
assert.NoError(t, bfs.Lchown("link", 1000, 1000))
// A genuinely missing node must still report ENOENT
assert.ErrorIs(t, bfs.Chmod("missing", 0777), vfs.ENOENT)
assert.ErrorIs(t, bfs.Chown("missing", 1000, 1000), vfs.ENOENT)
}
+60 -30
View File
@@ -12,6 +12,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net/netip"
"os/exec"
"strings"
"time"
@@ -62,7 +63,8 @@ process (on STDIN) would look similar to this:
|||json
{
"user": "me",
"pass": "mypassword"
"pass": "mypassword",
"client_ip": "192.168.1.1"
}
|||
@@ -72,10 +74,18 @@ proxy process (on STDIN) would look similar to this:
|||json
{
"user": "me",
"public_key": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDuwESFdAe14hVS6omeyX7edc...JQdf"
"public_key": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDuwESFdAe14hVS6omeyX7edc...JQdf",
"client_ip": "192.168.1.1"
}
|||
The |client_ip| key holds the IP address the client connected from,
without a port number. It can be used to restrict logins to certain
networks, or to log authentication attempts centrally. It is omitted if
the client has no IP address, for example when connecting over a unix
socket. Note that if rclone is behind a reverse proxy this will be the
address of the reverse proxy and not the original client.
And as an example return this on STDOUT
|||json
@@ -101,11 +111,12 @@ to make proxy to many different sftp backends, you could make the
in the output and the user to |user|. For security you'd probably want
to restrict the |host| to a limited list.
An internal cache of backends is keyed on the |user| and a hash of the
|pass| or |public_key|. This means that if a user's password or
public-key changes, or the proxy returns different config parameters
(eg a rotated |api_key|), a fresh backend will be created on the next
request rather than the cached one being reused.
An internal cache of backends is keyed on the |user|, a hash of the
|pass| or |public_key|, and the |client_ip|. This means that if a
user's password or public-key changes, the client connects from a new IP
address, or the proxy returns different config parameters (eg a rotated
|api_key|), a fresh backend will be created on the next request rather
than the cached one being reused.
This can be used to build general purpose proxies to any kind of
backend that rclone supports.
@@ -212,29 +223,41 @@ var cacheKeyHMACKey = func() []byte {
return key
}()
// generateCacheKey creates a composite cache key from user and auth credentials
func generateCacheKey(user, auth string) string {
// ipFromAddr returns the bare IP from a "host:port" address, or "" if it has none.
func ipFromAddr(addr string) string {
ap, err := netip.ParseAddrPort(addr)
if err != nil {
return ""
}
return ap.Addr().Unmap().String()
}
// generateCacheKey creates a composite cache key from the user, the auth
// credentials and the client's IP address.
func generateCacheKey(user, auth, clientIP string) string {
mac := hmac.New(sha256.New, cacheKeyHMACKey)
mac.Write([]byte(auth))
// Separate the two so ("ab", "c") can't collide with ("a", "bc")
mac.Write([]byte{0})
mac.Write([]byte(clientIP))
return user + "-" + hex.EncodeToString(mac.Sum(nil)[:8])
}
// call runs the auth proxy and returns a cacheEntry and an error
func (p *Proxy) call(user, auth string, isPublicKey bool) (value any, err error) {
var config configmap.Simple
func (p *Proxy) call(user, auth string, isPublicKey bool, clientIP string) (value any, err error) {
// Contact the proxy
if isPublicKey {
config, err = p.run(map[string]string{
"user": user,
"public_key": auth,
})
} else {
config, err = p.run(map[string]string{
"user": user,
"pass": auth,
})
in := map[string]string{
"user": user,
}
if isPublicKey {
in["public_key"] = auth
} else {
in["pass"] = auth
}
if clientIP != "" {
in["client_ip"] = clientIP
}
config, err := p.run(in)
if err != nil {
return nil, err
}
@@ -255,10 +278,10 @@ func (p *Proxy) call(user, auth string, isPublicKey bool) (value any, err error)
return nil, fmt.Errorf("proxy: couldn't find backend for %q: %w", fsName, err)
}
// Make the cache key include the auth so that changes to the
// auth (eg the proxy returning new config) create a fresh
// backend rather than reusing the cached one.
cacheKey := generateCacheKey(user, auth)
// Make the cache key include the auth and the client IP so that
// changes to either (eg the proxy returning new config) create a
// fresh backend rather than reusing the cached one.
cacheKey := generateCacheKey(user, auth, clientIP)
// base name of config on user name and auth hash. This may appear in logs
name := "proxy-" + cacheKey
@@ -298,16 +321,23 @@ func (p *Proxy) call(user, auth string, isPublicKey bool) (value any, err error)
// Call runs the auth proxy with the username and password/public key provided
// returning a *vfs.VFS and the key used in the VFS cache.
func (p *Proxy) Call(user, auth string, isPublicKey bool) (VFS *vfs.VFS, vfsKey string, err error) {
// Cache key includes the auth so credential changes don't hit a stale entry
cacheKey := generateCacheKey(user, auth)
//
// remoteAddr is the address of the client as returned by net.Addr.String().
// It may be empty if the client has no IP address, for example when
// connecting over a unix socket.
func (p *Proxy) Call(user, auth string, isPublicKey bool, remoteAddr string) (VFS *vfs.VFS, vfsKey string, err error) {
clientIP := ipFromAddr(remoteAddr)
// Cache key includes the auth and the client IP so credential or
// address changes don't hit a stale entry
cacheKey := generateCacheKey(user, auth, clientIP)
// Look in the cache first with the credential-aware key
value, ok := p.vfsCache.GetMaybe(cacheKey)
// If not found then call the proxy for a fresh answer
if !ok {
value, err = p.call(user, auth, isPublicKey)
value, err = p.call(user, auth, isPublicKey, clientIP)
if err != nil {
return nil, "", err
}
+93 -13
View File
@@ -42,6 +42,25 @@ func TestRun(t *testing.T) {
}, config)
})
t.Run("ClientIP", func(t *testing.T) {
config, err := p.run(map[string]string{
"type": "ftp",
"user": "me",
"pass": "pass",
"host": "127.0.0.1",
"client_ip": "192.0.2.1",
})
require.NoError(t, err)
assert.Equal(t, configmap.Simple{
"type": "ftp",
"user": "me-test",
"pass": "pass",
"host": "127.0.0.1",
"client_ip": "192.0.2.1",
"_root": "",
}, config)
})
t.Run("Error", func(t *testing.T) {
config, err := p.run(map[string]string{
"error": "potato",
@@ -74,6 +93,24 @@ func TestRun(t *testing.T) {
const testUser = "testUser"
const testPass = "testPass"
const testIP = "192.0.2.1"
const testAddr = testIP + ":1024"
const otherAddr = "198.51.100.1:1024"
t.Run("CacheKey", func(t *testing.T) {
// The source port differs on every connection so it must not
// affect the cache key, otherwise the proxy would be run for
// every connection rather than once per client.
assert.Equal(t,
generateCacheKey(testUser, testPass, ipFromAddr(testIP+":1024")),
generateCacheKey(testUser, testPass, ipFromAddr(testIP+":2048")))
// A different client IP must produce a different key so the
// proxy is consulted again
assert.NotEqual(t,
generateCacheKey(testUser, testPass, ipFromAddr(testAddr)),
generateCacheKey(testUser, testPass, ipFromAddr(otherAddr)))
})
t.Run("call w/Password", func(t *testing.T) {
// check cache empty
@@ -81,7 +118,7 @@ func TestRun(t *testing.T) {
defer p.vfsCache.Clear()
passwordBytes := []byte(testPass)
value, err := p.call(testUser, testPass, false)
value, err := p.call(testUser, testPass, false, testIP)
require.NoError(t, err)
entry, ok := value.(cacheEntry)
require.True(t, ok)
@@ -91,7 +128,7 @@ func TestRun(t *testing.T) {
require.NotNil(t, entry.vfs)
f := entry.vfs.Fs()
require.NotNil(t, f)
cacheKey := generateCacheKey(testUser, testPass)
cacheKey := generateCacheKey(testUser, testPass, testIP)
assert.Equal(t, "proxy-"+cacheKey, f.Name())
assert.True(t, strings.HasPrefix(f.String(), "Local file system"))
@@ -107,8 +144,8 @@ func TestRun(t *testing.T) {
assert.Equal(t, 0, p.vfsCache.Entries())
defer p.vfsCache.Clear()
cacheKey := generateCacheKey(testUser, testPass)
vfs, vfsKey, err := p.Call(testUser, testPass, false)
cacheKey := generateCacheKey(testUser, testPass, testIP)
vfs, vfsKey, err := p.Call(testUser, testPass, false, testAddr)
require.NoError(t, err)
require.NotNil(t, vfs)
assert.Equal(t, "proxy-"+cacheKey, vfs.Fs().Name())
@@ -129,7 +166,7 @@ func TestRun(t *testing.T) {
})
// now try again from the cache
vfs, vfsKey, err = p.Call(testUser, testPass, false)
vfs, vfsKey, err = p.Call(testUser, testPass, false, testAddr)
require.NoError(t, err)
require.NotNil(t, vfs)
assert.Equal(t, "proxy-"+cacheKey, vfs.Fs().Name())
@@ -141,7 +178,7 @@ func TestRun(t *testing.T) {
// A different password produces a different cache key, so it
// creates a fresh cache entry rather than hitting the existing
// one. Authentication itself is the proxy script's job.
vfs2, vfsKey2, err := p.Call(testUser, testPass+"different", false)
vfs2, vfsKey2, err := p.Call(testUser, testPass+"different", false, testAddr)
require.NoError(t, err)
require.NotNil(t, vfs2)
assert.NotEqual(t, cacheKey, vfsKey2)
@@ -152,18 +189,40 @@ func TestRun(t *testing.T) {
t.Error("fs/cache returned the stale backend after auth change")
}
// A different client IP also produces a different cache key, so
// the proxy is consulted again rather than the cached backend
// being reused - the proxy may be filtering on the IP.
vfs3, vfsKey3, err := p.Call(testUser, testPass, false, otherAddr)
require.NoError(t, err)
require.NotNil(t, vfs3)
assert.NotEqual(t, cacheKey, vfsKey3)
assert.Equal(t, 3, p.vfsCache.Entries())
// If a cached entry's pwHash somehow doesn't match the supplied
// auth (eg a hash collision on the cache key), Call must reject
// it. Simulate by corrupting the cached pwHash.
entry := cacheEntry{vfs: vfs, pwHash: sha256.Sum256([]byte("tampered"))}
p.vfsCache.Put(cacheKey, entry)
vfs, vfsKey, err = p.Call(testUser, testPass, false)
vfs, vfsKey, err = p.Call(testUser, testPass, false, testAddr)
require.Error(t, err)
require.Contains(t, err.Error(), "incorrect password")
require.Nil(t, vfs)
require.Equal(t, "", vfsKey)
})
t.Run("Call w/o Address", func(t *testing.T) {
// A client with no address, eg on a unix socket, must still
// authenticate
assert.Equal(t, 0, p.vfsCache.Entries())
defer p.vfsCache.Clear()
vfs, vfsKey, err := p.Call(testUser, testPass, false, "")
require.NoError(t, err)
require.NotNil(t, vfs)
assert.Equal(t, generateCacheKey(testUser, testPass, ""), vfsKey)
assert.Equal(t, 1, p.vfsCache.Entries())
})
privateKey, privateKeyErr := rsa.GenerateKey(rand.Reader, 2048)
if privateKeyErr != nil {
fs.Fatal(nil, "error generating test private key "+privateKeyErr.Error())
@@ -180,7 +239,7 @@ func TestRun(t *testing.T) {
assert.Equal(t, 0, p.vfsCache.Entries())
defer p.vfsCache.Clear()
value, err := p.call(testUser, publicKeyString, true)
value, err := p.call(testUser, publicKeyString, true, testIP)
require.NoError(t, err)
entry, ok := value.(cacheEntry)
require.True(t, ok)
@@ -190,7 +249,7 @@ func TestRun(t *testing.T) {
require.NotNil(t, entry.vfs)
f := entry.vfs.Fs()
require.NotNil(t, f)
cacheKey := generateCacheKey(testUser, publicKeyString)
cacheKey := generateCacheKey(testUser, publicKeyString, testIP)
assert.Equal(t, "proxy-"+cacheKey, f.Name())
assert.True(t, strings.HasPrefix(f.String(), "Local file system"))
@@ -206,11 +265,12 @@ func TestRun(t *testing.T) {
assert.Equal(t, 0, p.vfsCache.Entries())
defer p.vfsCache.Clear()
cacheKey := generateCacheKey(testUser, publicKeyString)
cacheKey := generateCacheKey(testUser, publicKeyString, testIP)
vfs, vfsKey, err := p.Call(
testUser,
publicKeyString,
true,
testAddr,
)
require.NoError(t, err)
require.NotNil(t, vfs)
@@ -232,7 +292,7 @@ func TestRun(t *testing.T) {
})
// now try again from the cache
vfs, vfsKey, err = p.Call(testUser, publicKeyString, true)
vfs, vfsKey, err = p.Call(testUser, publicKeyString, true, testAddr)
require.NoError(t, err)
require.NotNil(t, vfs)
assert.Equal(t, "proxy-"+cacheKey, vfs.Fs().Name())
@@ -244,7 +304,7 @@ func TestRun(t *testing.T) {
// A different public key produces a different cache key, so it
// creates a fresh cache entry rather than hitting the existing
// one. Authentication itself is the proxy script's job.
vfs2, vfsKey2, err := p.Call(testUser, publicKeyString+"different", true)
vfs2, vfsKey2, err := p.Call(testUser, publicKeyString+"different", true, testAddr)
require.NoError(t, err)
require.NotNil(t, vfs2)
assert.NotEqual(t, cacheKey, vfsKey2)
@@ -260,10 +320,30 @@ func TestRun(t *testing.T) {
// it. Simulate by corrupting the cached pwHash.
entry := cacheEntry{vfs: vfs, pwHash: sha256.Sum256([]byte("tampered"))}
p.vfsCache.Put(cacheKey, entry)
vfs, vfsKey, err = p.Call(testUser, publicKeyString, true)
vfs, vfsKey, err = p.Call(testUser, publicKeyString, true, testAddr)
require.Error(t, err)
require.Contains(t, err.Error(), "incorrect public key")
require.Nil(t, vfs)
require.Equal(t, "", vfsKey)
})
}
func TestIPFromAddr(t *testing.T) {
for _, test := range []struct {
in string
want string
}{
{"192.0.2.1:1024", "192.0.2.1"},
{"[2001:db8::1]:1024", "2001:db8::1"},
{"[::ffff:192.0.2.1]:1024", "192.0.2.1"},
{"[fe80::1%eth0]:1024", "fe80::1%eth0"},
{"/tmp/rclone.sock", ""},
{"/tmp/foo:bar.sock", ""},
{`C:\Users\me\rclone.sock`, ""},
{"@", ""},
{"<nil>", ""},
{"", ""},
} {
assert.Equal(t, test.want, ipFromAddr(test.in), test.in)
}
}
+3 -3
View File
@@ -133,8 +133,8 @@ func (w *Server) getVFS(ctx context.Context) (VFS *vfs.VFS, err error) {
}
// auth does proxy authorization
func (w *Server) auth(accessKeyID string) (value any, err error) {
VFS, _, err := w.proxy.Call(stringToMd5Hash(accessKeyID), accessKeyID, false)
func (w *Server) auth(r *http.Request, accessKeyID string) (value any, err error) {
VFS, _, err := w.proxy.Call(stringToMd5Hash(accessKeyID), accessKeyID, false, r.RemoteAddr)
if err != nil {
return nil, err
}
@@ -179,7 +179,7 @@ func authPairMiddleware(next http.Handler, ws *Server) http.Handler {
func proxyAuthMiddleware(next http.Handler, ws *Server) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
accessKey, _ := parseAccessKeyID(r)
value, err := ws.auth(accessKey)
value, err := ws.auth(r, accessKey)
if err != nil {
fs.Infof(r.URL.Path, "%s: Auth failed: %v", r.RemoteAddr, err)
}
+2 -1
View File
@@ -172,7 +172,7 @@ func (s *server) configure() (err error) {
fs.Debugf(describeConn(c), "Password login attempt for %s", c.User())
if s.proxy != nil {
// query the proxy for the config
_, vfsKey, err := s.proxy.Call(c.User(), string(pass), false)
_, vfsKey, err := s.proxy.Call(c.User(), string(pass), false, c.RemoteAddr().String())
if err != nil {
return nil, err
}
@@ -199,6 +199,7 @@ func (s *server) configure() (err error) {
c.User(),
base64.StdEncoding.EncodeToString(pubKey.Marshal()),
true,
c.RemoteAddr().String(),
)
if err != nil {
return nil, err
+2 -2
View File
@@ -350,8 +350,8 @@ func (w *WebDAV) getVFS(ctx context.Context) (VFS *vfs.VFS, err error) {
}
// auth does proxy authorization
func (w *WebDAV) auth(user, pass string) (value any, err error) {
VFS, _, err := w.proxy.Call(user, pass, false)
func (w *WebDAV) auth(r *http.Request, user, pass string) (value any, err error) {
VFS, _, err := w.proxy.Call(user, pass, false, r.RemoteAddr)
if err != nil {
return nil, err
}
+8
View File
@@ -1184,3 +1184,11 @@ put them back in again. -->
- Socialpranker <273312799+Socialpranker@users.noreply.github.com>
- phatlc <phatle.hsd@gmail.com>
- Punya Jain <4511945+punya10@users.noreply.github.com>
- acoeur <7315110+forestrock@users.noreply.github.com>
- SillyZir <269283839+SillyZir@users.noreply.github.com>
- am-at-enrollvb <arthur.melton@enrollvb.com>
- Loi Nguyen <vanloi999@gmail.com>
- debaditya <82204129+DebadityaHait@users.noreply.github.com>
- alliasgher <alliasgher123@gmail.com>
- Anton Karpov <karpovantonme@gmail.com>
- Edward Klesel <eklesel@bluecove.com>
+1 -1
View File
@@ -1442,7 +1442,7 @@ SFTP isn't supported under plan9 until [this
issue](https://github.com/pkg/sftp/issues/156) is fixed.
Note that since SFTP isn't HTTP based the following flags don't work
with it: `--dump-headers`, `--dump-bodies`, `--dump-auth`.
with it: `--dump headers`, `--dump bodies`, `--dump auth`.
Note that `--timeout` and `--contimeout` are both supported.
+1 -1
View File
@@ -14,7 +14,7 @@ Thank you to our sponsors:
<!-- markdownlint-capture -->
<!-- markdownlint-disable line-length no-bare-urls -->
{{< sponsor src="/img/logos/exaba.svg" width="300" height="200" title="Visit our sponsor Exaba" link="https://www.exaba.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_content=msp&utm_term=rclone">}}
{{< sponsor src="/img/logos/exaba.svg" width="300" height="200" title="Visit our sponsor Exaba" link="https://exaba.com/product/integration/rclone/?utm_source=rclone&utm_medium=referral&utm_campaign=ad&utm_content=developer&utm_term=rclone">}}
{{< sponsor src="/img/logos/idrive_e2.svg" width="300" height="200" title="Visit our sponsor IDrive e2" link="https://www.idrive.com/e2/?refer=rclone">}}
{{< sponsor src="/img/logos/filescom-enterprise-grade-workflows.png" width="300" height="200" title="Start Your Free Trial Today" link="https://files.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_term=rclone">}}
{{< sponsor src="/img/logos/mega-s4.svg" width="300" height="200" title="MEGA S4: New S3 compatible object storage. High scale. Low cost. Free egress." link="https://mega.io/objectstorage?utm_source=rclone&utm_medium=referral&utm_campaign=rclone-mega-s4&mct=rclonepromo">}}
+1 -1
View File
@@ -709,7 +709,7 @@ Request" error rather than a more sensible error when the
authentication fails for Swift.
So this most likely means your username / password is wrong. You can
investigate further with the `--dump-bodies` flag.
investigate further with the `--dump bodies` flag.
This may also be caused by specifying the region when you shouldn't
have (e.g. OVH).
+5 -5
View File
@@ -1,21 +1,21 @@
<div class="card">
<div class="card-header">Platinum Sponso⁠r</div>
<div class="card-body">
<a href="https://www.exaba.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_content=msp&utm_term=rclone" target="_blank" rel="noopener" title="Visit our sponsor Exaba"><img style="max-width: 100%; height: auto;" src="/img/logos/exaba.svg"></a><br />
<a href="https://exaba.com/product/integration/rclone/?utm_source=rclone&utm_medium=referral&utm_campaign=ad&utm_content=developer&utm_term=rclone" target="_blank" rel="noopener" title="Visit our sponsor Exaba"><img src="/img/logos/exaba.svg"></a><br />
</div>
</div>
<div class="card">
<div class="card-header">Gold Sponso⁠r</div>
<div class="card-body">
<a href="https://www.idrive.com/e2/?refer=rclone" target="_blank" rel="noopener" title="Visit rclone's sponsor IDrive e2"><img src="/img/logos/idrive_e2.svg" viewBox="0 0 60 55"></a><br />
<a href="https://www.idrive.com/e2/?refer=rclone" target="_blank" rel="noopener" title="Visit rclone's sponsor IDrive e2"><img src="/img/logos/idrive_e2.svg"></a><br />
</div>
</div>
<div class="card">
<div class="card-header">Gold Sponso⁠r</div>
<div class="card-body">
<a href="https://files.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_term=rclone" target="_blank" rel="noopener" title="Start Your Free Trial Today"><img style="max-width: 100%; height: auto;" src="/img/logos/filescom-enterprise-grade-workflows.png"></a><br />
<a href="https://files.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_term=rclone" target="_blank" rel="noopener" title="Start Your Free Trial Today"><img style="max-width: 100%; min-width: 100%; height: auto;" src="/img/logos/filescom-enterprise-grade-workflows.png"></a><br />
</div>
</div>
@@ -30,13 +30,13 @@
<div class="card">
<div class="card-header">Silver Sponso⁠r</div>
<div class="card-body">
<a href="https://shade.inc/" target="_blank" rel="noopener" title="Visit rclone's sponsor Shade"><img style="max-width: 100%; height: auto;" src="/img/logos/shade.svg"></a><br />
<a href="https://shade.inc/" target="_blank" rel="noopener" title="Visit rclone's sponsor Shade"><img src="/img/logos/shade.svg"></a><br />
</div>
</div>
<div class="card">
<div class="card-header">Silver Sponso⁠r</div>
<div class="card-body">
<a href="https://dataraven.io/r/rclone" target="_blank" rel="noopener" title="Data Raven: rclone, managed. Unlimited transfers, no per-GB fees."><img style="max-width: 100%; height: auto;" src="/img/logos/data-raven.svg"></a><br />
<a href="https://dataraven.io/r/rclone" target="_blank" rel="noopener" title="Data Raven: rclone, managed. Unlimited transfers, no per-GB fees."><img src="/img/logos/data-raven.svg"></a><br />
</div>
</div>
</div>
+1 -1
View File
@@ -1 +1 @@
v1.75.0
v1.76.0
+9
View File
@@ -1838,6 +1838,15 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
return nil, err
}
// Check transfer - the source may have ended before size
// bytes in which case the object will have been truncated
if sizeDiffers(ctx, info, obj) {
err = fmt.Errorf("corrupted on transfer: sizes differ src %d vs dst(%s) %d", info.Size(), fdst, obj.Size())
err = fs.CountError(ctx, err)
fs.Errorf(obj, "%v", err)
return obj, err
}
} else {
// Size unknown use Rcat
obj, err = Rcat(ctx, fdst, dstFileName, in, modTime, meta)
+12
View File
@@ -1637,6 +1637,18 @@ func TestRcatSize(t *testing.T) {
r.CheckRemoteItems(t, file1, file2)
}
func TestRcatSizeShortEOF(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
const body = "------------------------------------------------------------"
// Upload declaring twice as many bytes as the source supplies
bodyReader := io.NopCloser(strings.NewReader(body))
_, err := operations.RcatSize(ctx, r.Fremote, "potato1", bodyReader, 2*int64(len(body)), t1, nil)
require.Error(t, err, "uploading a source which ends before its declared size must not succeed")
}
func TestRcatSizeMetadata(t *testing.T) {
r := fstest.NewRun(t)
+1 -1
View File
@@ -1,4 +1,4 @@
package fs
// VersionTag of rclone
var VersionTag = "v1.75.0"
var VersionTag = "v1.76.0"
+125
View File
@@ -2544,6 +2544,131 @@ func Run(t *testing.T, opt *Opt) {
}
})
// TestFsPutShortEOF tests uploading a file where the reader
// returns EOF before the declared size worth of data has been
// read.
//
// go test -v -run 'TestIntegration/FsMkdir/FsPutShortEOF'
t.Run("FsPutShortEOF", func(t *testing.T) {
skipIfNotOk(t)
const putTimeout = 5 * time.Minute
// putShortEOF uploads a file declaring declared bytes but
// supplying only actual bytes, then checks the upload
// terminates and removes anything it created.
putShortEOF := func(t *testing.T, remote string, declared, actual int64) {
contents := random.String(int(actual))
obji := object.NewStaticObjectInfo(remote, fstest.Time("2003-02-03T04:05:06.499999999Z"), declared, true, nil, nil)
type result struct {
obj fs.Object
err error
panicked any
}
putCtx, cancel := context.WithCancel(ctx)
defer cancel()
resultChan := make(chan result, 1)
go func() {
var res result
defer func() {
res.panicked = recover()
resultChan <- res
}()
res.obj, res.err = f.Put(putCtx, bytes.NewBufferString(contents), obji)
}()
var res result
select {
case res = <-resultChan:
case <-time.After(putTimeout):
t.Errorf("Put did not return within %v with a source %d bytes short of its declared size", putTimeout, declared-actual)
cancel()
select {
case res = <-resultChan:
case <-time.After(time.Minute):
t.Fatal("Put still did not return after cancelling the context - giving up")
}
}
require.Nil(t, res.panicked, "Put must not panic when the source returns EOF early")
if res.err != nil {
t.Logf("Put returned an error (acceptable): %v", res.err)
// Remove any partial object left behind
obj, err := f.NewObject(ctx, remote)
if err == nil {
assert.NoError(t, obj.Remove(ctx))
}
return
}
// Put claimed success so the object must exist and must
// contain only the bytes actually supplied.
var obj fs.Object
retry(t, "FsPutShortEOF: check uploaded object exists", func() error {
var err error
obj, err = f.NewObject(ctx, remote)
if errors.Is(err, fs.ErrorObjectNotFound) {
return fserrors.RetryErrorf("object not found yet")
}
return err
})
if size := obj.Size(); size >= 0 {
assert.Equal(t, actual, size, "object uploaded from a short source must contain the bytes actually supplied, not the declared size")
}
assert.NoError(t, obj.Remove(ctx))
}
t.Run("Simple", func(t *testing.T) {
var N int64 = 5 * 1024
if *fstest.SizeLimit > 0 && N > *fstest.SizeLimit {
N = *fstest.SizeLimit
t.Logf("Reduce file size due to limit %d", N)
}
putShortEOF(t, "short-eof.bin", 2*N, N)
})
t.Run("Chunked", func(t *testing.T) {
if testing.Short() {
t.Skip("not running with -short")
}
if opt.ChunkedUpload.Skip {
t.Skip("skipping as ChunkedUpload.Skip is set")
}
setUploadChunkSizer, _ := f.(SetUploadChunkSizer)
if setUploadChunkSizer == nil {
t.Skipf("%T does not implement SetUploadChunkSizer", f)
}
setUploadCutoffer, _ := f.(SetUploadCutoffer)
minChunkSize := max(opt.ChunkedUpload.MinChunkSize, 100)
if opt.ChunkedUpload.CeilChunkSize != nil {
minChunkSize = opt.ChunkedUpload.CeilChunkSize(minChunkSize)
}
// Set the minimum chunk size and upload cutoff, restoring them at the end
oldChunkSize, err := setUploadChunkSizer.SetUploadChunkSize(minChunkSize)
require.NoError(t, err)
var oldUploadCutoff fs.SizeSuffix
if setUploadCutoffer != nil {
oldUploadCutoff, err = setUploadCutoffer.SetUploadCutoff(minChunkSize)
require.NoError(t, err)
}
defer func() {
_, err := setUploadChunkSizer.SetUploadChunkSize(oldChunkSize)
assert.NoError(t, err)
if setUploadCutoffer != nil {
_, err := setUploadCutoffer.SetUploadCutoff(oldUploadCutoff)
assert.NoError(t, err)
}
}()
// Declare a size spanning 4 chunks but EOF after 1.5
cs := int64(minChunkSize)
putShortEOF(t, "short-eof-chunked.bin", 4*cs, cs+cs/2)
})
})
// Copy files with chunked copy if available
t.Run("FsCopyChunked", func(t *testing.T) {
skipIfNotOk(t)
+6
View File
@@ -47,6 +47,7 @@ type Batcher[Item, Result any] struct {
in chan request[Item, Result] // incoming items to batch
closed chan struct{} // close to indicate batcher shut down
atexit atexit.FnHandle // atexit handle
admitMu sync.Mutex // serializes Commit admission with shutdown
shutOnce sync.Once // make sure we shutdown once only
wg sync.WaitGroup // wait for shutdown
}
@@ -239,6 +240,7 @@ func (b *Batcher[Item, Result]) Shutdown() {
b.shutOnce.Do(func() {
atexit.Unregister(b.atexit)
fs.Infof(b.f, "Committing uploads - please wait...")
b.admitMu.Lock()
// show that batcher is shutting down
close(b.closed)
// quit the commitLoop by sending a quitRequest message
@@ -247,6 +249,7 @@ func (b *Batcher[Item, Result]) Shutdown() {
// cause write to closed channel in Commit when we are
// exiting due to a signal.
b.in <- request[Item, Result]{quit: true}
b.admitMu.Unlock()
b.wg.Wait()
})
}
@@ -261,8 +264,10 @@ func (b *Batcher[Item, Result]) Shutdown() {
// This should not be called if batching is off - check first with
// IsBatching.
func (b *Batcher[Item, Result]) Commit(ctx context.Context, name string, item Item) (entry Result, err error) {
b.admitMu.Lock()
select {
case <-b.closed:
b.admitMu.Unlock()
return entry, fserrors.FatalError(errors.New("batcher is shutting down"))
default:
}
@@ -273,6 +278,7 @@ func (b *Batcher[Item, Result]) Commit(ctx context.Context, name string, item It
name: name,
result: resp,
}
b.admitMu.Unlock()
// If running async then don't wait for the result
if b.async {
return entry, nil
+89
View File
@@ -19,6 +19,21 @@ type (
Item string
)
// blockingStringer pauses Commit in its debug log after the shutdown check.
type blockingStringer struct {
started chan struct{}
release chan struct{}
once sync.Once
}
func (b *blockingStringer) String() string {
b.once.Do(func() {
close(b.started)
<-b.release
})
return "batcher test"
}
func TestBatcherNew(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
@@ -221,6 +236,80 @@ func TestBatcherCommitShutdown(t *testing.T) {
assert.Equal(t, 10, totalSize)
}
func TestBatcherCommitRacingShutdown(t *testing.T) {
for _, mode := range []string{"sync", "async"} {
t.Run(mode, func(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
oldLogLevel := ci.LogLevel
ci.LogLevel = fs.LogLevelDebug
defer func() { ci.LogLevel = oldLogLevel }()
committed := make(chan struct{})
commitBatch := func(ctx context.Context, items []Item, results []Result, errors []error) error {
close(committed)
for i := range items {
results[i] = Result(items[i])
}
return nil
}
blocker := &blockingStringer{
started: make(chan struct{}),
release: make(chan struct{}),
}
b, err := New[Item, Result](ctx, blocker, commitBatch, Options{
Mode: mode,
Size: 1,
Timeout: time.Hour,
MaxBatchSize: 1000,
})
require.NoError(t, err)
commitDone := make(chan error, 1)
go func() {
_, err := b.Commit(ctx, "item", Item("item"))
commitDone <- err
}()
select {
case <-blocker.started:
case <-time.After(time.Second):
t.Fatal("commit did not reach the admission point")
}
ci.LogLevel = oldLogLevel
shutdownDone := make(chan struct{})
go func() {
b.Shutdown()
close(shutdownDone)
}()
// Give Shutdown a chance to contend with the blocked admission.
select {
case <-b.closed:
case <-time.After(100 * time.Millisecond):
}
close(blocker.release)
select {
case err := <-commitDone:
require.NoError(t, err)
case <-time.After(time.Second):
t.Fatal("commit hung while racing shutdown")
}
select {
case <-shutdownDone:
case <-time.After(time.Second):
t.Fatal("shutdown hung while racing commit")
}
select {
case <-committed:
case <-time.After(time.Second):
t.Fatal("accepted commit was dropped during shutdown")
}
})
}
}
func TestBatcherCommitAsync(t *testing.T) {
ctx := context.Background()
+5 -1
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"html/template"
"net/http"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/flags"
@@ -68,8 +69,11 @@ Use ` + "`--{{ .Prefix }}salt`" + ` to change the password hashing salt from the
// CustomAuthFn if used will be used to authenticate user, pass. If an error
// is returned then the user is not authenticated.
//
// r is the request being authenticated, for example to find the address
// the client connected from in r.RemoteAddr.
//
// If a non nil value is returned then it is added to the context under the key
type CustomAuthFn func(user, pass string) (value any, err error)
type CustomAuthFn func(r *http.Request, user, pass string) (value any, err error)
// AuthConfigInfo descripts the Options in use
var AuthConfigInfo = fs.Options{{
+1 -1
View File
@@ -142,7 +142,7 @@ func MiddlewareAuthCustom(fn CustomAuthFn, realm string, userFromContext bool) M
return
}
value, err := fn(user, pass)
value, err := fn(r, user, pass)
if err != nil {
fs.Infof(r.URL.Path, "%s: Auth failed from %s: %v", r.RemoteAddr, user, err)
goauth.NewBasicAuthenticator(realm, func(user, realm string) string { return "" }).RequireAuth(w, r) //Reuse BasicAuth error reporting
+4 -4
View File
@@ -79,8 +79,8 @@ func TestMiddlewareAuth(t *testing.T) {
},
auth: AuthConfig{
Realm: "test",
CustomAuthFn: func(user, pass string) (value any, err error) {
if user == "custom" && pass == "custom" {
CustomAuthFn: func(r *http.Request, user, pass string) (value any, err error) {
if user == "custom" && pass == "custom" && r.RemoteAddr != "" {
return true, nil
}
return nil, errors.New("invalid credentials")
@@ -304,7 +304,7 @@ func TestMiddlewareAuthCertificateUser(t *testing.T) {
},
auth: AuthConfig{
Realm: "test",
CustomAuthFn: func(user, pass string) (value any, err error) {
CustomAuthFn: func(_ *http.Request, user, pass string) (value any, err error) {
if user == "custom" && pass == "custom" {
return true, nil
}
@@ -326,7 +326,7 @@ func TestMiddlewareAuthCertificateUser(t *testing.T) {
},
auth: AuthConfig{
Realm: "test",
CustomAuthFn: func(user, pass string) (value any, err error) {
CustomAuthFn: func(_ *http.Request, user, pass string) (value any, err error) {
fmt.Println("CUSTOMAUTH", user, pass)
if user == "rclone-dev-client" && pass == "" {
return true, nil
+7
View File
@@ -121,6 +121,13 @@ func UploadMultipart(ctx context.Context, src fs.ObjectInfo, in io.Reader, opt U
return nil, err
}
// Check the source supplied the number of bytes it declared before
// finalising, otherwise a truncated object would be created on the
// backend. Returning an error here aborts the upload.
if size >= 0 && off != size {
return nil, fmt.Errorf("multipart upload: expected %d bytes in input, but got %d: %w", size, off, io.ErrUnexpectedEOF)
}
err = chunkWriter.Close(ctx)
if err != nil {
return nil, fmt.Errorf("multipart upload: failed to finalise: %w", err)
+37 -16
View File
@@ -275,6 +275,8 @@ func getStatus(vfs *VFS, in rc.Params) (out rc.Params, err error) {
for k, v := range in {
return nil, fmt.Errorf("invalid parameter: %s=%s", k, v)
}
vfs.pollMu.Lock()
defer vfs.pollMu.Unlock()
return rc.Params{
"enabled": vfs.Opt.PollInterval != 0,
"supported": vfs.pollChan != nil,
@@ -286,6 +288,32 @@ func getStatus(vfs *VFS, in rc.Params) (out rc.Params, err error) {
}, nil
}
func setPollInterval(vfs *VFS, interval, timeout time.Duration) (timeoutHit bool, err error) {
vfs.pollMu.Lock()
defer vfs.pollMu.Unlock()
if vfs.ctx.Err() != nil {
return false, errors.New("VFS is shutting down")
}
if vfs.pollChan == nil {
return false, errors.New("poll-interval is not supported by this remote")
}
var timeoutChan <-chan time.Time
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
timeoutChan = timer.C
}
select {
case vfs.pollChan <- interval:
vfs.Opt.PollInterval = fs.Duration(interval)
case <-timeoutChan:
timeoutHit = true
case <-vfs.ctx.Done():
return false, errors.New("VFS is shutting down")
}
return timeoutHit, nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/poll-interval",
@@ -332,25 +360,18 @@ func rcPollInterval(ctx context.Context, in rc.Params) (out rc.Params, err error
for k, v := range in {
return nil, fmt.Errorf("invalid parameter: %s=%s", k, v)
}
if vfs.pollChan == nil {
return nil, errors.New("poll-interval is not supported by this remote")
}
if !intervalPresent {
vfs.pollMu.Lock()
supported := vfs.pollChan != nil
vfs.pollMu.Unlock()
if !supported {
return nil, errors.New("poll-interval is not supported by this remote")
}
return getStatus(vfs, in)
}
var timeoutHit bool
var timeoutChan <-chan time.Time
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
timeoutChan = timer.C
}
select {
case vfs.pollChan <- interval:
vfs.Opt.PollInterval = fs.Duration(interval)
case <-timeoutChan:
timeoutHit = true
timeoutHit, err := setPollInterval(vfs, interval, timeout)
if err != nil {
return nil, err
}
out, err = getStatus(vfs, in)
if out != nil {
+163
View File
@@ -2,7 +2,9 @@ package vfs
import (
"context"
"runtime"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
@@ -89,6 +91,40 @@ func TestRcRefresh(t *testing.T) {
// FIXME needs more tests
}
func newTestPollVFS(t *testing.T, changeNotify func(context.Context, func(string, fs.EntryType), <-chan time.Duration)) (*fstest.Run, *VFS, *rc.Call) {
t.Helper()
r := fstest.NewRun(t)
features := r.Fremote.Features()
originalChangeNotify := features.ChangeNotify
features.ChangeNotify = changeNotify
t.Cleanup(func() {
features.ChangeNotify = originalChangeNotify
})
vfs := New(context.Background(), r.Fremote, nil)
t.Cleanup(func() {
if vfs.inUse.Load() > 0 {
vfs.Shutdown()
}
})
call := rc.Calls.Get("vfs/poll-interval")
require.NotNil(t, call)
return r, vfs, call
}
func waitForPollLock(t *testing.T, vfs *VFS) {
t.Helper()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
if vfs.pollMu.TryLock() {
vfs.pollMu.Unlock()
runtime.Gosched()
continue
}
return
}
t.Fatal("poll interval update did not acquire poll lock")
}
func TestRcPollInterval(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/poll-interval")
_ = vfs
@@ -101,6 +137,133 @@ func TestRcPollInterval(t *testing.T) {
// FIXME needs more tests
}
func TestRcPollIntervalShutdown(t *testing.T) {
initialIntervalReceived := make(chan struct{})
r, vfs, call := newTestPollVFS(t, func(_ context.Context, _ func(string, fs.EntryType), pollInterval <-chan time.Duration) {
go func() {
<-pollInterval
close(initialIntervalReceived)
}()
})
<-initialIntervalReceived
originalInterval := vfs.Opt.PollInterval
type result struct {
out rc.Params
err error
}
resultCh := make(chan result, 1)
go func() {
out, err := call.Fn(context.Background(), rc.Params{
"fs": fs.ConfigString(r.Fremote),
"interval": "1h",
})
resultCh <- result{out: out, err: err}
}()
waitForPollLock(t, vfs)
shutdownDone := make(chan struct{})
go func() {
vfs.Shutdown()
close(shutdownDone)
}()
select {
case <-shutdownDone:
case <-time.After(time.Second):
t.Fatal("VFS shutdown blocked behind poll interval update")
}
select {
case got := <-resultCh:
require.EqualError(t, got.err, "VFS is shutting down")
assert.Nil(t, got.out)
case <-time.After(time.Second):
t.Fatal("poll interval update did not return after shutdown")
}
assert.Equal(t, originalInterval, vfs.Opt.PollInterval)
}
func TestSetPollIntervalAfterShutdown(t *testing.T) {
initialIntervalReceived := make(chan struct{})
_, vfs, _ := newTestPollVFS(t, func(_ context.Context, _ func(string, fs.EntryType), pollInterval <-chan time.Duration) {
go func() {
<-pollInterval
close(initialIntervalReceived)
for range pollInterval {
}
}()
})
<-initialIntervalReceived
vfs.Shutdown()
timeoutHit, err := setPollInterval(vfs, time.Hour, 0)
require.EqualError(t, err, "VFS is shutting down")
assert.False(t, timeoutHit)
}
func TestRcPollIntervalUpdate(t *testing.T) {
intervals := make(chan time.Duration, 2)
r, vfs, call := newTestPollVFS(t, func(_ context.Context, _ func(string, fs.EntryType), pollInterval <-chan time.Duration) {
go func() {
for interval := range pollInterval {
intervals <- interval
}
}()
})
assert.Equal(t, time.Duration(vfs.Opt.PollInterval), <-intervals)
status, err := call.Fn(context.Background(), rc.Params{
"fs": fs.ConfigString(r.Fremote),
})
require.NoError(t, err)
assert.Equal(t, true, status["supported"])
assert.Equal(t, vfs.Opt.PollInterval != 0, status["enabled"])
out, err := call.Fn(context.Background(), rc.Params{
"fs": fs.ConfigString(r.Fremote),
"interval": "1h",
})
require.NoError(t, err)
assert.Equal(t, time.Hour, <-intervals)
assert.Equal(t, fs.Duration(time.Hour), vfs.Opt.PollInterval)
assert.Equal(t, false, out["timeout"])
}
func TestRcPollIntervalTimeout(t *testing.T) {
initialIntervalReceived := make(chan struct{})
r, vfs, call := newTestPollVFS(t, func(_ context.Context, _ func(string, fs.EntryType), pollInterval <-chan time.Duration) {
go func() {
<-pollInterval
close(initialIntervalReceived)
}()
})
<-initialIntervalReceived
originalInterval := vfs.Opt.PollInterval
out, err := call.Fn(context.Background(), rc.Params{
"fs": fs.ConfigString(r.Fremote),
"interval": "1h",
"timeout": "10ms",
})
require.NoError(t, err)
assert.Equal(t, true, out["timeout"])
assert.Equal(t, originalInterval, vfs.Opt.PollInterval)
}
func TestRcPollIntervalUnsupported(t *testing.T) {
r, vfs, call := newTestPollVFS(t, nil)
out, err := call.Fn(context.Background(), rc.Params{
"fs": fs.ConfigString(r.Fremote),
"interval": "1h",
})
require.EqualError(t, err, "poll-interval is not supported by this remote")
assert.Nil(t, out)
assert.Nil(t, vfs.pollChan)
}
func TestRcList(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/list")
_ = vfs
+38 -3
View File
@@ -188,6 +188,7 @@ type VFS struct {
usageMu sync.Mutex
usageTime time.Time
usage *fs.Usage
pollMu sync.Mutex
pollChan chan time.Duration
inUse atomic.Int32 // count of number of opens
}
@@ -410,13 +411,15 @@ func (vfs *VFS) Shutdown() {
vfs.shutdownCache()
// Cancel any background go routines
vfs.cancel()
vfs.pollMu.Lock()
if vfs.pollChan != nil {
close(vfs.pollChan)
vfs.pollChan = nil
}
// Cancel any background go routines
vfs.cancel()
vfs.pollMu.Unlock()
}
// CleanUp deletes the contents of the on disk cache
@@ -745,6 +748,38 @@ func (vfs *VFS) Chtimes(name string, atime time.Time, mtime time.Time) error {
return nil
}
// Chmod changes the mode of the named file.
//
// If name is a symlink the mode of the link itself is changed, not
// its target (like lchmod). It does not follow the link, so it works
// on symlinks whose target doesn't exist.
//
// The VFS doesn't store file permissions so currently this returns
// ENOSYS if the file exists and ENOENT if it doesn't.
func (vfs *VFS) Chmod(name string, mode os.FileMode) error {
_, err := vfs.Stat(name)
if err != nil {
return err
}
return ENOSYS
}
// Chown changes the uid and gid of the named file.
//
// If name is a symlink the ownership of the link itself is changed,
// not its target (like lchown). It does not follow the link, so it
// works on symlinks whose target doesn't exist.
//
// The VFS doesn't store file ownership so currently this returns
// ENOSYS if the file exists and ENOENT if it doesn't.
func (vfs *VFS) Chown(name string, uid, gid int) error {
_, err := vfs.Stat(name)
if err != nil {
return err
}
return ENOSYS
}
// mkdir creates a new directory with the specified name and permission bits
// (before umask) returning the new directory node.
func (vfs *VFS) mkdir(name string, perm os.FileMode) (*Dir, error) {