Compare commits

...
Author SHA1 Message Date
Nick Craig-Wood 4b2f9d072a azureblob: fix spurious vfs cache corruption errors during chunked reads - fixes #9782
On a ranged download the metadata decoder stored the response's
Content-Length (the length of the range, not the blob) in the object's
size and only corrected it from the Content-Range total afterwards.
Object.Size() is read concurrently by the VFS cache and chunked reader
while a download is in progress, so with --vfs-read-chunk-size a reader
could observe the chunk length (e.g. 67108864 for 64M chunks) as the
object size. The VFS cache then logged

    vfs cache: cached file (N) is unexpectedly larger than the remote
    object (67108864). The cached file is likely corrupted after an
    unclean shutdown; recovering ...

and truncated the read request against the bogus size, breaking
sequential reads of large blobs with --vfs-cache-mode full.

This applies the Content-Range correction before the size is stored so
the range length is never published as the object size.
2026-08-17 12:48:59 +01:00
Nick Craig-Wood 8cb8689964 lib/rest: make ParseContentRange public 2026-08-17 12:48:22 +01:00
Nick Craig-Wood f0b210a886 build: fix multiple CVEs by upgrading to go1.26.6
- CVE-2026-56860: net/url: quadratic complexity in resolvePath
- CVE-2026-56858: html/template: JavaScript regexp context tracking
- CVE-2026-56862: crypto/tls: limit handshake messages accepted post-handshake
- CVE-2026-56853: net/http: apply ReadHeaderTimeout to unencrypted HTTP/2 check
- CVE-2026-56859: encoding/xml: recursion depth guard during decode
- CVE-2026-33818: encoding/asn1: enforce maximum recursion depth
- CVE-2026-46600: net: panic parsing an invalid SVCB or HTTPS RR in dnsmessage
- CVE-2026-39821: net/http: reject ASCII-only Punycode-encoded labels in idna

This also updates the go1.25 test job to go1.25.13 which contains the
same fixes.
2026-08-14 19:18:26 +01:00
Nick Craig-Wood 00593a96fe build: update golang.org/x/image to v0.45.0 to fix CVE-2026-46603
CVE-2026-46603: excessive memory allocation during VP8L decoding

This also updates golang.org/x/text to v0.41.0 as a dependency.
2026-08-14 19:18:26 +01:00
Nick Craig-Wood 64c9a28651 Add Dave to contributors 2026-08-14 19:18:26 +01:00
Nick Craig-Wood f81ccdf786 Add Shurong Cao to contributors 2026-08-14 19:18:26 +01:00
Nick Craig-Wood 8aba1c4378 Add Morax to contributors 2026-08-14 19:18:26 +01:00
Dave 6e0c71bd27 vfs/vfscache: fix reader deadlock when the item size drops below the read offset
_dispatchWaiters decided whether a waiter was satisfied by clipping its
range against dls.src.Size(), the size of the fs.Object snapshot taken
when the Downloaders was created. _ensureDownloader decided whether to
start a downloader from Item.FindMissing, which clips against
item.info.Size instead.

When item.info.Size dropped below the offset a waiter was parked on while
the source object still reported the full size, the two disagreed.
_ensureDownloader found nothing missing so it started no downloader, and
_dispatchWaiters found the range absent so it never released the waiter.
Nothing was downloaded and no error was produced, so the error count never
reached maxErrorCount and the waiter was never woken. The reader blocked
forever with nothing logged at any level.

Wake a waiter when FindMissing reports nothing left to download for it as
well as when its data has arrived. Since _ensureDownloader starts a
downloader only when FindMissing is non empty, a waiter with nothing
missing has nothing that could ever wake it.

Fixes #9769
2026-08-14 18:51:49 +02:00
Shurong Cao bb7c081ec5 sync: add pattern-based transfer ordering
Allow --order-by to rank files using comma-separated rclone path globs. Patterns are evaluated in order, unmatched files are placed last, and path ordering makes ties deterministic.

Fixes #3975
2026-08-14 18:47:15 +02:00
Morax 9f93da3299 operations: fall back when source ignores ranges
When a multi-thread source ignores ranged reads, abort the partial
destination and retry the copy as a single stream. Reset accounting
before the fallback so transfer progress remains accurate.
2026-08-14 18:40:40 +02:00
Morax 1003280bb1 webdav: reject ignored ranged responses
Validate ranged GET responses before returning their bodies. Close invalid
responses, retry malformed partial responses through the pacer, and return
without retrying when a server deterministically ignores Range.

Fixes #6980
2026-08-14 18:40:40 +02:00
Morax 69e5aff2a9 lib/rest: validate ranged responses
Add response validation for calls made with Range open options. Verify
Content-Range, Content-Length, response status, and the complete
representation size before a backend accepts the response body.

Return a shared sentinel when a server ignores a partial range so callers
can avoid retrying the same unsupported request.
2026-08-14 18:40:40 +02:00
Nick Craig-Wood 5a0b7d6746 crypt: fix hash mismatches with no_data_encryption on backends which check upload hashes
Before this change, when no_data_encryption was set, uploads from
local disk advertised the hash of the encrypted data even though the
data was uploaded unencrypted.

On backends which check upload hashes (eg b2) this made uploads of
small files fail with errors like "Checksum did not match data
received", and made chunked uploads store an incorrect hash so the
files failed their checksum on download with "corrupted on transfer:
SHA1 hashes differ".

See: https://forum.rclone.org/t/sha1-mismatches-on-b2-with-no-data-encryption-true/54121
2026-08-14 09:54:00 +01:00
Nick Craig-Wood afb4fa5f2b Add Pastalikek65 to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood d22c4509aa Add Dean Chen to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood f49e051507 Add Teddy Tennant to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood 926ccdac5d Add Jiacheng Xu to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood 49dc9fb919 Add Recoordinate to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood 7c7635bae3 Add Rodrigo Rodrigues to contributors 2026-08-14 09:54:00 +01:00
Nick Craig-Wood 86f981a05e Add Christian De Santis to contributors 2026-08-14 09:54:00 +01:00
Pastalikek65 adc7f2ebfa config: redact env var config values in logs
Before this change the environment variable getters in fs/configmap.go
logged the option value with %q, so a password set via
RCLONE_CONFIG_remote_pass (or RCLONE_remote_pass) was printed in full
to the debug log. Values from the config file were already redacted,
which made the leak easy to miss.

This change routes both getters through fs.RedactOptionValue, which
looks up the option in the backend's option list: options marked
IsPassword or Sensitive log as XXX, unknown options are conservatively
redacted, and --dump auth still shows the value for debugging.

Fixes #5794
2026-08-13 20:10:41 +02:00
Dean Chen c785ff90d7 docs/mount: mention nfsmount for macOS NFS mounts
The NFS section under Mounting on macOS talked about serve nfs without
pointing at rclone nfsmount, which is the command that actually does the
NFS-based mount on macOS.

Fixes #7869

Signed-off-by: Dean Chen <862469039@qq.com>
2026-08-13 19:59:16 +02:00
Teddy Tennant a182fcbce8 operations: speed up checksum by hashing files in parallel - fixes #9727
rclone checksum and rclone check --checkfile hashed one file at a time
unless --download was in use. The non-download branch of CheckSum called
Object.Hash synchronously from inside the listing callback, so --checkers
had no effect there; only the --download branch used the checker token
pool.

Both branches now do their work in the same goroutine bounded by
--checkers, so --checkers means the same thing with and without
--download. Checking a sum file against 2.6 GiB of local files with
--checkers 8 went from 1.70s to 0.31s here.

As a result the "hashing" checking transfer now covers the hashing work
in both branches, rather than being finished as soon as the download
goroutine had been started.
2026-08-13 19:54:45 +02:00
phatlc fc348fcb0b operations: check checksums in rcat with known size - fixes #6305
RcatSize streams the body straight into Put behind an ObjectInfo with no
hashes, so a known-size upload had its size checked but its checksum
never verified, unlike the unknown-size path through Rcat which hashes as
it goes.

The stream can only be read once, so hash it on the way past and compare
with the destination after the upload, as operations.Copy does. A
destination which reports no usable hash is still checked by size, and one
which fails either check has the failed copy removed.
2026-08-13 19:49:33 +02:00
Jiacheng Xu 35f052e29a size: include source in JSON output - fixes #5429 2026-08-13 19:37:59 +02:00
Recoordinate cfdc9d0558 docs: fix doubled words 2026-08-12 10:59:44 +01:00
Rodrigo Rodrigues 8b42a38e9d docs: fix typo in drive client_id section 2026-08-11 21:27:34 +01:00
Christian De Santis aba403fa79 iclouddrive: fix uploads into an app container failing with 412 - fixes #9729
Writing any file into a third-party app container - the Obsidian, Pages or
Shortcuts folders that iCloud Drive shows alongside your own - failed with

    HTTP error 412 (412 Precondition Failed) returned body:
    "{ ... \"error_code\" : \"VALIDATING_REFERENCE_ERROR\", \"reason\" :
    \"Request has out of order children to be chained but the parents were
    missing\" }"

Reading from those paths worked, and so did creating directories in them, so
the failure looked like a missing parent when the parent was plainly there.

Items in an app container live in a different zone from ordinary iCloud Drive
folders: a folder under Documents has a drive ID like
FOLDER::com.apple.CloudDocs::<uuid>, while the Obsidian container has
FOLDER::iCloud.md.obsidian::documents#o2v. DownloadFile already accounts for
this - it deconstructs the item's own ID and addresses the zone it finds - but
CreateUpload and UpdateFile hardcoded defaultZone, and UpdateFile built the
resulting Drivewsid with a hardcoded com.apple.CloudDocs as well.

So rclone asked Apple to chain the new document to a parent in
com.apple.CloudDocs while the parent lived in iCloud.md.obsidian. The parent
really was missing from the zone being addressed, which is what the error said.

Take the zone from the parent's drive ID instead, the same way the download
path does, and build the new item's ID with ConstructDriveID. Uploads outside
an app container are unaffected: their parents are in com.apple.CloudDocs, so
the derived zone is the value that was previously hardcoded.

Verified against a real remote: files now upload into an Obsidian vault inside
the container and read back correctly with an unpatched binary afterwards.
2026-08-11 21:17:13 +01:00
nielash abae66ee1a accounting: fix memory leak from stats groups on long-running rcd
Before this change, `NewStats` stored the context it was created from on the
`StatsInfo`. Stats groups are never freed -- they are only evicted once there are
`--max-stats-groups` of them -- so each one kept its context, and everything reachable
from it, alive for the life of the process. As the rc creates a group per call,
that included the call's filters and their compiled regexps.

The context was only ever used to get `ci.StatsFileNameLength` from the config.
`StatsInfo` already stores that same `*fs.ConfigInfo`, read from the same
context in `NewStats`.

This change fixes the issue by passing the stored ci to `transferMap.String` and
dropping the context from `StatsInfo`.
2026-08-11 22:12:51 +02:00
nielash 71a0932126 accounting: fix memory leak on long-running rcd
Before this change, Transfer.Done closed the account of a completed transfer but
never released it, because it assigned nil to only a local copy of the pointer.
As a result, every completed transfer continued to reference its account.

An Account holds the transfer context and the source reader, and the stats keep
completed transfers around up to `MaxCompletedTransfers` per group, with groups
discarded only at --max-stats-groups. On a long-running `rclone rcd`, this adds up.

It was noticeable when running bisync repeatedly via the rc, where the transfer
context carries `b.WriteResults` (bisync's `LoggerFn`). A `*bisyncRun` holds
Path1 and Path2 listings, which can be quite large, and are not supposed to be
retained between runs. (Naturally they aren't, when running bisync on the
command line -- which is probably why we didn't notice this issue sooner.)

This change fixes the issue by releasing `tr.acc` in Done, instead of the local
copy. `tr.Snapshot` reads the byte counts off the account, so the progress is
recorded on the transfer first. That read happens before taking `tr.mu`, because
`acc.progress()` locks `acc.values.mu`, `checkReadBefore` holds that lock while
calling `StatsInfo.GetBytes`, and `StatsInfo` locks back into `Transfer` in
`Transferred` and `_removeTransfer`.
2026-08-11 22:12:51 +02:00
Nick Craig-Wood 1947e4217c serve s3: clean up abandoned multipart uploads after --multipart-expiry
A client which started a multipart upload and vanished without either
completing or aborting it used to hold on to its resources forever.

Incomplete multipart uploads which have had no activity for
--multipart-expiry (default 24h) are now aborted and cleaned up
exactly as if the client had called AbortMultipartUpload, with a
NOTICE logged.

An upload with a part still being received is never expired, and each
completed part restarts the clock. Late operations on an expired
upload fail with NoSuchUpload, as they do on real S3 when a lifecycle
rule has aborted the upload.

Set --multipart-expiry 0 to keep incomplete uploads forever.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood b4db289d0a serve s3: upload all multipart uploads via the VFS
Multipart uploads used to be streamed directly to the remote with their
own PutStream machinery, bypassing the VFS, a design left over from
before the VFS could abandon a streaming write.

They are now written through the VFS exactly like plain object PUTs in
every cache mode. The parts are written, in part-number order, to a
temporary object which is renamed into place server-side on
completion.

With the default --vfs-cache-mode off the parts stream through the VFS
to the remote as they arrive. With --vfs-cache-mode writes or above
they are buffered in the VFS cache and uploaded by its write-back.

User visible changes:

- Multipart uploads now show in rclone's transfer stats and obey
  --bwlimit (previously they bypassed both).
- Remotes without streaming upload support now spool the upload to a
  temporary file on local disk instead of buffering it in memory.
- Multipart uploads are never buffered in memory because of missing
  remote capabilities - only --disable-multipart-streaming does that.
- Remotes that upload atomically now also write to a temporary object
  renamed into place, so an in-progress multipart upload is no longer
  briefly visible under its final key.
- On the few remotes with no server-side move or copy the parts are
  written straight to the final object in all cache modes.
- With --vfs-cache-mode writes, plain PUTs and multipart uploads to the
  same key go through the same cache entry, so an earlier PUT still in
  the write-back window can no longer be written back over a newer
  multipart upload.
- Failed write-backs are retried by the VFS without the client having
  to restart the upload, and completed objects are served from the
  cache for read-after-write.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood 0aa90200bd serve s3: reserve the .rclone_temp_ prefix for temporary objects
The temporary objects that uploads are written to before being renamed
into place are now named .rclone_temp_put_* and .rclone_temp_multipart_*,
and the whole .rclone_temp_ prefix is reserved: any object whose name
starts with it is hidden from S3 listings. This gives a single pattern
for cleaning up leftovers from killed servers:

    rclone delete --min-age 24h --include ".rclone_temp_*" remote:path

The .rclone_multipart_upload_* objects rclone v1.75 used are still
hidden from listings so leftovers from an older server stay invisible
to S3 clients.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood a3489456de serve s3: fix modtime not being set when only mtime metadata is supplied on PUT
The mtime metadata fallback was nested inside the X-Amz-Meta-Mtime
branch, so it only ran when X-Amz-Meta-Mtime was present but invalid -
and then set the modtime from the invalid value's failed parse rather
than parsing mtime. An object PUT with only mtime metadata kept the
upload time as its modtime.

Now the two keys are checked independently, as TouchObject already
does.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood 531d873bd7 serve s3: fix crash when a multipart upload is aborted while a part is uploading
streamPart did not check whether the upload had been torn down, but
AbortMultipartUpload sets the reorder buffer map to nil, so an abort
arriving while a part body was still being received panicked with an
assignment to a nil map once the part was buffered.

Now a part whose upload has been aborted or completed under it is
rejected with NoSuchUpload.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood 84298fc090 serve s3: fix failed uploads deleting or corrupting the object at the key - fixes #9718
A PUT which failed part way through removed the object at the
destination key. As well as differing from real S3 (where a failed PUT
never affects the stored object), this raced with the client's
automatic retry of the same PUT: the retry stored the object and
returned 200 OK, then the failed first attempt's cleanup deleted it,
silently losing an acknowledged upload. The interrupted upload could
also be committed as a truncated object, since closing the write handle
gave the streaming upload a clean end of stream.

Now a failed or interrupted PUT never disturbs the object at the key:

- The object at the key is never removed on error.
- On backends where a partial upload is visible at its final name
  (PartialUploads), and when the VFS cache mode is writes or above, the
  upload is written to a temporary object which is renamed into place
  on success and removed on failure, as streamed multipart uploads
  already do. Backends which upload atomically are still streamed
  straight to the destination.
- An interrupted or short body fails the upload via
  WriteFileHandle.CloseWithError instead of committing truncated data,
  and a body which ends cleanly short of its declared size is rejected
  with IncompleteBody.
2026-08-11 20:58:48 +01:00
Nick Craig-Wood 2f0657c35b vfs: add WriteFileHandle.CloseWithError to abandon streaming writes
Closing a streaming write handle sends a clean EOF to the backend
upload, so a writer which knows its data source failed part way through
had no way to stop the truncated file being stored as if it were
complete.

CloseWithError closes the handle failing the upload with the given
reason instead. EOF-like reasons are rewritten so the layers reading
the pipe can't mistake them for a clean end of stream and commit the
partial file.

Needed by serve s3 to abort interrupted PUTs - see #9718
2026-08-11 20:58:48 +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
106 changed files with 4075 additions and 528 deletions

No files matched your search

+9 -9
View File
@@ -37,7 +37,7 @@ jobs:
include:
- job_name: linux
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.6'
gotags: cmount
build_flags: '-include "^linux/"'
check: true
@@ -48,14 +48,14 @@ jobs:
- job_name: linux_386
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.6'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '~1.26.5'
go: '~1.26.6'
gotags: 'cmount'
build_flags: '-include "^darwin/amd64" -cgo'
quicktest: true
@@ -64,14 +64,14 @@ jobs:
- job_name: mac_arm64
os: macos-latest
go: '~1.26.5'
go: '~1.26.6'
gotags: 'cmount'
build_flags: '-include "^darwin/arm64" -cgo -macos-arch arm64 -cgo-cflags=-I/usr/local/include -cgo-ldflags=-L/usr/local/lib'
deploy: true
- job_name: windows
os: windows-latest
go: '~1.26.5'
go: '~1.26.6'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -81,14 +81,14 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.6'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
- job_name: go1.25
os: ubuntu-latest
go: '~1.25.12'
go: '~1.25.13'
quicktest: true
racequicktest: true
@@ -283,7 +283,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.26.5'
go-version: '~1.26.6'
check-latest: true
cache: false
@@ -398,7 +398,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.26.5'
go-version: '~1.26.6'
# Caching is handled explicitly below to share the module cache
# with the other jobs - see the build job for the rationale.
cache: false
+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.
+15 -20
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
@@ -19,7 +19,6 @@ import (
"path"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
@@ -52,6 +51,7 @@ import (
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
"github.com/rclone/rclone/lib/transferaccounter"
"golang.org/x/sync/errgroup"
)
@@ -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,
@@ -2346,6 +2347,16 @@ func (o *Object) decodeMetaDataFromDownloadResponse(info *blob.DownloadStreamRes
} else {
size = *info.ContentLength
}
// On a range request Content-Length is the length of the range, not the object, so take the
// object's size from the total in Content-Range instead.
if info.ContentRange != nil {
contentRange, err := rest.ParseContentRange(*info.ContentRange)
if err != nil {
fs.Debugf(o, "Failed to parse Content-Range %q: %v", *info.ContentRange, err)
} else if contentRange.Size >= 0 {
size = contentRange.Size
}
}
if isDirectoryMarker(size, metadata, o.remote) {
return fs.ErrorNotAFile
}
@@ -2379,22 +2390,6 @@ func (o *Object) decodeMetaDataFromDownloadResponse(info *blob.DownloadStreamRes
// o.accessTier = blob.AccessTier(*info.AccessTier)
// }
o.setMetadata(metadata)
// If it was a Range request, the size is wrong, so correct it
if info.ContentRange != nil {
contentRange := *info.ContentRange
slash := strings.IndexRune(contentRange, '/')
if slash >= 0 {
i, err := strconv.ParseInt(contentRange[slash+1:], 10, 64)
if err == nil {
o.size = i
} else {
fs.Debugf(o, "Failed to find parse integer from in %q: %v", contentRange, err)
}
} else {
fs.Debugf(o, "Failed to find length in %q", contentRange)
}
}
o.contentEncoding = info.ContentEncoding
// If decompressing then size and md5sum are unknown
+52 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !solaris && !js
//go:build !plan9 && !js
package azureblob
@@ -54,6 +54,57 @@ func TestBlockIDCreator(t *testing.T) {
assert.ErrorContains(t, bic2.checkID(chunkNumber, got), "random bytes")
}
func TestDecodeMetaDataFromDownloadResponse(t *testing.T) {
pInt64 := func(i int64) *int64 { return &i }
newTestObject := func() *Object {
return &Object{
fs: &Fs{},
remote: "test.bin",
size: -2, // sentinel to check it gets set
}
}
t.Run("WholeBlob", func(t *testing.T) {
o := newTestObject()
info := blob.DownloadStreamResponse{}
info.ContentLength = pInt64(12345)
require.NoError(t, o.decodeMetaDataFromDownloadResponse(&info))
assert.Equal(t, int64(12345), o.size)
})
t.Run("RangeRequest", func(t *testing.T) {
// On a ranged download Content-Length is the chunk length so the
// size must come from the total in Content-Range
o := newTestObject()
info := blob.DownloadStreamResponse{}
info.ContentLength = pInt64(67108864)
info.ContentRange = pString("bytes 67108864-134217727/169721004032")
require.NoError(t, o.decodeMetaDataFromDownloadResponse(&info))
assert.Equal(t, int64(169721004032), o.size)
})
t.Run("BadContentRange", func(t *testing.T) {
o := newTestObject()
info := blob.DownloadStreamResponse{}
info.ContentLength = pInt64(67108864)
info.ContentRange = pString("potato")
require.NoError(t, o.decodeMetaDataFromDownloadResponse(&info))
assert.Equal(t, int64(67108864), o.size)
})
t.Run("UnknownLength", func(t *testing.T) {
o := newTestObject()
info := blob.DownloadStreamResponse{}
require.NoError(t, o.decodeMetaDataFromDownloadResponse(&info))
assert.Equal(t, int64(-1), o.size)
})
}
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
+5
View File
@@ -1179,6 +1179,11 @@ func (o *ObjectInfo) Size() int64 {
// Hash returns the selected checksum of the file
// If no checksum is available it returns ""
func (o *ObjectInfo) Hash(ctx context.Context, hash hash.Type) (string, error) {
// If the data is unchanged then the hash of the source is the
// hash of the object which will be uploaded
if o.f.opt.NoDataEncryption {
return o.ObjectInfo.Hash(ctx, hash)
}
var srcObj fs.Object
var ok bool
// Get the underlying object if there is one
+4
View File
@@ -84,6 +84,10 @@ func testObjectInfo(t *testing.T, f *Fs, wrap bool) {
// Test ObjectInfo.Hash
wantHash := md5.Sum(outBuf.Bytes())
if f.opt.NoDataEncryption {
// If the data isn't encrypted, the hash should be that of the plaintext
wantHash = md5.Sum([]byte(contents))
}
gotHash, err := src.Hash(ctx, hash.MD5)
require.NoError(t, err)
assert.Equal(t, fmt.Sprintf("%x", wantHash), gotHash)
+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
+17 -5
View File
@@ -498,7 +498,7 @@ func (d *DriveService) CopyDocByItemID(ctx context.Context, itemID string) (*Dri
}
// CreateUpload creates an url for an upload.
func (d *DriveService) CreateUpload(ctx context.Context, size int64, name string) (*UploadResponse, *http.Response, error) {
func (d *DriveService) CreateUpload(ctx context.Context, size int64, name, zone string) (*UploadResponse, *http.Response, error) {
// first we need to request an upload url
values := map[string]any{
"filename": name,
@@ -513,7 +513,7 @@ func (d *DriveService) CreateUpload(ctx context.Context, size int64, name string
opts := rest.Opts{
Method: "POST",
Path: "/ws/" + defaultZone + "/upload/web",
Path: "/ws/" + zone + "/upload/web",
ExtraHeaders: d.icloud.Session.GetHeaders(map[string]string{}),
RootURL: d.docsEndpoint,
Body: body,
@@ -552,14 +552,14 @@ func (d *DriveService) Upload(ctx context.Context, in io.Reader, size int64, nam
// ctx: the context.Context object for the request.
// r: a pointer to the UpdateFileInfo struct containing the information for the file update.
// Returns a pointer to the DriveItem struct representing the updated file, the http.Response object, and an error if any.
func (d *DriveService) UpdateFile(ctx context.Context, r *UpdateFileInfo) (*DriveItem, *http.Response, error) {
func (d *DriveService) UpdateFile(ctx context.Context, r *UpdateFileInfo, zone string) (*DriveItem, *http.Response, error) {
body, err := IntoReader(r)
if err != nil {
return nil, nil, err
}
opts := rest.Opts{
Method: "POST",
Path: "/ws/" + defaultZone + "/update/documents",
Path: "/ws/" + zone + "/update/documents",
ExtraHeaders: d.icloud.Session.GetHeaders(map[string]string{}),
RootURL: d.docsEndpoint,
Body: body,
@@ -572,7 +572,7 @@ func (d *DriveService) UpdateFile(ctx context.Context, r *UpdateFileInfo) (*Driv
doc := responseInfo.Results[0].Document
item := DriveItem{
Drivewsid: "FILE::com.apple.CloudDocs::" + doc.DocumentID,
Drivewsid: ConstructDriveID(doc.DocumentID, zone, "FILE"),
Docwsid: doc.DocumentID,
Itemid: doc.ItemID,
Etag: doc.Etag,
@@ -892,6 +892,18 @@ func DeconstructDriveID(id string) (docType, zone, docid string) {
return split[0], split[1], split[2]
}
// ZoneFromDriveID returns the zone a drive ID belongs to, or the default zone
// for an ID that carries none. Items in an app container -- Obsidian, Pages,
// Shortcuts -- live in that app's zone rather than com.apple.CloudDocs, and a
// write addressed to the wrong zone cannot resolve its parent.
func ZoneFromDriveID(id string) string {
_, zone, _ := DeconstructDriveID(id)
if zone == "" {
return defaultZone
}
return zone
}
// ConstructDriveID constructs a drive ID from the given components.
func ConstructDriveID(id string, zone string, t string) string {
return strings.Join([]string{t, zone, id}, "::")
+32
View File
@@ -0,0 +1,32 @@
package api
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestZoneFromDriveID(t *testing.T) {
for _, test := range []struct {
name string
id string
want string
}{
{"app container", "FOLDER::iCloud.md.obsidian::documents#o2v", "iCloud.md.obsidian"},
{"another app container", "FOLDER::com.apple.Pages::documents#7qt", "com.apple.Pages"},
{"ordinary folder", "FOLDER::com.apple.CloudDocs::B847FE2D", "com.apple.CloudDocs"},
{"file in a container", "FILE::iCloud.md.obsidian::abc123", "iCloud.md.obsidian"},
{"no zone", "root", defaultZone},
{"empty", "", defaultZone},
} {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, ZoneFromDriveID(test.id))
})
}
}
func TestZoneFromDriveIDRoundTrip(t *testing.T) {
id := ConstructDriveID("abc123", "iCloud.md.obsidian", "FILE")
assert.Equal(t, "FILE::iCloud.md.obsidian::abc123", id)
assert.Equal(t, "iCloud.md.obsidian", ZoneFromDriveID(id))
}
+3 -3
View File
@@ -343,7 +343,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
var item *api.DriveItem
if err = f.pacer.Call(func() (bool, error) {
item, resp, err = f.service.UpdateFile(ctx, &r)
item, resp, err = f.service.UpdateFile(ctx, &r, api.ZoneFromDriveID(pathID))
return retryResultUnknown(ctx, resp, err)
}); err != nil {
return nil, err
@@ -949,7 +949,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Create document
var uploadInfo *api.UploadResponse
if err = o.fs.pacer.Call(func() (bool, error) {
uploadInfo, resp, err = o.fs.service.CreateUpload(ctx, size, name)
uploadInfo, resp, err = o.fs.service.CreateUpload(ctx, size, name, api.ZoneFromDriveID(dirID))
return ignoreResultUnknown(ctx, resp, err)
}); err != nil {
return err
@@ -988,7 +988,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Update metadata
var item *api.DriveItem
if err = o.fs.pacer.Call(func() (bool, error) {
item, resp, err = o.fs.service.UpdateFile(ctx, &r)
item, resp, err = o.fs.service.UpdateFile(ctx, &r, api.ZoneFromDriveID(dirID))
return ignoreResultUnknown(ctx, resp, err)
}); err != nil {
return err
+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 {
+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) {
+12
View File
@@ -1546,6 +1546,18 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
}
err = o.fs.pacer.Call(func() (bool, error) {
resp, err = o.fs.srv.Call(ctx, &opts)
if err == nil {
err = rest.CheckContentRange(resp, options, o.size)
if err != nil {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
if errors.Is(err, fs.ErrorRangeIgnored) {
return false, err
}
return true, fserrors.RetryError(err)
}
}
return o.fs.shouldRetry(ctx, resp, err)
})
if err != nil {
+133
View File
@@ -3,16 +3,20 @@ package webdav_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/rclone/rclone/backend/local"
"github.com/rclone/rclone/backend/webdav"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configfile"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/operations"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -151,3 +155,132 @@ func TestReservedCharactersInPathAreEscaped(t *testing.T) {
assert.Contains(t, capturedPath, "my%3Btest", "semicolons in path should be percent-encoded")
assert.NotContains(t, capturedPath, "my;test", "raw semicolons should not appear in path")
}
const fileInfoResponse = `<d:multistatus xmlns:d="DAV:">
<d:response>
<d:href>/file.txt</d:href>
<d:propstat>
<d:prop>
<d:getcontentlength>10</d:getcontentlength>
<d:resourcetype/>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>`
func prepareFileObject(ctx context.Context, t *testing.T, getHandler http.HandlerFunc) (fs.Object, func()) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "PROPFIND" {
w.WriteHeader(http.StatusMultiStatus)
_, err := fmt.Fprint(w, fileInfoResponse)
require.NoError(t, err)
return
}
if r.Method == http.MethodGet {
getHandler(w, r)
return
}
http.Error(w, "unexpected method", http.StatusMethodNotAllowed)
})
ts := httptest.NewServer(handler)
configfile.Install()
f, err := webdav.NewFs(ctx, remoteName, "", configmap.Simple{
"type": "webdav",
"url": ts.URL,
})
require.NoError(t, err)
o, err := f.NewObject(ctx, "file.txt")
require.NoError(t, err)
return o, ts.Close
}
func TestOpenDoesNotRetryIgnoredRange(t *testing.T) {
var getRequests atomic.Int32
o, tidy := prepareFileObject(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "bytes=2-4", r.Header.Get("Range"))
getRequests.Add(1)
w.Header().Set("Content-Length", "10")
w.WriteHeader(http.StatusOK)
_, err := io.WriteString(w, "abcdefghij")
require.NoError(t, err)
})
defer tidy()
in, err := o.Open(context.Background(), &fs.RangeOption{Start: 2, End: 4})
assert.Nil(t, in)
assert.ErrorIs(t, err, fs.ErrorRangeIgnored)
assert.Equal(t, int32(1), getRequests.Load())
}
func TestOpenRetriesMismatchedContentRange(t *testing.T) {
var getRequests atomic.Int32
o, tidy := prepareFileObject(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "bytes=2-4", r.Header.Get("Range"))
if getRequests.Add(1) == 1 {
w.Header().Set("Content-Length", "3")
w.Header().Set("Content-Range", "bytes 0-2/10")
w.WriteHeader(http.StatusPartialContent)
_, err := io.WriteString(w, "abc")
require.NoError(t, err)
return
}
w.Header().Set("Content-Length", "3")
w.Header().Set("Content-Range", "bytes 2-4/10")
w.WriteHeader(http.StatusPartialContent)
_, err := io.WriteString(w, "cde")
require.NoError(t, err)
})
defer tidy()
in, err := o.Open(context.Background(), &fs.RangeOption{Start: 2, End: 4})
require.NoError(t, err)
defer func() { require.NoError(t, in.Close()) }()
contents, err := io.ReadAll(in)
require.NoError(t, err)
assert.Equal(t, "cde", string(contents))
assert.Equal(t, int32(2), getRequests.Load())
}
func TestCopyFallsBackWhenRangeIgnored(t *testing.T) {
var rangeRequests atomic.Int32
var fullRequests atomic.Int32
ctx, ci := fs.AddConfig(context.Background())
ci.LowLevelRetries = 2
ci.MultiThreadStreams = 2
ci.MultiThreadSet = true
ci.MultiThreadCutoff = 1
ci.MultiThreadChunkSize = 4
src, tidy := prepareFileObject(ctx, t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Range") == "" {
fullRequests.Add(1)
} else {
rangeRequests.Add(1)
}
w.Header().Set("Content-Length", "10")
w.WriteHeader(http.StatusOK)
_, err := io.WriteString(w, "abcdefghij")
require.NoError(t, err)
})
defer tidy()
dstFs, err := local.NewFs(ctx, "local", t.TempDir(), configmap.Simple{
"no_preallocate": "true",
"no_sparse": "true",
})
require.NoError(t, err)
dst, err := operations.Copy(ctx, dstFs, nil, "file.txt", src)
require.NoError(t, err)
in, err := dst.Open(ctx)
require.NoError(t, err)
defer func() { require.NoError(t, in.Close()) }()
contents, err := io.ReadAll(in)
require.NoError(t, err)
assert.Equal(t, "abcdefghij", string(contents))
assert.Positive(t, rangeRequests.Load())
assert.LessOrEqual(t, rangeRequests.Load(), int32(3))
assert.Equal(t, int32(1), fullRequests.Load())
}
+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 {
+5
View File
@@ -280,6 +280,11 @@ for all `mount` and `serve` commands on macOS. For details, see [vfs-case-sensit
#### NFS mount
For macOS (and other platforms where this path is supported), prefer the dedicated
[rclone nfsmount](/commands/rclone_nfsmount/) command. It starts the NFS server and
performs the mount for you. `rclone mount` itself still uses FUSE (macFUSE/FUSE-T)
and does not switch to NFS via a flag.
This method spins up an NFS server using [serve nfs](/commands/rclone_serve_nfs/)
command and mounts it to the specified mountpoint. If you run this in background
mode using |--daemon|, you will need to send SIGTERM signal to the rclone process
+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)
}
}
+75 -11
View File
@@ -12,16 +12,27 @@ import (
"sync"
"time"
"github.com/google/uuid"
"github.com/ncw/swift/v2"
"github.com/rclone/gofakes3"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
)
var (
emptyPrefix = &gofakes3.Prefix{}
)
// tempObjectPrefix is reserved for serve s3's temporary objects: an object
// whose leaf name starts with it is hidden from S3 listings.
const tempObjectPrefix = ".rclone_temp_"
// putObjectPrefix is prepended to the leaf name of the temporary object a
// PutObject upload is written to before it is renamed into place.
const putObjectPrefix = tempObjectPrefix + "put_"
// s3Backend implements the gofacess3.Backend interface to make an S3
// backend for gofakes3. It also implements gofakes3.MultipartBackend so that
// multipart uploads stream straight through to the underlying Fs via
@@ -37,13 +48,17 @@ type s3Backend struct {
// warnInMemoryOnce logs a single NOTICE the first time a multipart
// upload falls back to being buffered in memory.
warnInMemoryOnce sync.Once
reaperQuit chan struct{} // closed to stop the abandoned upload reaper
reaperStop sync.Once
}
// newBackend creates a new SimpleBucketBackend.
func newBackend(s *Server) gofakes3.Backend {
func newBackend(s *Server) *s3Backend {
return &s3Backend{
s: s,
meta: new(sync.Map),
s: s,
meta: new(sync.Map),
reaperQuit: make(chan struct{}),
}
}
@@ -311,6 +326,9 @@ func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]
}
// PutObject creates or overwrites the object with the given name.
//
// A failed or interrupted upload should never disturb what is stored
// at the key.
func (b *s3Backend) PutObject(
ctx context.Context,
bucketName, objectName string,
@@ -343,24 +361,63 @@ func (b *s3Backend) PutObject(
}
}
f, err := _vfs.Create(fp)
// Upload via a temporary object renamed into place if needed. The handle
// is opened read-write, which the VFS routes through the cache - where a
// failed upload commits what it has on Close and can't be abandoned -
// from --vfs-cache-mode minimal up, not just writes.
fsys := _vfs.Fs()
tmpFp := fp
if (fsys.Features().PartialUploads || _vfs.Opt.CacheMode >= vfscommon.CacheModeMinimal) && operations.CanServerSideMove(fsys) {
tmpFp = path.Join(objectDir, putObjectPrefix+uuid.New().String())
}
// cleanup discards a failed upload, removing the temporary object
// (never the object at fp) and any stale VFS state for fp.
cleanup := func() {
if tmpFp != fp {
b.forgetPath(_vfs, tmpFp)
_ = _vfs.Remove(tmpFp)
} else {
b.forgetPath(_vfs, fp)
}
}
f, err := _vfs.Create(tmpFp)
if err != nil {
return result, err
}
if _, err := io.Copy(f, input); err != nil {
// remove file when i/o error occurred (FsPutErr)
_ = f.Close()
_ = _vfs.Remove(fp)
n, err := io.Copy(f, input)
if err == nil && size >= 0 && n != size {
// The body ended cleanly but short of its declared size
err = gofakes3.ErrIncompleteBody
}
if err != nil {
// The upload from the client failed part way through - abort the
// write so a streaming upload fails rather than committing a
// truncated object.
if aborter, ok := f.(interface{ CloseWithError(error) error }); ok {
_ = aborter.CloseWithError(err)
} else {
_ = f.Close()
}
cleanup()
return result, err
}
if err := f.Close(); err != nil {
// remove file when close error occurred (FsPutErr)
_ = _vfs.Remove(fp)
cleanup()
return result, err
}
// Rename the temporary object into place
if tmpFp != fp {
if err := _vfs.Rename(tmpFp, fp); err != nil {
cleanup()
return result, err
}
}
_, err = _vfs.Stat(fp)
if err != nil {
return result, err
@@ -375,8 +432,11 @@ func (b *s3Backend) PutObject(
return result, _vfs.Chtimes(fp, ti, ti)
}
// ignore error since the file is successfully created
}
if val, ok := meta["mtime"]; ok {
if val, ok := meta["mtime"]; ok {
ti, err := swift.FloatStringToTime(val)
if err == nil {
b.storeModtime(fp, meta, val)
return result, _vfs.Chtimes(fp, ti, ti)
}
@@ -541,6 +601,10 @@ func (b *s3Backend) CopyObject(ctx context.Context, srcBucket, srcKey, dstBucket
meta["mtime"] = swift.TimeToFloatString(cStat.ModTime())
}
// PutObject rejects a body shorter than its declared size, so a copy
// whose source is being overwritten as it is read - its stated size no
// longer matching its readable bytes - fails with IncompleteBody rather
// than storing a mixture.
_, err = b.PutObject(ctx, dstBucket, dstKey, meta, c.Contents, c.Size)
if err != nil {
return
+1 -1
View File
@@ -37,7 +37,7 @@ func newTestBackend(t *testing.T) (*s3Backend, string) {
w, err := newServer(ctx, f, &opt, &vfscommon.Opt, &proxy.Opt)
require.NoError(t, err)
return newBackend(w).(*s3Backend), root
return newBackend(w), root
}
const rootSecret = "ROOT_LEVEL_SECRET_MARKER"
+7 -2
View File
@@ -8,6 +8,11 @@ import (
"github.com/rclone/rclone/vfs"
)
// legacyMultipartUploadPrefix marked the temporary objects of in-progress
// multipart uploads before the tempObjectPrefix namespace was reserved
// (rclone v1.75); leftovers from an older server are still hidden.
const legacyMultipartUploadPrefix = ".rclone_multipart_upload_"
func (b *s3Backend) entryListR(_vfs *vfs.VFS, bucketName, fdPath, name string, addPrefix bool, response *gofakes3.ObjectList) error {
fp, err := bucketDirPath(bucketName, fdPath)
if err != nil {
@@ -23,8 +28,8 @@ func (b *s3Backend) entryListR(_vfs *vfs.VFS, bucketName, fdPath, name string, a
for _, entry := range dirEntries {
object := entry.Name()
// Hide the in-progress multipart uploads
if strings.HasPrefix(object, multipartUploadPrefix) {
// Hide the temporary objects of in-progress uploads
if strings.HasPrefix(object, tempObjectPrefix) || strings.HasPrefix(object, legacyMultipartUploadPrefix) {
continue
}
+240 -154
View File
@@ -1,13 +1,17 @@
// Multipart upload support for serve s3.
//
// Multipart uploads received by serve s3 are streamed, in part-number order,
// into a single PutStream upload to the underlying Fs, so the whole file is
// never buffered in memory. This implements the gofakes3.MultipartBackend
// Multipart uploads received by serve s3 are written, in part-number order,
// through the VFS, exactly like a plain PutObject: to a temporary object
// which is renamed into place on completion, so the object at the key only
// ever changes atomically on success. With the default --vfs-cache-mode off
// the parts stream through the VFS into a single upload to the remote; with
// --vfs-cache-mode writes or above they are buffered in the VFS cache and
// uploaded by its write-back. This implements the gofakes3.MultipartBackend
// interface on s3Backend.
//
// When streaming is disabled (--disable-multipart-streaming) or the Fs has no
// PutStream, ErrMultipartUploadNotSupported is returned so that gofakes3 falls
// back to buffering the parts in memory.
// When streaming is disabled (--disable-multipart-streaming),
// ErrMultipartUploadNotSupported is returned so that gofakes3 falls back to
// buffering the parts in memory.
package s3
@@ -29,40 +33,44 @@ import (
"github.com/ncw/swift/v2"
"github.com/rclone/gofakes3"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
)
// multipartUploadPrefix is prepended to the leaf name of the temporary object
// a streamed multipart upload is written to before it is moved into place.
const multipartUploadPrefix = ".rclone_multipart_upload_"
const multipartUploadPrefix = tempObjectPrefix + "multipart_"
// multipartUpload tracks one in-flight S3 multipart upload that is being
// streamed, in part order, into a single PutStream upload to the underlying Fs.
// multipartUpload tracks one in-flight S3 multipart upload. The parts are
// written, in part-number order, into fh - a VFS file handle which either
// streams straight through to the remote (the default) or is backed by the
// VFS cache (when the VFS is caching writes).
type multipartUpload struct {
bucket, key string
fp string // final object path
streamFp string // path the parts are streamed to (fp when the backend uploads atomically)
streamFp string // path the parts are written to (fp when the remote has no server-side move or copy)
meta map[string]string
pipeW *io.PipeWriter // parts are streamed here, in part-number order
fh io.WriteCloser // sink the in-order parts are written to
vfs *vfs.VFS // the VFS fh was created on, used for all later operations
mu sync.Mutex
cond *sync.Cond // signalled when buffered shrinks, nextPart advances or the upload closes
partMD5s map[int][]byte // raw MD5 sums per part (for the final S3 multipart ETag)
partSizes map[int]int64 // observed part sizes
closed bool
aborted bool // closed by abort, so nothing was committed
active int // requests in flight for this upload, protecting it from the reaper
lastUsed time.Time // when the last request for this upload finished
putCancel context.CancelFunc // cancels the background PutStream
putDone chan struct{} // closed when the background PutStream returns
putErr error // PutStream result (read only after putDone is closed)
nextPart int // next part number to stream (1-based)
streamBuf map[int]*pool.RW // parts received ahead of nextPart, awaiting their turn
pumping bool // a goroutine is currently writing to the pipe
buffered int64 // bytes of parts admitted but not yet streamed or released
bufferLimit int64 // max buffered before parts ahead of nextPart must wait (<= 0 for no limit)
nextPart int // next part number to stream (1-based)
streamBuf map[int]*pool.RW // parts received ahead of nextPart, awaiting their turn
pumping bool // a goroutine is currently writing to the sink
buffered int64 // bytes of parts admitted but not yet streamed or released
bufferLimit int64 // max buffered before parts ahead of nextPart must wait (<= 0 for no limit)
}
// newMultipartUpload allocates an upload struct.
@@ -78,11 +86,27 @@ func newMultipartUpload(bucket, key, fp, streamFp string, meta map[string]string
nextPart: 1,
streamBuf: map[int]*pool.RW{},
bufferLimit: bufferLimit,
lastUsed: time.Now(),
}
up.cond = sync.NewCond(&up.mu)
return up
}
// startActivity marks the upload as having a request in flight.
func (up *multipartUpload) startActivity() {
up.mu.Lock()
up.active++
up.mu.Unlock()
}
// endActivity marks the request done and restarts the upload's idle time.
func (up *multipartUpload) endActivity() {
up.mu.Lock()
up.active--
up.lastUsed = time.Now()
up.mu.Unlock()
}
// loadUpload looks up an in-flight upload by ID.
func (b *s3Backend) loadUpload(uploadID gofakes3.UploadID) (*multipartUpload, error) {
v, ok := b.multipartUploads.Load(uploadID)
@@ -92,22 +116,26 @@ func (b *s3Backend) loadUpload(uploadID gofakes3.UploadID) (*multipartUpload, er
return v.(*multipartUpload), nil
}
// CreateMultipartUpload begins a new multipart upload that streams the parts,
// in part-number order, into a single PutStream upload to the underlying Fs.
// CreateMultipartUpload begins a new multipart upload.
//
// Backends that upload atomically (PartialUploads=false) are streamed
// straight to the final object. An aborted or failed upload never
// makes a partial object visible or disturbs a pre-existing one.
// Backends where a partial upload is visible (PartialUploads=true)
// are instead streamed to a temporary object that is moved into
// place, server-side, on completion, giving the same atomic
// behaviour.
// The parts are written, in part-number order, through the VFS to a temporary
// object which is renamed into place on completion. With the default
// --vfs-cache-mode off the write streams through to the remote as the parts
// arrive; with --vfs-cache-mode writes or above it lands in the VFS cache and
// is uploaded by the write-back. Either way an aborted or failed upload never
// makes a partial object visible at the final path or disturbs a pre-existing
// one.
//
// If streaming is disabled (--disable-multipart-streaming), the Fs has no
// PutStream, or a non-atomic Fs can't move/copy objects server-side,
// ErrMultipartUploadNotSupported is returned so that gofakes3 falls back to
// buffering the whole upload in memory; a one-off NOTICE warns about the
// memory use.
// On a remote with no server-side move or copy the parts are written straight
// to the final object instead, trading some atomicity for never buffering in
// memory: the in-flight upload is visible at the key, and a failed or aborted
// upload can leave partial data there when the remote doesn't upload atomically
// or the VFS is caching writes (a write to the cache can't be abandoned).
//
// With --disable-multipart-streaming, ErrMultipartUploadNotSupported is
// returned so that gofakes3 falls back to buffering the whole upload in
// memory; a one-off NOTICE warns about the memory use. A caching VFS needs
// no streaming support, so it ignores the flag.
func (b *s3Backend) CreateMultipartUpload(ctx context.Context, bucketName, objectName string, meta map[string]string) (gofakes3.UploadID, error) {
_vfs, err := b.s.getVFS(ctx)
if err != nil {
@@ -117,11 +145,9 @@ func (b *s3Backend) CreateMultipartUpload(ctx context.Context, bucketName, objec
return "", gofakes3.BucketNotFound(bucketName)
}
f := _vfs.Fs()
features := f.Features()
if reason := b.noStreamingReason(f); reason != "" {
if b.s.opt.DisableMultipartStreaming && _vfs.Opt.CacheMode < vfscommon.CacheModeMinimal {
b.warnInMemoryOnce.Do(func() {
fs.Logf(nil, "serve s3: buffering multipart uploads in memory because %s - this may use a lot of memory", reason)
fs.Logf(nil, "serve s3: buffering multipart uploads in memory because --disable-multipart-streaming is set - this may use a lot of memory")
})
return "", gofakes3.ErrMultipartUploadNotSupported
}
@@ -139,53 +165,36 @@ func (b *s3Backend) CreateMultipartUpload(ctx context.Context, bucketName, objec
uploadID := gofakes3.UploadID(uuid.New().String())
streamFp := fp
// If partial uploads visible, stream to temporary object
if features.PartialUploads {
// Write to a temporary object moved into place on completion if the
// remote supports server-side move (if not write directly to the final
// object). Unlike a plain PutObject all remotes use a temporary object.
// S3 semantics say the key must not show it until it completes. This is
// at the cost of a server-side copy and delete where the remote has no
// server side move.
if operations.CanServerSideMove(_vfs.Fs()) {
streamFp = path.Join(objectDir, multipartUploadPrefix+string(uploadID))
}
up := newMultipartUpload(bucketName, objectName, fp, streamFp, meta, int64(b.s.opt.MultipartStreamingBufferLimit))
src := object.NewStaticObjectInfo(streamFp, time.Now(), -1, true, nil, f)
pr, pw := io.Pipe()
// Use a context that outlives this request (it's cancelled on abort) but
// keeps its values.
putCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
up.pipeW = pw
up.putCancel = cancel
up.putDone = make(chan struct{})
go func() {
_, err := features.PutStream(putCtx, pr, src)
up.putErr = err
_ = pr.CloseWithError(err)
close(up.putDone)
}()
fh, err := _vfs.Create(streamFp)
if err != nil {
return "", err
}
up.fh = fh
up.vfs = _vfs
b.multipartUploads.Store(uploadID, up)
return uploadID, nil
}
// noStreamingReason returns a non-empty reason why streamed multipart uploads
// can't be used for f, or "" if they can.
func (b *s3Backend) noStreamingReason(f fs.Fs) string {
switch {
case b.s.opt.DisableMultipartStreaming:
return "--disable-multipart-streaming is set"
case f.Features().PutStream == nil:
return "this backend doesn't support streaming uploads"
case f.Features().PartialUploads && !operations.CanServerSideMove(f):
return "this backend can't upload atomically and has no server-side move or copy"
default:
return ""
}
}
// UploadPart writes a single part from the S3 client into the streaming upload.
func (b *s3Backend) UploadPart(ctx context.Context, bucketName, objectName string, uploadID gofakes3.UploadID, partNumber int, contentLength int64, body io.Reader) (string, error) {
up, err := b.loadUpload(uploadID)
if err != nil {
return "", err
}
up.startActivity()
defer up.endActivity()
// Wait until there is room to buffer this part, bounding the memory a
// client which uploads faster than the backend drains can consume.
@@ -222,7 +231,7 @@ func (b *s3Backend) UploadPart(ctx context.Context, bucketName, objectName strin
// client sends parts faster than the backend drains them.
//
// The next part the stream needs (and any retry of an earlier one) is always
// admitted so the pipe can keep draining; so is a single part bigger than the
// admitted so the sink can keep draining; so is a single part bigger than the
// limit when the buffer is empty, to guarantee progress. Reserved bytes are
// returned with release, or by the pump as the part is streamed.
func (up *multipartUpload) waitForTurn(partNumber int, size int64) error {
@@ -249,11 +258,11 @@ func (up *multipartUpload) release(size int64) {
up.mu.Unlock()
}
// streamPart records a part and streams the parts into the pipe in order.
// streamPart records a part and streams the parts into the sink in order.
//
// Parts must be uploaded in ascending, contiguous part-number order. A part
// that arrives ahead of the next expected one is buffered until its turn; the
// parts are then pumped into the pipe in order. Whichever goroutine finds the
// parts are then pumped into the sink in order. Whichever goroutine finds the
// next part available does the pumping, so concurrent (but in-order) clients
// are tolerated, with the buffering bounded by waitForTurn.
//
@@ -265,6 +274,15 @@ func (up *multipartUpload) release(size int64) {
// one is rejected.
func (up *multipartUpload) streamPart(partNumber int, size int64, md5Sum []byte, rw *pool.RW) error {
up.mu.Lock()
if up.closed {
// The upload was aborted or completed while the part body was
// being received.
up.buffered -= size
up.cond.Broadcast()
up.mu.Unlock()
_ = rw.Close()
return gofakes3.ErrNoSuchUpload
}
if oldMD5, exists := up.partMD5s[partNumber]; exists {
if old, buffered := up.streamBuf[partNumber]; buffered {
_ = old.Close()
@@ -289,13 +307,21 @@ func (up *multipartUpload) streamPart(partNumber int, size int64, md5Sum []byte,
up.streamBuf[partNumber] = rw
if up.pumping {
// Another goroutine owns the pipe and will pump this part in turn.
// Another goroutine owns the sink and will pump this part in turn.
up.mu.Unlock()
return nil
}
up.pumping = true
for {
if up.closed {
// Aborted while pumping: the sink is closed and any
// parts still buffered were released by the abort, so
// report the upload gone rather than success.
up.pumping = false
up.mu.Unlock()
return gofakes3.ErrNoSuchUpload
}
prw, ok := up.streamBuf[up.nextPart]
if !ok {
up.pumping = false
@@ -306,14 +332,21 @@ func (up *multipartUpload) streamPart(partNumber int, size int64, md5Sum []byte,
psize := prw.Size()
up.mu.Unlock()
err := pipePart(up.pipeW, prw)
err := pipePart(up.fh, prw)
_ = prw.Close()
if err != nil {
up.mu.Lock()
up.pumping = false
up.buffered -= psize
closed := up.closed
up.cond.Broadcast()
up.mu.Unlock()
if closed {
// The write failed because the upload was aborted while
// this part was being pumped: report the upload gone
// rather than the sink's ECLOSED as an internal error.
return gofakes3.ErrNoSuchUpload
}
return err
}
@@ -324,7 +357,7 @@ func (up *multipartUpload) streamPart(partNumber int, size int64, md5Sum []byte,
}
}
// pipePart writes the whole of rw into w (the pipe).
// pipePart writes the whole of rw into w (the sink).
func pipePart(w io.Writer, rw *pool.RW) error {
if _, err := rw.Seek(0, io.SeekStart); err != nil {
return err
@@ -333,110 +366,144 @@ func pipePart(w io.Writer, rw *pool.RW) error {
return err
}
// CompleteMultipartUpload finalises a streamed multipart upload. It closes the
// pipe (so PutStream finishes), registers the new file with the VFS, computes
// the S3-style multipart ETag, and stores the user metadata so HeadObject and
// CompleteMultipartUpload finalises a multipart upload. It closes the sink,
// committing the upload, renames the temporary object into place, computes the
// S3-style multipart ETag, and stores the user metadata so HeadObject and
// GetObject see the same fields the in-memory PutObject path produces.
func (b *s3Backend) CompleteMultipartUpload(ctx context.Context, bucketName, objectName string, uploadID gofakes3.UploadID, input *gofakes3.CompleteMultipartUploadRequest) (gofakes3.VersionID, string, error) {
up, err := b.loadUpload(uploadID)
if err != nil {
return "", "", err
}
defer b.multipartUploads.Delete(uploadID)
up.startActivity()
defer up.endActivity()
if err := up.validate(input); err != nil {
_ = up.abort(ctx)
b.forgetPath(ctx, up.streamFp)
b.multipartUploads.Delete(uploadID)
_ = up.abort()
b.discardUpload(up)
return "", "", err
}
// All parts must have been streamed: contiguous part numbers from 1 with
// nothing left buffered. A leftover means the client used non-contiguous
// part numbers, which the in-order stream can't place.
up.mu.Lock()
streamed := up.nextPart - 1
total := len(up.partSizes)
leftover := len(up.streamBuf)
up.mu.Unlock()
if leftover != 0 || streamed != total {
_ = up.abort(ctx)
b.forgetPath(ctx, up.streamFp)
return "", "", gofakes3.ErrInvalidPart
}
if err := up.close(ctx); err != nil {
b.forgetPath(ctx, up.streamFp)
// close commits the upload, failing with the upload left open if the
// streamed parts don't form the complete object; abort then tears it
// down. (After a successful or failed commit the abort is a no-op.)
if err := up.close(); err != nil {
b.multipartUploads.Delete(uploadID)
_ = up.abort()
b.discardUpload(up)
return "", "", err
}
_vfs, err := b.s.getVFS(ctx)
if err != nil {
return "", "", err
}
// If the parts were streamed to a temporary object move it into place
// Rename the temporary object into place: on a caching VFS the
// write-back then uploads it under the final name, otherwise it is
// moved server-side on the remote. On failure the upload record is
// kept, because gofakes3 keeps its own record when the backend errors
// so that the client can retry the CompleteMultipartUpload: the
// committed close is idempotent, so the retry just renames again.
if up.streamFp != up.fp {
if err := b.moveIntoPlace(ctx, _vfs.Fs(), up.streamFp, up.fp); err != nil {
b.forgetPath(ctx, up.streamFp)
b.forgetPath(ctx, up.fp)
if err := up.vfs.Rename(up.streamFp, up.fp); err != nil {
return "", "", err
}
b.forgetPath(ctx, up.streamFp)
}
b.forgetPath(ctx, up.fp)
b.multipartUploads.Delete(uploadID)
b.meta.Store(up.fp, up.meta)
if val, ok := up.meta["X-Amz-Meta-Mtime"]; ok {
if ti, err := swift.FloatStringToTime(val); err == nil {
b.storeModtime(up.fp, up.meta, val)
_ = _vfs.Chtimes(up.fp, ti, ti)
_ = up.vfs.Chtimes(up.fp, ti, ti)
}
} else if val, ok := up.meta["mtime"]; ok {
if ti, err := swift.FloatStringToTime(val); err == nil {
b.storeModtime(up.fp, up.meta, val)
_ = _vfs.Chtimes(up.fp, ti, ti)
_ = up.vfs.Chtimes(up.fp, ti, ti)
}
}
return "", up.multipartETag(input), nil
}
// AbortMultipartUpload tears down an in-progress upload, asking the background
// PutStream to discard any data already sent.
// AbortMultipartUpload tears down an in-progress upload, discarding any data
// already received.
func (b *s3Backend) AbortMultipartUpload(ctx context.Context, bucketName, objectName string, uploadID gofakes3.UploadID) error {
up, err := b.loadUpload(uploadID)
if err != nil {
return err
}
defer b.multipartUploads.Delete(uploadID)
err = up.abort(ctx)
// An atomic backend leaves the final object untouched by the aborted
// upload; a non-atomic one only ever wrote the temporary object. Either way
// invalidating streamFp is enough.
b.forgetPath(ctx, up.streamFp)
return err
if err := up.abort(); err != nil {
fs.Errorf(up.fp, "aborting multipart upload: %v", err)
}
b.discardUpload(up)
return nil
}
// moveIntoPlace moves the temporary object srcFp to its final path dstFp on f,
// server-side, overwriting any object already there.
func (b *s3Backend) moveIntoPlace(ctx context.Context, f fs.Fs, srcFp, dstFp string) error {
srcObj, err := f.NewObject(ctx, srcFp)
if err != nil {
return fmt.Errorf("failed to find uploaded object: %w", err)
// startReaper starts a goroutine which aborts incomplete multipart
// uploads once they have been idle for expiry. Stopped by stopReaper.
func (b *s3Backend) startReaper(expiry time.Duration) {
interval := min(expiry/2, time.Minute)
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-b.reaperQuit:
return
case <-ticker.C:
b.reapExpiredUploads(time.Now(), expiry)
}
}
}()
}
// stopReaper stops the abandoned upload reaper, if running.
func (b *s3Backend) stopReaper() {
b.reaperStop.Do(func() {
close(b.reaperQuit)
})
}
// reapExpiredUploads aborts and cleans up multipart uploads which have had
// no request activity for longer than expiry.
func (b *s3Backend) reapExpiredUploads(now time.Time, expiry time.Duration) {
b.multipartUploads.Range(func(key, value any) bool {
uploadID := key.(gofakes3.UploadID)
up := value.(*multipartUpload)
up.mu.Lock()
expired := up.active == 0 && now.Sub(up.lastUsed) >= expiry
up.mu.Unlock()
if !expired {
return true
}
fs.Logf(up.fp, "aborting multipart upload %s idle for more than %v", uploadID, expiry)
b.multipartUploads.Delete(uploadID)
if err := up.abort(); err != nil {
fs.Errorf(up.fp, "aborting abandoned multipart upload: %v", err)
}
b.discardUpload(up)
return true
})
}
// discardUpload cleans up after a failed or aborted upload, removing the
// temporary object and any stale VFS state for it. It never removes the
// object at the final path: when the parts were written straight to the
// final object (a remote with no server-side move or copy) it may hold a
// pre-existing object the abandoned streaming write never disturbed, so
// only the VFS's view of the path is refreshed. (A caching VFS on such a
// remote commits the partial data instead - see abort.)
func (b *s3Backend) discardUpload(up *multipartUpload) {
b.forgetPath(up.vfs, up.streamFp)
if up.streamFp == up.fp {
return
}
if _, err := operations.Move(ctx, f, nil, dstFp, srcObj); err != nil {
return fmt.Errorf("failed to move uploaded object into place: %w", err)
}
return nil
_ = up.vfs.Remove(up.streamFp)
}
// forgetPath invalidates the parent directory's cached VFS listing so that
// subsequent VFS Stat / List calls re-read fp from the underlying Fs.
func (b *s3Backend) forgetPath(ctx context.Context, fp string) {
_vfs, err := b.s.getVFS(ctx)
if err != nil {
return
}
func (b *s3Backend) forgetPath(_vfs *vfs.VFS, fp string) {
if root, err := _vfs.Root(); err == nil {
root.ForgetPath(fp, fs.EntryObject)
}
@@ -469,39 +536,59 @@ func (up *multipartUpload) validate(input *gofakes3.CompleteMultipartUploadReque
return nil
}
// close finalises the upload by signalling EOF to the background PutStream and
// waiting for it to finish.
func (up *multipartUpload) close(ctx context.Context) error {
// close finalises the upload, committing it: closing the sink completes the
// streaming upload to the remote, or the write to the VFS cache whose
// write-back then uploads it.
//
// The upload is only committed if the streamed parts form the complete
// object: contiguous part numbers from 1 with nothing left buffered (a
// leftover means the client used non-contiguous part numbers, which the
// in-order stream can't place). Otherwise ErrInvalidPart is returned and
// the upload is left open. The check and the commit share one critical
// section so no late part can slip into the stream between them.
//
// Returns ErrNoSuchUpload if the upload was aborted by a concurrent
// AbortMultipartUpload, in which case nothing has been committed - the
// upload must not be reported as complete.
func (up *multipartUpload) close() error {
up.mu.Lock()
if up.closed {
aborted := up.aborted
up.mu.Unlock()
if aborted {
return gofakes3.ErrNoSuchUpload
}
return nil
}
if len(up.streamBuf) != 0 || up.nextPart-1 != len(up.partSizes) {
up.mu.Unlock()
return gofakes3.ErrInvalidPart
}
up.closed = true
up.cond.Broadcast()
up.mu.Unlock()
err := up.pipeW.Close()
<-up.putDone
up.putCancel()
if up.putErr != nil {
return up.putErr
}
return err
return up.fh.Close()
}
// errMultipartAborted makes the background PutStream fail when an upload is
// aborted, so it tears down its partial object instead of completing.
// errMultipartAborted is the reason an aborted upload's write is abandoned
// with, so the streaming upload fails instead of committing what it has.
var errMultipartAborted = errors.New("serve s3: multipart upload aborted")
// abort cancels the background PutStream and releases any buffered parts.
func (up *multipartUpload) abort(ctx context.Context) error {
// abort tears down the upload and releases any buffered parts. The write is
// abandoned so nothing is committed; a sink which can't abandon (a caching
// one) is closed normally, committing what it has to the cache - the caller
// then removes its temporary file, except on a remote with no server-side
// move or copy, where the parts went straight to the final path and the
// partial data is left to be written back.
func (up *multipartUpload) abort() error {
up.mu.Lock()
if up.closed {
up.mu.Unlock()
return nil
}
up.closed = true
up.aborted = true
streamBuf := up.streamBuf
up.streamBuf = nil
up.cond.Broadcast()
@@ -511,12 +598,11 @@ func (up *multipartUpload) abort(ctx context.Context) error {
_ = rw.Close()
}
// Fail the background PutStream (so it discards its partial object) and
// wait for it to return.
up.putCancel()
_ = up.pipeW.CloseWithError(errMultipartAborted)
<-up.putDone
return nil
if aborter, ok := up.fh.(interface{ CloseWithError(error) error }); ok {
_ = aborter.CloseWithError(errMultipartAborted)
return nil
}
return up.fh.Close()
}
// multipartETag computes the S3 multipart ETag for the assembled object:
+511 -5
View File
@@ -5,6 +5,7 @@ package s3
import (
"bytes"
"context"
"crypto/md5"
"fmt"
"io"
"net/url"
@@ -16,10 +17,14 @@ import (
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/rclone/gofakes3"
_ "github.com/rclone/rclone/backend/memory"
"github.com/rclone/rclone/cmd/serve/proxy"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
@@ -40,9 +45,8 @@ func newMultipartTestServer(t *testing.T, disableStreaming bool) (*minio.Core, f
// newMultipartTestServerBacking is like newMultipartTestServer but backed by
// the named remote (a fresh local temp directory if empty). ":memory:" gives
// an atomic (PartialUploads=false) backing, so the streamed-straight-to-the-
// destination path is exercised as well as the temporary-object path that
// local (PartialUploads=true) uses.
// an atomic (PartialUploads=false) backing, so both flavours of remote go
// through the temporary-object-plus-rename path.
func newMultipartTestServerBacking(t *testing.T, backing string, disableStreaming bool) (*minio.Core, fs.Fs, string) {
return newMultipartTestServerOpt(t, backing, disableStreaming, nil)
}
@@ -50,8 +54,22 @@ func newMultipartTestServerBacking(t *testing.T, backing string, disableStreamin
// newMultipartTestServerOpt is like newMultipartTestServerBacking but also
// applies tweak (if non-nil) to the server Options before starting it.
func newMultipartTestServerOpt(t *testing.T, backing string, disableStreaming bool, tweak func(*Options)) (*minio.Core, fs.Fs, string) {
return newMultipartTestServerVFS(t, backing, disableStreaming, tweak, nil)
}
// newMultipartTestServerVFS is like newMultipartTestServerOpt but also
// overrides the VFS options (nil for the defaults) and disables the named
// features on the backing remote. A backing with features disabled must have
// a unique config string (e.g. a distinct description=) so an active VFS
// wrapping a fully-featured instance of the same remote isn't reused.
func newMultipartTestServerVFS(t *testing.T, backing string, disableStreaming bool, tweak func(*Options), vfsOpt *vfscommon.Options, disableFeatures ...string) (*minio.Core, fs.Fs, string) {
fstest.Initialise()
ctx := context.Background()
if len(disableFeatures) > 0 {
var ci *fs.ConfigInfo
ctx, ci = fs.AddConfig(ctx)
ci.DisableFeatures = disableFeatures
}
if backing == "" {
backing = t.TempDir()
}
@@ -61,10 +79,13 @@ func newMultipartTestServerOpt(t *testing.T, backing string, disableStreaming bo
// process-wide store, so a fixed name would leak objects between tests.
bucket := fmt.Sprintf("test-%d", testBackingCounter.Add(1))
require.NoError(t, f.Mkdir(ctx, bucket))
if vfsOpt == nil {
vfsOpt = &vfscommon.Opt
}
// The VFS is cached per remote (fs.ConfigString), so a shared ":memory:"
// server reuses a VFS whose cached root listing predates the bucket just
// created; forget it so the new bucket is visible.
if root, err := vfs.New(ctx, f, &vfscommon.Opt).Root(); err == nil {
if root, err := vfs.New(ctx, f, vfsOpt).Root(); err == nil {
root.ForgetAll()
}
@@ -77,7 +98,7 @@ func newMultipartTestServerOpt(t *testing.T, backing string, disableStreaming bo
if tweak != nil {
tweak(&opt)
}
w, err := newServer(ctx, f, &opt, &vfscommon.Opt, &proxy.Opt)
w, err := newServer(ctx, f, &opt, vfsOpt, &proxy.Opt)
require.NoError(t, err)
go func() { _ = w.Serve() }()
t.Cleanup(func() { _ = w.Shutdown() })
@@ -448,6 +469,491 @@ func TestMultipartBufferLimit(t *testing.T) {
assert.Equal(t, want, readObject(t, f, bucket, object))
}
// stubSink is a multipartUpload sink which records how it was closed.
type stubSink struct {
closed bool
abortErr error // the reason passed to CloseWithError
}
func (s *stubSink) Write(p []byte) (int, error) { return len(p), nil }
func (s *stubSink) Close() error {
s.closed = true
return nil
}
func (s *stubSink) CloseWithError(err error) error {
s.closed = true
s.abortErr = err
return nil
}
// TestMultipartAbortDuringUploadPart aborts the upload between a part's
// waitForTurn and its streamPart - as happens when the abort arrives while
// the part body is still being received from the client - and checks that
// streamPart fails cleanly instead of panicking on the torn-down upload.
func TestMultipartAbortDuringUploadPart(t *testing.T) {
up := newMultipartUpload("bucket", "key", "bucket/key", "bucket/key", nil, 0)
sink := &stubSink{}
up.fh = sink
// An UploadPart in progress: the part is admitted, then the abort lands
// while its body is still being received.
contents := []byte("hello")
require.NoError(t, up.waitForTurn(1, int64(len(contents))))
require.NoError(t, up.abort())
// The abort must abandon the write rather than committing it.
assert.True(t, sink.closed)
assert.Equal(t, errMultipartAborted, sink.abortErr)
// The UploadPart resumes: it buffers the part and calls streamPart.
rw := multipart.NewRW()
_, err := rw.Write(contents)
require.NoError(t, err)
md5Sum := md5.Sum(contents)
err = up.streamPart(1, int64(len(contents)), md5Sum[:], rw)
require.ErrorIs(t, err, gofakes3.ErrNoSuchUpload)
// The reorder buffer reservation must have been returned
up.mu.Lock()
assert.Equal(t, int64(0), up.buffered)
up.mu.Unlock()
}
// TestMultipartCloseAfterAbort checks that a close racing an abort reports
// the abort: gofakes3 can dispatch CompleteMultipartUpload and
// AbortMultipartUpload for the same uploadID concurrently, and a Complete
// that loses the race must not report success for data that was never
// committed.
func TestMultipartCloseAfterAbort(t *testing.T) {
up := newMultipartUpload("bucket", "key", "bucket/key", "bucket/key", nil, 0)
up.fh = &stubSink{}
require.NoError(t, up.abort())
require.ErrorIs(t, up.close(), gofakes3.ErrNoSuchUpload)
// close stays idempotent after a successful close.
up = newMultipartUpload("bucket", "key", "bucket/key", "bucket/key", nil, 0)
up.fh = &stubSink{}
require.NoError(t, up.close())
require.NoError(t, up.close())
}
// TestMultipartCloseIncomplete checks that close refuses to commit while a
// part is still buffered awaiting an earlier one, leaving the upload open
// for more parts or an abort.
func TestMultipartCloseIncomplete(t *testing.T) {
up := newMultipartUpload("bucket", "key", "bucket/key", "bucket/key", nil, 0)
sink := &stubSink{}
up.fh = sink
// Part 2 arrives ahead of part 1 so it is buffered, not streamed.
contents := []byte("hello")
rw := multipart.NewRW()
_, err := rw.Write(contents)
require.NoError(t, err)
md5Sum := md5.Sum(contents)
require.NoError(t, up.waitForTurn(2, int64(len(contents))))
require.NoError(t, up.streamPart(2, int64(len(contents)), md5Sum[:], rw))
require.ErrorIs(t, up.close(), gofakes3.ErrInvalidPart)
assert.False(t, sink.closed)
// The upload is still open so abort tears it down.
require.NoError(t, up.abort())
assert.True(t, sink.closed)
}
// failingSink is a sink whose Close fails and which cannot abandon writes,
// like a caching VFS handle whose synchronous write-back fails.
type failingSink struct{}
func (failingSink) Write(p []byte) (int, error) { return len(p), nil }
func (failingSink) Close() error { return errBoom }
// TestMultipartAbortAlwaysSucceeds checks that AbortMultipartUpload reports
// success even when closing the sink fails: the upload is torn down either
// way, and an error reply would leave gofakes3's record of the upload alive
// with ours consumed, so every retried abort would 404 on a ghost upload.
func TestMultipartAbortAlwaysSucceeds(t *testing.T) {
b, _, bucket := newPutTestBackend(t, "", nil)
ctx := context.Background()
_vfs, err := b.s.getVFS(ctx)
require.NoError(t, err)
up := newMultipartUpload(bucket, "key", bucket+"/key", bucket+"/"+multipartUploadPrefix+"x", nil, 0)
up.fh = failingSink{}
up.vfs = _vfs
const uploadID = gofakes3.UploadID("failing-close")
b.multipartUploads.Store(uploadID, up)
require.NoError(t, b.AbortMultipartUpload(ctx, bucket, "key", uploadID))
// The upload record is consumed - a second abort is NoSuchUpload.
require.ErrorIs(t, b.AbortMultipartUpload(ctx, bucket, "key", uploadID), gofakes3.ErrNoSuchUpload)
}
// TestMultipartCompleteRenameFailureKeepsUpload checks that a Complete
// failing after the commit (here: the rename of the temporary object) keeps
// the upload record, so the retried CompleteMultipartUpload which gofakes3
// allows on a backend error finds the upload instead of a NoSuchUpload.
func TestMultipartCompleteRenameFailureKeepsUpload(t *testing.T) {
b, _, bucket := newPutTestBackend(t, "", nil)
ctx := context.Background()
_vfs, err := b.s.getVFS(ctx)
require.NoError(t, err)
// A committed upload whose temporary object is missing: the rename
// fails after the commit succeeded.
up := newMultipartUpload(bucket, "key", bucket+"/key", bucket+"/"+multipartUploadPrefix+"missing", nil, 0)
up.fh = &stubSink{}
up.vfs = _vfs
const uploadID = gofakes3.UploadID("rename-fails")
b.multipartUploads.Store(uploadID, up)
_, _, err = b.CompleteMultipartUpload(ctx, bucket, "key", uploadID, &gofakes3.CompleteMultipartUploadRequest{})
require.Error(t, err)
_, err = b.loadUpload(uploadID)
require.NoError(t, err, "the upload record must survive a retryable Complete failure")
}
// TestMultipartReaper checks that an incomplete multipart upload abandoned
// by its client is aborted and cleaned up after --multipart-expiry, and that
// late operations on it fail with NoSuchUpload.
func TestMultipartReaper(t *testing.T) {
core, f, bucket := newMultipartTestServerOpt(t, "", false, func(opt *Options) {
opt.MultipartExpiry = fs.Duration(100 * time.Millisecond)
})
ctx := context.Background()
const object = "abandoned.bin"
uploadID, err := core.NewMultipartUpload(ctx, bucket, object, minio.PutObjectOptions{})
require.NoError(t, err)
data := []byte(random.String(50 * 1024))
_, err = core.PutObjectPart(ctx, bucket, object, uploadID, 1, bytes.NewReader(data), int64(len(data)), minio.PutObjectPartOptions{})
require.NoError(t, err)
// Wait for well over the expiry and the reaper interval, then the
// upload must be gone.
time.Sleep(time.Second)
_, err = core.PutObjectPart(ctx, bucket, object, uploadID, 2, bytes.NewReader(data), int64(len(data)), minio.PutObjectPartOptions{})
require.Error(t, err)
assert.Contains(t, err.Error(), "NoSuchUpload")
err = core.AbortMultipartUpload(ctx, bucket, object, uploadID)
require.Error(t, err)
assert.Contains(t, err.Error(), "NoSuchUpload")
// Nothing is left at the key or as a temporary object.
_, err = f.NewObject(ctx, path.Join(bucket, object))
require.ErrorIs(t, err, fs.ErrorObjectNotFound)
requireOnly(t, f, bucket)
}
// TestMultipartReapExpiredUploads checks the reaper's rules directly: an
// idle upload past the expiry is aborted and cleaned up, one with a request
// in flight is left alone however stale its idle time, and a fresh one is
// kept.
func TestMultipartReapExpiredUploads(t *testing.T) {
b, _, bucket := newPutTestBackend(t, "", nil)
ctx := context.Background()
_vfs, err := b.s.getVFS(ctx)
require.NoError(t, err)
newUp := func(id string) *multipartUpload {
up := newMultipartUpload(bucket, id, bucket+"/"+id, bucket+"/"+multipartUploadPrefix+id, nil, 0)
up.fh = &stubSink{}
up.vfs = _vfs
b.multipartUploads.Store(gofakes3.UploadID(id), up)
return up
}
const expiry = time.Hour
now := time.Now()
newUp("fresh")
idle := newUp("idle")
busy := newUp("busy")
busy.startActivity()
for _, up := range []*multipartUpload{idle, busy} {
up.mu.Lock()
up.lastUsed = now.Add(-2 * expiry)
up.mu.Unlock()
}
b.reapExpiredUploads(now, expiry)
_, err = b.loadUpload("fresh")
assert.NoError(t, err, "a fresh upload must not be reaped")
_, err = b.loadUpload("busy")
assert.NoError(t, err, "an upload with a request in flight must not be reaped")
_, err = b.loadUpload("idle")
assert.ErrorIs(t, err, gofakes3.ErrNoSuchUpload, "an idle upload past the expiry must be reaped")
// The reaped upload was aborted, not committed.
sink := idle.fh.(*stubSink)
assert.True(t, sink.closed)
assert.Equal(t, errMultipartAborted, sink.abortErr)
}
// cacheWritesVFSOpt returns VFS options with --vfs-cache-mode writes and the
// given write-back delay.
func cacheWritesVFSOpt(writeBack time.Duration) *vfscommon.Options {
vfsOpt := vfscommon.Opt
vfsOpt.CacheMode = vfscommon.CacheModeWrites
vfsOpt.WriteBack = fs.Duration(writeBack)
return &vfsOpt
}
// waitForContent waits for bucket/object on the backing Fs to hold want
// (e.g. after the VFS write-back delay).
func waitForContent(t *testing.T, f fs.Fs, bucket, object string, want []byte) {
ctx := context.Background()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if o, err := f.NewObject(ctx, path.Join(bucket, object)); err == nil {
if rc, err := o.Open(ctx); err == nil {
got, err := io.ReadAll(rc)
_ = rc.Close()
if err == nil && bytes.Equal(got, want) {
return
}
}
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("object %s/%s never reached the expected content on the backing remote", bucket, object)
}
// TestMultipartCacheModeWrites checks that with --vfs-cache-mode writes a
// multipart upload goes through the VFS cache and is written back to the
// backing remote, with no temporary object left behind. Also run with
// --disable-multipart-streaming, which only affects the streaming path - the
// cache needs no PutStream, so backends without one take this path instead
// of buffering in memory.
func TestMultipartCacheModeWrites(t *testing.T) {
for _, tc := range []struct {
name string
disableStreaming bool
}{
{"Streaming", false},
{"NoStreaming", true},
} {
t.Run(tc.name, func(t *testing.T) {
core, f, bucket := newMultipartTestServerVFS(t, "", tc.disableStreaming, nil, cacheWritesVFSOpt(100*time.Millisecond))
const object = "cached.bin"
want, err := multipartUploadParts(t, core, bucket, object, []int{120 * 1024, 100 * 1024, 53 * 1024})
require.NoError(t, err)
waitForContent(t, f, bucket, object, want)
requireOnly(t, f, bucket, object)
})
}
}
// TestMultipartCacheModeMinimal checks that --vfs-cache-mode minimal takes
// the cached path just like writes - the parts are written through a
// read-write handle, which the VFS caches from minimal up - including with
// --disable-multipart-streaming set, which only affects the streaming path.
func TestMultipartCacheModeMinimal(t *testing.T) {
vfsOpt := vfscommon.Opt
vfsOpt.CacheMode = vfscommon.CacheModeMinimal
vfsOpt.WriteBack = fs.Duration(100 * time.Millisecond)
core, f, bucket := newMultipartTestServerVFS(t, "", true, nil, &vfsOpt)
const object = "cached-minimal.bin"
want, err := multipartUploadParts(t, core, bucket, object, []int{120 * 1024, 100 * 1024, 53 * 1024})
require.NoError(t, err)
waitForContent(t, f, bucket, object, want)
requireOnly(t, f, bucket, object)
}
// TestMultipartCacheModeWritesAbort checks that with --vfs-cache-mode writes
// an aborted upload is discarded from the cache: nothing reaches the backing
// remote and an existing object at the key survives.
func TestMultipartCacheModeWritesAbort(t *testing.T) {
core, f, bucket := newMultipartTestServerVFS(t, "", false, nil, cacheWritesVFSOpt(100*time.Millisecond))
ctx := context.Background()
const object = "cached-abort.bin"
existing := []byte(random.String(100))
_, err := core.PutObject(ctx, bucket, object, bytes.NewReader(existing), int64(len(existing)), "", "", minio.PutObjectOptions{})
require.NoError(t, err)
waitForContent(t, f, bucket, object, existing)
uploadID, err := core.NewMultipartUpload(ctx, bucket, object, minio.PutObjectOptions{})
require.NoError(t, err)
data := []byte(random.String(50 * 1024))
_, err = core.PutObjectPart(ctx, bucket, object, uploadID, 1, bytes.NewReader(data), int64(len(data)), minio.PutObjectPartOptions{})
require.NoError(t, err)
require.NoError(t, core.AbortMultipartUpload(ctx, bucket, object, uploadID))
// Wait out several write-back intervals: the aborted upload must not be
// written back, neither over the object nor as a temporary object.
time.Sleep(time.Second)
assert.Equal(t, existing, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
}
// TestMultipartCacheModeWritesSupersedesPut checks that a multipart upload
// completed while an earlier PUT to the same key is still in the write-back
// window ends up with the multipart data: both writes go through the same
// cache item, so the earlier PUT's write-back cannot land on top of the
// newer multipart object.
func TestMultipartCacheModeWritesSupersedesPut(t *testing.T) {
core, f, bucket := newMultipartTestServerVFS(t, "", false, nil, cacheWritesVFSOpt(500*time.Millisecond))
ctx := context.Background()
const object = "supersede.bin"
// PUT an object; it sits in the cache awaiting write-back.
old := []byte(random.String(100))
_, err := core.PutObject(ctx, bucket, object, bytes.NewReader(old), int64(len(old)), "", "", minio.PutObjectOptions{})
require.NoError(t, err)
// Immediately replace it with a multipart upload to the same key.
want, err := multipartUploadParts(t, core, bucket, object, []int{60 * 1024, 40 * 1024})
require.NoError(t, err)
// After all write-backs settle the multipart data must have won.
waitForContent(t, f, bucket, object, want)
time.Sleep(time.Second)
assert.Equal(t, want, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
}
// TestMultipartNoPutStream checks that a multipart upload to a remote
// without streaming upload support works with the default cache mode: the
// parts are spooled to a temporary file on local disk and uploaded with a
// known size, rather than being buffered in memory.
func TestMultipartNoPutStream(t *testing.T) {
core, f, bucket := newMultipartTestServerVFS(t, "", false, nil, nil, "PutStream")
require.Nil(t, f.Features().PutStream)
const object = "no-putstream.bin"
want, err := multipartUploadParts(t, core, bucket, object, []int{120 * 1024, 100 * 1024, 53 * 1024})
require.NoError(t, err)
assert.Equal(t, want, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
}
// TestMultipartNoServerSideMove checks multipart uploads to an atomic remote
// with no server-side move or copy, where the parts stream straight to the
// final object: an upload round-trips, and an aborted upload leaves an
// existing object at the key untouched.
func TestMultipartNoServerSideMove(t *testing.T) {
// The distinct description= gives this remote its own config string so
// it doesn't share a VFS with the fully-featured ":memory:" servers.
core, f, bucket := newMultipartTestServerVFS(t, ":memory,description=no-server-side-move:", false, nil, nil, "Copy")
require.False(t, operations.CanServerSideMove(f))
ctx := context.Background()
const object = "direct.bin"
existing := []byte(random.String(100))
_, err := core.PutObject(ctx, bucket, object, bytes.NewReader(existing), int64(len(existing)), "", "", minio.PutObjectOptions{})
require.NoError(t, err)
// An aborted upload must leave the existing object untouched.
uploadID, err := core.NewMultipartUpload(ctx, bucket, object, minio.PutObjectOptions{})
require.NoError(t, err)
data := []byte(random.String(50 * 1024))
_, err = core.PutObjectPart(ctx, bucket, object, uploadID, 1, bytes.NewReader(data), int64(len(data)), minio.PutObjectPartOptions{})
require.NoError(t, err)
require.NoError(t, core.AbortMultipartUpload(ctx, bucket, object, uploadID))
assert.Equal(t, existing, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
// A completed upload replaces it.
want, err := multipartUploadParts(t, core, bucket, object, []int{60 * 1024, 40 * 1024})
require.NoError(t, err)
assert.Equal(t, want, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
}
// TestMultipartNoServerSideMovePartialUploads checks that a multipart upload
// to a remote where partial uploads are visible and which has no server-side
// move or copy round-trips: the parts are written straight to the final
// object rather than being buffered in memory.
func TestMultipartNoServerSideMovePartialUploads(t *testing.T) {
core, f, bucket := newMultipartTestServerVFS(t, "", false, nil, nil, "Move", "Copy")
require.False(t, operations.CanServerSideMove(f))
require.True(t, f.Features().PartialUploads)
const object = "direct-partial.bin"
want, err := multipartUploadParts(t, core, bucket, object, []int{60 * 1024, 40 * 1024})
require.NoError(t, err)
assert.Equal(t, want, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
}
// TestMultipartCacheModeWritesNoServerSideMove checks that with
// --vfs-cache-mode writes a remote with no server-side move or copy is still
// written through the cache rather than falling back to buffering the upload
// in memory, and pins the documented trade-offs of that path: the parts go
// into the cache under the final key, so the in-flight upload is visible
// there, and an aborted upload cannot be abandoned once in the cache, so its
// partial data is written back as if it were a completed object.
func TestMultipartCacheModeWritesNoServerSideMove(t *testing.T) {
// The distinct description= gives this remote its own config string so
// it doesn't share a VFS with the fully-featured ":memory:" servers.
core, f, bucket := newMultipartTestServerVFS(t, ":memory,description=no-move-cache:", false, nil, cacheWritesVFSOpt(100*time.Millisecond), "Copy")
require.False(t, operations.CanServerSideMove(f))
ctx := context.Background()
// A round trip goes through the cache under the final key.
const object = "cached-direct.bin"
want, err := multipartUploadParts(t, core, bucket, object, []int{120 * 1024, 100 * 1024, 53 * 1024})
require.NoError(t, err)
waitForContent(t, f, bucket, object, want)
// The parts are written to the cache, not buffered in memory, so the
// in-flight upload is visible at the key.
const object2 = "cached-direct-inflight.bin"
uploadID, err := core.NewMultipartUpload(ctx, bucket, object2, minio.PutObjectOptions{})
require.NoError(t, err)
data := []byte(random.String(50 * 1024))
_, err = core.PutObjectPart(ctx, bucket, object2, uploadID, 1, bytes.NewReader(data), int64(len(data)), minio.PutObjectPartOptions{})
require.NoError(t, err)
_, err = core.StatObject(ctx, bucket, object2, minio.StatObjectOptions{})
assert.NoError(t, err, "in-flight upload should be visible at the key")
// An aborted upload's partial data is committed to the cache and
// written back.
require.NoError(t, core.AbortMultipartUpload(ctx, bucket, object2, uploadID))
waitForContent(t, f, bucket, object2, data)
requireOnly(t, f, bucket, object, object2)
}
// TestTempObjectsHiddenFromListings checks that the reserved .rclone_temp_
// prefix, and the multipart prefix used before it was reserved, are hidden
// from S3 listings while remaining visible to rclone itself for cleanup.
func TestTempObjectsHiddenFromListings(t *testing.T) {
core, f, bucket := newMultipartTestServer(t, false)
ctx := context.Background()
names := []string{
"visible.bin",
tempObjectPrefix + "anything",
multipartUploadPrefix + "leftover",
putObjectPrefix + "leftover",
legacyMultipartUploadPrefix + "leftover",
}
for _, name := range names {
data := []byte("x")
src := object.NewStaticObjectInfo(path.Join(bucket, name), time.Now(), int64(len(data)), true, nil, f)
_, err := f.Put(ctx, bytes.NewReader(data), src)
require.NoError(t, err)
}
// All the objects really exist on the backing remote...
requireOnly(t, f, bucket, names...)
// ...but only the visible one appears in an S3 listing.
result, err := core.ListObjects(bucket, "", "", "", 1000)
require.NoError(t, err)
var keys []string
for _, o := range result.Contents {
keys = append(keys, o.Key)
}
assert.Equal(t, []string{"visible.bin"}, keys)
}
// TestMultipartOverwrite checks that a completed multipart upload atomically
// replaces an existing object of the same name.
func TestMultipartOverwrite(t *testing.T) {
+224
View File
@@ -0,0 +1,224 @@
// PutObject error handling tests for serve s3.
//
// A PUT which fails part way through its body must never disturb the object
// already stored at the key.
package s3
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"path"
"testing"
"time"
"github.com/ncw/swift/v2"
"github.com/rclone/gofakes3"
"github.com/rclone/rclone/cmd/serve/proxy"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// errorReader yields data then fails with err.
type errorReader struct {
data []byte
err error
}
func (r *errorReader) Read(p []byte) (int, error) {
if len(r.data) == 0 {
return 0, r.err
}
n := copy(p, r.data)
r.data = r.data[n:]
return n, nil
}
// newPutTestBackend returns an s3Backend for direct PutObject tests, backed by
// the named remote, plus the backing Fs and a bucket created on it. vfsOpt
// overrides the VFS options (nil for the defaults).
func newPutTestBackend(t *testing.T, backing string, vfsOpt *vfscommon.Options) (*s3Backend, fs.Fs, string) {
fstest.Initialise()
ctx := context.Background()
if backing == "" {
backing = t.TempDir()
}
f, err := fs.NewFs(ctx, backing)
require.NoError(t, err)
bucket := fmt.Sprintf("test-%d", testBackingCounter.Add(1))
require.NoError(t, f.Mkdir(ctx, bucket))
if vfsOpt == nil {
vfsOpt = &vfscommon.Opt
}
// The VFS is cached per remote, so a shared ":memory:" backing reuses a
// VFS whose cached root listing predates the bucket just created; forget
// it so the new bucket is visible.
if root, err := vfs.New(ctx, f, vfsOpt).Root(); err == nil {
root.ForgetAll()
}
opt := Opt
opt.HTTP.ListenAddr = []string{endpoint}
w, err := newServer(ctx, f, &opt, vfsOpt, &proxy.Opt)
require.NoError(t, err)
t.Cleanup(func() { _ = w.Shutdown() })
return newBackend(w), f, bucket
}
var errBoom = errors.New("boom")
// failureModes enumerates the ways a PUT body can fail to arrive in full:
// an arbitrary read error, the unexpected EOF a dropped connection gives
// (which must not be mistaken for a clean end of stream), and a body which
// ends cleanly short of its declared size.
var failureModes = []struct {
name string
readerErr error
wantErr error
}{
{"ReadError", errBoom, errBoom},
{"UnexpectedEOF", io.ErrUnexpectedEOF, io.ErrUnexpectedEOF},
{"ShortBody", io.EOF, gofakes3.ErrIncompleteBody},
}
// failPut makes a PutObject call to bucket/object whose body fails with
// readerErr part way through and asserts wantErr is passed back.
func failPut(t *testing.T, b *s3Backend, bucket, object string, readerErr, wantErr error) {
_, err := b.PutObject(context.Background(), bucket, object, map[string]string{},
&errorReader{data: []byte(random.String(50)), err: readerErr}, 1000)
require.ErrorIs(t, err, wantErr)
}
// TestPutObjectFailurePreservesExisting checks that a failed PUT leaves the
// object stored at the key untouched - neither removed nor overwritten with
// truncated data - with no temporary object left behind.
func TestPutObjectFailurePreservesExisting(t *testing.T) {
for _, tc := range testRemotes {
for _, fm := range failureModes {
t.Run(tc.name+"/"+fm.name, func(t *testing.T) {
b, f, bucket := newPutTestBackend(t, tc.backing, nil)
ctx := context.Background()
const object = "existing.txt"
existing := []byte(random.String(100))
_, err := b.PutObject(ctx, bucket, object, map[string]string{}, bytes.NewReader(existing), int64(len(existing)))
require.NoError(t, err)
assert.Equal(t, existing, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
failPut(t, b, bucket, object, fm.readerErr, fm.wantErr)
assert.Equal(t, existing, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
// The object must still be served correctly - in particular
// HeadObject must not report the failed upload's size.
head, err := b.HeadObject(ctx, bucket, object)
require.NoError(t, err)
assert.Equal(t, int64(len(existing)), head.Size)
})
}
}
}
// TestPutObjectFailureNewKey checks that a failed PUT to a key with no
// existing object leaves nothing behind - no partial object at the key and
// no temporary object.
func TestPutObjectFailureNewKey(t *testing.T) {
for _, tc := range testRemotes {
for _, fm := range failureModes {
t.Run(tc.name+"/"+fm.name, func(t *testing.T) {
b, f, bucket := newPutTestBackend(t, tc.backing, nil)
ctx := context.Background()
const object = "new.txt"
failPut(t, b, bucket, object, fm.readerErr, fm.wantErr)
_, err := f.NewObject(ctx, path.Join(bucket, object))
require.ErrorIs(t, err, fs.ErrorObjectNotFound)
requireOnly(t, f, bucket)
// The failed upload must not be served either
_, err = b.HeadObject(ctx, bucket, object)
require.Error(t, err)
})
}
}
}
// TestPutObjectMtime checks that the object's modtime is set from the
// "X-Amz-Meta-Mtime" or "mtime" metadata supplied with the PUT.
func TestPutObjectMtime(t *testing.T) {
want := fstest.Time("2011-12-25T12:59:59.123456789Z")
for _, metaKey := range []string{"X-Amz-Meta-Mtime", "mtime"} {
t.Run(metaKey, func(t *testing.T) {
b, f, bucket := newPutTestBackend(t, "", nil)
ctx := context.Background()
const object = "mtime.txt"
contents := []byte(random.String(50))
meta := map[string]string{metaKey: swift.TimeToFloatString(want)}
_, err := b.PutObject(ctx, bucket, object, meta, bytes.NewReader(contents), int64(len(contents)))
require.NoError(t, err)
o, err := f.NewObject(ctx, path.Join(bucket, object))
require.NoError(t, err)
fstest.AssertTimeEqualWithPrecision(t, object, want, o.ModTime(ctx), f.Precision())
})
}
}
// waitForObject waits for bucket/object to appear on the backing Fs (e.g.
// after the VFS write-back delay).
func waitForObject(t *testing.T, f fs.Fs, bucket, object string) {
ctx := context.Background()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if _, err := f.NewObject(ctx, path.Join(bucket, object)); err == nil {
return
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("object %s/%s never appeared on the backing remote", bucket, object)
}
// TestPutObjectFailureCached checks the failed PUT semantics with the cache
// modes that write through the VFS cache - minimal and above, since the PUT
// opens its handle read-write: the truncated file the failed upload leaves
// in the cache must be discarded, not written back over the object at the
// key.
func TestPutObjectFailureCached(t *testing.T) {
for _, cm := range []vfscommon.CacheMode{vfscommon.CacheModeMinimal, vfscommon.CacheModeWrites} {
for _, tc := range testRemotes {
t.Run(cm.String()+"/"+tc.name, func(t *testing.T) {
vfsOpt := vfscommon.Opt
vfsOpt.CacheMode = cm
vfsOpt.WriteBack = fs.Duration(100 * time.Millisecond)
b, f, bucket := newPutTestBackend(t, tc.backing, &vfsOpt)
const object = "cached.txt"
existing := []byte(random.String(100))
_, err := b.PutObject(context.Background(), bucket, object, map[string]string{}, bytes.NewReader(existing), int64(len(existing)))
require.NoError(t, err)
waitForObject(t, f, bucket, object)
assert.Equal(t, existing, readObject(t, f, bucket, object))
failPut(t, b, bucket, object, errBoom, errBoom)
// Wait out several write-back intervals to catch the truncated
// data being written back before checking the object is
// untouched.
time.Sleep(time.Second)
assert.Equal(t, existing, readObject(t, f, bucket, object))
requireOnly(t, f, bucket, object)
})
}
}
}
+8 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
_ "embed"
"strings"
"time"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/cmd/serve"
@@ -39,11 +40,15 @@ var OptionsInfo = fs.Options{{
}, {
Name: "disable_multipart_streaming",
Default: false,
Help: "Buffer multipart uploads in memory instead of streaming them to the backend (see the Multipart uploads docs section)",
Help: "Buffer multipart uploads in memory instead of streaming them to the backend",
}, {
Name: "multipart_streaming_buffer_limit",
Default: fs.SizeSuffix(256 * 1024 * 1024),
Help: "Maximum memory buffered per streamed multipart upload for parts arriving out of order, 0 for unlimited (see the Multipart uploads docs section)",
Help: "Maximum memory buffered per streamed multipart upload for parts arriving out of order, 0 for unlimited",
}, {
Name: "multipart_expiry",
Default: fs.Duration(24 * time.Hour),
Help: "Abort incomplete multipart uploads idle for longer than this, 0 to keep forever",
}}.
Add(httplib.ConfigInfo).
Add(httplib.AuthConfigInfo)
@@ -57,6 +62,7 @@ type Options struct {
NoCleanup bool `config:"no_cleanup"`
DisableMultipartStreaming bool `config:"disable_multipart_streaming"`
MultipartStreamingBufferLimit fs.SizeSuffix `config:"multipart_streaming_buffer_limit"`
MultipartExpiry fs.Duration `config:"multipart_expiry"`
Auth httplib.AuthConfig
HTTP httplib.Config
}
+184 -41
View File
@@ -88,24 +88,73 @@ access_key_id = ACCESS_KEY_ID
secret_access_key = SECRET_ACCESS_KEY
```
### Object uploads (PUT)
A `PutObject` upload only ever changes the object at its key atomically, on
success, a failed or interrupted PUT neither removes nor overwrites the
object already stored at the key, and never leaves a partial object visible
at it.
Remotes that upload atomically (e.g. object stores such as `s3`) are streamed
straight to the destination. On remotes where a partial upload would
otherwise be visible (e.g. `local`), and whenever `--vfs-cache-mode` is
`writes` or above, the upload is written to a temporary object that is
renamed into place on success; these remotes need to support a server-side
move or copy for this (nearly all do - without move or copy the upload is
written directly and a failed PUT may leave a partial object at the key). If
`serve s3` is killed part-way through an upload the temporary object (named
with a leading `.rclone_temp_put_`) may be left behind; it is hidden from
S3 listings but must be removed manually.
### Multipart uploads
By default `serve s3` **streams** each multipart upload, in part-number
order, into a single `PutStream` upload to the underlying remote, so the
whole file is never buffered in memory - memory use stays bounded by the
parts in flight. The remote then performs its own internal upload (for
example its own multipart upload, still with bounded memory). This works
for any remote that supports `PutStream`, which is nearly all of them,
including through `crypt`.
The upload is atomic so the destination object only ever changes on a
Multipart uploads are written, in part-number order, to a temporary
object which is renamed into place, server-side, on completion, so the
upload is atomic. The object at the key only ever changes on a
successful completion. A failed or aborted upload never affects any
object already stored under that name. Remotes that upload atomically
already (object stores such as `s3`) are streamed straight to the
destination. On remotes where a partial upload would otherwise be visible
(such as `local`), the parts are streamed to a temporary object that is
moved into place, server-side, on completion; these remotes therefore
also need to support a server-side move or copy.
object already stored under that name and a partly-uploaded object
never becomes visible under it.
With the default `--vfs-cache-mode off` `serve s3` **streams** each
multipart upload, in part-number order, into a single streaming upload
to the underlying remote, so the whole file is never buffered in
memory. Memory use stays bounded by the parts in flight. The remote
then performs its own internal upload (for example its own multipart
upload, still with bounded memory). Remotes that don't support
streaming uploads (those that must know the file size before the
upload starts, such as `onedrive`, `pcloud`, `jottacloud`, `mailru`,
`opendrive`, `putio`, `protondrive` and `zoho`) have the parts spooled
to a temporary file on **local disk** instead, and uploaded with the
size then known on completion, so they need local disk space for the
largest objects in flight rather than memory.
With `--vfs-cache-mode writes` (or `full`) the parts are written to a
temporary file in the VFS cache and uploaded by the VFS write-back -
see [Multipart uploads and the VFS
cache](#multipart-uploads-and-the-vfs-cache) below.
The rename into place needs the remote to support a server-side move
or copy, which nearly all do. It is a cheap rename on most remotes,
but on object stores without a real rename (such as `s3` itself) the
move is performed as a server-side copy and delete of the whole
object, which can take time and API calls for large objects.
Concurrent multipart uploads of the same key (which S3 permits) are
safe. Each writes its own temporary object and the last to complete
wins.
On the few remotes that support neither server side move nor copy, the
parts are written straight to the destination object instead and never
buffered in memory. This is at some cost in atomicity - the incomplete
object is visible under its final name while the upload is in flight,
as it also is for a plain object PUT on such remotes, and concurrent
multipart uploads of the same key write to the same object and can
interleave. A failed or aborted upload still leaves any pre-existing
object untouched provided the remote uploads atomically and the VFS
cache is off; on a remote where partial uploads are visible it may
leave partial data at the key (like a plain PUT there), and with
`--vfs-cache-mode writes` (or `full`) a write to the cache cannot be
abandoned, so an aborted upload's partial data is written back to the
remote as if it had completed.
**Features**
@@ -120,10 +169,14 @@ also need to support a server-side move or copy.
as one continuous stream.
- The destination object only ever changes atomically, on completion: an
aborted or failed upload leaves any pre-existing object of the same
name untouched, and a partly-uploaded object never becomes visible.
- Backend-agnostic - it only needs the remote to support `PutStream`
(plus a server-side move or copy on remotes that don't upload
atomically).
name untouched, and a partly-uploaded object never becomes visible
(except on the few remotes with no server-side move or copy, as
above).
- Multipart uploads go through the VFS like any other upload, so they
show in rclone's transfer stats and obey `--bwlimit`.
- Backend-agnostic - it only needs the remote to support a server-side
move or copy for the rename into place, which nearly all do; a remote
without streaming upload support spools to local disk as above.
**Limitations**
@@ -149,31 +202,121 @@ also need to support a server-side move or copy.
upload and the client must start it again. (The remote's own upload
still retries its internal chunks.)
- Parts are serialised into one stream, so ingest from the client is
effectively single-threaded, although the remote's own upload still
runs concurrently.
- On remotes that don't upload atomically (such as `local`), the
completed object is moved into place with a server-side operation.
This is a cheap rename on most such remotes. On these remotes, if
`serve s3` is killed part-way through an upload the temporary object
(named with a leading `.rclone_multipart_upload_`) may be left behind;
it is hidden from S3 listings but must be removed manually.
effectively single-threaded. When streaming, the remote's own upload
runs concurrently with the parts arriving; with the local disk spool
or the VFS cache the upload to the remote only starts on completion.
- If `serve s3` is killed part-way through an upload the temporary
object (named with a leading `.rclone_temp_multipart_`) may be left
behind; it is hidden from S3 listings but must be removed manually.
#### Multipart uploads and the VFS cache
With `--vfs-cache-mode writes` (or `full`) multipart uploads do not
stream to the remote at all. The parts are written, in part-number
order, to a temporary file in the VFS cache. On completion the file is
renamed into place and uploaded by the VFS write-back, exactly like a
plain object PUT. This needs no streaming upload support from the
remote. The rename normally happens in the cache before the upload has
started, but the VFS requires the remote to support a server-side move
or copy to rename files at all (and uses one if the temporary file has
already been written back, e.g. with `--vfs-write-back 0`). On remotes
without either, the parts are written to the cache directly under the
final key instead: the upload still never touches memory, but it loses
its atomicity - the in-flight upload is visible at the key, and an
aborted upload cannot be abandoned once in the cache, so its partial
data is written back to the remote as if it were a completed object.
Remotes that benefit from `--vfs-cache-mode writes`:
- **Remotes over slow or unreliable links.** A failure in a streamed
upload aborts the whole multipart upload and the client must start
again from the first part; a failed write-back upload is retried by
the VFS (see `--vfs-cache-max-age` and friends) without the client
being involved. Ingest from the client also runs at local disk speed
rather than being throttled to the remote's pace.
- **Workloads that read back or overwrite what they just wrote.** The
completed object stays in the cache, so subsequent `GET`/`HEAD`
requests are served locally, and plain PUTs and multipart uploads to
the same key go through the same cache entry so the last write wins
regardless of upload style.
The trade-offs of the VFS cache:
- The whole object lands on local disk, so the cache (`--cache-dir`)
needs space for the largest objects in flight; `--vfs-cache-max-size`
cannot evict files which are still being uploaded.
- The `200 OK` for `CompleteMultipartUpload` means the data is safely
in the **local cache**, not yet on the remote - the same durability
the cache gives plain PUTs. If an acknowledgement must mean the data
has reached the remote (for example WAL archiving), use the default
`--vfs-cache-mode off`.
- The upload to the remote only starts on completion, rather than
overlapping with the parts arriving, so the data reaches the remote
later than with streaming.
- If `serve s3` is killed part-way through an upload, the temporary
file survives in the cache and the VFS cache recovery uploads it to
the remote on restart as a temporary object (named with a leading
`.rclone_temp_multipart_`); as with the streaming path, it is
hidden from S3 listings but must be removed manually.
#### Cleaning up temporary objects
If `serve s3` is killed part-way through an upload it can leave a
temporary object behind, named with a leading `.rclone_temp_`. This
whole prefix is reserved: any object whose name (the last
`/`-separated segment of its key) starts with `.rclone_temp_` is
hidden from S3 listings, so don't give real objects such names - an
existing object with such a name disappears from listings (though it
stays accessible directly by its key: only listings hide reserved
names, `GET`, `HEAD` and `DELETE` of the exact key still work). A
temporary object never holds acknowledged data - uploads whose
temporary object survived were never confirmed to the client - so old
ones are safe to delete:
rclone delete --min-age 24h --include ".rclone_temp_*" remote:path
The `--min-age` protects uploads which are still in progress: make sure
it is longer than your longest upload, especially if several `serve s3`
instances share the same remote.
rclone v1.75 named its temporary multipart objects
`.rclone_multipart_upload_*`; leftovers from an older server are also
hidden from listings and can be cleaned up the same way.
#### Abandoned uploads
A client which starts a multipart upload and vanishes without either
completing or aborting it would otherwise hold on to its resources
forever.
An incomplete multipart upload which has had no activity for
`--multipart-expiry` (default `24h`) is therefore aborted and cleaned
up, exactly as if the client had called `AbortMultipartUpload`, and a
`NOTICE` is logged.
An upload with a part still being received is never expired, however
slowly the part is arriving, and each completed part restarts the
clock, so the expiry only needs to outlast the client's pauses
*between* parts, not the whole upload.
Late operations on an expired upload fail with `NoSuchUpload`, as they
do on real S3 when a lifecycle rule has aborted the upload. Set
`--multipart-expiry 0` to keep incomplete uploads forever.
#### Disabling streaming
If you pass `--disable-multipart-streaming`, or the remote doesn't
support `PutStream` (or doesn't upload atomically and can't move or copy
server-side), multipart uploads are instead **buffered in memory**
by the underlying S3 library: every part is held in memory and the whole
object is written out in one go when the upload completes (the previous
behaviour). This removes the in-order/contiguous-part restriction above,
so parts can be uploaded in any order, but **memory use grows with the
size of the upload**, so it is only suitable for small objects. A one-off
`NOTICE` is logged the first time this happens.
Alternatively, if the client is an rclone `s3` remote (like the
`[serves3]` example above), you can set `use_multipart_uploads = false`
on it so it uploads each object as a single stream and skips multipart
uploads altogether.
If you pass `--disable-multipart-streaming`, multipart uploads are
instead **buffered in memory** by the underlying S3 library: every
part is held in memory and the whole object is written out in one go
when the upload completes. This removes the in-order/contiguous-part
restriction above, so parts can be uploaded in any order, but **memory
use grows with the size of the upload**, so it is only suitable for
small objects. A one-off `NOTICE` is logged the first time this
happens. This flag is the only thing that makes multipart uploads
buffer in memory - it is never done because of missing remote
capabilities. Consider `--vfs-cache-mode writes` instead, which
buffers the upload in the VFS cache on disk and takes precedence over
`--disable-multipart-streaming`.
### Bugs
+12 -4
View File
@@ -11,6 +11,7 @@ import (
"net"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/rclone/gofakes3"
@@ -36,6 +37,7 @@ type Server struct {
f fs.Fs
_vfs *vfs.VFS // don't use directly, use getVFS
faker *gofakes3.GoFakeS3
backend *s3Backend
handler http.Handler
proxy *proxy.Proxy
ctx context.Context // for global config
@@ -75,9 +77,14 @@ func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Opt
return nil, fmt.Errorf("parsing auth list failed: %q", err)
}
w.backend = newBackend(w)
if w.opt.MultipartExpiry > 0 {
w.backend.startReaper(time.Duration(w.opt.MultipartExpiry))
}
var newLogger logger
w.faker = gofakes3.New(
newBackend(w),
w.backend,
gofakes3.WithHostBucket(!opt.ForcePathStyle),
gofakes3.WithLogger(newLogger),
gofakes3.WithRequestID(rand.Uint64()),
@@ -133,8 +140,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
}
@@ -161,6 +168,7 @@ func (w *Server) Addr() net.Addr {
// Shutdown the server
func (w *Server) Shutdown() error {
w.backend.stopReaper()
return w.server.Shutdown()
}
@@ -179,7 +187,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
}
+5 -3
View File
@@ -52,9 +52,10 @@ of the size command.`,
cmd.Run(false, false, command, func() error {
var err error
var results struct {
Count int64 `json:"count"`
Bytes int64 `json:"bytes"`
Sizeless int64 `json:"sizeless"`
Count int64 `json:"count"`
Bytes int64 `json:"bytes"`
Sizeless int64 `json:"sizeless"`
Fs string `json:"fs"`
}
results.Count, results.Bytes, results.Sizeless, err = operations.Count(context.Background(), fsrc)
@@ -65,6 +66,7 @@ of the size command.`,
fs.Logf(fsrc, "Size may be underestimated due to %d objects with unknown size", results.Sizeless)
}
if jsonOutput {
results.Fs = args[0]
return json.NewEncoder(os.Stdout).Encode(results)
}
count := strconv.FormatInt(results.Count, 10)
+18
View File
@@ -1184,3 +1184,21 @@ 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>
- Christian De Santis <41491267+christiandesantis@users.noreply.github.com>
- Rodrigo Rodrigues <191260313+MVP0TAT0@users.noreply.github.com>
- Recoordinate <296084221+latent-9@users.noreply.github.com>
- Jiacheng Xu <169599847+Stardust0831@users.noreply.github.com>
- Teddy Tennant <teddytennant@icloud.com>
- Dean Chen <862469039@qq.com>
- Pastalikek65 <Pastalikek65@users.noreply.github.com>
- Morax <james20081204@gmail.com>
- Shurong Cao <170531907+CAOShurong@users.noreply.github.com>
- Dave <davixk83@gmail.com>
+11 -2
View File
@@ -2260,7 +2260,7 @@ Most multi-thread transfers do not take additional memory, but some do
at maximum `--transfers` \* `--multi-thread-chunk-size` \*
`--multi-thread-streams` or specifically for the s3 backend
`--transfers` \* `--s3-chunk-size` \* `--s3-concurrency`. However you
can use the the [--max-buffer-memory](/docs/#max-buffer-memory) flag
can use the [--max-buffer-memory](/docs/#max-buffer-memory) flag
to control the maximum memory used here.
**NB** that this **only** works with supported backends as the
@@ -2378,8 +2378,10 @@ describes what aspect is being measured:
- `size` - order by the size of the files
- `name` - order by the full path of the files
- `modtime` - order by the modification date of the files
- `pattern` - order by a list of path glob patterns
This can have a modifier appended with a comma:
The `size`, `name` and `modtime` comparisons can have a modifier appended with
a comma:
- `ascending` or `asc` - order so that the smallest (or oldest) is processed first
- `descending` or `desc` - order so that the largest (or newest) is processed first
@@ -2398,11 +2400,18 @@ processed continuously.
If no modifier is supplied then the order is `ascending`.
For `pattern`, append one or more comma-separated patterns. Patterns use the
[filter pattern syntax](/filtering/#patterns). Files matching the first pattern
are processed first, followed by files matching the second pattern, and so on.
Files which do not match a pattern are processed last. Within each group, files
are ordered by full path. Patterns cannot contain a comma.
For example
- `--order-by size,desc` - send the largest files first
- `--order-by modtime,ascending` - send the oldest files first
- `--order-by name` - send the files with alphabetically by path first
- `--order-by 'pattern,*.tar.gz,*.md5'` - send archives before checksum files
If the `--order-by` flag is not supplied or it is supplied with an
empty string then the default ordering will be used which is as
+1 -1
View File
@@ -2015,7 +2015,7 @@ including
You should now see the three scopes on your Data access page. Now press save
at the bottom!
6. After adding scopes, click Audience
6. After adding scopes, click Audience.
Scroll down and click "+ Add users". Add yourself as a test user and press save.
7. Go to Overview on the left panel, click "Create OAuth client". Choose
+1 -1
View File
@@ -24,7 +24,7 @@ path is resolved from the root of the domain.
If the path following the `remote:` ends with `/` it will be assumed to point
to a directory. If the path does not end with `/`, then a HEAD request is sent
and the response used to decide if it it is treated as a file or a directory
and the response used to decide if it is treated as a file or a directory
(run with `-vv` to see details). When [--http-no-head](#http-no-head) is
specified, a path without ending `/` is always assumed to be a file. If rclone
incorrectly assumes the path is a file, the solution is to specify the path with
+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
+2 -4
View File
@@ -33,7 +33,6 @@ var MaxCompletedTransfers = 100
// to correctly count the updated fields
type StatsInfo struct {
mu sync.RWMutex
ctx context.Context
ci *fs.ConfigInfo
bytes int64
errors int64
@@ -85,7 +84,6 @@ type averageValues struct {
func NewStats(ctx context.Context) *StatsInfo {
ci := fs.GetConfig(ctx)
s := &StatsInfo{
ctx: ctx,
ci: ci,
checking: newTransferMap(ci.Checkers, "checking"),
transferring: newTransferMap(ci.Transfers, "transferring"),
@@ -518,10 +516,10 @@ func (s *StatsInfo) String() string {
// Add per transfer stats if required
if !s.ci.StatsOneLine {
if !s.checking.empty() {
_, _ = fmt.Fprintf(buf, "Checking:\n%s\n", s.checking.String(s.ctx, s.inProgress, s.transferring))
_, _ = fmt.Fprintf(buf, "Checking:\n%s\n", s.checking.String(s.ci, s.inProgress, s.transferring))
}
if !s.transferring.empty() {
_, _ = fmt.Fprintf(buf, "Transferring:\n%s\n", s.transferring.String(s.ctx, s.inProgress, nil))
_, _ = fmt.Fprintf(buf, "Transferring:\n%s\n", s.transferring.String(s.ci, s.inProgress, nil))
}
}
+12 -3
View File
@@ -66,6 +66,7 @@ type Transfer struct {
acc *Account
err error
completedAt time.Time
doneBytes int64
}
// newCheckingTransfer instantiates new checking of the object.
@@ -116,12 +117,20 @@ func (tr *Transfer) Done(ctx context.Context, err error) {
}
// Signal done with accounting
acc.Done()
// free the account since we may keep the transfer
acc = nil
}
var doneBytes int64
if acc != nil {
doneBytes, _ = acc.progress()
}
tr.mu.Lock()
tr.completedAt = time.Now()
if acc != nil {
tr.doneBytes = doneBytes
}
// free the account since we may keep the transfer
tr.acc = nil
tr.mu.Unlock()
if tr.checking {
@@ -181,7 +190,7 @@ func (tr *Transfer) Snapshot() TransferSnapshot {
tr.mu.RLock()
defer tr.mu.RUnlock()
var s, b int64 = tr.size, 0
b, s := tr.doneBytes, tr.size
if tr.acc != nil {
b, s = tr.acc.progress()
}
+21
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"io"
"strings"
"testing"
"github.com/rclone/rclone/fs/rc"
@@ -56,6 +57,26 @@ func TestTransfer(t *testing.T) {
assert.Equal(t, "dstFs:dstFs", snap.DstFs)
})
t.Run("DoneReleasesAccount", func(t *testing.T) {
content := "hello world"
o := mockobject.New("obj").WithContent([]byte(content), mockobject.SeekModeNone)
tr := newTransfer(s, o, srcFs, dstFs)
in := tr.Account(ctx, io.NopCloser(strings.NewReader(content)))
_, err := io.Copy(io.Discard, in)
require.NoError(t, err)
tr.Done(ctx, nil)
tr.mu.RLock()
acc := tr.acc
tr.mu.RUnlock()
assert.Nil(t, acc)
snap := tr.Snapshot()
assert.Equal(t, int64(len(content)), snap.Bytes)
assert.Equal(t, int64(len(content)), snap.Size)
})
t.Run("rcStats", func(t *testing.T) {
out := tr.rcStats()
assert.Equal(t, rc.Params{
+1 -3
View File
@@ -1,7 +1,6 @@
package accounting
import (
"context"
"fmt"
"maps"
"sort"
@@ -91,10 +90,9 @@ func (tm *transferMap) _sortedSlice() []*Transfer {
// String returns string representation of map items excluding any in
// exclude (if set).
func (tm *transferMap) String(ctx context.Context, progress *inProgress, exclude *transferMap) string {
func (tm *transferMap) String(ci *fs.ConfigInfo, progress *inProgress, exclude *transferMap) string {
tm.mu.RLock()
defer tm.mu.RUnlock()
ci := fs.GetConfig(ctx)
stringList := make([]string, 0, len(tm.items))
for _, tr := range tm._sortedSlice() {
var what = tr.what
+12 -7
View File
@@ -3,20 +3,25 @@
package fs
import (
"context"
"os"
"github.com/rclone/rclone/fs/config/configmap"
)
// A configmap.Getter to read from the environment RCLONE_CONFIG_backend_option_name
type configEnvVars string
type configEnvVars struct {
configName string
options Options
}
// Get a config item from the environment variables if possible
func (configName configEnvVars) Get(key string) (value string, ok bool) {
envKey := ConfigToEnv(string(configName), key)
func (c configEnvVars) Get(key string) (value string, ok bool) {
envKey := ConfigToEnv(c.configName, key)
value, ok = os.LookupEnv(envKey)
if ok {
Debugf(nil, "Setting %s=%q for %q from environment variable %s", key, value, configName, envKey)
opt := c.options.Get(key)
Debugf(nil, "Setting %s=%s for %q from environment variable %s", key, RedactOptionValue(GetConfig(context.Background()), opt, value), c.configName, envKey)
}
return value, ok
}
@@ -41,13 +46,13 @@ func (oev optionEnvVars) Get(key string) (value string, ok bool) {
}
value, ok = os.LookupEnv(envKey)
if ok {
Debugf(nil, "Setting %s %s=%q from environment variable %s", oev.prefix, key, value, envKey)
Debugf(nil, "Setting %s %s=%s from environment variable %s", oev.prefix, key, RedactOptionValue(GetConfig(context.Background()), opt, value), envKey)
} else if opt.NoPrefix {
// For options with NoPrefix set, check without prefix too
envKey := OptionToEnv(key)
value, ok = os.LookupEnv(envKey)
if ok {
Debugf(nil, "Setting %s=%q for %s from environment variable %s", key, value, oev.prefix, envKey)
Debugf(nil, "Setting %s=%s for %s from environment variable %s", key, RedactOptionValue(GetConfig(context.Background()), opt, value), oev.prefix, envKey)
}
}
return value, ok
@@ -125,7 +130,7 @@ func ConfigMap(prefix string, options Options, configName string, connectionStri
// remote specific environment vars
if configName != "" {
config.AddGetter(configEnvVars(configName), configmap.PriorityNormal)
config.AddGetter(configEnvVars{configName: configName, options: options}, configmap.PriorityNormal)
}
// backend specific environment vars
+93
View File
@@ -0,0 +1,93 @@
package fs
import (
"bytes"
"context"
"log/slog"
"testing"
"github.com/stretchr/testify/assert"
)
// captureLog redirects the fs logger into a buffer and enables debug
// logging for the duration of the test.
func captureLog(t *testing.T) *bytes.Buffer {
var buf bytes.Buffer
oldLogger := logger
t.Cleanup(func() { logger = oldLogger })
SetLogger(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug}))
ci := GetConfig(context.Background())
oldLevel := ci.LogLevel
t.Cleanup(func() { ci.LogLevel = oldLevel })
ci.LogLevel = LogLevelDebug
return &buf
}
// TestConfigEnvVarsRedactsPassword checks that the value of a
// password config option set via the environment
// (RCLONE_CONFIG_backend_option) is not logged (see #5794).
func TestConfigEnvVarsRedactsPassword(t *testing.T) {
t.Setenv("RCLONE_CONFIG_SRC_PASS", "obscured_pass")
t.Setenv("RCLONE_CONFIG_SRC_HOST", "example.com")
buf := captureLog(t)
config := configEnvVars{
configName: "src",
options: Options{
{Name: "pass", IsPassword: true},
{Name: "host"},
},
}
// The value is still returned to the caller...
value, ok := config.Get("pass")
assert.True(t, ok)
assert.Equal(t, "obscured_pass", value)
// ...but not logged
assert.NotContains(t, buf.String(), "obscured_pass")
// Non sensitive values are still logged
buf.Reset()
value, ok = config.Get("host")
assert.True(t, ok)
assert.Equal(t, "example.com", value)
assert.Contains(t, buf.String(), "example.com")
}
// TestConfigEnvVarsDumpAuthShowsPassword checks that with --dump auth
// set the password value is still shown in the log for debugging.
func TestConfigEnvVarsDumpAuthShowsPassword(t *testing.T) {
t.Setenv("RCLONE_CONFIG_SRC_PASS", "obscured_pass")
buf := captureLog(t)
ci := GetConfig(context.Background())
oldDump := ci.Dump
t.Cleanup(func() { ci.Dump = oldDump })
ci.Dump = DumpAuth
config := configEnvVars{
configName: "src",
options: Options{
{Name: "pass", IsPassword: true},
},
}
_, ok := config.Get("pass")
assert.True(t, ok)
assert.Contains(t, buf.String(), "obscured_pass")
}
// TestOptionEnvVarsRedactsPassword checks that the value of a
// password option set via the environment (RCLONE_backend_option) is
// not logged (see #5794).
func TestOptionEnvVarsRedactsPassword(t *testing.T) {
t.Setenv("RCLONE_SFTP_PASS", "obscured_pass")
buf := captureLog(t)
oev := optionEnvVars{
prefix: "sftp",
options: Options{{Name: "pass", IsPassword: true}},
}
value, ok := oev.Get("pass")
assert.True(t, ok)
assert.Equal(t, "obscured_pass", value)
assert.NotContains(t, buf.String(), "obscured_pass")
}
+1
View File
@@ -53,6 +53,7 @@ var (
ErrorFileNameTooLong = errors.New("file name too long")
ErrorCantListRoot = errors.New("can't list root")
ErrorFileTooSmall = errors.New("file too small for multipart upload")
ErrorRangeIgnored = errors.New("server ignored requested range")
)
// FileTooSmallError is returned by OpenChunkWriter when a file is below the
+10 -13
View File
@@ -481,24 +481,16 @@ func (c *checkMarch) checkSum(ctx context.Context, obj fs.Object, download bool,
return
}
var err error
tr := accounting.Stats(ctx).NewCheckingTransfer(obj, "hashing")
defer tr.Done(ctx, err)
if !sumFound {
err = errors.New("sum not found")
err := errors.New("sum not found")
_ = fs.CountError(ctx, err)
fs.Errorf(obj, "%v", err)
c.differences.Add(1)
c.srcFilesMissing.Add(1)
c.report(obj, c.opt.MissingOnSrc, '-')
return
}
if !download {
var objHash string
objHash, err = obj.Hash(ctx, hashType)
c.matchSum(ctx, sumHash, objHash, obj, err, hashType)
tr.Done(ctx, nil)
return
}
@@ -512,16 +504,21 @@ func (c *checkMarch) checkSum(ctx context.Context, obj fs.Object, download bool,
)
defer func() {
c.matchSum(ctx, sumHash, objHash, obj, err, hashType)
tr.Done(ctx, nil)
<-c.tokens // get the token back to free up a slot
c.wg.Done()
}()
if !download {
objHash, err = obj.Hash(ctx, hashType)
return
}
if in, err = Open(ctx, obj); err != nil {
return
}
tr := accounting.Stats(ctx).NewTransfer(obj, nil)
in = tr.Account(ctx, in).WithBuffer() // account and buffer the transfer
dlTr := accounting.Stats(ctx).NewTransfer(obj, nil)
in = dlTr.Account(ctx, in).WithBuffer() // account and buffer the transfer
defer func() {
tr.Done(ctx, nil) // will close the stream
dlTr.Done(ctx, nil) // will close the stream
}()
hashVals, err2 := hash.StreamTypes(in, hash.NewHashSet(hashType))
if err2 != nil {
+118
View File
@@ -8,7 +8,9 @@ import (
"io"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/rclone/rclone/cmd/bisync/bilib"
"github.com/rclone/rclone/fs"
@@ -16,6 +18,8 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/mockfs"
"github.com/rclone/rclone/fstest/mockobject"
"github.com/rclone/rclone/lib/readers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -541,6 +545,120 @@ func TestCheckSumDownload(t *testing.T) {
testCheckSum(t, true)
}
// hashProbe records how many hashing operations are running at once. Each
// operation blocks until want of them are in flight, or until the deadline
// expires so a serial implementation finishes instead of deadlocking.
type hashProbe struct {
mu sync.Mutex
inFlight int
max int
want int
once sync.Once
reached chan struct{}
timedOut chan struct{}
}
func newHashProbe(t *testing.T, want int, deadline time.Duration) *hashProbe {
p := &hashProbe{
want: want,
reached: make(chan struct{}),
timedOut: make(chan struct{}),
}
timer := time.AfterFunc(deadline, func() { close(p.timedOut) })
t.Cleanup(func() { timer.Stop() })
return p
}
func (p *hashProbe) enter() {
p.mu.Lock()
p.inFlight++
p.max = max(p.max, p.inFlight)
full := p.inFlight >= p.want
p.mu.Unlock()
if full {
p.once.Do(func() { close(p.reached) })
}
select {
case <-p.reached:
case <-p.timedOut:
}
}
func (p *hashProbe) leave() {
p.mu.Lock()
p.inFlight--
p.mu.Unlock()
}
func (p *hashProbe) maxInFlight() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.max
}
// probeObject is an object whose hashing is instrumented by a hashProbe
type probeObject struct {
*mockobject.ContentMockObject
probe *hashProbe
}
func (o *probeObject) Hash(ctx context.Context, ht hash.Type) (string, error) {
o.probe.enter()
defer o.probe.leave()
return o.ContentMockObject.Hash(ctx, ht)
}
func (o *probeObject) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
o.probe.enter()
defer o.probe.leave()
return o.ContentMockObject.Open(ctx, options...)
}
func testCheckSumConcurrency(t *testing.T, download bool) {
const (
checkers = 2
numFiles = 4
sumFile = "test.sum"
)
hashType := hash.MD5
ctx, ci := fs.AddConfig(context.Background())
ci.Checkers = checkers
probe := newHashProbe(t, checkers, 10*time.Second)
f, err := mockfs.NewFs(ctx, "checkSum", "checkSum", nil)
require.NoError(t, err)
fsrc := f.(*mockfs.Fs)
fsrc.SetHashes(hash.NewHashSet(hashType))
sums := &bytes.Buffer{}
for i := range numFiles {
remote := fmt.Sprintf("file%d", i)
o := mockobject.New(remote).WithContent([]byte("contents of "+remote), mockobject.SeekModeNone)
sum, err := o.Hash(ctx, hashType)
require.NoError(t, err)
_, _ = fmt.Fprintf(sums, "%s %s\n", sum, remote)
fsrc.AddObject(&probeObject{ContentMockObject: o, probe: probe})
}
f, err = mockfs.NewFs(ctx, "sums", "sums", nil)
require.NoError(t, err)
fsum := f.(*mockfs.Fs)
fsum.AddObject(mockobject.New(sumFile).WithContent(sums.Bytes(), mockobject.SeekModeNone))
opt := operations.CheckOpt{Combined: new(bytes.Buffer)}
require.NoError(t, operations.CheckSum(ctx, fsrc, fsum, sumFile, hashType, &opt, download))
assert.Equal(t, checkers, probe.maxInFlight(), "hashing was not run --checkers at a time")
}
func TestCheckSumConcurrency(t *testing.T) {
testCheckSumConcurrency(t, false)
}
func TestCheckSumDownloadConcurrency(t *testing.T) {
testCheckSumConcurrency(t, true)
}
func TestApplyTransforms(t *testing.T) {
var (
hashType = hash.MD5
+6 -1
View File
@@ -266,7 +266,12 @@ func (c *copy) manualCopy(ctx context.Context) (actionTaken string, newDst fs.Ob
}
if doMultiThreadCopy(ctx, c.f, c.src) {
return c.multiThreadCopy(ctx, uploadOptions)
actionTaken, newDst, err = c.multiThreadCopy(ctx, uploadOptions)
if !errors.Is(err, fs.ErrorRangeIgnored) {
return actionTaken, newDst, err
}
fs.Logf(c.src, "multi-thread copy: %v: downloading in a single stream", err)
c.tr.Reset(ctx)
}
var in io.ReadCloser
+36 -3
View File
@@ -1818,8 +1818,20 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
defer func() {
tr.Done(ctx, err)
}()
body := io.NopCloser(in) // we let the server close the body
in := tr.Account(ctx, body) // account the transfer (no buffering)
// The stream can only be read once, so hash it on the way past
// and compare with the destination afterwards.
hashType, hashOption := CommonHash(ctx, fdst, fdst)
var hasher *hash.MultiHasher
var streamIn io.Reader = in
if hashType != hash.None {
hasher, err = hash.NewMultiHasherTypes(hashOption.Hashes)
if err != nil {
return nil, err
}
streamIn = io.TeeReader(streamIn, hasher)
}
body := io.NopCloser(streamIn) // we let the server close the body
in := tr.Account(ctx, body) // account the transfer (no buffering)
if SkipDestructive(ctx, dstFileName, "upload from pipe") {
// prevents "broken pipe" errors
@@ -1827,7 +1839,7 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
return nil, err
}
var options []fs.OpenOption
options := []fs.OpenOption{hashOption}
for _, option := range fs.GetConfig(ctx).UploadHeaders {
options = append(options, option)
}
@@ -1838,6 +1850,27 @@ func RcatSize(ctx context.Context, fdst fs.Fs, dstFileName string, in io.ReadClo
return nil, err
}
// Verify the upload
if sizeDiffers(ctx, info, obj) {
err = fmt.Errorf("corrupted on transfer: sizes differ src %d vs dst(%s) %d", size, obj.Fs(), obj.Size())
} else if hasher != nil {
src := object.NewStaticObjectInfo(dstFileName, modTime, size, true, hasher.Sums(), fdst)
// checkHashes logs and counts errors
same, _, srcHash, dstHash, _ := checkHashes(ctx, src, obj, hashType)
if !same {
err = fmt.Errorf("corrupted on transfer: %v hashes differ src %q vs dst(%s) %q", hashType, srcHash, obj.Fs(), dstHash)
}
}
if err != nil {
err = fs.CountError(ctx, err)
fs.Errorf(obj, "%v", err)
fs.Infof(obj, "Removing failed copy")
if removeErr := obj.Remove(ctx); removeErr != nil {
fs.Infof(obj, "Failed to remove failed copy: %s", removeErr)
}
return nil, err
}
} else {
// Size unknown use Rcat
obj, err = Rcat(ctx, fdst, dstFileName, in, modTime, meta)
+104
View File
@@ -39,6 +39,7 @@ import (
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
@@ -1637,6 +1638,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)
@@ -1727,6 +1740,97 @@ func TestRcatSizeUploadHeaders(t *testing.T) {
assert.True(t, found, "X-Upload-Header not found in options passed to Put")
}
// corruptingFs wraps an fs.Fs, storing data which doesn't match the
// data streamed into Put.
type corruptingFs struct {
fs.Fs
}
func (f *corruptingFs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
n, err := io.Copy(io.Discard, in)
if err != nil {
return nil, err
}
return f.Fs.Put(ctx, bytes.NewReader(bytes.Repeat([]byte("!"), int(n))), src, options...)
}
// noHashFs wraps an fs.Fs, reporting that it supports no hashes.
type noHashFs struct {
fs.Fs
}
func (f *noHashFs) Hashes() hash.Set {
return hash.NewHashSet()
}
// truncatingFs wraps an fs.Fs, storing one byte less than was streamed
// into Put and reporting that it supports no hashes, so only the size
// can reveal the corruption.
type truncatingFs struct {
fs.Fs
}
func (f *truncatingFs) Hashes() hash.Set {
return hash.NewHashSet()
}
func (f *truncatingFs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
n, err := io.Copy(io.Discard, in)
if err != nil {
return nil, err
}
short := bytes.Repeat([]byte("!"), int(n)-1)
info := object.NewStaticObjectInfo(src.Remote(), src.ModTime(ctx), int64(len(short)), true, nil, f.Fs)
return f.Fs.Put(ctx, bytes.NewReader(short), info, options...)
}
func TestRcatSizeChecksum(t *testing.T) {
const body = "------------------------------------------------------------"
t.Run("Corrupted", func(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
if r.Fremote.Hashes().Count() == 0 {
t.Skip("Skipping as destination doesn't support hashes")
}
bodyReader := io.NopCloser(strings.NewReader(body))
_, err := operations.RcatSize(ctx, &corruptingFs{Fs: r.Fremote}, "potato1", bodyReader, int64(len(body)), t1, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "corrupted on transfer")
r.CheckRemoteItems(t)
})
// A destination which reports no hashes can only be checked by its
// size, so the size has to be compared as well as the hash.
t.Run("SizeDiffers", func(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
bodyReader := io.NopCloser(strings.NewReader(body))
_, err := operations.RcatSize(ctx, &truncatingFs{Fs: r.Fremote}, "potato4", bodyReader, int64(len(body)), t1, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "corrupted on transfer: sizes differ")
r.CheckRemoteItems(t)
})
t.Run("IgnoreChecksum", func(t *testing.T) {
ctx, ci := fs.AddConfig(context.Background())
ci.IgnoreChecksum = true
r := fstest.NewRun(t)
bodyReader := io.NopCloser(strings.NewReader(body))
_, err := operations.RcatSize(ctx, &corruptingFs{Fs: r.Fremote}, "potato2", bodyReader, int64(len(body)), t1, nil)
require.NoError(t, err)
})
t.Run("NoHashes", func(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
bodyReader := io.NopCloser(strings.NewReader(body))
obj, err := operations.RcatSize(ctx, &noHashFs{Fs: r.Fremote}, "potato3", bodyReader, int64(len(body)), t1, nil)
require.NoError(t, err)
assert.Equal(t, int64(len(body)), obj.Size())
})
}
func TestTouchDir(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
+1 -1
View File
@@ -254,7 +254,7 @@ func TestOptionGetters(t *testing.T) {
// set up getters
// A configmap.Getter to read from the environment RCLONE_CONFIG_backend_option_name
configEnvVarsGetter := configEnvVars("local")
configEnvVarsGetter := configEnvVars{configName: "local"}
// A configmap.Getter to read from the environment RCLONE_option_name
optionEnvVarsGetter := optionEnvVars{"local", testOptions}
+36 -3
View File
@@ -10,6 +10,7 @@ import (
"github.com/aalpar/deheap"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/fserrors"
)
@@ -187,8 +188,8 @@ func newLess(orderBy string) (less lessFn, fraction int, err error) {
if orderBy == "" {
return nil, fraction, nil
}
parts := strings.Split(strings.ToLower(orderBy), ",")
switch parts[0] {
parts := strings.Split(orderBy, ",")
switch strings.ToLower(parts[0]) {
case "name":
less = func(a, b fs.ObjectPair) bool {
return a.Src.Remote() < b.Src.Remote()
@@ -202,12 +203,44 @@ func newLess(orderBy string) (less lessFn, fraction int, err error) {
ctx := context.Background()
return a.Src.ModTime(ctx).Before(b.Src.ModTime(ctx))
}
case "pattern":
if len(parts) < 2 {
return nil, fraction, fmt.Errorf("pattern requires at least one glob")
}
matches := make([]func(string) bool, 0, len(parts)-1)
for _, glob := range parts[1:] {
if glob == "" {
return nil, fraction, fmt.Errorf("empty pattern glob")
}
re, err := filter.GlobPathToRegexp(glob, false)
if err != nil {
return nil, fraction, fmt.Errorf("bad pattern glob %q: %w", glob, err)
}
matches = append(matches, re.MatchString)
}
rank := func(remote string) int {
for i, match := range matches {
if match(remote) {
return i
}
}
return len(matches)
}
less = func(a, b fs.ObjectPair) bool {
aRemote, bRemote := a.Src.Remote(), b.Src.Remote()
aRank, bRank := rank(aRemote), rank(bRemote)
if aRank != bRank {
return aRank < bRank
}
return aRemote < bRemote
}
return less, fraction, nil
default:
return nil, fraction, fmt.Errorf("unknown --order-by comparison %q", parts[0])
}
descending := false
if len(parts) > 1 {
switch parts[1] {
switch strings.ToLower(parts[1]) {
case "ascending", "asc":
case "descending", "desc":
descending = true
+35
View File
@@ -250,6 +250,41 @@ func TestNewLess(t *testing.T) {
assert.Contains(t, err.Error(), "unknown --order-by sort direction")
})
t.Run("patternNeedsGlob", func(t *testing.T) {
_, _, err := newLess("pattern")
require.Error(t, err)
assert.Contains(t, err.Error(), "pattern requires at least one glob")
})
t.Run("patternRejectsEmptyGlob", func(t *testing.T) {
_, _, err := newLess("pattern,")
require.Error(t, err)
assert.Contains(t, err.Error(), "empty pattern glob")
})
t.Run("patternRejectsBadGlob", func(t *testing.T) {
_, _, err := newLess("pattern,[")
require.Error(t, err)
assert.Contains(t, err.Error(), "bad pattern glob")
})
t.Run("patternOrder", func(t *testing.T) {
less, fraction, err := newLess("pattern,*.tar.gz,*.md5")
require.NoError(t, err)
assert.Equal(t, -1, fraction)
archiveA := fs.ObjectPair{Src: mockobject.New("a/archive.tar.gz")}
archiveB := fs.ObjectPair{Src: mockobject.New("b/archive.tar.gz")}
checksum := fs.ObjectPair{Src: mockobject.New("a/archive.md5")}
unmatched := fs.ObjectPair{Src: mockobject.New("a/README")}
assert.True(t, less(archiveA, checksum))
assert.True(t, less(checksum, unmatched))
assert.False(t, less(unmatched, archiveA))
assert.True(t, less(archiveA, archiveB))
assert.False(t, less(archiveB, archiveA))
})
var (
obj1 = mockobject.New("b").WithContent([]byte("1"), mockobject.SeekModeNone)
obj2 = mockobject.New("a").WithContent([]byte("22"), mockobject.SeekModeNone)
+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)
+2 -2
View File
@@ -100,7 +100,7 @@ require (
golang.org/x/oauth2 v0.36.0
golang.org/x/sync v0.22.0
golang.org/x/sys v0.47.0
golang.org/x/text v0.40.0
golang.org/x/text v0.41.0
golang.org/x/time v0.15.0
google.golang.org/api v0.279.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
@@ -261,7 +261,7 @@ require (
go.yaml.in/yaml/v3 v3.0.4 // indirect
go4.org v0.0.0-20260112195520-a5071408f32f // indirect
golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597 // indirect
golang.org/x/image v0.44.0 // indirect
golang.org/x/image v0.45.0 // indirect
golang.org/x/tools v0.48.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260715232425-e75dac1f907d // indirect
google.golang.org/grpc v1.84.0-dev.0.20260723093437-b6eac429d7b6 // indirect
+4 -4
View File
@@ -662,8 +662,8 @@ golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597 h1:qLvzZeaANDgyVOA8pyHCOStGlXn0rseXma+GQjeuv2g=
golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q=
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
golang.org/x/mobile v0.0.0-20260709172247-6129f5bee9d5 h1:Mn1OzFmF0ZKX/ZayHz/UdnWHufPp1wlD9lZ5U8LRDFY=
golang.org/x/mobile v0.0.0-20260709172247-6129f5bee9d5/go.mod h1:YX+n47s+53POxN3dx9cIGxG3hGUm/lD64hvrRJFbcSA=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@@ -732,8 +732,8 @@ golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+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)
+154
View File
@@ -1,11 +1,165 @@
package rest
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/rclone/rclone/fs"
)
// ContentRange is a parsed Content-Range response header.
type ContentRange struct {
Start int64 // first byte position of the range
End int64 // last byte position of the range (inclusive)
Size int64 // complete length of the representation, or -1 if unknown
}
// ParseContentRange parses a Content-Range header of the form
// "bytes start-end/size" as returned with a ranged (206) response.
// The Size is -1 if the complete length is unknown ("*").
func ParseContentRange(value string) (ContentRange, error) {
const prefix = "bytes "
if !strings.HasPrefix(value, prefix) {
return ContentRange{}, fmt.Errorf("doesn't start with %q", prefix)
}
rangeAndSize := strings.Split(value[len(prefix):], "/")
if len(rangeAndSize) != 2 {
return ContentRange{}, errors.New("must contain one '/'")
}
bounds := strings.Split(rangeAndSize[0], "-")
if len(bounds) != 2 {
return ContentRange{}, errors.New("must contain one '-'")
}
start, err := strconv.ParseInt(bounds[0], 10, 64)
if err != nil || start < 0 {
return ContentRange{}, errors.New("invalid start")
}
end, err := strconv.ParseInt(bounds[1], 10, 64)
if err != nil || end < start {
return ContentRange{}, errors.New("invalid end")
}
size := int64(-1)
if rangeAndSize[1] != "*" {
size, err = strconv.ParseInt(rangeAndSize[1], 10, 64)
if err != nil || size < 0 || end >= size {
return ContentRange{}, errors.New("invalid complete length")
}
}
return ContentRange{Start: start, End: end, Size: size}, nil
}
// CheckContentRange checks that a response satisfies a Range open option.
// The size is the expected size of the complete representation, or -1 if it is
// unknown. Calls without a Range option are ignored.
func CheckContentRange(resp *http.Response, options []fs.OpenOption, size int64) error {
var requestRange string
for _, option := range options {
key, value := option.Header()
if strings.EqualFold(key, "Range") {
requestRange = value
}
}
if requestRange == "" {
return nil
}
requested, err := fs.ParseRangeOption(requestRange)
if err != nil {
return fmt.Errorf("invalid requested range %q: %w", requestRange, err)
}
if requested.Start < 0 && requested.End < 0 {
return fmt.Errorf("invalid requested range %q", requestRange)
}
if requested.Start >= 0 && requested.End >= 0 && requested.End < requested.Start {
return fmt.Errorf("invalid requested range %q", requestRange)
}
if resp == nil {
return errors.New("nil response to range request")
}
if resp.StatusCode == http.StatusOK {
responseSize := size
if resp.ContentLength >= 0 {
if size >= 0 && resp.ContentLength != size {
return fmt.Errorf("Content-Length %d does not match expected size %d", resp.ContentLength, size)
}
responseSize = resp.ContentLength
}
if responseSize >= 0 {
offset, limit := requested.Decode(responseSize)
if limit < 0 {
limit = responseSize - offset
}
if offset == 0 && limit >= responseSize {
return nil
}
} else if requested.Start == 0 && requested.End < 0 {
return nil
}
return fmt.Errorf("%w %q", fs.ErrorRangeIgnored, requestRange)
}
if resp.StatusCode != http.StatusPartialContent {
return fmt.Errorf("response status %d does not satisfy requested range %q", resp.StatusCode, requestRange)
}
responseRange := resp.Header.Get("Content-Range")
got, err := ParseContentRange(responseRange)
if err != nil {
return fmt.Errorf("invalid Content-Range %q: %w", responseRange, err)
}
if size >= 0 && got.Size >= 0 && got.Size != size {
return fmt.Errorf("Content-Range %q does not match expected size %d", responseRange, size)
}
rangeSize := size
if rangeSize < 0 {
rangeSize = got.Size
}
expectedStart := requested.Start
expectedEnd := requested.End
if requested.Start >= 0 {
if rangeSize >= 0 && (expectedEnd < 0 || expectedEnd >= rangeSize) {
expectedEnd = rangeSize - 1
}
} else if rangeSize >= 0 {
expectedStart = rangeSize - requested.End
if expectedStart < 0 {
expectedStart = 0
}
expectedEnd = rangeSize - 1
}
var matches bool
if requested.Start < 0 && rangeSize < 0 {
matches = got.End-got.Start+1 <= requested.End
} else {
matches = got.Start == expectedStart
if expectedEnd >= 0 {
matches = matches && got.End == expectedEnd
}
}
if !matches {
return fmt.Errorf("Content-Range %q does not match requested range %q", responseRange, requestRange)
}
contentLength := got.End - got.Start + 1
if contentLength <= 0 {
return fmt.Errorf("invalid Content-Range %q: length overflows", responseRange)
}
if resp.ContentLength >= 0 && resp.ContentLength != contentLength {
return fmt.Errorf("Content-Length %d does not match Content-Range %q", resp.ContentLength, responseRange)
}
return nil
}
// ParseSizeFromHeaders parses HTTP response headers to get the full file size.
// Returns -1 if the headers did not exist or were invalid.
func ParseSizeFromHeaders(headers http.Header) (size int64) {
+194
View File
@@ -4,6 +4,7 @@ import (
"net/http"
"testing"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
)
@@ -39,3 +40,196 @@ func TestParseSizeFromHeaders(t *testing.T) {
assert.Equalf(t, testCase.Size, ParseSizeFromHeaders(headers), "%+v", testCase)
}
}
func TestCheckContentRange(t *testing.T) {
testCases := []struct {
name string
status int
contentRange string
contentLength int64
unknownSize bool
options []fs.OpenOption
wantErr bool
wantErrorIs error
}{
{
name: "exact range",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/10",
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
},
{
name: "unknown content length",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/10",
contentLength: -1,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
},
{
name: "unknown complete length",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/*",
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
},
{
name: "open ended range",
status: http.StatusPartialContent,
contentRange: "bytes 2-9/10",
contentLength: 8,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: -1}},
},
{
name: "suffix range",
status: http.StatusPartialContent,
contentRange: "bytes 6-9/10",
contentLength: 4,
options: []fs.OpenOption{&fs.RangeOption{Start: -1, End: 4}},
},
{
name: "suffix range with unknown complete length",
status: http.StatusPartialContent,
contentRange: "bytes 6-9/*",
contentLength: 4,
options: []fs.OpenOption{&fs.RangeOption{Start: -1, End: 4}},
},
{
name: "suffix range larger than representation",
status: http.StatusPartialContent,
contentRange: "bytes 0-9/10",
contentLength: 10,
options: []fs.OpenOption{&fs.RangeOption{Start: -1, End: 20}},
},
{
name: "seek option",
status: http.StatusPartialContent,
contentRange: "bytes 2-9/10",
contentLength: 8,
options: []fs.OpenOption{&fs.SeekOption{Offset: 2}},
},
{
name: "whole representation range",
status: http.StatusOK,
contentLength: 10,
options: []fs.OpenOption{&fs.RangeOption{Start: 0, End: 9}},
},
{
name: "open ended whole representation range with unknown size",
status: http.StatusOK,
contentLength: -1,
unknownSize: true,
options: []fs.OpenOption{&fs.RangeOption{Start: 0, End: -1}},
},
{
name: "partial range ignored",
status: http.StatusOK,
contentLength: 10,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
wantErrorIs: fs.ErrorRangeIgnored,
},
{
name: "whole range response has wrong length",
status: http.StatusOK,
contentLength: 9,
options: []fs.OpenOption{&fs.RangeOption{Start: 0, End: 9}},
wantErr: true,
},
{
name: "no range requested",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/10",
contentLength: 3,
},
{
name: "missing content range",
status: http.StatusPartialContent,
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "wrong unit",
status: http.StatusPartialContent,
contentRange: "items 2-4/10",
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "wrong start",
status: http.StatusPartialContent,
contentRange: "bytes 0-2/10",
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "wrong end",
status: http.StatusPartialContent,
contentRange: "bytes 2-5/10",
contentLength: 4,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "wrong content length",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/10",
contentLength: 4,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "invalid complete length",
status: http.StatusPartialContent,
contentRange: "bytes 2-10/10",
contentLength: 9,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 10}},
wantErr: true,
},
{
name: "wrong complete length",
status: http.StatusPartialContent,
contentRange: "bytes 2-4/11",
contentLength: 3,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
{
name: "unexpected successful status",
status: http.StatusNoContent,
contentLength: 0,
options: []fs.OpenOption{&fs.RangeOption{Start: 2, End: 4}},
wantErr: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
expectedSize := int64(10)
if testCase.unknownSize {
expectedSize = -1
}
resp := &http.Response{
StatusCode: testCase.status,
Header: make(http.Header),
ContentLength: testCase.contentLength,
}
if testCase.contentRange != "" {
resp.Header.Set("Content-Range", testCase.contentRange)
}
err := CheckContentRange(resp, testCase.options, expectedSize)
if testCase.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
if testCase.wantErrorIs != nil {
assert.ErrorIs(t, err, testCase.wantErrorIs)
}
})
}
}
+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) {
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more