Compare commits

..
Author SHA1 Message Date
Nick Craig-Wood 687d264b68 Version v1.75.1 2026-09-04 17:03:20 +01:00
Nick Craig-Wood 4158f63d2f Start v1.75.1-DEV development 2026-09-04 16:50:38 +01:00
Hakan İSMAİL c47832ad34 serve: fix VFS instance leaks on server startup failures and shutdown
(cherry picked from commit 216d2a8c76)
2026-09-04 16:39:12 +01:00
Nick Craig-Wood 60e96416df rc: silence deprecation lint warning in the old web gui plugin proxy
Raising the minimum Go version to 1.26 made staticcheck flag the
deprecated ReverseProxy.Director. This code is unmaintained and has
been removed on the development branch, so suppress the warning rather
than rewrite it.
2026-09-04 16:34:03 +01:00
Nick Craig-Wood c841c3bba3 build: disable staticcheck SA4023 to fix lint job timeout
The dataflow analysis behind SA4023, new in the staticcheck 0.8.0
bundled with golangci-lint v2.13.0, makes linting large packages more
than 10x slower (89s vs 7s for backend/s3 alone) which took the CI
lint job past its 30 minute limit. golangci-lint no longer enforces
its run timeout during analysis so the job ran until cancelled, and
the cancellation meant the lint cache was never saved, making every
subsequent run cold and guaranteeing the timeout repeated.

The check also produces false positives (eg claiming operations.Delete
never returns nil).

(cherry picked from commit 357c2a2b44)
2026-09-04 16:33:21 +01:00
Nick Craig-Wood 79fbc0842f fshttp: don't send --header values to other hosts on redirect GHSA-486v-q2wf-fp2r CVE-PENDING
The headers set with --header and --header-download are added to
every request by the rclone transport, including redirect hops which
net/http makes to other hosts, so a credential passed with --header
for one host could be sent to any host that server chose to redirect
to.

The transport now walks the redirect chain net/http records on each
redirected request and, once the chain has visited a host other than
the one originally requested, removes the headers rather than adding
them.

Also restore the global --client-cert and --client-key config after
TestCertificates so its temporary files are not used by later tests.

(cherry picked from commit 101c3e342c86ae65c7c743474d7319330f0eb0ca)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 22859b7e69 http: don't leak configured headers to other hosts or over plaintext on redirect GHSA-486v-q2wf-fp2r CVE-PENDING
The headers set with --http-headers are documented for passing
credentials such as Authorization or Cookie. The backend used the
default net/http redirect policy which copies all but a handful of
well known headers to any redirect target, so a redirect from the
configured server to another host would send those credentials to
that host, and a redirect from https to http would send them in
plaintext.

When headers are configured this installs a CheckRedirect function
which:

- removes the configured headers from every hop once the redirect
  chain has left the originally requested host
- refuses a redirect from https to http with an error

(cherry picked from commit 0adc0082dff7ef6ed1597418f85ac691478a6fa5)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 925fb4fb21 rest: add SameHost and check HTTPS downgrades against the original request GHSA-486v-q2wf-fp2r CVE-PENDING
SameHost compares two URLs by host name (case insensitively) and port
(treating the scheme's default port as no port) so redirect policies
can tell a real change of host from a server spelling its own host
differently, e.g. redirecting "https://example.com/" to
"https://EXAMPLE.com:443/".

The HTTPS downgrade check now compares the redirect target against
the original request rather than the previous hop, so a chain which
started on plaintext http, passed through an https server and came
back to http is no longer refused - nothing is being downgraded
relative to what the user asked for. A chain which started on https
and reaches http via any number of hops is still refused.

(cherry picked from commit fc7a64f61c2e4b364b5789f6ea17ad0485d8246e)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 96f298bdec archive: hide any archive entry which escapes the directory being listed GHSA-66hp-wgxq-6f5q
Whether an archive entry name can escape the archive's namespace was
left entirely to each archiver. Enforce it in the archive backend too.

List only passes on direct children of the directory listed and
NewObject only returns the object asked for, so a future archiver
which forgets to validate names cannot expose a traversal to fs/sync
and fs/operations.

(cherry picked from commit a6a7d95e081b91231b49c4004e8a2bff16da4cd8)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 60fb55dc6a archive: fix "directory not found" for archive paths containing "./" or "//" GHSA-66hp-wgxq-6f5q
The path inside the archive was compared against the cleaned entry
names without being cleaned itself, so `archive.zip/sub/./dir` or
`archive.zip/sub//dir` failed to list even though `archive.zip/sub/dir`
worked.

(cherry picked from commit 34636f34079585f3a8f883038483ece58d39b084)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 181ef190ce archive: fix zip entry named "." hiding every other file GHSA-66hp-wgxq-6f5q
A zip containing a file entry whose name refers to the archive's own
root (".", "/" or "") was presented as a single file called "." and
all its other entries disappeared. A file at the root can only be the
archive member the backend was pointed at, so with no root such an
entry is skipped like any other unsafe name.

(cherry picked from commit c9fac578aae7707faf340b58cf45465a5f698cbd)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood ad8cd41c49 archive: reject unsafe entry names when mounting squashfs images GHSA-66hp-wgxq-6f5q
Entry names read from a squashfs directory are not sanitized by
go-diskfs. The squashfs backend joined each leaf name onto its
directory to form the object's remote, so a crafted image could escape
its directory.

Use sanitize.Leaf to skip unsafe entries in List. A "\" is an
ordinary character in a file name on the systems squashfs images are
made on and in an rclone remote path, so it is deliberately not
rejected; making it safe for the destination is the destination
backend's job.

Skipped entries are logged at DEBUG with a single NOTICE count per
listing so a crafted image under a mount cannot flood the log.

(cherry picked from commit 63385c66175141b63bb53b3e42b50908649f8437)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 5dae3adbf5 archive: fix zip subdirectory root matching sibling directories GHSA-66hp-wgxq-6f5q
When a zip archive was mounted at a subdirectory root, readZip used a bare
strings.HasPrefix to decide which entries fell inside the root. This
matched on a raw string prefix rather than a path boundary, so mounting
root "foo" also exposed sibling entries such as "foobar/..." with their
names left uncorrected.

Require a path boundary when filtering by root.

(cherry picked from commit b444227264cee2a9307f03ba90c2a411e7eeb693)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 6507e13d5a archive: fix zip slip path traversal in untrusted zip files GHSA-66hp-wgxq-6f5q CVE-PENDING
The zip backend mounts a zip file as a browsable Fs. Go's archive/zip
does not sanitize entry names, and readZip applied path.Clean but did
not reject a cleaned name that still pointed outside the archive. A
crafted zip could make rclone copy/sync attempt writes outside the
intended destination.

Sanitize entry names with sanitize.Path - the same check used by
rclone archive extract - skipping any entry with a ".." path
component, whether separated by "/" or "\". A backslash is otherwise
kept as an ordinary character in the name, as archive extract does. It
is up to the destination backend to make names safe for its storage.

Skipped entries are logged as a single count per archive so a crafted
archive with many escaping entries cannot flood the log.

(cherry picked from commit 224fe97ac13105094651264a9e16ee3cf41ccf77)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood e4913c9e91 lib/sanitize: factor untrusted path sanitization out of archive extract
Move the archive entry name validation added for CVE-2026-59732 from
cmd/archive/extract into a new lib/sanitize package as sanitize.Path,
so the same check can be shared with the archive backend which mounts
archives as a filesystem.

sanitize.Path keeps the extract semantics - reject any name with a
".." path component, treating both "/" and "\" as separators - and
additionally cleans the name with path.Clean. This corrects two edge
cases in extract: a repeated "./" prefix ("././file.txt") is now fully
stripped rather than only the first, and a bare "." entry is now
treated as the archive root and skipped.

Add sanitize.Leaf, which rejects a name that is empty, ".", ".." or
contains a "/", for checking a single directory entry name read from
an archive.

The names handled are rclone remote paths, in which "/" is the only
separator and "\" an ordinary character, so Leaf does not reject a
backslash: making a name safe for its storage is the destination
backend's job (the local backend encodes "\" on Windows and refuses
paths which escape its root). Path's rejection of ".." between
backslashes is kept as defence in depth for extract.

(cherry picked from commit 4aab7cd450127e902509b4c8e3a1e4f5c12056df)
2026-09-04 16:18:35 +01:00
Nick Craig-Wood 28bf49d66f local: fix panic on Range request past the end of a symlink GHSA-p6m2-r3w9-mpxw CVE-PENDING
With --links/-l, a symlink is served as a .rclonelink object whose
content is the target path. A Range request with a start offset beyond
the target length (e.g. "Range: bytes=99999999999-") reached
openTranslatedLink and sliced the target string at that offset, panicking
with "slice bounds out of range".

Clamp the offset to the target length so an out-of-range start reads
empty, matching how a real file read past EOF behaves.

(cherry picked from commit 3fa32192c20f0b4cfd4f4b07636dc3445026041a)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood 17b0c03338 local: fix btime escaping the root via a planted symlink GHSA-f8g7-2xjc-7mfh CVE-PENDING
The birth-time (btime) write in writeMetadataToFile followed symlinks for
any object that was not a translated link, so under -l/--links a symlink
planted by an untrusted source at the destination path could redirect the
btime write to a target outside the backup destination on OSes where
birth time is settable (Windows).

Use the NOFOLLOW birth-time write whenever translating symlinks, not only
for translated links. It is a no-op on a real file or directory and stops
a planted symlink from being followed out of the destination.

(cherry picked from commit bd86336faac7cfc4e9057add38ec5fd12d762d02)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood a7ab39d3d1 local: fix dir metadata escaping the root through a planted symlink GHSA-f8g7-2xjc-7mfh CVE-PENDING
With -l/--links the local backend faithfully recreates a source ".rclonelink" as
a real symlink at the destination. Directory metadata (chmod/chown/chtimes),
however, was applied with the raw following syscalls
os.Chmod/os.Chown/os.Chtimes rather than through the os.Root sandbox used for
content writes. A Directory is never a translatedLink, so when the destination
path already existed as a symlink planted by an untrusted source, the metadata
was applied through it to a target outside the backup destination.

Route directory metadata through os.Root when translating symlinks, so a planted
symlink can no longer redirect chmod/chown/chtimes out of the destination, while
legitimate in-tree directories are unaffected.

(cherry picked from commit b764ccbd23582f29c611862f11f86dde3544035a)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood 7a594b09c6 serve docker: reject volume names resolving to the base directory itself GHSA-p6vx-hf7p-98j6
An empty or "." volume name joined onto the base directory resolves to the
base directory itself. newVolume does not call validate, so such a name
would mount a remote over the base directory and shadow every other
volume's mountpoint.

Require the resolved mountpoint to be a strict descendant of the base
directory so these degenerate names are refused.

(cherry picked from commit 4765ab020802ebf8ffbc2f2e529a6b23e640bf6f)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood f376c64784 serve docker: re-derive volume mountpoint from name when restoring state GHSA-p6vx-hf7p-98j6
When the plugin restarts it reads its persisted state file and used the
stored mountpoint verbatim. A state file written by an older rclone that
allowed escaping volume names, or one that was tampered with, could point
the mountpoint outside the base directory, so upgrading did not remediate
an already-escaped volume.

Re-derive the mountpoint from the base directory and the volume name on
restore, confined to the base directory, rather than trusting the stored
path.

(cherry picked from commit b4069bc49676e55b9c8843de9a1919f940a585ac)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood afeb26ae74 serve docker: reject volume names that escape the base directory GHSA-p6vx-hf7p-98j6
A Docker VolumeDriver.Create request carries a raw volume name that was
joined onto the base directory with filepath.Join and used verbatim as the
mountpoint. filepath.Join collapses ".." components, so a crafted name such
as "../../../etc/foo" resolved to a host path outside the base directory,
where the plugin then created a directory and mounted the remote.

Confine the mountpoint to the base directory and refuse any name that
resolves outside it.

(cherry picked from commit d9ed70376eb500d23d4d7ed0d6b3db2f3c7242e8)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood c6af0b57c2 serve ftp: fix auth-proxy sessions sharing credentials by username GHSA-c476-6w5q-jw77 CVE-PENDING
When serving FTP with --auth-proxy, the obscured password was cached in a
driver-global map keyed only by the username. Two sessions that logged in
with the same username but different credentials shared one map entry, so a
later login overwrote it and every subsequent operation on the earlier,
still-authenticated session was re-authorized with the later session's
credential and executed against the later session's backend.

Bind the credential to the FTP session by storing the obscured password in
the per-session goftp Session.Data map instead, so each session always
resolves the backend it authenticated for.

(cherry picked from commit 0bc745328dbf4669561d2abd9c81c596fbb0787d)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood 90595f34f2 serve s3: fix auth proxy accepting any request signed with an empty secret GHSA-xwwr-4h3p-r22c CVE-PENDING
With --auth-proxy set and --auth-key unset, serve s3 registered every client
supplied access key ID with an empty secret and verified the SigV4 signature
against that, so anyone could sign a request for an arbitrary access key ID with
an empty secret and be let in. The proxy program was only ever given the access
key ID (as both user and pass) so it had nothing with which to authenticate the
client either.

An S3 client never sends its secret, only a signature made with it, so the
server has to know the secret to check the request. The auth proxy protocol as
been changed to handle this. For serve s3 the proxy program is given just the
access key ID as the user (no pass or public_key) and must return the matching
secret as _secret_access_key in its output. rclone verifies the request's
signature against that secret, refusing the request if the proxy rejects the
access key ID, doesn't return a secret or returns an empty one, or the signature
doesn't match. The secret is only used for this server's own verification and is
never registered with gofakes3, so other serve s3 instances in the same process
don't honour it.

The proxy's answers are cached. If a signature fails against a cached secret the
proxy is consulted again so a rotated secret takes effect immediately - but only
for a signature mismatch, and at most once every 10 seconds per access key ID
and client IP, so a stream of bad signatures can't make the proxy program run
for every request. A rotation never shuts down the cached backend under requests
still using it. A cached answer is checked with the proxy again once it is 5
minutes old even if in constant use, so revoking an access key ID takes effect
within 5 minutes.

This means --auth-key is no longer needed with --auth-proxy: it is ignored and a
warning is given at startup if both are set. The proxy is the source of truth
for both the credentials and the backend they map to. Presigned URLs (credential
in the query string) are now recognised by the proxy middleware too. The auth
proxy docs are added to serve s3.

Note that the serve s3 auth proxy protocol has changed. The proxy program is now
given the access key ID as "user" (it was previously given an MD5 hash of it,
with the access key ID as "pass") and must return the matching secret as
"_secret_access_key".

This needs gofakes3 v0.0.9 for signature.V4SignVerifyWithSecret.

(cherry picked from commit 7306f0668125ecbd1cb9d704f570fbb492a76fb8)
2026-09-04 16:18:19 +01:00
Nick Craig-Wood b3cf0444a2 serve s3: fix each server accepting the --auth-key credentials of all the others
gofakes3 kept the keys given with --auth-key in a store global to the process,
so when more than one serve s3 was running in one rclone (eg started via the rc)
each accepted the others' credentials and a client with the key for one server
could read and write the backend of another.

This updates gofakes3 to v0.0.9 which keeps auth keys per instance and adds a
test that two servers only accept their own keys.

(cherry picked from commit b81c9c892f855095924b89e623f0e4c4e7149168)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood 11ff6e49bb serve sftp: fix auth proxy configured via rc being silently ignored GHSA-p569-5gjg-9cmj CVE-PENDING
From v1.70.0, an SFTP server started through the rc serve/start API with
a per-server proxyOpt.AuthProxy decided whether to enable proxy
authentication by checking the process-global proxy.Opt.AuthProxy
instead of the supplied proxyOpt.AuthProxy. In the normal rc case the
global is empty, so the auth proxy was silently ignored: the server
either failed to start with "no authorization found" or authenticated
against the local authorized_keys file instead of routing each login
through the proxy the operator configured.

The serve Provider refactor (f425f8d46) fixed the constructor by building the
provider from the supplied proxyOpt, but the authorized-keys handling in
configure() still consulted the global option. Make it depend on whether
proxy mode is actually active, and add a regression test for the
per-server option.

(cherry picked from commit 929933f5c303d6e7d5ab0cdcbae843862cb15e73)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood bcef98db3f serve s3: fix misleading anonymous access log and add test for auth proxy via rc GHSA-p569-5gjg-9cmj CVE-PENDING
From v1.70.0 until the serve Provider refactor (f425f8d46), an S3 server started
through the rc serve/start API with a per-server proxyOpt.AuthProxy
decided whether to enable proxy authentication by checking the
process-global proxy.Opt.AuthProxy instead of the supplied
proxyOpt.AuthProxy. In the normal rc case the global is empty, so the
auth proxy was silently ignored and the server served the fixed
filesystem supplied to serve/start rather than routing each access key
to the backend chosen by the proxy, bypassing the operator's intended
per-key authorization.

The Provider refactor fixed this incidentally by building the provider
from the proxyOpt passed to the constructor. This adds a regression test
so the per-server option cannot silently stop working again, and only
logs "allowing anonymous access" when neither an auth key nor an auth
proxy is configured so the log reflects the effective mode.

(cherry picked from commit 1e8134e83bbdcededfdc3c48f00e52544a775342)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood f18aacf2c7 serve ftp: add test for auth proxy configured via rc GHSA-p569-5gjg-9cmj CVE-PENDING
From v1.70.0 until the serve Provider refactor (f425f8d46), an FTP server started
through the rc serve/start API with a per-server proxyOpt.AuthProxy
decided whether to enable proxy authentication by checking the
process-global proxy.Opt.AuthProxy instead of the supplied
proxyOpt.AuthProxy. In the normal rc case the global is empty, so the
auth proxy was silently ignored and the server fell back to its
fixed-backend mode, whose default account accepts user "anonymous" with
any password - a complete authentication bypass.

The Provider refactor fixed this incidentally by building the provider
from the proxyOpt passed to the constructor. This adds a regression test
so the per-server option cannot silently stop working again.

(cherry picked from commit f89737278f27dc233f4dae2cb126a5e8b1980f70)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood ab1f458013 serve s3: reject bogus multipart part sizes in the reorder buffer GHSA-2p48-j3qc-rx9f
The multipart reorder-buffer admission trusted the client-declared part length.
A negative length was accepted, and `buffered + size` could overflow int64 for
a huge declared length, wrapping the running total negative and admitting
further parts past --multipart-streaming-buffer-limit.

Reject a negative length and use the overflow-safe comparison `size <=
bufferLimit - buffered` so an untrusted Content-Length can neither poison nor
overflow the budget.

(cherry picked from commit 337ab7f76ba6ba3731fba04b088bd831511bca04)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood 7c1dfd99f3 serve s3: fix memory exhaustion from client-declared multipart part size GHSA-2p48-j3qc-rx9f CVE-PENDING
Streamed multipart UploadPart called Reserve(contentLength) before reading any
body bytes, so the pool immediately allocated one 1 MiB page per MiB of the
client-declared Content-Length (or X-Amz-Decoded-Content-Length). An client
could declare a huge part size, send no body, and force an arbitrarily large
allocation without paying the bandwidth cost of the declared body.

Drop the Reserve so the pool-backed buffer grows a page at a time as the body
is actually read: memory now tracks the bytes received, not the unverified
header.

(cherry picked from commit 8f2ad09941b0d69b67366101d5c2c350ca2a12df)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood 57842c5ee4 fs: confine directory listing entries that escape the root GHSA-3vxh-3pcx-9m8q GHSA-38xv-hf3p-h7mq CVE-PENDING
The rclone core does not sanitise ".." in an object's Remote(). Such a name can
arrive from a malicious or buggy backend - an object store permits keys
containing ".." or a leading "/" - and, if acted on, lets a listing or transfer
escape the configured root. A source object named "../../other/x" is copied to
"other/x" outside the destination root, and a crafted listing name surfaces
outside the directory being listed.

Add list.RemoteEscapesRoot, which reports whether a Remote climbs above the
root when joined onto it, and list.RemoveEscaping, which drops and logs such
entries.

Apply RemoveEscaping unconditionally - independent of the include/exclude
filters - at the three per-entry filtering points every listing passes through:
filterDir, walk.listR and walk.walkRDirTree (recursive ListR).
operations.StatJSON calls List and NewObject directly, bypassing those, so it
rejects an escaping remote up front.

This confines every backend at once, so no per-backend change is needed.

(cherry picked from commit 3530367fcdefeb718d9cac14a5147836b448bc73)
2026-09-04 16:18:18 +01:00
Hakan İSMAİL 739403963a serve: refactor VFS and proxy handling into Provider
(cherry picked from commit f425f8d466)
2026-09-04 16:18:18 +01:00
am-at-enrollvb 1bec2133c5 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.

(cherry picked from commit 5dd34275dc)
2026-09-04 16:18:18 +01:00
Nick Craig-Wood 64de81e6a0 build: make go1.26 the minimum required version
golang.org/x/crypto v0.56.0, which fixes CVE-2026-78662 and
CVE-2026-56855 in its ssh package, requires go1.26, so rclone can no
longer be built with go1.25.
2026-09-04 14:07:42 +01:00
Nick Craig-Wood 0b187f3d7a build: update golang.org/x/crypto to v0.56.0 to fix CVE-2026-78662 and CVE-2026-56855
CVE-2026-78662: a malicious peer could flood an undecided channel's
incoming requests, deadlocking the whole connection in
golang.org/x/crypto/ssh (GO-2026-6354)

CVE-2026-56855: a malicious peer could send crafted messages on an
established channel, deadlocking the whole connection in
golang.org/x/crypto/ssh (GO-2026-6355)

(cherry picked from commit f550317590)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 0e5100203c bisync: fix failed transfers of empty files being recorded as synced
When bisync is interrupted with a graceful shutdown it keeps the files
which transferred successfully in its listings and rolls the rest back.
An operator precedence mistake in that check meant a transfer of an
empty file (or one of unknown size) was kept even when it had failed,
so bisync recorded it as synced when it had not been.

(cherry picked from commit 7e17e1b90d)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood ba3d34b9f8 docs: describe how backends should allocate memory
(cherry picked from commit 220fe76192)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 77e6390f5b quatrix: fix chunk upload retries and fix memory leak
Each upload chunk is buffered in a pool.RW from the global memory pool
but was never closed, so its pages were never returned to the pool.

Close the buffer after each chunk is uploaded and on the read error
path.

A chunk that failed with a retryable error was also retried without
rewinding the buffer, so the retry sent an empty body with the original
Content-Length and Content-Range and failed.

Seek the chunk back to the start inside the pacer closure so each
attempt re-sends it in full.

The FsPutRetry integration test covers the retry of a failed upload
request and checks the buffers are returned to the pool.

(cherry picked from commit 2f0228029e)
2026-09-04 14:07:19 +01:00
SillyZir f190b34d95 onedrive: fall back to manual drive ID entry when drive listing fails
When both /me/drives and /me/drive fail during config (for example an
account-level 403 serviceReadOnly "Database Is Read Only"), send the
config state machine to the existing manual drive ID entry state
instead of dead-ending at choose_type with the raw error. The drive
itself remains usable when only the enumeration API is blocked.

Fixes #9794

(cherry picked from commit 03fe2ef794)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 49e7016d12 build: update golang.org/x/crypto to v0.55.0 to fix CVE-2026-56854
CVE-2026-56854: source-address critical option not enforced for
non-public-key auth callbacks in golang.org/x/crypto/ssh (GO-2026-6303)

(cherry picked from commit e5e1ee3e96)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 6240cbb694 crypt: warn about directories with legacy version-like encrypted names
Directory names which look like they have a --b2-versions version
string are now encrypted in full, so directories created by older
rclone (which left the version string in plain text) no longer
decrypt and vanished silently from listings.

DecryptDirName now falls back to the old form for such names so the
directory is listed, and logs the name it needs to be renamed to on
the underlying remote to make it accessible again. Document this in
the crypt docs.

(cherry picked from commit 1583cce1e2)
2026-09-04 14:07:19 +01:00
CAOShurong 66bc465d1a docs: fix dead links in sia and storj backends
(cherry picked from commit 413138f56b)
2026-09-04 14:07:19 +01:00
0rangeSeaW0lf b576cbdf40 internxt: persist rotated token returned by the user info call
The refresh endpoint returns a rotated token with a fresh expiry on
every successful call, but getUserInfo discarded it, so routine use
never extended the stored token's life. Once the stored token aged
out, accounts with 2FA enabled could not recover non-interactively
and required a manual reconnect.

Carry the rotated token out of getUserInfo and persist it in NewFs
via the same jwtToOAuth2Token + oauthutil.PutToken path that
refreshJWTToken uses, keeping f.cfg.Token in sync (same pattern as
refreshOrReLogin).

Fixes #9584

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit 66761670da)
2026-09-04 14:07:19 +01:00
TowyTowy 66dba8239f crypt: fix directory names which look like versioned file names
The --b2-versions support added in 3fe2aaf96 strips a version string
from the last segment of a path before encrypting it, so that the
plain text version suffixes which the underlying backend appends to
encrypted file leaf names can be handled. EncryptDirName and
DecryptDirName share that code, so the last segment of a *directory*
name was version stripped too. Only file leaf names are ever given a
version string by the backend - a directory gets a
version-string-like name from the user, and such a name is encrypted
verbatim when it appears as the parent of a file name, so the same
directory ended up with two different encryptions.

Before this change, with a directory whose name matches rclone's
version format, eg dir-v2001-02-03-040506-123:

    rclone copy file.txt crypt:dir-v2001-02-03-040506-123/
    rclone ls crypt:dir-v2001-02-03-040506-123
    # => "directory not found" - the file is invisible to listings
    rclone mkdir crypt:dir-v2001-02-03-040506-123
    # => creates a second directory with the same decrypted name

After this change EncryptDirName and DecryptDirName encrypt directory
names verbatim, so a directory encrypts the same way whether it is
named on its own or as the parent of a file. Version strings are only
added to file names by the underlying backend, so --b2-versions is
unaffected and the existing version tests are untouched.

A directory which was created by the old EncryptDirName will no longer
decrypt and will be reported as undecryptable in listings. Such
directories were already unusable - anything copied into one was
written to a different encrypted directory - so nothing which worked
before is broken by this.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit 67b184d6e7)
2026-09-04 14:07:19 +01:00
Anatoly Tarnavsky 92ef010fd2 s3: fix server side copy failing with --s3-no-head-object - fixes #9629
With no_head_object set, NewObject does not read any metadata, so the
destination object returned from a server side copy had a size of 0.
The size check in operations.Copy then failed with "corrupted on
transfer: sizes differ N vs 0" and deleted the newly copied object.
This also broke Move and hence renames through rclone mount.

Populate the destination object's size and MD5 from the source object
when no_head_object is set, as a server side copy produces an object
with identical content.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit 6df7b8aba1)
2026-09-04 14:07:19 +01:00
Loi Nguyen feb0664b64 dropbox: fix ChangeNotify when the root's case differs from Dropbox's - fixes #9692
Dropbox is case insensitive and the path_display it returns in
change notifications may not match the case of the configured root.
Before this change the root was trimmed with a case sensitive prefix
match, so when the cases differed the full path was passed to the
ChangeNotify callback and the notification was ignored.

This trims the root case insensitively while preserving the display
case of the remaining path.

(cherry picked from commit 4af64270cc)
2026-09-04 14:07:19 +01:00
Sune Mølgaard 61427e9729 serve http: prevent scrolling to the top on page reload - fixes #9771
(cherry picked from commit bdeb95ae01)
2026-09-04 14:07:19 +01:00
Vijay Misal 3d1fd51f61 vfscache: fix log message growing without bound on repeated write errors
Write() overwrote a successful write's nil error with the stale
lastErr returned by kickWaiters() once the downloader had recorded
too many errors. download() then wrapped that stale error again and
stored it back as the new lastErr, so every subsequent write added
another "vfs reader: failed to write to cache file:" prefix - fixes #4998

(cherry picked from commit efa5e8fcc1)
2026-09-04 14:07:19 +01:00
Rayan Salhab 6c44400bf7 accounting: fix bwlimit burst overflow - fixes #9820
Co-authored-by: cyphercodes <cyphercodes@users.noreply.github.com>
(cherry picked from commit 468eccb122)
2026-09-04 14:07:19 +01:00
water 041b766428 fix: do not retry multipart upload chunk on 404 (upload session not found)
(cherry picked from commit 5d1feea7e8)
2026-09-04 14:07:19 +01:00
shaurya 3c505b1e99 docs: fix broken links and wrong s3 directory bucket flag name
Several documentation links pointed at anchors or paths that no longer
resolve, and the S3 directory buckets section named the config option
and flag in the plural, which does not match the backend.

Co-authored-by: shaurya <19599684+no-hup@users.noreply.github.com>
Co-authored-by: no-hup <shauryaj.finance@gmail.com>
(cherry picked from commit 9dbfd9d852)
2026-09-04 14:07:19 +01:00
CAOShurong 6317faccc0 s3: treat UploadPart success without ETag as retryable error
A successful UploadPart whose response carries no ETag header made
WriteChunk panic dereferencing uout.ETag in a debug log line. The part
ETag is required by CompleteMultipartUpload, so an ETag-less 200 is
unusable: return a retryable error from inside the pacer callback so
the chunk is retried instead of crashing the transfer or completing
the upload with a broken part list.

Fixes #9822

Co-authored-by: Shurong Cao <170531907+CAOShurong@users.noreply.github.com>
(cherry picked from commit 660144d311)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 5a490a31c5 docs: update sponsors
(cherry picked from commit c140d36a1f)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood b8470e4cac test_all: pikpak: ignore TestRcatSizeChecksum/Corrupted
Pikpak never returns MD5 for uploads which causes this test to fail.

Perhaps Pikpak should not declare MD5 but that is a bigger decision
being discussed in #9826

(cherry picked from commit 4369d16a1c)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood e7ae39f42d webdav: fix SetModTime failing and hashes missing on Nextcloud
Nextcloud only stores a checksum which is supplied in the OC-Checksum
header of an upload, and discards it again when the modification time
is set with PROPPATCH. Re-sending the checksum in the PROPPATCH (as is
done for ownCloud) is rejected by Nextcloud with 403 Forbidden which
made the whole PROPPATCH fail, so SetModTime returned an error on any
object which had a hash. Uploads from sources without hashes, eg
streamed uploads with `rclone rcat`, were stored with no hash at all.

Use the Nextcloud PATCH extension with the X-Recalculate-Hash header
to have the server calculate and store the SHA1 of an object after a
streamed upload and after setting the modification time. This gives
a server side hash of the stored data which also lets rclone verify
streamed uploads.

(cherry picked from commit f7c510af49)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 43f107e049 pikpak: fix truncated single part uploads reported as ok when source ends early
If the source supplied fewer bytes than its declared size, the single
part upload path accepted the short body and stored a truncated file
recorded with the declared size, reporting a successful upload. The
multipart path already checks for this.

Count the bytes actually read and fail the upload if they do not match
the declared size, which cancels the partially created file.

This was found by the FsPutShortEOF integration test.

(cherry picked from commit 8e744de5e6)
2026-09-04 14:07:19 +01:00
machsix 748eaf9b28 onedrive: fix 403 Forbidden for configuration personal onedrive
(cherry picked from commit 8869a848f2)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 11dd394670 azureblob: fix test which didn't compile
We accidentally merged this commit with non compiling tests.

bee45bccfd azureblob: fix spurious vfs cache corruption errors during chunked reads #9782

(cherry picked from commit d3a71eea36)
2026-09-04 14:07:19 +01:00
Sanjay Kanth A 21483522a6 dropbox: decode received shared-file names - fixes #9707
listSharedFolders already decoded shared-folder names with
f.opt.Enc.ToStandardName, but listReceivedFiles stored the raw name
returned by the Dropbox API unchanged. Names that require encoding
(e.g. a trailing space, which Dropbox itself rejects, so rclone
stores it as "name␠" via EncodeRightSpace) were therefore shown under
their raw, encoded form for received files instead of being decoded
back to the standard name, and findSharedFile could not resolve such
a file by its standard name.

Apply the same ToStandardName conversion listSharedFolders uses.

(cherry picked from commit f3a7aaf635)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood f92262d48c 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.

(cherry picked from commit bee45bccfd)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood ad87bf6c93 lib/rest: make ParseContentRange public
(cherry picked from commit 2a8d8afd0f)
2026-09-04 14:07:19 +01:00
kingston125 f1c06a047e filelu: fix duplicate root path during multipart folder creation
(cherry picked from commit 6ee1d851ec)
2026-09-04 14:07:19 +01:00
Rohit Behera d6fb148d9b huaweidrive: fix truncated files being uploaded successfully when the source ends early
The multipart upload copied the source into the request buffer without
checking how many bytes it had read, so a source that supplied fewer
bytes than its declared size was accepted by the server and reported as
a success with a truncated file stored.

Count the bytes actually read and fail the upload if they do not match
the declared size.

Signed-off-by: Rohit Behera <126186063+r0h1tb@users.noreply.github.com>
(cherry picked from commit 83b143103c)
2026-09-04 14:07:19 +01:00
Nick Craig-Wood 930de88f69 protondrive: fix files uploaded with v1.75.0 not being readable in the Proton apps
rclone v1.75.0 started creating files in Proton Drive's new
crypto-refresh encryption format, following guidance from Proton that
new file node keys should use the v6/AEAD profile. It turns out the
official Proton web app cannot decrypt files whose node key is a v6
key (but the Android app can), so every file uploaded with v1.75.0 (or
a beta after 2026-07-13) shows 'Item cannot be decrypted' in the web
app, even though rclone itself reads the files fine. Inspecting a file
created by the web app shows Proton itself still creates v4 node keys,
using the new format only for the file content.

New files are now created with the same fully pre-crypto-refresh
format as v1.74.4 (v4 node key, v3 PKESK content key, v1 SEIPD
blocks), which every Proton client can read. Reading files in the new
format still works, new revisions of files which already use the new
content format keep it, and the auxiliary fields (name, node
passphrase, extended attributes, block signatures) are pinned to the
old format regardless of the recipient key's preferences, as Proton
requires.

Files already uploaded with v1.75.0 cannot be repaired in place -
uploading a new revision does not change the file's node key. To make
such a file readable by the Proton apps again, delete it from the
remote and upload it again with a fixed version of rclone.

This updates Proton-API-Bridge to v1.0.5 and go-proton-api to v1.0.4.

See: https://forum.rclone.org/t/proton-drive-unable-to-decrypt/54087
(cherry picked from commit d9aa903358)
2026-09-04 14:07:19 +01:00
Rohit Behera fad0359e6b box: fix truncated files being uploaded successfully when the source ends early
The single-shot upload path sent the source straight to Box as a multipart
body with no Content-Length, so a source that supplied fewer bytes than its
declared size produced a short request that Box accepted and stored, and the
upload was reported as a success.

Count the bytes actually read and fail the upload if they do not match the
declared size. The multipart path already reads each chunk with io.ReadFull
and so already fails in this case.

(cherry picked from commit 64ab1ac322)
2026-09-04 14:07:18 +01:00
Rahman Yilmaz c14e507609 walk: stop directory traversal when the context is cancelled - fixes #9788
The concurrent walker created by walk() only stopped when the callback
returned an error or the whole tree had been listed. Cancelling the
context (for example via the rc job/stop endpoint for an async
operations/size or recursive operations/list call) was therefore
ignored: the checkers kept pulling list jobs from the channel and kept
listing the entire tree, burning CPU and making job cancellation
useless for every backend without a native ListR implementation.

Make every checker select on ctx.Done() so a cancelled walk shuts down
promptly through the existing quit/drain path and reports the context
error. Also check the context between directory read chunks in the
local backend so a single huge directory does not block cancellation.

(cherry picked from commit 5eb5c01e36)
2026-09-04 14:07:18 +01:00
Rohit Behera 0720a194cf yandex: fix truncated files being uploaded successfully when the source ends early
Update already wrapped the source in a counting reader but never looked at the
count, so a source that supplied fewer bytes than its declared size was
uploaded as a chunked request, accepted by the server and reported as a
success with a truncated file stored.

Compare the bytes actually read against the declared size.

(cherry picked from commit 1128693468)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 194d22ce71 build: untap aws/tap to silence homebrew tap trust warnings on macOS
(cherry picked from commit be7f9b38b0)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 7995d87cd5 s3: Mega: update endpoints
(cherry picked from commit ec3a95c279)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 2d261879dd docs: add assigned CVE numbers to the v1.75.0 security advisories in the changelog
Five of the advisories released with v1.75.0 now have CVEs assigned:

- GHSA-45pq-889g-fcgh serve restic path traversal: CVE-2026-71309
- GHSA-xhf4-832v-7xcr lib/proxy CONNECT header OOM: CVE-2026-71310
- GHSA-8c48-q9wj-3w37 ftp command injection: CVE-2026-71311
- GHSA-2m8m-jhrm-w6j2 sftp PowerShell command injection: CVE-2026-71312
- GHSA-7p4m-qxvv-g567 local file name escape: CVE-2026-71313

GHSA-6jcg-q3wp-x2f4 (squashfs) loses its CVE-PENDING marker as GitHub
declined to issue a CVE from the rclone repository - the vulnerable code
is in go-diskfs so any CVE must come from an advisory there.

GHSA-mfvx-7rcj-9m5g (pprof) keeps its CVE-PENDING marker as the CVE
request is still awaiting allocation.

(cherry picked from commit 2c1174af0d)
2026-09-04 14:07:18 +01:00
VXNCXNX 2e0718167f lib/transform: fix panic in truncate_keep_extension
Return error when extension is longer than truncation limit.

(cherry picked from commit c667e53638)
2026-09-04 14:07:18 +01:00
Shantanav Mukherjee 9718ed3fc2 docs: clarify VFS cache age semantics
(cherry picked from commit 4f22d62c66)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 645e1ea5be 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.

(cherry picked from commit f0b210a886)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 40dab7ecdd 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.

(cherry picked from commit 00593a96fe)
2026-09-04 14:07:18 +01:00
Dave 43a2a92950 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

(cherry picked from commit 6e0c71bd27)
2026-09-04 14:07:18 +01:00
Morax 62f8f944e2 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.

(cherry picked from commit 69e5aff2a9)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 841ff2d418 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
(cherry picked from commit 5a0b7d6746)
2026-09-04 14:07:18 +01:00
Pastalikek65 33ab81ce6d 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

(cherry picked from commit adc7f2ebfa)
2026-09-04 14:07:18 +01:00
Dean Chen 632ff74375 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>
(cherry picked from commit c785ff90d7)
2026-09-04 14:07:18 +01:00
Recoordinate 39b926a2ce docs: fix doubled words
(cherry picked from commit cfdc9d0558)
2026-09-04 14:07:18 +01:00
Rodrigo Rodrigues 31f4c78c5e docs: fix typo in drive client_id section
(cherry picked from commit 8b42a38e9d)
2026-09-04 14:07:18 +01:00
Christian De Santis fcb317e226 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.

(cherry picked from commit aba403fa79)
2026-09-04 14:07:18 +01:00
nielash 82a4a63b92 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`.

(cherry picked from commit abae66ee1a)
2026-09-04 14:07:18 +01:00
nielash d407018995 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`.

(cherry picked from commit 71a0932126)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood b5f0ea9b7b 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.

(cherry picked from commit 1947e4217c)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood d166eaf635 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.

(cherry picked from commit b4db289d0a)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 62a1df7271 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.

(cherry picked from commit 0aa90200bd)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood e171f996d6 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.

(cherry picked from commit a3489456de)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 2bf9e0d20e 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.

(cherry picked from commit 531d873bd7)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood afb1daa8fa 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.

(cherry picked from commit 84298fc090)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 5775f0430b 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

(cherry picked from commit 2f0657c35b)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood d0f00a22d5 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.

(cherry picked from commit 7357fb82a9)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood ad7e0c64af 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.

(cherry picked from commit 5d057549b9)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 674d7a8a70 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.

(cherry picked from commit a2baa978db)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 1274301521 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.

(cherry picked from commit 5b7cc097e3)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 840755543f 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.

(cherry picked from commit e1bf9405e2)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 2472718b7c 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.

(cherry picked from commit 884b28c203)
2026-09-04 14:07:18 +01:00
nielash a4f1c1558e 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.

(cherry picked from commit 387b4b5e11)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 76d5c49ae6 docs: update sponsor links
(cherry picked from commit 1aa9efef17)
2026-09-04 14:07:18 +01:00
Edward Klesel 9fec073ab7 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.

(cherry picked from commit e4c7aca6bd)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood a9c4548d92 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.

(cherry picked from commit 5629f2668c)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood d038b8b1c9 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.

(cherry picked from commit a06df7a2de)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 3ceea42329 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.

(cherry picked from commit 9b13247ba8)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 6beb4a5bd2 docs: fix width of sponsor images on very big screens
(cherry picked from commit 1318962a96)
2026-09-04 14:07:18 +01:00
Anton Karpov 7d70921bf5 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.

(cherry picked from commit 6cb4732cc3)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 76c6992260 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.

(cherry picked from commit 18fa445ffc)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood f1297d6298 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.

(cherry picked from commit e0701daea0)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood 9a112f40c1 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.

(cherry picked from commit bff17664ad)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood a3dcf7f0ad 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

(cherry picked from commit 03f8582a55)
2026-09-04 14:07:18 +01:00
alliasgher 3084177049 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.

(cherry picked from commit ea9a64c751)
2026-09-04 14:07:18 +01:00
alliasgher e4b778b5e3 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.

(cherry picked from commit 065af89635)
2026-09-04 14:07:18 +01:00
Nick Craig-Wood ee363b1826 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.

(cherry picked from commit 01d32dbde5)
2026-09-04 14:07:18 +01:00
Loi Nguyen e7f9c7bc10 smb: test closing failed dial connections
Followup to:

74f9f182aa smb: fix TCP connection leak when connection setup fails - #9678

(cherry picked from commit 23f1dbfe50)
2026-09-04 14:07:18 +01:00
debaditya 10eb7b5b10 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

(cherry picked from commit c97ab80ca1)
2026-09-04 14:07:18 +01:00
Loi Nguyen e0faeeb5d6 vfs: make poll shutdown lifecycle deterministic
(cherry picked from commit 1d03a77172)
2026-09-04 14:07:17 +01:00
Loi Nguyen dcf15b5f9c vfs: test poll interval update lifecycle
(cherry picked from commit d5275c4ebb)
2026-09-04 14:07:17 +01:00
Loi Nguyen c93cc1e1ae vfs: synchronize poll updates with shutdown - fixes #9689
(cherry picked from commit f132aef295)
2026-09-04 14:07:17 +01:00
Loi Nguyen 21c98ff5ff 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.

(cherry picked from commit 8c8062da78)
2026-09-04 14:07:17 +01:00
Loi Nguyen 5fbc677ed4 lib/batcher: prevent commits racing shutdown - fixes #9687
(cherry picked from commit 7f6207fae2)
2026-09-04 14:07:17 +01:00
SillyZir 00347ecf36 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

(cherry picked from commit 7804c1b315)
2026-09-04 14:07:17 +01:00
206 changed files with 10200 additions and 8831 deletions

No files matched your search

+8 -8
View File
@@ -37,7 +37,7 @@ jobs:
include:
- job_name: linux
os: ubuntu-latest
go: '~1.27.0'
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.27.0'
go: '~1.26.6'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '~1.27.0'
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.27.0'
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.27.0'
go: '~1.26.6'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -81,7 +81,7 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '~1.27.0'
go: '~1.26.6'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
@@ -284,7 +284,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.27.0'
go-version: '~1.26.6'
check-latest: true
cache: false
@@ -399,7 +399,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v7
with:
go-version: '~1.27.0'
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
Generated
+2233 -1480
View File
File diff suppressed because it is too large. Load diff
Generated
+1426 -816
View File
File diff suppressed because it is too large. Load diff
Generated
+1489 -813
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
v1.76.0
v1.75.1
+7 -8
View File
@@ -36,7 +36,6 @@ import (
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/fspath"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/sanitize"
)
// Register with Fs
@@ -530,14 +529,14 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// isDirectChild reports whether remote names an entry directly in dir
// ("" being the root), with no ".." or other components in between.
func isDirectChild(dir, remote string) bool {
if dir != "" {
var ok bool
remote, ok = strings.CutPrefix(remote, dir+"/")
if !ok {
return false
}
if remote == "" || remote == "." || remote == ".." || strings.HasSuffix(remote, "/") {
return false
}
return sanitize.Leaf(remote) == nil
parent := path.Dir(remote)
if parent == "." || parent == "/" {
parent = ""
}
return parent == dir && path.Clean(remote) == remote
}
// NewObject creates a new remote archive file object
-24
View File
@@ -379,27 +379,3 @@ func TestArchiveEscapingArchiver(t *testing.T) {
_, err = f.NewObject(ctx, "test.escaping/file.txt")
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
}
// TestIsDirectChild checks the guard which decides whether an entry
// returned by an archiver belongs directly in the directory listed.
func TestIsDirectChild(t *testing.T) {
for _, test := range []struct {
dir, remote string
want bool
}{
{"", "a.txt", true},
{"", "/a.txt", false},
{"", "a.txt/", false},
{"", "../a.txt", false},
{"", "sub/a.txt", false},
{"d", "d/a.txt", true},
{"d", "d", false},
{"d", "d/", false},
{"d", "d//a.txt", false},
{"d", "d/../a.txt", false},
{"d", "dd/a.txt", false},
{"d", "a.txt", false},
} {
assert.Equal(t, test.want, isDirectChild(test.dir, test.remote), "dir=%q remote=%q", test.dir, test.remote)
}
}
+10 -12
View File
@@ -9,7 +9,6 @@ import (
"io"
"os"
"path"
"slices"
"strings"
"time"
@@ -145,13 +144,6 @@ func (f *Fs) readZip() (singleObject bool, err error) {
skipped++
continue
}
isDir := strings.HasSuffix(file.Name, "/")
// A file entry whose last component is "", "." or ".." names
// a directory rather than a file, so skip
if !isDir && sanitize.Leaf(path.Base(file.Name)) != nil {
skipped++
continue
}
remote = path.Join(f.prefix, remote)
if f.root != "" {
// Ignore all files outside the root, requiring a path
@@ -166,12 +158,19 @@ func (f *Fs) readZip() (singleObject bool, err error) {
remote = strings.TrimPrefix(remote, f.root+"/")
}
}
if isDir {
if strings.HasSuffix(file.Name, "/") {
dir := fs.NewDir(remote, file.Modified)
dt.AddDir(dir)
} else {
if remote == "" {
// A file at the root is the archive member f.root points at
// A file at the root itself can only be the
// archive member f.root points at - with no root
// it is a crafted name for the archive's own
// directory, which can't be a file
if f.root == "" {
skipped++
continue
}
remote = path.Base(f.root)
singleObject = true
dt = dirtree.New()
@@ -218,8 +217,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
return nil, fs.ErrorDirNotFound
}
fs.Debugf(f, "dir=%q, entries=%v", dir, entries)
// Return a copy as callers may filter the listing in place
return slices.Clone(entries), nil
return entries, nil
}
// NewObject finds the Object at remote.
+6 -48
View File
@@ -4,7 +4,6 @@ import (
"archive/zip"
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"sort"
@@ -106,12 +105,10 @@ func TestReadZipRootBoundary(t *testing.T) {
assert.Equal(t, []string{"a.txt"}, remotes)
}
// A file entry whose name refers to a directory (".", "/", "./", "" or
// "sub/.") must be skipped, not turn the archive or the directory
// mounted as its root into a single file which hides every other
// entry, or become an object named for the archive itself when the
// archive is found by listing its directory.
func TestReadZipDirNamedFileEntry(t *testing.T) {
// A file entry whose name refers to the archive's own root (".", "/",
// "./" or "") must be skipped, not turn the whole archive into a single
// file which hides every other entry.
func TestReadZipRootNamedEntry(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
name := writeZip(t, dir, "dot.zip",
@@ -120,53 +117,14 @@ func TestReadZipDirNamedFileEntry(t *testing.T) {
"./",
"",
"good.txt",
"sub/",
"sub/.",
"sub/good.txt",
)
localFs, err := cache.Get(ctx, dir)
require.NoError(t, err)
for _, test := range []struct {
prefix, root string
want []string
}{
{"", "", []string{"good.txt", "sub/good.txt"}},
{"sub/dot.zip", "", []string{"sub/dot.zip/good.txt", "sub/dot.zip/sub/good.txt"}},
{"", "sub", []string{"good.txt"}},
} {
t.Run(fmt.Sprintf("prefix=%q,root=%q", test.prefix, test.root), func(t *testing.T) {
f, err := New(ctx, localFs, name, test.prefix, test.root)
require.NoError(t, err)
assert.Equal(t, test.want, allRemotes(t, f))
})
}
}
// Listings are served from a cache which must survive callers
// filtering the returned slice in place, as fs/list does.
func TestListCacheNotAliased(t *testing.T) {
ctx := context.Background()
dir := t.TempDir()
name := writeZip(t, dir, "test.zip", "a.txt", "b.txt", "c.txt")
localFs, err := cache.Get(ctx, dir)
require.NoError(t, err)
f, err := New(ctx, localFs, name, "", "")
require.NoError(t, err)
entries, err := f.List(ctx, "")
require.NoError(t, err)
require.Len(t, entries, 3)
// Compact in place, dropping the first entry
copy(entries, entries[1:])
entries, err = f.List(ctx, "")
require.NoError(t, err)
var remotes []string
for _, entry := range entries {
remotes = append(remotes, entry.Remote())
}
assert.Equal(t, []string{"a.txt", "b.txt", "c.txt"}, remotes)
remotes := allRemotes(t, f)
assert.Equal(t, []string{"good.txt"}, remotes)
}
+4 -4
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
// Parallel listing support for azureblob, built on the Apache Arrow
// listing format.
@@ -66,7 +66,7 @@ func (f *Fs) listArrowParallel(ctx context.Context, containerName, directory, pr
// Schedule every shard; SetLimit bounds concurrency, so more shards than
// workers gives free load balancing as workers pick up the next shard.
var total atomic.Int64
var total int64
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(f.opt.ListParallelism)
for _, sh := range shards {
@@ -89,12 +89,12 @@ func (f *Fs) listArrowParallel(ctx context.Context, containerName, directory, pr
shardOpts.EndBefore = nil
}
n, err := f.listBlobsPager(gCtx, containerName, directory, prefix, addContainer, &shardOpts, delimiter, safeFn)
total.Add(int64(n))
atomic.AddInt64(&total, int64(n))
return err
})
}
err := g.Wait()
found := int(total.Load())
found := int(atomic.LoadInt64(&total))
if isEndBeforeUnsupported(err) {
// The account can't honour the shards' endBefore bounds, so parallel
// listing can't be used on it.
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
package azureblob
+2 -2
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
@@ -157,7 +157,7 @@ func parseArrowStream(body io.Reader) ([]*container.BlobItem, *string, error) {
rec := reader.RecordBatch()
rows := int(rec.NumRows())
for row := range rows {
for row := 0; row < rows; row++ {
item := &container.BlobItem{
Properties: &container.BlobProperties{},
}
+2 -2
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
@@ -198,7 +198,7 @@ func TestHandleFlatListResponse_MultiRecordBatch(t *testing.T) {
// First batch: 2 rows
builder := arrowArray.NewRecordBuilder(alloc, schema)
for range 2 {
for i := 0; i < 2; i++ {
builder.Field(0).(*arrowArray.StringBuilder).Append("batch1_blob")
for j := 1; j < 11; j++ {
builder.Field(j).AppendNull()
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
// Package arrowlist implements the experimental "Blob Listing with Apache
// Arrow" feature on top of the released Azure azblob SDK.
+12 -11
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
package arrowlist
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/apache/arrow-go/v18/arrow"
@@ -53,12 +54,12 @@ func TestPagerArrow(t *testing.T) {
opts := &ListBlobsHierarchyOptions{
ListBlobsHierarchyOptions: container.ListBlobsHierarchyOptions{
Include: container.ListBlobsInclude{Metadata: true, Tags: true},
Prefix: new("dir/"),
MaxResults: new(int32(1000)),
StartFrom: new("testcontainer/dir/a"),
Prefix: to.Ptr("dir/"),
MaxResults: to.Ptr(int32(1000)),
StartFrom: to.Ptr("testcontainer/dir/a"),
},
EndBefore: new("testcontainer/dir/n"),
UseArrowFormat: new(true),
EndBefore: to.Ptr("testcontainer/dir/n"),
UseArrowFormat: to.Ptr(true),
}
pager := client.NewListBlobsHierarchyPager("/", opts)
@@ -124,7 +125,7 @@ func TestPagerXMLFallback(t *testing.T) {
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: new(true),
UseArrowFormat: to.Ptr(true),
})
page, err := pager.NextPage(context.Background())
require.NoError(t, err)
@@ -148,8 +149,8 @@ func TestPagerXMLFallbackWithEndBefore(t *testing.T) {
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
EndBefore: new("testcontainer/n"),
UseArrowFormat: new(true),
EndBefore: to.Ptr("testcontainer/n"),
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.ErrorIs(t, err, ErrEndBeforeXMLFallback)
@@ -171,7 +172,7 @@ func TestPagerSharedKeyAuth(t *testing.T) {
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: new(true),
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.NoError(t, err)
@@ -190,7 +191,7 @@ func TestPagerResponseError(t *testing.T) {
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: new(true),
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.Error(t, err)
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !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 && !js
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
+23 -15
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
package azureblob
@@ -27,6 +27,7 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
@@ -575,7 +576,8 @@ func (f *Fs) shouldRetry(ctx context.Context, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
if storageErr, ok := errors.AsType[*azcore.ResponseError](err); ok {
var storageErr *azcore.ResponseError
if errors.As(err, &storageErr) {
// General errors from:
// https://learn.microsoft.com/en-us/rest/api/storageservices/common-rest-api-error-codes
// Blob specific errors from:
@@ -904,15 +906,15 @@ func mapMetadataToAzure(meta map[string]string, logf func(string, ...any)) (head
lowerKey := strings.ToLower(k)
switch lowerKey {
case "cache-control":
headers.BlobCacheControl = new(v)
headers.BlobCacheControl = pString(v)
case "content-disposition":
headers.BlobContentDisposition = new(v)
headers.BlobContentDisposition = pString(v)
case "content-encoding":
headers.BlobContentEncoding = new(v)
headers.BlobContentEncoding = pString(v)
case "content-language":
headers.BlobContentLanguage = new(v)
headers.BlobContentLanguage = pString(v)
case "content-type":
headers.BlobContentType = new(v)
headers.BlobContentType = pString(v)
case "x-ms-tags":
parsed, perr := parseXMsTags(v)
if perr != nil {
@@ -1206,7 +1208,7 @@ func (f *Fs) list(ctx context.Context, containerName, directory, prefix string,
// maxResults==1 probe (isEmpty) which doesn't benefit.
useArrow := f.opt.UseArrowList && maxResults != 1
if useArrow {
opts.UseArrowFormat = new(true)
opts.UseArrowFormat = to.Ptr(true)
}
var foundItems int
@@ -2629,6 +2631,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
return downloadResponse.Body, nil
}
// Converts a string into a pointer to a string
func pString(s string) *string {
return &s
}
// readSeekCloser joins an io.Reader and an io.Seeker and provides a no-op io.Closer
type readSeekCloser struct {
io.Reader
@@ -2783,7 +2790,8 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
// isInvalidBlockOrBlob looks for the InvalidBlockOrBlob error in err
// returning true if it is found
func isInvalidBlockOrBlob(err error) bool {
if storageErr, ok := errors.AsType[*azcore.ResponseError](err); ok {
var storageErr *azcore.ResponseError
if errors.As(err, &storageErr) {
return storageErr.ErrorCode == string(bloberror.InvalidBlobOrBlock)
}
return false
@@ -3155,7 +3163,7 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
// Start with default content-type based on source
ui.httpHeaders = blob.HTTPHeaders{
BlobContentType: new(fs.MimeType(ctx, src)),
BlobContentType: pString(fs.MimeType(ctx, src)),
}
// Apply mapped metadata/headers/tags if requested
@@ -3201,15 +3209,15 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
o.tags[parts[0]] = parts[1]
}
case "cache-control":
ui.httpHeaders.BlobCacheControl = new(value)
ui.httpHeaders.BlobCacheControl = pString(value)
case "content-disposition":
ui.httpHeaders.BlobContentDisposition = new(value)
ui.httpHeaders.BlobContentDisposition = pString(value)
case "content-encoding":
ui.httpHeaders.BlobContentEncoding = new(value)
ui.httpHeaders.BlobContentEncoding = pString(value)
case "content-language":
ui.httpHeaders.BlobContentLanguage = new(value)
ui.httpHeaders.BlobContentLanguage = pString(value)
case "content-type":
ui.httpHeaders.BlobContentType = new(value)
ui.httpHeaders.BlobContentType = pString(value)
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !js
package azureblob
+1 -1
View File
@@ -1,6 +1,6 @@
// Test AzureBlob filesystem interface
//go:build !plan9 && !js
//go:build !plan9 && !solaris && !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 || js
//go:build plan9 || solaris || js
// Package azureblob provides an interface to the Microsoft Azure blob object storage system
package azureblob
+11 -6
View File
@@ -650,6 +650,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
return resp.Body, nil
}
// Returns a pointer to t - useful for returning pointers to constants
func ptr[T any](t T) *T {
return &t
}
var warnStreamUpload sync.Once
// Update the object with the contents of the io.Reader, modTime, size and MD5 hash
@@ -813,8 +818,8 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, fmt.Errorf("Move: mkParentDir failed: %w", err)
}
opt := file.RenameOptions{
IgnoreReadOnly: new(true),
ReplaceIfExists: new(true),
IgnoreReadOnly: ptr(true),
ReplaceIfExists: ptr(true),
}
dstAbsPath := f.absPath(remote)
fc := srcObj.fileClient()
@@ -859,8 +864,8 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
}
opt := directory.RenameOptions{
IgnoreReadOnly: new(false),
ReplaceIfExists: new(false),
IgnoreReadOnly: ptr(false),
ReplaceIfExists: ptr(false),
}
dstAbsPath := dstFs.absPath(dstRemote)
dirClient := srcFs.dirClient(srcRemote)
@@ -899,8 +904,8 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
ChangeTime: file.SourceCopyFileChangeTime{},
CreationTime: file.SourceCopyFileCreationTime{},
LastWriteTime: file.SourceCopyFileLastWriteTime{},
PermissionCopyMode: new(file.PermissionCopyModeTypeSource),
IgnoreReadOnly: new(true),
PermissionCopyMode: ptr(file.PermissionCopyModeTypeSource),
IgnoreReadOnly: ptr(true),
},
}
srcURL := srcObj.fileClient().URL()
+3 -8
View File
@@ -64,7 +64,7 @@ const (
maxParts = 10000
maxVersions = 100 // maximum number of versions we search in --b2-versions mode
minChunkSize = 5 * fs.Mebi
defaultChunkSize = 16 * fs.Mebi
defaultChunkSize = 96 * fs.Mebi
defaultUploadCutoff = 200 * fs.Mebi
largeFileCopyCutoff = 4 * fs.Gibi // 5E9 is the max
defaultMaxAge = 24 * time.Hour
@@ -153,12 +153,7 @@ The minimum is 0 and the maximum is 4.6 GiB.`,
When uploading large files, chunk the file into this size.
Must fit in memory. These chunks are buffered in memory and there
might be a maximum of "--transfers" * "--b2-upload-concurrency"
chunks in progress at once.
B2 has a fixed per part overhead of about a second, so upload speed
is roughly proportional to the chunk size multiplied by
"--b2-upload-concurrency".
might a maximum of "--transfers" chunks in progress at once.
5,000,000 Bytes is the minimum size.`,
Default: defaultChunkSize,
@@ -173,7 +168,7 @@ concurrently.
Note that chunks are stored in memory and there may be up to
"--transfers" * "--b2-upload-concurrency" chunks stored at once
in memory.`,
Default: 8,
Default: 4,
Advanced: true,
}, {
Name: "disable_checksum",
+15 -23
View File
@@ -3,6 +3,7 @@
package box
import (
"bytes"
"context"
"crypto/sha1"
"encoding/base64"
@@ -19,7 +20,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/lib/atexit"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/rest"
)
@@ -55,15 +55,9 @@ func sha1Digest(digest []byte) string {
}
// uploadPart uploads a part in an upload session
//
// chunk must contain exactly the part's data and is read from the start
// on each attempt.
func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, totalSize int64, chunk io.ReadSeeker, wrap accounting.WrapFn, options ...fs.OpenOption) (response *api.UploadPartResponse, err error) {
hasher := sha1.New()
chunkSize, err := io.Copy(hasher, chunk)
if err != nil {
return nil, err
}
func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, totalSize int64, chunk []byte, wrap accounting.WrapFn, options ...fs.OpenOption) (response *api.UploadPartResponse, err error) {
chunkSize := int64(len(chunk))
sha1sum := sha1.Sum(chunk)
opts := rest.Opts{
Method: "PUT",
Path: "/files/upload_sessions/" + SessionID,
@@ -73,16 +67,12 @@ func (o *Object) uploadPart(ctx context.Context, SessionID string, offset, total
ContentRange: fmt.Sprintf("bytes %d-%d/%d", offset, offset+chunkSize-1, totalSize),
Options: options,
ExtraHeaders: map[string]string{
"Digest": sha1Digest(hasher.Sum(nil)),
"Digest": sha1Digest(sha1sum[:]),
},
}
var resp *http.Response
err = o.fs.pacer.Call(func() (bool, error) {
_, err = chunk.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
opts.Body = wrap(chunk)
opts.Body = wrap(bytes.NewReader(chunk))
resp, err = o.fs.srv.CallJSON(ctx, &opts, nil, &response)
return shouldRetry(ctx, resp, err)
})
@@ -223,25 +213,27 @@ outer:
reqSize := min(remaining, chunkSize)
// Read the chunk into memory from the global pool, hashing
// it for the whole file hash (must be done sequentially)
rw := multipart.NewRW().Reserve(reqSize)
_, err = io.CopyN(rw, io.TeeReader(in, hash), reqSize)
// Make a block of memory
buf := make([]byte, reqSize)
// Read the chunk
_, err = io.ReadFull(in, buf)
if err != nil {
_ = rw.Close()
err = fmt.Errorf("multipart upload failed to read source: %w", err)
break outer
}
// Make the global hash (must be done sequentially)
_, _ = hash.Write(buf)
// Transfer the chunk
wg.Add(1)
o.fs.uploadToken.Get()
go func(part int, position int64) {
defer wg.Done()
defer o.fs.uploadToken.Put()
defer func() { _ = rw.Close() }()
fs.Debugf(o, "Uploading part %d/%d offset %v/%v part size %v", part+1, session.TotalParts, fs.SizeSuffix(position), fs.SizeSuffix(size), fs.SizeSuffix(chunkSize))
partResponse, err := o.uploadPart(ctx, session.ID, position, size, rw, wrap, options...)
partResponse, err := o.uploadPart(ctx, session.ID, position, size, buf, wrap, options...)
if err != nil {
err = fmt.Errorf("multipart upload failed to upload part: %w", err)
select {
+1 -1
View File
@@ -43,7 +43,7 @@ func testPutLarge(t *testing.T, f *Fs, kilobytes int) {
type settings map[string]any
func deriveFs(ctx context.Context, t *testing.T, f fs.Fs, path string, opts settings) fs.Fs {
fsName, _, _ := strings.Cut(f.Name(), "{") // strip off hash
fsName := strings.Split(f.Name(), "{")[0] // strip off hash
configMap := configmap.Simple{}
for key, val := range opts {
configMap[key] = fmt.Sprintf("%v", val)
+2 -2
View File
@@ -472,8 +472,8 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
if updateOptions, ok := option.(*api.UpdateOptions); ok {
if updateOptions.PublicID != "" {
updateObject = true
params.Overwrite = new(true)
params.Invalidate = new(true)
params.Overwrite = SDKApi.Bool(true)
params.Invalidate = SDKApi.Bool(true)
params.PublicID = updateOptions.PublicID
params.ResourceType = updateOptions.ResourceType
params.Type = SDKApi.DeliveryType(updateOptions.DeliveryType)
+5 -19
View File
@@ -31,7 +31,6 @@ import (
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/multipart"
)
// Globals
@@ -564,19 +563,15 @@ type compressionResult[T sgzip.GzipMetadata | SzstdMetadata] struct {
func (f *Fs) rcat(ctx context.Context, dstFileName string, in io.ReadCloser, modTime time.Time, options []fs.OpenOption) (o fs.Object, err error) {
// cache small files in memory and do normal upload
rw := multipart.NewRW()
defer fs.CheckClose(rw, &err)
_, err = io.CopyN(rw, in, int64(f.opt.RAMCacheLimit))
if err == io.EOF {
src := object.NewStaticObjectInfo(dstFileName, modTime, rw.Size(), false, nil, f.Fs)
return f.Fs.Put(ctx, rw, src, options...)
} else if err != nil {
return nil, err
buf := make([]byte, f.opt.RAMCacheLimit)
if n, err := io.ReadFull(in, buf); err == io.EOF || err == io.ErrUnexpectedEOF {
src := object.NewStaticObjectInfo(dstFileName, modTime, int64(len(buf[:n])), false, nil, f.Fs)
return f.Fs.Put(ctx, bytes.NewBuffer(buf[:n]), src, options...)
}
// Need to include what we already read
in = &ReadCloserWrapper{
Reader: io.MultiReader(rw, in),
Reader: io.MultiReader(bytes.NewReader(buf), in),
Closer: in,
}
@@ -1125,15 +1120,6 @@ func (o *Object) Remove(ctx context.Context) error {
return objErr
}
// countingDiscard is an io.Writer which discards its input and counts
// the bytes written
type countingDiscard int64
func (c *countingDiscard) Write(p []byte) (int, error) {
*c += countingDiscard(len(p))
return len(p), nil
}
// ReadCloserWrapper combines a Reader and a Closer to a ReadCloser
type ReadCloserWrapper struct {
io.Reader
+3 -2
View File
@@ -2,6 +2,7 @@ package compress
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"encoding/hex"
@@ -22,7 +23,7 @@ type gzipModeHandler struct{}
// isCompressible checks the compression ratio of the provided data and returns true if the ratio exceeds
// the configured threshold
func (g *gzipModeHandler) isCompressible(r io.Reader, compressionMode int) (bool, error) {
var b countingDiscard
var b bytes.Buffer
var n int64
w, err := sgzip.NewWriterLevel(&b, sgzip.DefaultCompression)
if err != nil {
@@ -36,7 +37,7 @@ func (g *gzipModeHandler) isCompressible(r io.Reader, compressionMode int) (bool
if err != nil {
return false, err
}
ratio := float64(n) / float64(b)
ratio := float64(n) / float64(b.Len())
return ratio > minCompressionRatio, nil
}
-137
View File
@@ -1,137 +0,0 @@
package compress
import (
"bytes"
"context"
"crypto/rand"
"io"
"testing"
"time"
_ "github.com/rclone/rclone/backend/memory"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// putRecorder wraps an fs.Fs and records what rcat hands to Put and
// PutStream. It reads each body twice when it is seekable to model a
// backend retrying an upload.
type putRecorder struct {
fs.Fs
t *testing.T
stream bool // expose PutStream from the wrapped Fs
size int64
seekable bool
body []byte
streamed bool
}
func (r *putRecorder) Features() *fs.Features {
features := *r.Fs.Features()
features.PutStream = nil
if r.stream {
features.PutStream = r.PutStream
}
return &features
}
func (r *putRecorder) record(in io.Reader, src fs.ObjectInfo) []byte {
r.size = src.Size()
body, err := io.ReadAll(in)
require.NoError(r.t, err)
if seeker, ok := in.(io.Seeker); ok {
r.seekable = true
_, err = seeker.Seek(0, io.SeekStart)
require.NoError(r.t, err)
again, err := io.ReadAll(in)
require.NoError(r.t, err)
assert.Equal(r.t, body, again, "retried body should be identical")
}
r.body = body
return body
}
func (r *putRecorder) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
body := r.record(in, src)
return r.Fs.Put(ctx, bytes.NewReader(body), object.NewStaticObjectInfo(src.Remote(), src.ModTime(ctx), int64(len(body)), true, nil, r.Fs), options...)
}
func (r *putRecorder) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
r.streamed = true
return r.Put(ctx, in, src, options...)
}
// TestRcat checks the three upload paths rcat takes: small files buffered
// in memory and uploaded with a known size and a seekable body, large
// files streamed when the wrapped remote supports it, and large files
// spooled to a temporary file when it doesn't. Pool pages taken for the
// buffer must be returned on every path.
func TestRcat(t *testing.T) {
ctx := context.Background()
const limit = 1024
for _, test := range []struct {
name string
size int
stream bool
wantSize int64
}{
{name: "Small", size: limit / 2, stream: true, wantSize: limit / 2},
{name: "Empty", size: 0, stream: true, wantSize: 0},
{name: "ExactLimit", size: limit, stream: true, wantSize: -1},
{name: "LargeStream", size: 3 * limit, stream: true, wantSize: -1},
{name: "LargeSpool", size: 3 * limit, stream: false, wantSize: 3 * limit},
} {
t.Run(test.name, func(t *testing.T) {
remote, err := fs.NewFs(ctx, ":memory:rcat-"+test.name)
require.NoError(t, err)
rec := &putRecorder{Fs: remote, t: t, stream: test.stream}
f := &Fs{Fs: rec}
f.opt.RAMCacheLimit = limit
content := []byte(random.String(test.size))
inUse := pool.Global().InUse()
o, err := f.rcat(ctx, "file", io.NopCloser(bytes.NewReader(content)), time.Now(), nil)
require.NoError(t, err)
assert.Equal(t, inUse, pool.Global().InUse(), "pool pages not returned")
assert.Equal(t, test.wantSize, rec.size)
assert.Equal(t, content, rec.body)
assert.Equal(t, test.stream && test.size >= limit, rec.streamed)
if test.size < limit {
assert.True(t, rec.seekable, "small file body should be seekable")
}
rc, err := o.Open(ctx)
require.NoError(t, err)
got, err := io.ReadAll(rc)
require.NoError(t, err)
require.NoError(t, rc.Close())
assert.Equal(t, content, got)
})
}
}
// TestIsCompressible checks the compressibility heuristic on data at
// both ends of the scale for every compression mode which has one.
func TestIsCompressible(t *testing.T) {
compressible := bytes.Repeat([]byte("compress me "), 4096)
incompressible := make([]byte, len(compressible))
_, err := io.ReadFull(rand.Reader, incompressible)
require.NoError(t, err)
for name, handler := range map[string]compressionModeHandler{
"gzip": &gzipModeHandler{},
"zstd": &zstdModeHandler{},
} {
t.Run(name, func(t *testing.T) {
ok, err := handler.isCompressible(bytes.NewReader(compressible), 0)
require.NoError(t, err)
assert.True(t, ok)
ok, err = handler.isCompressible(bytes.NewReader(incompressible), 0)
require.NoError(t, err)
assert.False(t, ok)
})
}
}
+3 -2
View File
@@ -2,6 +2,7 @@ package compress
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"encoding/hex"
@@ -22,7 +23,7 @@ type zstdModeHandler struct{}
// isCompressible checks the compression ratio of the provided data and returns true if the ratio exceeds
// the configured threshold
func (z *zstdModeHandler) isCompressible(r io.Reader, compressionMode int) (bool, error) {
var b countingDiscard
var b bytes.Buffer
var n int64
w, err := NewWriterSzstd(&b, zstd.WithEncoderLevel(zstd.SpeedDefault))
if err != nil {
@@ -36,7 +37,7 @@ func (z *zstdModeHandler) isCompressible(r io.Reader, compressionMode int) (bool
if err != nil {
return false, err
}
ratio := float64(n) / float64(b)
ratio := float64(n) / float64(b.Len())
return ratio > minCompressionRatio, nil
}
-104
View File
@@ -8,14 +8,10 @@ import (
"fmt"
"io"
"mime"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"strings"
stdsync "sync"
"sync/atomic"
"testing"
"time"
@@ -29,113 +25,13 @@ 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
+2 -4
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,9 +131,7 @@ 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
}
+18 -30
View File
@@ -11,6 +11,7 @@
package drive
import (
"bytes"
"context"
"encoding/json"
"fmt"
@@ -21,7 +22,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/readers"
"google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
@@ -112,13 +112,8 @@ func (f *Fs) Upload(ctx context.Context, in io.Reader, size int64, contentType,
}
// Make an http.Request for the range passed in
//
// The body is wrapped in readers.NoCloser so the transport can't upgrade it
// to an io.Closer and close it after each attempt — the chunk buffer is
// pool-backed, so an early close would free its pages and a retry would then
// read a dead buffer. The upload loop owns the buffer's lifetime.
func (rx *resumableUpload) makeRequest(ctx context.Context, start int64, body io.ReadSeeker, reqSize int64) *http.Request {
req, _ := http.NewRequestWithContext(ctx, "POST", rx.URI, readers.NoCloser(body))
req, _ := http.NewRequestWithContext(ctx, "POST", rx.URI, body)
req.ContentLength = reqSize
totalSize := "*"
if rx.ContentLength >= 0 {
@@ -173,40 +168,37 @@ func (rx *resumableUpload) Upload(ctx context.Context) (*drive.File, error) {
start := int64(0)
var StatusCode int
var err error
chunkSize := int64(rx.f.opt.ChunkSize)
buf := make([]byte, int(rx.f.opt.ChunkSize))
for finished := false; !finished; {
reqSize := chunkSize
var reqSize int64
var chunk io.ReadSeeker
if rx.ContentLength >= 0 {
// If size known use repeatable reader for smoother bwlimit
if start >= rx.ContentLength {
break
}
reqSize = min(rx.ContentLength-start, chunkSize)
}
// Buffer the chunk in memory from the global pool so reads are
// repeatable for retries
rw := multipart.NewRW()
var n int64
n, err = io.CopyN(rw, rx.Media, reqSize)
if rx.ContentLength < 0 {
reqSize = min(rx.ContentLength-start, int64(rx.f.opt.ChunkSize))
chunk = readers.NewRepeatableLimitReaderBuffer(rx.Media, buf, reqSize)
} else {
// If size unknown read into buffer
var n int
n, err = readers.ReadFill(rx.Media, buf)
if err == io.EOF {
// Send the last chunk with the correct ContentLength
// otherwise Google doesn't know we've finished
rx.ContentLength = start + n
rx.ContentLength = start + int64(n)
finished = true
err = nil
} else if err != nil {
return nil, err
}
reqSize = n
}
if err != nil {
_ = rw.Close()
return nil, err
reqSize = int64(n)
chunk = bytes.NewReader(buf[:reqSize])
}
// Transfer the chunk
err = rx.f.pacer.Call(func() (bool, error) {
fs.Debugf(rx.remote, "Sending chunk %d length %d", start, reqSize)
StatusCode, err = rx.transferChunk(ctx, start, rw, reqSize)
StatusCode, err = rx.transferChunk(ctx, start, chunk, reqSize)
again, err := rx.f.shouldRetry(ctx, err)
if StatusCode == statusResumeIncomplete || StatusCode == http.StatusCreated || StatusCode == http.StatusOK {
again = false
@@ -214,13 +206,9 @@ func (rx *resumableUpload) Upload(ctx context.Context) (*drive.File, error) {
}
return again, err
})
closeErr := rw.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
start += reqSize
}
-57
View File
@@ -1,57 +0,0 @@
package drive
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestResumableUploadRetry checks that a chunk which fails with a 5xx is
// retried successfully. The chunk buffer is pool-backed and implements
// io.Closer, so if it reaches the http transport unwrapped the transport
// closes it after the failed attempt, returning its pages to the pool, and
// the retry then reads a freed buffer.
func TestResumableUploadRetry(t *testing.T) {
content := bytes.Repeat([]byte("resumable"), 512)
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
if attempts.Add(1) == 1 {
w.WriteHeader(http.StatusInternalServerError)
return
}
assert.Equal(t, content, body, "retried chunk should re-send the full chunk")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"id":"fake-id","name":"remote"}`))
}))
defer server.Close()
f := &Fs{
pacer: fs.NewPacer(context.Background(), pacer.NewGoogleDrive()),
client: server.Client(),
}
f.opt.ChunkSize = fs.SizeSuffix(len(content))
rx := &resumableUpload{
f: f,
remote: "remote",
URI: server.URL,
Media: bytes.NewReader(content),
MediaType: "application/octet-stream",
ContentLength: int64(len(content)),
}
info, err := rx.Upload(context.Background())
require.NoError(t, err)
require.NotNil(t, info)
assert.Equal(t, "fake-id", info.Id)
assert.Equal(t, int32(2), attempts.Load(), "expected exactly one failed attempt and one retry")
}
+10 -17
View File
@@ -51,7 +51,6 @@ import (
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/batcher"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
@@ -2080,6 +2079,11 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
// write chunks
in := readers.NewCountingReader(in0)
bufSize := chunkSize
if size >= 0 && size < bufSize {
bufSize = size
}
buf := make([]byte, int(bufSize))
cursor := files.UploadSessionCursor{
SessionId: res.SessionId,
Offset: 0,
@@ -2099,21 +2103,14 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
fs.Debugf(o, "Uploading chunk %d/%d", currentChunk, chunks)
}
// Buffer the chunk in memory from the global pool for retries
rw := multipart.NewRW()
var n int64
n, err = io.CopyN(rw, in, chunkSize)
if err != nil && err != io.EOF {
_ = rw.Close()
return nil, err
}
chunk := readers.NewRepeatableLimitReaderBuffer(in, buf, chunkSize)
skip := int64(0)
err = o.fs.pacer.Call(func() (bool, error) {
// seek to the start in case this is a retry
if _, err = rw.Seek(skip, io.SeekStart); err != nil {
if _, err = chunk.Seek(skip, io.SeekStart); err != nil {
return false, err
}
err = o.fs.srv.UploadSessionAppendV2Context(ctx, &appendArg, rw)
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
@@ -2125,10 +2122,10 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
what := fmt.Sprintf("incorrect offset error received: sent %d, need %d, skip %d", cursor.Offset, correctOffset, skip)
if skip < 0 {
return false, fmt.Errorf("can't seek backwards to correct offset: %s", what)
} else if skip == n {
} else if skip == chunkSize {
fs.Debugf(o, "%s: chunk received OK - continuing", what)
return false, nil
} else if skip > n {
} else if skip > chunkSize {
// This error should never happen
return false, fmt.Errorf("can't seek forwards by more than a chunk to correct offset: %s", what)
}
@@ -2145,13 +2142,9 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
}
return err != nil, err
})
closeErr := rw.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
if size >= 0 {
// Check for sources which truncate early
expected := min(uint64(currentChunk)*uint64(chunkSize), uint64(size))
+54 -56
View File
@@ -1,6 +1,7 @@
package filelu
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -10,11 +11,9 @@ import (
"net/http"
"net/url"
"path"
"strconv"
"strings"
"github.com/rclone/rclone/fs"
rclonemultipart "github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/rest"
)
@@ -48,32 +47,40 @@ func (f *Fs) multipartUpload(ctx context.Context, in io.Reader, remote string) e
server := initResp.Result.Server
objectPath := initResp.Result.ObjectPath
chunkSize := int64(f.opt.ChunkSize)
if chunkSize <= 0 {
return fmt.Errorf("multipart upload: chunk_size must be positive: %v", f.opt.ChunkSize)
}
for partNo := 1; ; partNo++ {
// Buffer the part in memory from the global pool so it can be
// re-sent on retry
rw := rclonemultipart.NewRW()
n, err := io.CopyN(rw, in, chunkSize)
if err != nil && err != io.EOF {
_ = rw.Close()
return fmt.Errorf("read failed: %w", err)
}
chunkSize := int(f.opt.ChunkSize)
buf := make([]byte, 0, chunkSize)
tmp := make([]byte, 1024*1024)
partNo := 1
for {
n, errRead := in.Read(tmp)
if n > 0 {
uploadErr := f.uploadPart(ctx, server, uploadID, sessID, objectPath, partNo, rw, n)
if uploadErr != nil {
_ = rw.Close()
return fmt.Errorf("upload part %d failed: %w", partNo, uploadErr)
buf = append(buf, tmp[:n]...)
// If buffer reached chunkSize, upload a full part
if len(buf) >= chunkSize {
err = f.uploadPart(ctx, server, uploadID, sessID, objectPath, partNo, bytes.NewReader(buf))
if err != nil {
return fmt.Errorf("upload part %d failed: %w", partNo, err)
}
partNo++
buf = buf[:0]
}
}
if closeErr := rw.Close(); closeErr != nil {
return closeErr
}
if err == io.EOF {
if errRead == io.EOF {
break
}
if errRead != nil {
return fmt.Errorf("read failed: %w", errRead)
}
}
if len(buf) > 0 {
err = f.uploadPart(ctx, server, uploadID, sessID, objectPath, partNo, bytes.NewReader(buf))
if err != nil {
return fmt.Errorf("upload part %d failed: %w", partNo, err)
}
}
err = f.completeMultipart(ctx, server, uploadID, sessID, objectPath)
@@ -84,40 +91,31 @@ func (f *Fs) multipartUpload(ctx context.Context, in io.Reader, remote string) e
return nil
}
// uploadPart sends a single multipart chunk of size bytes to the upload server.
func (f *Fs) uploadPart(ctx context.Context, server, uploadID, sessID, objectPath string, partNo int, r io.ReadSeeker, size int64) error {
opts := rest.Opts{
Method: "PUT",
RootURL: server,
Parameters: url.Values{
"partNumber": {strconv.Itoa(partNo)},
"uploadId": {uploadID},
},
Body: r,
ContentLength: &size,
ExtraHeaders: map[string]string{
"X-RC-Upload-Id": uploadID,
"X-RC-Part-No": strconv.Itoa(partNo),
"X-Sess-ID": sessID,
"X-Object-Path": objectPath,
},
NoResponse: true,
// uploadPart sends a single multipart chunk to the upload server.
func (f *Fs) uploadPart(ctx context.Context, server, uploadID, sessID, objectPath string, partNo int, r io.Reader) error {
url := fmt.Sprintf("%s?partNumber=%d&uploadId=%s", server, partNo, uploadID)
req, err := http.NewRequestWithContext(ctx, "PUT", url, r)
if err != nil {
return err
}
return f.pacer.Call(func() (bool, error) {
// rewind the pooled buffer so each attempt sends the whole chunk
_, err := r.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
resp, err := f.srv.Call(ctx, &opts)
if err != nil {
if resp != nil {
return shouldRetryHTTP(resp.StatusCode), fmt.Errorf("uploadPart failed: %w", err)
}
return shouldRetry(err), err
}
return false, nil
})
req.Header.Set("X-RC-Upload-Id", uploadID)
req.Header.Set("X-RC-Part-No", fmt.Sprintf("%d", partNo))
req.Header.Set("X-Sess-ID", sessID)
req.Header.Set("X-Object-Path", objectPath)
resp, err := f.client.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
return fmt.Errorf("uploadPart failed: %s", resp.Status)
}
return nil
}
// uploadFile uploads a file to FileLu
-29
View File
@@ -1,29 +0,0 @@
package filelu
import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest/fstests"
)
// SetUploadChunkSize changes the configured chunk size, returning the old value.
//
// It is only called by the integration tests while no transfer is in progress.
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
var old fs.SizeSuffix
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
return old, nil
}
// SetUploadCutoff changes the configured upload cutoff, returning the old value.
//
// It is only called by the integration tests while no transfer is in progress.
func (f *Fs) SetUploadCutoff(cutoff fs.SizeSuffix) (fs.SizeSuffix, error) {
var old fs.SizeSuffix
old, f.opt.UploadCutoff = f.opt.UploadCutoff, cutoff
return old, nil
}
var (
_ fstests.SetUploadChunkSizer = (*Fs)(nil)
_ fstests.SetUploadCutoffer = (*Fs)(nil)
)
-3
View File
@@ -12,8 +12,5 @@ func TestIntegration(t *testing.T) {
RemoteName: "TestFileLu:",
NilObject: nil,
SkipInvalidUTF8: true,
ChunkedUpload: fstests.ChunkedUploadConfig{
MinChunkSize: 1,
},
})
}
+11 -14
View File
@@ -19,7 +19,6 @@ import (
"github.com/Files-com/files-sdk-go/v3/file"
file_migration "github.com/Files-com/files-sdk-go/v3/filemigration"
"github.com/Files-com/files-sdk-go/v3/folder"
files_sdk_lib "github.com/Files-com/files-sdk-go/v3/lib"
"github.com/Files-com/files-sdk-go/v3/session"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
@@ -177,13 +176,6 @@ func shouldRetry(ctx context.Context, err error) (bool, error) {
}
}
// Errors from the upload storage servers are of this type
var httpErr files_sdk_lib.ResponseError
if errors.As(err, &httpErr) && slices.Contains(retryErrorCodes, httpErr.StatusCode) {
fs.Debugf(nil, "Retrying HTTP error %v", err)
return true, err
}
return fserrors.ShouldRetry(err), err
}
@@ -353,7 +345,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
}
for it.Next() {
item := new(it.File())
item := ptr(it.File())
remote := f.opt.Enc.ToStandardPath(item.DisplayName)
remote = path.Join(dir, remote)
if remote == dir {
@@ -424,7 +416,7 @@ func (f *Fs) mkdir(ctx context.Context, path string) error {
params := files_sdk.FolderCreateParams{
Path: path,
MkdirParents: new(true),
MkdirParents: ptr(true),
}
err := f.pacer.Call(func() (bool, error) {
@@ -466,7 +458,7 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
params := files_sdk.FileDeleteParams{
Path: path,
Recursive: new(!check),
Recursive: ptr(!check),
}
err := f.pacer.Call(func() (bool, error) {
@@ -537,7 +529,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dstObj fs.
params := files_sdk.FileCopyParams{
Path: srcPath,
Destination: dstPath,
Overwrite: new(true),
Overwrite: ptr(true),
}
var action files_sdk.FileAction
@@ -680,7 +672,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
Paths: []string{f.absPath(remote)},
}
if expire < fs.DurationOff {
params.ExpiresAt = new(time.Now().Add(time.Duration(expire)))
params.ExpiresAt = ptr(time.Now().Add(time.Duration(expire)))
}
var bundle files_sdk.Bundle
@@ -842,6 +834,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
return
}
// Returns a pointer to t - useful for returning pointers to constants
func ptr[T any](t T) *T {
return &t
}
func isFolderNotEmpty(err error) bool {
var re files_sdk.ResponseError
ok := errors.As(err, &re)
@@ -861,7 +858,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
file.UploadWithProvidedMtime(src.ModTime(ctx)),
}
err := o.fs.pacer.CallNoRetry(func() (bool, error) {
err := o.fs.pacer.Call(func() (bool, error) {
err := o.fs.fileClient.Upload(uploadOpts...)
return shouldRetry(ctx, err)
})
+1 -1
View File
@@ -43,7 +43,7 @@ func TestCommandEncodingNeutralisesCRLF(t *testing.T) {
type settings map[string]any
func deriveFs(ctx context.Context, t *testing.T, f fs.Fs, opts settings) fs.Fs {
fsName, _, _ := strings.Cut(f.Name(), "{") // strip off hash
fsName := strings.Split(f.Name(), "{")[0] // strip off hash
configMap := configmap.Simple{}
for key, val := range opts {
configMap[key] = fmt.Sprintf("%v", val)
+2 -1
View File
@@ -194,7 +194,8 @@ var retryErrorCodes = []int{
// Return true if the api error has the status given
func isAPIErr(err error, status string) bool {
if apiErr, ok := errors.AsType[api.Error](err); ok {
var apiErr api.Error
if errors.As(err, &apiErr) {
return apiErr.Status == status
}
return false
+61 -73
View File
@@ -10,6 +10,7 @@ package hidrive
// to be resolved prior to execution with resolvePath(...).
import (
"bytes"
"context"
"errors"
"io"
@@ -23,9 +24,8 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/ranges"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
@@ -454,17 +454,17 @@ func (f *Fs) deleteObject(ctx context.Context, path string) error {
}
// createFile creates a file at the given path
// with the content of the buffer.
// with the content of the io.ReadSeeker.
// This guarantees that existing files will not be overwritten.
// The maximum size of the content is limited by MaximumUploadBytes.
// The caller remains responsible for closing the buffer.
// The io.ReadSeeker should be resettable by seeking to its start.
// If modTime is not the zero time instant,
// it will be set as the file's modification time after the operation.
//
// This returns fs.ErrorDirNotFound
// if the parent directory of the file is not found.
// This returns ErrorFileExists if a file already exists at the specified path.
func (f *Fs) createFile(ctx context.Context, path string, content *pool.RW, modTime time.Time, onExist OnExistAction) (*api.HiDriveObject, error) {
func (f *Fs) createFile(ctx context.Context, path string, content io.ReadSeeker, modTime time.Time, onExist OnExistAction) (*api.HiDriveObject, error) {
parameters := api.NewQueryParameters()
parameters.SetFileInDirectory(path)
if onExist == AutoNameOnExist {
@@ -479,14 +479,12 @@ func (f *Fs) createFile(ctx context.Context, path string, content *pool.RW, modT
}
}
contentLength := content.Size()
opts := rest.Opts{
Method: "POST",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
ContentLength: &contentLength,
Parameters: parameters.Values,
Method: "POST",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
Parameters: parameters.Values,
}
var result api.HiDriveObject
@@ -512,16 +510,16 @@ func (f *Fs) createFile(ctx context.Context, path string, content *pool.RW, modT
}
// overwriteFile updates the content of the file at the given path
// with the content of the buffer.
// with the content of the io.ReadSeeker.
// If the file does not exist it will be created.
// The maximum size of the content is limited by MaximumUploadBytes.
// The caller remains responsible for closing the buffer.
// The io.ReadSeeker should be resettable by seeking to its start.
// If modTime is not the zero time instant,
// it will be set as the file's modification time after the operation.
//
// This returns fs.ErrorDirNotFound
// if the parent directory of the file is not found.
func (f *Fs) overwriteFile(ctx context.Context, path string, content *pool.RW, modTime time.Time) (*api.HiDriveObject, error) {
func (f *Fs) overwriteFile(ctx context.Context, path string, content io.ReadSeeker, modTime time.Time) (*api.HiDriveObject, error) {
parameters := api.NewQueryParameters()
parameters.SetFileInDirectory(path)
@@ -533,14 +531,12 @@ func (f *Fs) overwriteFile(ctx context.Context, path string, content *pool.RW, m
}
}
contentLength := content.Size()
opts := rest.Opts{
Method: "PUT",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
ContentLength: &contentLength,
Parameters: parameters.Values,
Method: "PUT",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
Parameters: parameters.Values,
}
var result api.HiDriveObject
@@ -638,18 +634,11 @@ func (f *Fs) updateFileChunked(ctx context.Context, path string, content io.Read
}
// Read a chunk of data.
var (
chunkReader *pool.RW
bytesRead int64
)
chunkReader, bytesRead, readErr = readerForChunk(content, int64(chunkSize))
if bytesRead < int64(chunkSize) {
chunkReader, bytesRead, readErr := readerForChunk(content, chunkSize)
if bytesRead < chunkSize {
startMoreTransfers = false
}
if readErr != nil || bytesRead <= 0 {
if chunkReader != nil {
_ = chunkReader.Close()
}
break
}
@@ -659,12 +648,11 @@ func (f *Fs) updateFileChunked(ctx context.Context, path string, content io.Read
// After this upload is done,
// signal that another transfer can be started.
defer transferSemaphore.Release(1)
defer func() { _ = chunkReader.Close() }()
uploadErr := f.patchFile(gCtx, path, chunkReader, chunkOffset, zeroTime)
uploadErr := f.patchFile(gCtx, path, cachedReader(chunkReader), chunkOffset, zeroTime)
if uploadErr == nil {
// Remember successfully written chunks.
okChunksMu.Lock()
okChunks = append(okChunks, ranges.Range{Pos: int64(chunkOffset), Size: bytesRead})
okChunks = append(okChunks, ranges.Range{Pos: int64(chunkOffset), Size: int64(bytesRead)})
okChunksMu.Unlock()
fs.Debugf(f, "Done uploading chunk of size %v at offset %v.", bytesRead, chunkOffset)
} else {
@@ -708,10 +696,10 @@ func (f *Fs) updateFileChunked(ctx context.Context, path string, content io.Read
// starting at the given offset.
//
// Replaces the file contents starting from the given byte offset
// with the content of the buffer.
// with the content of the io.ReadSeeker.
// If the offset is beyond the file end, the file is extended up to the offset.
// The maximum size of the update is limited by MaximumUploadBytes.
// The caller remains responsible for closing the buffer.
// The io.ReadSeeker should be resettable by seeking to its start.
// If modTime is not the zero time instant,
// it will be set as the file's modification time after the operation.
//
@@ -723,7 +711,7 @@ func (f *Fs) updateFileChunked(ctx context.Context, path string, content io.Read
// usually expand the holes into regions of 0-bytes.
//
// This returns fs.ErrorObjectNotFound if the object is not found.
func (f *Fs) patchFile(ctx context.Context, path string, content *pool.RW, offset uint64, modTime time.Time) error {
func (f *Fs) patchFile(ctx context.Context, path string, content io.ReadSeeker, offset uint64, modTime time.Time) error {
parameters := api.NewQueryParameters()
parameters.SetPath(path)
parameters.Set("offset", strconv.FormatUint(offset, 10))
@@ -735,15 +723,13 @@ func (f *Fs) patchFile(ctx context.Context, path string, content *pool.RW, offse
}
}
contentLength := content.Size()
opts := rest.Opts{
Method: "PATCH",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
ContentLength: &contentLength,
Parameters: parameters.Values,
NoResponse: true,
Method: "PATCH",
Path: "/file",
Body: content,
ContentType: "application/octet-stream",
Parameters: parameters.Values,
NoResponse: true,
}
var resp *http.Response
@@ -853,39 +839,41 @@ func createHiDriveScopes(role string, access string) []string {
return []string{}
}
// unwrapAccounting splits any transfer accounting off reader,
// returning the raw stream and the accounting (nil if there is none),
// so the stream can be buffered and accounted when the buffer is uploaded.
func unwrapAccounting(reader io.Reader) (unwrapped io.Reader, acc *accounting.Account) {
// Any kind of accounter re-wraps into the one type UnWrapAccounting
// knows how to take the *Account out of.
unwrapped, wrap := accounting.UnWrap(reader)
_, acc = accounting.UnWrapAccounting(wrap(unwrapped))
return unwrapped, acc
}
// readerForChunk reads up to length bytes from reader into a buffer
// from the global memory pool and returns it
// along with the number of bytes that have been read from reader.
// Reaching the end of reader early is not an error.
//
// Any accounting on reader is applied when the buffer is read instead,
// so the upload is what gets accounted.
// The caller must Close the buffer when done with it.
func readerForChunk(reader io.Reader, length int64) (chunkReader *pool.RW, bytesRead int64, err error) {
reader, acc := unwrapAccounting(reader)
chunkReader = multipart.NewRW()
if acc != nil {
chunkReader.SetAccounting(acc.AccountRead)
// cachedReader returns a version of the reader that caches its contents and
// can therefore be reset using Seek.
func cachedReader(reader io.Reader) io.ReadSeeker {
bytesReader, ok := reader.(*bytes.Reader)
if ok {
return bytesReader
}
bytesRead, err = io.CopyN(chunkReader, reader, length)
if err == io.EOF {
repeatableReader, ok := reader.(*readers.RepeatableReader)
if ok {
return repeatableReader
}
return readers.NewRepeatableReader(reader)
}
// readerForChunk reads a chunk of bytes from reader (after handling any accounting).
// Returns a new io.Reader (chunkReader) for that chunk
// and the number of bytes that have been read from reader.
func readerForChunk(reader io.Reader, length int) (chunkReader io.Reader, bytesRead int, err error) {
// Unwrap any accounting from the input if present.
reader, wrap := accounting.UnWrap(reader)
// Read a chunk of data.
buffer := make([]byte, length)
bytesRead, err = io.ReadFull(reader, buffer)
if err == io.EOF || err == io.ErrUnexpectedEOF {
err = nil
}
if err != nil {
_ = chunkReader.Close()
return nil, bytesRead, err
}
return chunkReader, bytesRead, nil
// Truncate unused capacity.
buffer = buffer[:bytesRead]
// Use wrap to put any accounting back for chunkReader.
return wrap(bytes.NewReader(buffer)), bytesRead, nil
}
+4 -17
View File
@@ -30,7 +30,6 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/rest"
)
@@ -515,14 +514,8 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
// (i.e. everything up to the cutoff) in the first request,
// avoids files being created on upload failure for small files.
// (As opposed to creating an empty file and then uploading the content.)
//
// Only buffer as much as the source declares it has,
// so small files do not cost the whole cutoff in memory.
prefixSize := int64(f.opt.UploadCutoff)
if size := src.Size(); size >= 0 && size < prefixSize {
prefixSize = size
}
cutoffReader, bytesRead, err := readerForChunk(in, prefixSize)
tmpReader, bytesRead, err := readerForChunk(in, int(f.opt.UploadCutoff))
cutoffReader := cachedReader(tmpReader)
if err != nil {
return nil, err
}
@@ -547,7 +540,6 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
}
return false, createErr
})
_ = cutoffReader.Close()
if err != nil {
return nil, err
@@ -564,7 +556,7 @@ func (f *Fs) PutUnchecked(ctx context.Context, in io.Reader, src fs.ObjectInfo,
}
// If there is more left to write, o.Update needs to skip ahead.
// Use a fs.SeekOption with the current offset to do this.
options = append(options, &fs.SeekOption{Offset: bytesRead})
options = append(options, &fs.SeekOption{Offset: int64(bytesRead)})
err = o.Update(ctx, in, src, options...)
if err == nil {
@@ -979,12 +971,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Metadata should be updated even if the upload fails.
info, metaErr = o.fs.fetchMetadataForPath(ctx, resolvedPath, api.HiDriveObjectWithMetadataFields)
} else {
var content *pool.RW
content, _, err = readerForChunk(in, src.Size())
if err == nil {
info, err = o.fs.overwriteFile(ctx, resolvedPath, content, modTime)
_ = content.Close()
}
info, err = o.fs.overwriteFile(ctx, resolvedPath, cachedReader(in), modTime)
metaErr = err
}
+1 -1
View File
@@ -593,7 +593,7 @@ func (f *Fs) readDir(ctx context.Context, dir string) (names []string, err error
return nil, fmt.Errorf("failed to readDir: %w", err)
}
contentType, _, _ := strings.Cut(res.Header.Get("Content-Type"), ";")
contentType := strings.SplitN(res.Header.Get("Content-Type"), ";", 2)[0]
switch contentType {
case "text/html":
names, err = parse(u, res.Body)
+70 -65
View File
@@ -37,44 +37,44 @@ type FileList struct {
// File represents a file or folder in Huawei Drive
type File struct {
ID string `json:"id"`
FileName string `json:"fileName"`
OriginalFilename string `json:"originalFilename,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
Category string `json:"category"`
Size int64 `json:"size,omitempty"`
SHA256 string `json:"sha256,omitempty"`
CreatedTime time.Time `json:"createdTime"`
EditedTime time.Time `json:"editedTime"`
EditedByMeTime time.Time `json:"editedByMeTime"`
ParentFolder []string `json:"parentFolder,omitempty"`
Owners []User `json:"owners"`
LastEditor User `json:"lastEditor"`
Permissions []Permission `json:"permissions"`
PermissionIDs []string `json:"permissionIds"`
Capabilities FileCapabilities `json:"capabilities"`
OwnedByMe bool `json:"ownedByMe"`
EditedByMe bool `json:"editedByMe"`
ViewedByMe bool `json:"viewedByMe"`
HasShared bool `json:"hasShared"`
Recycled bool `json:"recycled"`
DirectlyRecycled bool `json:"directlyRecycled"`
Favorite bool `json:"favorite"`
ExistThumbnail bool `json:"existThumbnail"`
ThumbnailVersion int64 `json:"thumbnailVersion"`
IconDownloadLink string `json:"iconDownloadLink,omitempty"`
ContentDownloadLink string `json:"contentDownloadLink,omitempty"`
ContentVersion string `json:"contentVersion,omitempty"`
LastHistoryVersionID string `json:"lastHistoryVersionId,omitempty"`
OccupiedSpace int64 `json:"occupiedSpace,omitempty"`
Version int64 `json:"version"`
WritersHasSharePermission bool `json:"writersHasSharePermission"`
WriterHasCopyPermission bool `json:"writerHasCopyPermission"`
Containers []string `json:"containers"`
Properties map[string]any `json:"properties,omitempty"`
AppSettings map[string]any `json:"appSettings,omitempty"`
ContentExtras *ContentExtras `json:"contentExtras,omitempty"`
ID string `json:"id"`
FileName string `json:"fileName"`
OriginalFilename string `json:"originalFilename,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
Category string `json:"category"`
Size int64 `json:"size,omitempty"`
SHA256 string `json:"sha256,omitempty"`
CreatedTime time.Time `json:"createdTime"`
EditedTime time.Time `json:"editedTime"`
EditedByMeTime time.Time `json:"editedByMeTime,omitempty"`
ParentFolder []string `json:"parentFolder,omitempty"`
Owners []User `json:"owners"`
LastEditor User `json:"lastEditor"`
Permissions []Permission `json:"permissions"`
PermissionIDs []string `json:"permissionIds"`
Capabilities FileCapabilities `json:"capabilities"`
OwnedByMe bool `json:"ownedByMe"`
EditedByMe bool `json:"editedByMe"`
ViewedByMe bool `json:"viewedByMe"`
HasShared bool `json:"hasShared"`
Recycled bool `json:"recycled"`
DirectlyRecycled bool `json:"directlyRecycled"`
Favorite bool `json:"favorite"`
ExistThumbnail bool `json:"existThumbnail"`
ThumbnailVersion int64 `json:"thumbnailVersion"`
IconDownloadLink string `json:"iconDownloadLink,omitempty"`
ContentDownloadLink string `json:"contentDownloadLink,omitempty"`
ContentVersion string `json:"contentVersion,omitempty"`
LastHistoryVersionID string `json:"lastHistoryVersionId,omitempty"`
OccupiedSpace int64 `json:"occupiedSpace,omitempty"`
Version int64 `json:"version"`
WritersHasSharePermission bool `json:"writersHasSharePermission"`
WriterHasCopyPermission bool `json:"writerHasCopyPermission"`
Containers []string `json:"containers"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
ContentExtras *ContentExtras `json:"contentExtras,omitempty"`
}
// IsDir returns true if the file is a directory
@@ -125,41 +125,41 @@ type Thumbnail struct {
// CreateFolderRequest represents request to create a folder
type CreateFolderRequest struct {
FileName string `json:"fileName"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
ParentFolder []string `json:"parentFolder,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Properties map[string]any `json:"properties,omitempty"`
AppSettings map[string]any `json:"appSettings,omitempty"`
AutoRename int `json:"autoRename,omitempty"`
FileName string `json:"fileName"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
ParentFolder []string `json:"parentFolder,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
AutoRename int `json:"autoRename,omitempty"`
}
// UpdateFileRequest represents request to update a file
type UpdateFileRequest struct {
FileName string `json:"fileName,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Favorite *bool `json:"favorite,omitempty"`
Recycled *bool `json:"recycled,omitempty"`
OriginalFilename string `json:"originalFilename,omitempty"`
WriterHasCopyPermission *bool `json:"writerHasCopyPermission,omitempty"`
WritersHasSharePermission *bool `json:"writersHasSharePermission,omitempty"`
Properties map[string]any `json:"properties,omitempty"`
AppSettings map[string]any `json:"appSettings,omitempty"`
AddParentFolder []string `json:"addParentFolder,omitempty"`
RemoveParentFolder []string `json:"removeParentFolder,omitempty"`
CreatedTime *time.Time `json:"createdTime,omitempty"`
EditedTime *time.Time `json:"editedTime,omitempty"`
FileName string `json:"fileName,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Favorite *bool `json:"favorite,omitempty"`
Recycled *bool `json:"recycled,omitempty"`
OriginalFilename string `json:"originalFilename,omitempty"`
WriterHasCopyPermission *bool `json:"writerHasCopyPermission,omitempty"`
WritersHasSharePermission *bool `json:"writersHasSharePermission,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
AddParentFolder []string `json:"addParentFolder,omitempty"`
RemoveParentFolder []string `json:"removeParentFolder,omitempty"`
CreatedTime *time.Time `json:"createdTime,omitempty"`
EditedTime *time.Time `json:"editedTime,omitempty"`
}
// CopyFileRequest represents request to copy a file
type CopyFileRequest struct {
FileName string `json:"fileName,omitempty"`
MimeType string `json:"mimeType,omitempty"`
ParentFolder []string `json:"parentFolder,omitempty"`
Properties map[string]any `json:"properties,omitempty"`
AppSettings map[string]any `json:"appSettings,omitempty"`
FileName string `json:"fileName,omitempty"`
MimeType string `json:"mimeType,omitempty"`
ParentFolder []string `json:"parentFolder,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
}
// ResumeUploadInitResponse represents response to resume upload init
@@ -224,6 +224,11 @@ var GlobalDomains = map[string]bool{
"drive.cloud.hicloud.com": true,
}
// BoolPtr returns a pointer to a bool value (helper for UpdateFileRequest)
func BoolPtr(b bool) *bool {
return &b
}
// StartCursor represents response to Changes.getStartCursor endpoint
type StartCursor struct {
Category string `json:"category"` // "drive#startCursor"
+31 -46
View File
@@ -33,7 +33,6 @@ import (
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
"golang.org/x/oauth2"
@@ -1032,7 +1031,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
fs.Debugf(f, "Copy: failed to get metadata options: %v", err)
}
if len(mergedMeta) > 0 {
copyReq.Properties = make(map[string]any)
copyReq.Properties = make(map[string]interface{})
for key, value := range mergedMeta {
switch key {
case "content-type", "sha256", "btime", "mtime", "utime",
@@ -1722,7 +1721,7 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, direct
}
// Create metadata
metadata := map[string]any{
metadata := map[string]interface{}{
"fileName": leaf,
"mimeType": mimeType,
}
@@ -1742,10 +1741,9 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, direct
metadata["autoRename"] = 3
}
// Build the multipart body in pooled memory so it can be re-sent on retry
rw := pool.NewRW(pool.Global())
defer fs.CheckClose(rw, &err)
writer := multipart.NewWriter(rw)
// Create multipart form
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
// Add metadata part - use exact format from Huawei docs
metadataWriter, err := writer.CreatePart(textproto.MIMEHeader{
@@ -1791,17 +1789,15 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, direct
return fmt.Errorf("failed to close multipart writer: %w", err)
}
bodySize := rw.Size()
bodyBytes := buf.Bytes()
opts := rest.Opts{
Method: "POST",
Parameters: url.Values{
"uploadType": []string{"multipart"},
"fields": []string{"*"},
},
ContentType: fmt.Sprintf("multipart/related; boundary=%s", writer.Boundary()),
ContentLength: &bodySize,
RootURL: o.fs.uploadURL,
Body: rw,
ContentType: fmt.Sprintf("multipart/related; boundary=%s", writer.Boundary()),
RootURL: o.fs.uploadURL,
}
if o.id != "" {
@@ -1815,10 +1811,7 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, leaf, direct
var info *api.File
err = o.fs.pacer.Call(func() (bool, error) {
_, err := rw.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
opts.Body = bytes.NewReader(bodyBytes)
resp, err := srv.CallJSON(ctx, &opts, nil, &info)
return shouldRetry(ctx, resp, err)
})
@@ -1879,7 +1872,7 @@ func (o *Object) uploadResume(ctx context.Context, in io.Reader, leaf, directory
}
// Prepare metadata for resumable upload initialization
metadata := map[string]any{
metadata := map[string]interface{}{
"fileName": leaf,
}
@@ -1912,26 +1905,25 @@ func (o *Object) uploadResume(ctx context.Context, in io.Reader, leaf, directory
}
// Now upload the content in chunks
// Note 256k is the minimum chunk size and 64M the maximum
// single upload size according to the Huawei Drive API
chunkSize := min(max(int64(o.fs.opt.ChunkSize), 256*1024), 64*1024*1024)
chunkSize := int64(o.fs.opt.ChunkSize)
if chunkSize < 256*1024 {
chunkSize = 256 * 1024 // Minimum chunk size according to Huawei Drive API
}
if chunkSize > 64*1024*1024 {
chunkSize = 64 * 1024 * 1024 // Maximum single upload size
}
buf := make([]byte, chunkSize)
var offset int64
for offset < size {
// Buffer the chunk in pooled memory so it can be re-sent on retry
rw := pool.NewRW(pool.Global())
n, err := io.CopyN(rw, in, min(size-offset, chunkSize))
if err != nil {
// io.EOF here means the source ran out before the declared size
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
_ = rw.Close()
n, err := io.ReadFull(in, buf)
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
return fmt.Errorf("failed to read chunk at offset %d: %w", offset, err)
}
end := offset + n - 1
chunk := buf[:n]
end := offset + int64(n) - 1
// Upload this chunk using the original client with OAuth authentication
chunkOpts := rest.Opts{
@@ -1939,20 +1931,17 @@ func (o *Object) uploadResume(ctx context.Context, in io.Reader, leaf, directory
RootURL: location,
Path: "", // Empty path since RootURL contains the full URL
ExtraHeaders: map[string]string{
"Content-Range": fmt.Sprintf("bytes %d-%d/%d", offset, end, size),
"Content-Type": mimeType,
"Content-Range": fmt.Sprintf("bytes %d-%d/%d", offset, end, size),
"Content-Length": strconv.Itoa(n),
"Content-Type": mimeType,
},
ContentLength: &n,
Body: rw,
}
var info *api.File
var chunkResp *http.Response
err = o.fs.pacer.Call(func() (bool, error) {
_, err := rw.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
chunkOpts.Body = bytes.NewReader(chunk)
var err error
chunkResp, err = srv.CallJSON(ctx, &chunkOpts, nil, &info)
// 308 means continue uploading (incomplete)
if chunkResp != nil && chunkResp.StatusCode == 308 {
@@ -1966,15 +1955,11 @@ func (o *Object) uploadResume(ctx context.Context, in io.Reader, leaf, directory
}
return shouldRetry(ctx, chunkResp, err)
})
closeErr := rw.Close()
if err != nil {
return fmt.Errorf("failed to upload chunk at offset %d: %w", offset, err)
}
if closeErr != nil {
return closeErr
}
offset += n
offset += int64(n)
// If we got file info back, we're done
if info != nil && info.ID != "" {
@@ -2105,8 +2090,8 @@ func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
// Prepare the update request payload
updateReq := api.UpdateFileRequest{
Properties: make(map[string]any),
AppSettings: make(map[string]any),
Properties: make(map[string]interface{}),
AppSettings: make(map[string]interface{}),
}
// Process metadata and separate into properties and app settings
@@ -2117,7 +2102,7 @@ func (o *Object) SetMetadata(ctx context.Context, metadata fs.Metadata) error {
updateReq.Description = value
case "favorite":
if favorite, err := strconv.ParseBool(value); err == nil {
updateReq.Favorite = new(favorite)
updateReq.Favorite = api.BoolPtr(favorite)
}
case "content-type":
// Allow setting/overriding MIME type
-34
View File
@@ -19,49 +19,15 @@ import (
"github.com/rclone/rclone/lib/encoder"
)
// Limits on the chunk size accepted by the resumable upload API
const (
minChunkSize = 256 * fs.Kibi
maxChunkSize = 64 * fs.Mebi
)
// TestIntegration runs integration tests against the remote
func TestIntegration(t *testing.T) {
fstests.Run(t, &fstests.Opt{
RemoteName: "TestHuaweiDrive:",
NilObject: (*Object)(nil),
SkipBadWindowsCharacters: true,
ChunkedUpload: fstests.ChunkedUploadConfig{
MinChunkSize: minChunkSize,
MaxChunkSize: maxChunkSize,
CeilChunkSize: fstests.NextPowerOfTwo,
},
})
}
// SetUploadChunkSize changes the configured chunk size, returning the old value.
//
// It is only called by the integration tests while no transfer is in progress.
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
var old fs.SizeSuffix
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
return old, nil
}
// SetUploadCutoff changes the configured upload cutoff, returning the old value.
//
// It is only called by the integration tests while no transfer is in progress.
func (f *Fs) SetUploadCutoff(cutoff fs.SizeSuffix) (fs.SizeSuffix, error) {
var old fs.SizeSuffix
old, f.opt.UploadCutoff = f.opt.UploadCutoff, cutoff
return old, nil
}
var (
_ fstests.SetUploadChunkSizer = (*Fs)(nil)
_ fstests.SetUploadCutoffer = (*Fs)(nil)
)
// TestNewFs tests the NewFs constructor
func TestNewFs(t *testing.T) {
ctx := context.Background()
+4 -3
View File
@@ -8,7 +8,6 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path"
@@ -1618,7 +1617,9 @@ func (ps *PhotosService) GetLibraryAlbumCounts(ctx context.Context) (map[string]
if err := ps.requestForArea(ctx, area, "internal/records/query/batch", map[string]any{"batch": batch}, &response); err != nil {
return nil, fmt.Errorf("failed to get library album counts: %w", err)
}
maps.Copy(counts, response.toCounts(order))
for k, v := range response.toCounts(order) {
counts[k] = v
}
}
return counts, nil
}
@@ -2031,7 +2032,7 @@ func (album *Album) fetchPhotosParallel(ctx context.Context, totalPhotos int64)
sem := make(chan struct{}, workers)
var wg sync.WaitGroup
for i := range numPartitions {
for i := 0; i < numPartitions; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
+2 -2
View File
@@ -1191,7 +1191,7 @@ func TestFlushCaches_NoPendingDeltaRace(t *testing.T) {
done := make(chan struct{})
go func() {
defer close(done)
for range 100 {
for i := 0; i < 100; i++ {
lib.deltaMu.Lock()
lib.pendingDelta = &deltaPayload{
records: []json.RawMessage{json.RawMessage(`{"recordName":"m1","recordType":"CPLMaster"}`)},
@@ -1201,7 +1201,7 @@ func TestFlushCaches_NoPendingDeltaRace(t *testing.T) {
lib.applyPendingDelta(context.Background())
}
}()
for range 100 {
for i := 0; i < 100; i++ {
ps.FlushCaches()
// Re-add the library since FlushCaches clears it
ps.mu.Lock()
+5 -3
View File
@@ -718,7 +718,7 @@ func (s *Session) GetAuthState(ctx context.Context) (*AuthStateResponse, error)
Path: "",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
ContentLength: new(int64(0)),
ContentLength: int64Ptr(0),
}
// Use srv.Call directly to capture the raw response body for debugging
resp, err := s.srv.Call(ctx, &opts)
@@ -828,7 +828,7 @@ func (s *Session) TrustSession(ctx context.Context) error {
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
NoResponse: true,
ContentLength: new(int64(0)),
ContentLength: int64Ptr(0),
}
_, err := s.Request(ctx, opts, nil, nil)
@@ -846,7 +846,7 @@ func (s *Session) ValidateSession(ctx context.Context) error {
Path: "/validate",
ExtraHeaders: s.GetHeaders(map[string]string{}),
RootURL: setupEndpoint,
ContentLength: new(int64(0)),
ContentLength: int64Ptr(0),
}
_, err := s.Request(ctx, opts, nil, &s.AccountInfo)
if err != nil {
@@ -904,6 +904,8 @@ func GetCommonHeaders(overwrite map[string]string) map[string]string {
return headers
}
func int64Ptr(v int64) *int64 { return &v }
// NewSession creates a new Session instance with default values
func NewSession() *Session {
session := &Session{
+6 -2
View File
@@ -376,7 +376,8 @@ func (f *PhotosFs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut
return "", false, nil
}
if libraryName, ok := strings.CutPrefix(pathID, "lib:"); ok {
if strings.HasPrefix(pathID, "lib:") {
libraryName := strings.TrimPrefix(pathID, "lib:")
libraries, err := photosService.GetLibraries(ctx)
if err != nil {
return "", false, err
@@ -735,7 +736,10 @@ func (f *PhotosFs) ListR(ctx context.Context, dir string, callback fs.ListRCallb
}
close(jobCh)
workers := min(len(jobs), fs.GetConfig(ctx).Checkers)
workers := fs.GetConfig(ctx).Checkers
if len(jobs) < workers {
workers = len(jobs)
}
errs := make(chan error, workers)
for range workers {
+6 -3
View File
@@ -54,7 +54,8 @@ func (f *Fs) shouldRetry(ctx context.Context, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
if httpErr, ok := errors.AsType[*sdkerrors.HTTPError](err); ok {
var httpErr *sdkerrors.HTTPError
if errors.As(err, &httpErr) {
switch httpErr.StatusCode() {
case 401:
if !f.authFailed {
@@ -1082,7 +1083,8 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
err := o.f.pacer.Call(func() (bool, error) {
err := files.DeleteFile(ctx, o.f.cfg, backupUUID)
if err != nil {
if httpErr, ok := errors.AsType[*sdkerrors.HTTPError](err); ok {
var httpErr *sdkerrors.HTTPError
if errors.As(err, &httpErr) {
// Treat 404 (Not Found) and 204 (No Content) as success
switch httpErr.StatusCode() {
case 404, 204:
@@ -1134,7 +1136,8 @@ func isEmptyFileLimitError(err error) bool {
// fileTooLargeError extracts the SDK's FileTooLargeError from a wrapped error
// chain, returning it (or nil) so callers can branch on the size limit.
func fileTooLargeError(err error) *sdkerrors.FileTooLargeError {
if tooLarge, ok := errors.AsType[*sdkerrors.FileTooLargeError](err); ok {
var tooLarge *sdkerrors.FileTooLargeError
if errors.As(err, &tooLarge) {
return tooLarge
}
return nil
+9 -11
View File
@@ -34,7 +34,6 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/list"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
@@ -1925,9 +1924,8 @@ func readMD5(in io.Reader, size, threshold int64) (md5sum string, out io.Reader,
// nothing to clean up by default
cleanup = func() {}
// don't cache small files on disk to reduce wear of the disk, but
// spool unknown sized streams there as they can't be bounded in memory
if size > threshold || size < 0 {
// don't cache small files on disk to reduce wear of the disk
if size > threshold {
var tempFile *os.File
// create the cache file
@@ -1957,15 +1955,15 @@ func readMD5(in io.Reader, size, threshold int64) (md5sum string, out io.Reader,
// replace the already read source with a reader of our cached file
out = tempFile
} else {
// that's a small file, just read it into memory from the global pool
rw := multipart.NewRW()
cleanup = func() {
_ = rw.Close()
}
if _, err = io.Copy(rw, teeReader); err != nil {
// that's a small file, just read it into memory
var inData []byte
inData, err = io.ReadAll(teeReader)
if err != nil {
return
}
out = rw
// set the reader to our read memory block
out = bytes.NewReader(inData)
}
return hex.EncodeToString(md5Hasher.Sum(nil)), out, cleanup, nil
}
+1 -34
View File
@@ -5,14 +5,12 @@ import (
"crypto/md5"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/readers"
"github.com/stretchr/testify/assert"
@@ -30,16 +28,11 @@ func TestReadMD5(t *testing.T) {
wantMD5 := fmt.Sprintf("%x", hasher.Sum(nil))
for _, threshold := range []int64{512, 1024, 10 * 1024, 20 * 1024} {
t.Run(fmt.Sprintf("%d", threshold), func(t *testing.T) {
inUse := pool.Global().InUse()
in := readers.NewPatternReader(size)
gotMD5, out, cleanup, err := readMD5(in, size, threshold)
defer cleanup()
require.NoError(t, err)
assert.Equal(t, wantMD5, gotMD5)
if size > threshold {
assert.IsType(t, (*os.File)(nil), out, "big files should be spooled to disk")
} else {
assert.IsType(t, (*pool.RW)(nil), out, "small files should be buffered in the pool")
}
// check md5hash of out
hasher := md5.New()
@@ -48,36 +41,10 @@ func TestReadMD5(t *testing.T) {
assert.Equal(t, n, size)
outMD5 := fmt.Sprintf("%x", hasher.Sum(nil))
assert.Equal(t, wantMD5, outMD5)
// check cleanup returns the buffer to the pool
cleanup()
assert.Equal(t, inUse, pool.Global().InUse(), "pool buffers leaked")
})
}
})
}
// Unknown sized streams can't be bounded in memory so must be spooled to disk
t.Run("UnknownSize", func(t *testing.T) {
const size = 1024
inUse := pool.Global().InUse()
hasher := md5.New()
_, err := io.Copy(hasher, readers.NewPatternReader(size))
require.NoError(t, err)
wantMD5 := fmt.Sprintf("%x", hasher.Sum(nil))
gotMD5, out, cleanup, err := readMD5(readers.NewPatternReader(size), -1, 10*size)
require.NoError(t, err)
assert.Equal(t, wantMD5, gotMD5)
assert.IsType(t, (*os.File)(nil), out)
hasher.Reset()
n, err := io.Copy(hasher, out)
require.NoError(t, err)
assert.Equal(t, int64(size), n)
assert.Equal(t, wantMD5, fmt.Sprintf("%x", hasher.Sum(nil)))
cleanup()
assert.Equal(t, inUse, pool.Global().InUse())
})
}
func (f *Fs) InternalTestMetadata(t *testing.T) {
+9 -28
View File
@@ -11,10 +11,10 @@ package linkbox
*/
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -35,9 +35,7 @@ import (
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/rest"
)
@@ -48,8 +46,7 @@ const (
pacerBurst = 1
linkboxAPIURL = "https://www.linkbox.to/api/open/"
linkboxWebAPIURL = "https://www.linkbox.to/api/"
rootID = "0" // ID of root directory
prefixSize = 10 * 1024 * 1024 // the API wants the MD5 of the first 10 MiB of a file
rootID = "0" // ID of root directory
)
func init() {
@@ -670,21 +667,6 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
return res.Body, nil
}
// readPrefix reads up to prefixSize bytes of in into a buffer from the
// global pool returning it along with the hex MD5 of what was read.
//
// The caller must Close the returned buffer when done with it.
func readPrefix(in io.Reader) (rw *pool.RW, md5sum string, err error) {
rw = multipart.NewRW()
hasher := md5.New()
_, err = io.CopyN(rw, io.TeeReader(in, hasher), prefixSize)
if err != nil && err != io.EOF {
_ = rw.Close()
return nil, "", err
}
return rw, hex.EncodeToString(hasher.Sum(nil)), nil
}
// Update in to the object with the modTime given of the given size
//
// When called from outside an Fs by rclone, src.Size() will always be >= 0.
@@ -719,13 +701,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
}
prefix, prefixMD5, err := readPrefix(in)
first10m := io.LimitReader(in, 10_485_760)
first10mBytes, err := io.ReadAll(first10m)
if err != nil {
return fmt.Errorf("Update err in reading file: %w", err)
}
defer func() {
_ = prefix.Close()
}()
// get upload authorization (step 1)
opts := &rest.Opts{
@@ -735,7 +715,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
Options: options,
Parameters: url.Values{
"token": {o.fs.opt.Token},
"fileMd5ofPre10m": {prefixMD5},
"fileMd5ofPre10m": {fmt.Sprintf("%x", md5.Sum(first10mBytes))},
"fileSize": {itoa64(size)},
},
}
@@ -777,7 +757,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return fmt.Errorf("head upload URL: %w", err)
}
file := io.MultiReader(prefix, in)
file := io.MultiReader(bytes.NewReader(first10mBytes), in)
opts.Method = "PUT"
opts.Body = file
@@ -817,7 +797,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
Options: options,
Parameters: url.Values{
"token": {o.fs.opt.Token},
"fileMd5ofPre10m": {prefixMD5},
"fileMd5ofPre10m": {fmt.Sprintf("%x", md5.Sum(first10mBytes))},
"fileSize": {itoa64(size)},
"pid": {dirID},
"diyName": {leaf},
@@ -1039,7 +1019,8 @@ func (f *Fs) shouldRetry(ctx context.Context, resp *http.Response, err error) (b
// intermittently returns an HTML challenge page with a 200
// status instead of JSON. This surfaces as a JSON syntax error,
// so retry it to let the pacer back off until the block lifts.
if _, ok := errors.AsType[*json.SyntaxError](err); ok {
var syntaxErr *json.SyntaxError
if errors.As(err, &syntaxErr) {
return true, err
}
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
-41
View File
@@ -1,41 +0,0 @@
package linkbox
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"testing"
"github.com/rclone/rclone/lib/pool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReadPrefix(t *testing.T) {
for _, size := range []int64{1, 1024, prefixSize - 1, prefixSize, prefixSize + 1, 3 * prefixSize} {
t.Run(fmt.Sprintf("%d", size), func(t *testing.T) {
inUse := pool.Global().InUse()
content := bytes.Repeat([]byte("x"), int(size))
for i := range content {
content[i] = byte(i)
}
wantPrefix := content[:min(size, prefixSize)]
wantMD5 := fmt.Sprintf("%x", md5.Sum(wantPrefix))
in := bytes.NewReader(content)
rw, gotMD5, err := readPrefix(in)
require.NoError(t, err)
assert.Equal(t, wantMD5, gotMD5)
assert.Equal(t, int64(len(wantPrefix)), rw.Size())
// The prefix followed by the rest of in must reproduce the content
got, err := io.ReadAll(io.MultiReader(rw, in))
require.NoError(t, err)
assert.Equal(t, content, got)
require.NoError(t, rw.Close())
assert.Equal(t, inUse, pool.Global().InUse(), "pool buffers leaked")
})
}
}
+3 -4
View File
@@ -1699,13 +1699,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
out = nopWriterCloser{&symlinkData}
}
// Calculate the hash of the object as we write it
var w io.Writer = out
// Calculate the hash of the object we are reading as we go along
if hasher != nil {
w = io.MultiWriter(w, hasher)
in = io.TeeReader(in, hasher)
}
_, err = io.Copy(w, in)
_, err = io.Copy(out, in)
closeErr := out.Close()
if err == nil {
err = closeErr
-44
View File
@@ -97,19 +97,7 @@ func TestVerifyCopy(t *testing.T) {
assert.Error(t, err)
}
// skipIfNoSymlinks skips the test if this process can't create symlinks.
//
// Windows grants the privilege only to an elevated process or one running with
// Developer Mode enabled, so an ordinary user gets ERROR_PRIVILEGE_NOT_HELD.
func skipIfNoSymlinks(t *testing.T) {
t.Helper()
if err := os.Symlink("target", filepath.Join(t.TempDir(), "link")); err != nil {
t.Skipf("Skipping as symlinks are unavailable: %v", err)
}
}
func TestSymlink(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
@@ -277,7 +265,6 @@ func linksMode(f *Fs) {
// faithful backup of the source) but must refuse to write through it, so
// nothing lands outside the destination (CWE-59).
func TestSymlinkEscapeWriteThroughBlocked(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
// A directory outside the destination the attacker wants to write into
@@ -313,7 +300,6 @@ func TestSymlinkEscapeWriteThroughBlocked(t *testing.T) {
// re-validated against the root, so the write-through is refused and nothing
// escapes.
func TestSymlinkEscapeNestedBlocked(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
evil := t.TempDir()
@@ -365,7 +351,6 @@ func TestSymlinkEscapeConcurrent(t *testing.T) {
// use: an in-tree symlink to a sibling directory can still be created and
// written through, since that write stays inside the destination.
func TestSymlinkInTreeWriteThroughWorks(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
r := fstest.NewRun(t)
@@ -668,32 +653,6 @@ func TestHashOnUpdate(t *testing.T) {
assert.Equal(t, "45685e95985e20822fb2538a522a5ccf", md5)
}
// Test the hash cached by Update matches a HashesOption hint passed by the caller
func TestHashOnUpdateWithHashOption(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
const filePath = "file.txt"
when := time.Now()
r.WriteFile(filePath, "x", when)
f := r.Flocal.(*Fs)
o, err := f.NewObject(ctx, filePath)
require.NoError(t, err)
b := bytes.NewBufferString("content")
src := object.NewStaticObjectInfo(filePath, when, int64(b.Len()), true, nil, f)
options := []fs.OpenOption{&fs.HashesOption{Hashes: hash.NewHashSet(hash.MD5)}}
require.NoError(t, o.Update(ctx, b, src, options...))
gotContent, err := os.ReadFile(filepath.Join(f.root, filePath))
require.NoError(t, err)
assert.Equal(t, "content", string(gotContent))
md5, err := o.Hash(ctx, hash.MD5)
require.NoError(t, err)
assert.Equal(t, "9a0364b9e99bb480dd25e1f0284c8555", md5)
}
// Test hashes on deleting an object
func TestHashOnDelete(t *testing.T) {
ctx := context.Background()
@@ -724,7 +683,6 @@ func TestHashOnDelete(t *testing.T) {
}
func TestMetadata(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
r := fstest.NewRun(t)
const filePath = "metafile.txt"
@@ -1001,7 +959,6 @@ func TestFilter(t *testing.T) {
}
func testFilterSymlink(t *testing.T, copyLinks bool) {
skipIfNoSymlinks(t)
ctx := context.Background()
r := fstest.NewRun(t)
defer r.Finalise()
@@ -1106,7 +1063,6 @@ func TestFilterSymlinkLinks(t *testing.T) {
}
func TestCopySymlink(t *testing.T) {
skipIfNoSymlinks(t)
ctx := context.Background()
r := fstest.NewRun(t)
defer r.Finalise()
+8 -17
View File
@@ -36,7 +36,6 @@ import (
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
@@ -1615,6 +1614,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
var (
fileBuf []byte
fileHash []byte
newHash []byte
slowHash bool
@@ -1660,19 +1660,15 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Attempt to put by calculating hash in memory
if trySpeedup && size <= int64(o.fs.opt.SpeedupMaxMem) {
rw := multipart.NewRW()
defer func() {
_ = rw.Close()
}()
hasher := mrhash.New()
if _, err = io.Copy(rw, io.TeeReader(in, hasher)); err != nil {
fileBuf, err = io.ReadAll(in)
if err != nil {
return err
}
fileHash = hasher.Sum(nil)
fileHash = mrhash.Sum(fileBuf)
if o.putByHash(ctx, fileHash, src, "memory") {
return nil
}
wrapIn = rw
wrapIn = bytes.NewReader(fileBuf)
trySpeedup = false // speedup failed, force upload
}
@@ -1706,8 +1702,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Upload object data
if size <= mrhash.Size {
// Optimize upload: skip extra request if data fits in the hash buffer.
var fileBuf []byte
fileBuf, err = io.ReadAll(wrapIn)
if fileBuf == nil {
fileBuf, err = io.ReadAll(wrapIn)
}
if fileHash == nil && err == nil {
fileHash = mrhash.Sum(fileBuf)
}
@@ -1872,12 +1869,6 @@ func (o *Object) upload(ctx context.Context, in io.Reader, size int64, options .
strHash string
)
err = o.fs.pacer.Call(func() (bool, error) {
// Rewind seekable bodies so a retry resends the whole file
if seeker, ok := in.(io.Seeker); ok {
if _, err := seeker.Seek(0, io.SeekStart); err != nil {
return false, err
}
}
res, err = o.fs.srv.Call(ctx, &opts)
if err == nil {
strHash, err = readBodyWord(res)
-65
View File
@@ -1,65 +0,0 @@
package mailru
import (
"bytes"
"context"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/rclone/rclone/backend/mailru/mrhash"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)
// TestUploadRetry checks that an upload from a seekable pooled buffer
// whose first attempt fails with a retriable error is retried with the
// full body rather than the drained reader.
func TestUploadRetry(t *testing.T) {
content := bytes.Repeat([]byte("mailru"), 512)
wantHash := mrhash.Sum(content)
var attempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
if attempts.Add(1) == 1 {
// Drop the connection so the client sees a retriable error
conn, _, err := w.(http.Hijacker).Hijack()
require.NoError(t, err)
_ = conn.Close()
return
}
assert.Equal(t, content, body, "retried upload should re-send the full body")
_, _ = w.Write([]byte(hex.EncodeToString(wantHash) + "\n"))
}))
defer server.Close()
ctx := context.Background()
f := &Fs{
srv: rest.NewClient(server.Client()),
source: oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "token"}),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(10*time.Millisecond))),
shardURL: server.URL,
shardExpiry: time.Now().Add(time.Hour),
}
o := &Object{fs: f, remote: "remote"}
rw := multipart.NewRW()
defer func() { _ = rw.Close() }()
_, err := rw.Write(content)
require.NoError(t, err)
gotHash, err := o.upload(ctx, rw, int64(len(content)))
require.NoError(t, err)
assert.Equal(t, wantHash, gotHash)
assert.Equal(t, int32(2), attempts.Load(), "expected exactly one failed attempt and one retry")
}
+3 -17
View File
@@ -37,9 +37,9 @@ import (
"github.com/rclone/rclone/lib/atexit"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -2748,26 +2748,12 @@ func (o *Object) uploadMultipart(ctx context.Context, in io.Reader, src fs.Objec
position := int64(0)
for remaining > 0 {
n := min(remaining, int64(o.fs.opt.ChunkSize))
// Buffer the chunk in memory from the global pool so it can be
// re-sent (or partly re-sent after a 416) on retry
rw := multipart.NewRW()
_, err = io.CopyN(rw, in, n)
if err != nil {
_ = rw.Close()
if err == io.EOF {
err = fmt.Errorf("expected %d bytes in input, but got %d: %w", size, position, io.ErrUnexpectedEOF)
}
return nil, err
}
seg := readers.NewRepeatableReader(io.LimitReader(in, n))
fs.Debugf(o, "Uploading segment %d/%d size %d", position, size, n)
info, err = o.uploadFragment(ctx, uploadURL, position, size, rw, n, options...)
closeErr := rw.Close()
info, err = o.uploadFragment(ctx, uploadURL, position, size, seg, n, options...)
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
remaining -= n
position += n
}
-120
View File
@@ -1,120 +0,0 @@
package onedrive
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// fragmentServer is a fake OneDrive upload session which records the
// fragments it receives. fail is called for each PUT before the body is
// accepted and may write an error response, returning true to reject it.
type fragmentServer struct {
t *testing.T
size int64
mu sync.Mutex
received []byte // bytes accepted so far
fragments int // number of accepted fragments
fail func(w http.ResponseWriter, attempt int) bool
attempts int
}
func (s *fragmentServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
switch {
case r.Method == "POST" && r.URL.Path == "/root/createUploadSession":
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"uploadUrl":"http://%s/upload","nextExpectedRanges":["0-"]}`, r.Host)
case r.Method == "GET" && r.URL.Path == "/upload":
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"nextExpectedRanges":["%d-%d"]}`, len(s.received), s.size-1)
case r.Method == "PUT" && r.URL.Path == "/upload":
body, err := io.ReadAll(r.Body)
require.NoError(s.t, err)
s.attempts++
if s.fail != nil && s.fail(w, s.attempts) {
return
}
var start, end, total int64
_, err = fmt.Sscanf(r.Header.Get("Content-Range"), "bytes %d-%d/%d", &start, &end, &total)
require.NoError(s.t, err)
assert.Equal(s.t, int64(len(s.received)), start, "fragment sent out of order")
assert.Equal(s.t, int64(len(body)), end-start+1, "Content-Range disagrees with body length")
assert.Equal(s.t, s.size, total)
s.received = append(s.received, body...)
s.fragments++
w.Header().Set("Content-Type", "application/json")
if int64(len(s.received)) == s.size {
w.WriteHeader(http.StatusCreated)
_, _ = fmt.Fprintf(w, `{"id":"fake-id","name":"remote","size":%d,"file":{}}`, s.size)
return
}
w.WriteHeader(http.StatusAccepted)
_, _ = fmt.Fprintf(w, `{"nextExpectedRanges":["%d-%d"]}`, len(s.received), s.size-1)
default:
s.t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}
// newUploadTest returns an Object wired to a fragmentServer which
// uploads content in chunks of chunkSize.
func newUploadTest(t *testing.T, content []byte, chunkSize int) (*Object, *fragmentServer, *httptest.Server) {
s := &fragmentServer{t: t, size: int64(len(content))}
server := httptest.NewServer(s)
t.Cleanup(server.Close)
client := rest.NewClient(server.Client()).SetRoot(server.URL)
f := &Fs{
ci: fs.GetConfig(context.Background()),
srv: client,
unAuth: client,
pacer: fs.NewPacer(context.Background(), pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(10*time.Millisecond))),
}
f.opt.ChunkSize = fs.SizeSuffix(chunkSize)
f.opt.UploadCutoff = fs.SizeSuffix(chunkSize)
return &Object{fs: f}, s, server
}
// TestUploadMultipartSkip checks that a 416 response makes the upload
// read the server's position and re-send only the unreceived tail of
// the fragment.
func TestUploadMultipartSkip(t *testing.T) {
content := bytes.Repeat([]byte("onedrive"), 1024)
chunkSize := len(content) / 2
skip := chunkSize / 4
o, s, _ := newUploadTest(t, content, chunkSize)
s.fail = func(w http.ResponseWriter, attempt int) bool {
if attempt == 1 {
// Pretend the first part of the fragment was received
// before the connection broke
s.received = append(s.received, content[:skip]...)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusRequestedRangeNotSatisfiable)
_ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"code": "invalidRange", "message": "bad range"}})
return true
}
return false
}
src := object.NewStaticObjectInfo("remote", time.Now(), int64(len(content)), true, nil, nil)
info, err := o.uploadMultipart(context.Background(), bytes.NewReader(content), src)
require.NoError(t, err)
require.NotNil(t, info)
assert.Equal(t, content, s.received)
assert.Equal(t, 2, s.fragments)
assert.Equal(t, 3, s.attempts, "expected one 416, a partial re-send and the final fragment")
}
+5 -18
View File
@@ -23,8 +23,8 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -1047,6 +1047,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// resp.Body.Close()
// fs.Debugf(nil, "PostOpen: %#v", openResponse)
buf := make([]byte, o.fs.opt.ChunkSize)
chunkOffset := int64(0)
remainingBytes := size
chunkCounter := 0
@@ -1056,27 +1057,17 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
remainingBytes -= currentChunkSize
fs.Debugf(o, "Uploading chunk %d, size=%d, remain=%d", chunkCounter, currentChunkSize, remainingBytes)
// Buffer the chunk in memory from the global pool so reads are
// repeatable for retries
rw := multipart.NewRW()
_, err = io.CopyN(rw, in, currentChunkSize)
if err != nil {
_ = rw.Close()
if err == io.EOF {
err = fmt.Errorf("short read of chunk %d: %w", chunkCounter, io.ErrUnexpectedEOF)
}
return fmt.Errorf("failed to create file: %w", err)
}
chunk := readers.NewRepeatableLimitReaderBuffer(in, buf, currentChunkSize)
var reply uploadFileChunkReply
err = o.fs.pacer.Call(func() (bool, error) {
// seek to the start in case this is a retry
if _, err = rw.Seek(0, io.SeekStart); err != nil {
if _, err = chunk.Seek(0, io.SeekStart); err != nil {
return false, err
}
opts := rest.Opts{
Method: "POST",
Path: "/upload/upload_file_chunk.json",
Body: rw,
Body: chunk,
MultipartParams: url.Values{
"session_id": []string{o.fs.session.SessionID},
"file_id": []string{o.id},
@@ -1091,13 +1082,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
resp, err = o.fs.srv.CallJSON(ctx, &opts, nil, &reply)
return o.fs.shouldRetry(ctx, resp, err)
})
closeErr := rw.Close()
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
if closeErr != nil {
return fmt.Errorf("failed to create file: %w", closeErr)
}
if reply.TotalWritten != currentChunkSize {
return fmt.Errorf("failed to create file: incomplete write of %d/%d bytes", reply.TotalWritten, currentChunkSize)
}
@@ -1,17 +0,0 @@
package opendrive
import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest/fstests"
)
// SetUploadChunkSize changes the configured chunk size, returning the old value.
//
// It is only called by the integration tests while no transfer is in progress.
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
var old fs.SizeSuffix
old, f.opt.ChunkSize = f.opt.ChunkSize, cs
return old, nil
}
var _ fstests.SetUploadChunkSizer = (*Fs)(nil)
-3
View File
@@ -13,8 +13,5 @@ func TestIntegration(t *testing.T) {
fstests.Run(t, &fstests.Opt{
RemoteName: "TestOpenDrive:",
NilObject: (*opendrive.Object)(nil),
ChunkedUpload: fstests.ChunkedUploadConfig{
MinChunkSize: 1,
},
})
}
+15 -14
View File
@@ -10,6 +10,7 @@ import (
"os"
"strings"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/objectstorage"
)
@@ -72,54 +73,54 @@ func populateSSECustomerKeys(opt *Options) error {
// https://docs.oracle.com/en-us/iaas/Content/Object/Tasks/usingyourencryptionkeys.htm
func useBYOKPutObject(fs *Fs, request *objectstorage.PutObjectRequest) {
if fs.opt.SSEKMSKeyID != "" {
request.OpcSseKmsKeyId = new(fs.opt.SSEKMSKeyID)
request.OpcSseKmsKeyId = common.String(fs.opt.SSEKMSKeyID)
}
if fs.opt.SSECustomerAlgorithm != "" {
request.OpcSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
request.OpcSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
}
if fs.opt.SSECustomerKey != "" {
request.OpcSseCustomerKey = new(fs.opt.SSECustomerKey)
request.OpcSseCustomerKey = common.String(fs.opt.SSECustomerKey)
}
if fs.opt.SSECustomerKeySha256 != "" {
request.OpcSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
request.OpcSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
}
}
func useBYOKHeadObject(fs *Fs, request *objectstorage.HeadObjectRequest) {
if fs.opt.SSECustomerAlgorithm != "" {
request.OpcSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
request.OpcSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
}
if fs.opt.SSECustomerKey != "" {
request.OpcSseCustomerKey = new(fs.opt.SSECustomerKey)
request.OpcSseCustomerKey = common.String(fs.opt.SSECustomerKey)
}
if fs.opt.SSECustomerKeySha256 != "" {
request.OpcSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
request.OpcSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
}
}
func useBYOKGetObject(fs *Fs, request *objectstorage.GetObjectRequest) {
if fs.opt.SSECustomerAlgorithm != "" {
request.OpcSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
request.OpcSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
}
if fs.opt.SSECustomerKey != "" {
request.OpcSseCustomerKey = new(fs.opt.SSECustomerKey)
request.OpcSseCustomerKey = common.String(fs.opt.SSECustomerKey)
}
if fs.opt.SSECustomerKeySha256 != "" {
request.OpcSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
request.OpcSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
}
}
func useBYOKCopyObject(fs *Fs, request *objectstorage.CopyObjectRequest) {
if fs.opt.SSEKMSKeyID != "" {
request.OpcSseKmsKeyId = new(fs.opt.SSEKMSKeyID)
request.OpcSseKmsKeyId = common.String(fs.opt.SSEKMSKeyID)
}
if fs.opt.SSECustomerAlgorithm != "" {
request.OpcSseCustomerAlgorithm = new(fs.opt.SSECustomerAlgorithm)
request.OpcSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
}
if fs.opt.SSECustomerKey != "" {
request.OpcSseCustomerKey = new(fs.opt.SSECustomerKey)
request.OpcSseCustomerKey = common.String(fs.opt.SSECustomerKey)
}
if fs.opt.SSECustomerKeySha256 != "" {
request.OpcSseCustomerKeySha256 = new(fs.opt.SSECustomerKeySha256)
request.OpcSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
}
}
+3 -2
View File
@@ -10,7 +10,6 @@ import (
"encoding/base64"
"encoding/hex"
"io"
"maps"
"net/http"
"net/http/httptest"
"strconv"
@@ -63,7 +62,9 @@ func TestGzipEncoding(t *testing.T) {
"namespace": "test",
"endpoint": srv.URL,
}
maps.Copy(m, extraConfig)
for k, v := range extraConfig {
m[k] = v
}
fsInfo, err := NewFs(ctx, "TestOOSGzip", "bucket", m)
require.NoError(t, err)
return fsInfo.(*Fs)
+12 -12
View File
@@ -198,12 +198,12 @@ func (f *Fs) rename(ctx context.Context, remote, newName string) (any, error) {
return nil, fs.ErrorNotAFile
}
details := objectstorage.RenameObjectDetails{
SourceName: new(objectPath),
NewName: new(newName),
SourceName: common.String(objectPath),
NewName: common.String(newName),
}
request := objectstorage.RenameObjectRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucketName),
RenameObjectDetails: details,
OpcClientRequestId: nil,
RequestMetadata: common.RequestMetadata{},
@@ -284,8 +284,8 @@ func (f *Fs) listMultipartUploadsObject(ctx context.Context, bucketName, directo
uploads = []*objectstorage.MultipartUpload{}
req := objectstorage.ListMultipartUploadsRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucketName),
}
var response objectstorage.ListMultipartUploadsResponse
@@ -322,11 +322,11 @@ func (f *Fs) listMultipartUploadParts(ctx context.Context, bucketName, bucketPat
uploadedParts map[int]objectstorage.MultipartUploadPartSummary, err error) {
uploadedParts = make(map[int]objectstorage.MultipartUploadPartSummary)
req := objectstorage.ListMultipartUploadPartsRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
ObjectName: new(bucketPath),
UploadId: new(uploadID),
Limit: new(1000),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucketName),
ObjectName: common.String(bucketPath),
UploadId: common.String(uploadID),
Limit: common.Int(1000),
}
var response objectstorage.ListMultipartUploadPartsResponse
@@ -351,7 +351,7 @@ func (f *Fs) listMultipartUploadParts(ctx context.Context, bucketName, bucketPat
func (f *Fs) restore(ctx context.Context, opt map[string]string) (any, error) {
req := objectstorage.RestoreObjectsRequest{
NamespaceName: new(f.opt.Namespace),
NamespaceName: common.String(f.opt.Namespace),
RestoreObjectsDetails: objectstorage.RestoreObjectsDetails{},
}
if hours := opt["hours"]; hours != "" {
+8 -7
View File
@@ -8,6 +8,7 @@ import (
"strings"
"time"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/objectstorage"
"github.com/rclone/rclone/fs"
)
@@ -60,16 +61,16 @@ func (f *Fs) copy(ctx context.Context, dstObj *Object, srcObj *Object) (err erro
}
}
copyObjectDetails := objectstorage.CopyObjectDetails{
SourceObjectName: new(srcPath),
DestinationRegion: new(dstObj.fs.opt.Region),
DestinationNamespace: new(dstObj.fs.opt.Namespace),
DestinationBucket: new(dstBucket),
DestinationObjectName: new(dstPath),
SourceObjectName: common.String(srcPath),
DestinationRegion: common.String(dstObj.fs.opt.Region),
DestinationNamespace: common.String(dstObj.fs.opt.Namespace),
DestinationBucket: common.String(dstBucket),
DestinationObjectName: common.String(dstPath),
DestinationObjectMetadata: metadataWithOpcPrefix(srcObj.meta),
}
req := objectstorage.CopyObjectRequest{
NamespaceName: new(srcObj.fs.opt.Namespace),
BucketName: new(srcBucket),
NamespaceName: common.String(srcObj.fs.opt.Namespace),
BucketName: common.String(srcBucket),
CopyObjectDetails: copyObjectDetails,
}
useBYOKCopyObject(f, &req)
+14 -14
View File
@@ -161,13 +161,13 @@ func (w *objectChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, rea
}
}
req := objectstorage.UploadPartRequest{
NamespaceName: new(w.f.opt.Namespace),
NamespaceName: common.String(w.f.opt.Namespace),
BucketName: w.bucket,
ObjectName: w.key,
UploadId: w.uploadID,
UploadPartNum: new(ossPartNumber),
ContentLength: new(currentChunkSize),
ContentMD5: new(md5sum),
UploadPartNum: common.Int(ossPartNumber),
ContentLength: common.Int64(currentChunkSize),
ContentMD5: common.String(md5sum),
}
w.o.applyPartUploadOptions(w.ui.req, &req)
var resp objectstorage.UploadPartResponse
@@ -213,7 +213,7 @@ func (w *objectChunkWriter) addCompletedPart(partNum *int, eTag *string) {
func (w *objectChunkWriter) Close(ctx context.Context) (err error) {
req := objectstorage.CommitMultipartUploadRequest{
NamespaceName: new(w.f.opt.Namespace),
NamespaceName: common.String(w.f.opt.Namespace),
BucketName: w.bucket,
ObjectName: w.key,
UploadId: w.uploadID,
@@ -290,9 +290,9 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
bucket, bucketPath := o.split()
ui.req = &objectstorage.PutObjectRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucket),
ObjectName: new(bucketPath),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucket),
ObjectName: common.String(bucketPath),
}
// Set the mtime in the metadata
@@ -305,7 +305,7 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
ui.req.OpcMeta = make(map[string]string, len(meta)+2)
// merge metadata into request and user metadata
for k, v := range meta {
pv := new(v)
pv := common.String(v)
k = strings.ToLower(k)
switch k {
case "cache-control":
@@ -366,10 +366,10 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
}
// Set the content type if it isn't set already
if ui.req.ContentType == nil {
ui.req.ContentType = new(fs.MimeType(ctx, src))
ui.req.ContentType = common.String(fs.MimeType(ctx, src))
}
if size >= 0 {
ui.req.ContentLength = new(size)
ui.req.ContentLength = common.Int64(size)
}
if md5sumBase64 != "" {
ui.req.ContentMD5 = &md5sumBase64
@@ -420,10 +420,10 @@ func (o *Object) createMultipartUpload(ctx context.Context, putReq *objectstorag
}
}
req := objectstorage.CreateMultipartUploadRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucketName),
}
req.Object = new(bucketPath)
req.Object = common.String(bucketPath)
if o.fs.opt.StorageTier != "" {
storageTier, ok := objectstorage.GetMappingStorageTierEnum(o.fs.opt.StorageTier)
if !ok {
+22 -22
View File
@@ -83,9 +83,9 @@ func (o *Object) readMetaData(ctx context.Context) (err error) {
func (o *Object) headObject(ctx context.Context) (info *objectstorage.HeadObjectResponse, err error) {
bucketName, objectPath := o.split()
req := objectstorage.HeadObjectRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucketName),
ObjectName: new(objectPath),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucketName),
ObjectName: common.String(objectPath),
}
useBYOKHeadObject(o.fs, &req)
var response objectstorage.HeadObjectResponse
@@ -235,10 +235,10 @@ func (o *Object) SetTier(tier string) (err error) {
}
req := objectstorage.UpdateObjectStorageTierRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucketName),
UpdateObjectStorageTierDetails: objectstorage.UpdateObjectStorageTierDetails{
ObjectName: new(bucketPath),
ObjectName: common.String(bucketPath),
StorageTier: tierEnum,
},
}
@@ -321,9 +321,9 @@ func (o *Object) Storable() bool {
func (o *Object) Remove(ctx context.Context) error {
bucketName, bucketPath := o.split()
req := objectstorage.DeleteObjectRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucketName),
ObjectName: new(bucketPath),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucketName),
ObjectName: common.String(bucketPath),
}
err := o.fs.pacer.Call(func() (bool, error) {
resp, err := o.fs.srv.DeleteObject(ctx, req)
@@ -336,9 +336,9 @@ func (o *Object) Remove(ctx context.Context) error {
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
bucketName, bucketPath := o.split()
req := objectstorage.GetObjectRequest{
NamespaceName: new(o.fs.opt.Namespace),
BucketName: new(bucketName),
ObjectName: new(bucketPath),
NamespaceName: common.String(o.fs.opt.Namespace),
BucketName: common.String(bucketName),
ObjectName: common.String(bucketPath),
}
o.applyGetObjectOptions(&req, options...)
useBYOKGetObject(o.fs, &req)
@@ -456,15 +456,15 @@ func (o *Object) applyPutOptions(req *objectstorage.PutObjectRequest, options ..
case "":
// ignore
case "cache-control":
req.CacheControl = new(value)
req.CacheControl = common.String(value)
case "content-disposition":
req.ContentDisposition = new(value)
req.ContentDisposition = common.String(value)
case "content-encoding":
req.ContentEncoding = new(value)
req.ContentEncoding = common.String(value)
case "content-language":
req.ContentLanguage = new(value)
req.ContentLanguage = common.String(value)
case "content-type":
req.ContentType = new(value)
req.ContentType = common.String(value)
default:
if strings.HasPrefix(lowerKey, ociMetaPrefix) {
req.OpcMeta[lowerKey] = value
@@ -496,15 +496,15 @@ func (o *Object) applyGetObjectOptions(req *objectstorage.GetObjectRequest, opti
case "":
// ignore
case "cache-control":
req.HttpResponseCacheControl = new(value)
req.HttpResponseCacheControl = common.String(value)
case "content-disposition":
req.HttpResponseContentDisposition = new(value)
req.HttpResponseContentDisposition = common.String(value)
case "content-encoding":
req.HttpResponseContentEncoding = new(value)
req.HttpResponseContentEncoding = common.String(value)
case "content-language":
req.HttpResponseContentLanguage = new(value)
req.HttpResponseContentLanguage = common.String(value)
case "content-type":
req.HttpResponseContentType = new(value)
req.HttpResponseContentType = common.String(value)
case "range":
// do nothing
default:
@@ -329,14 +329,14 @@ func (f *Fs) list(ctx context.Context, bucket, directory, prefix string, addBuck
chunkSize = limit
}
var request = objectstorage.ListObjectsRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucket),
Prefix: new(directory),
Limit: new(chunkSize),
Fields: new("name,size,etag,timeCreated,md5,timeModified,storageTier,archivalState"),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucket),
Prefix: common.String(directory),
Limit: common.Int(chunkSize),
Fields: common.String("name,size,etag,timeCreated,md5,timeModified,storageTier,archivalState"),
}
if delimiter != "" {
request.Delimiter = new(delimiter)
request.Delimiter = common.String(delimiter)
}
for {
@@ -471,8 +471,8 @@ func (f *Fs) listBuckets(ctx context.Context) (entries fs.DirEntries, err error)
return nil, fmt.Errorf("can't list buckets with %v provider, use a valid auth provider in config file", noAuth)
}
var request = objectstorage.ListBucketsRequest{
NamespaceName: new(f.opt.Namespace),
CompartmentId: new(f.opt.Compartment),
NamespaceName: common.String(f.opt.Namespace),
CompartmentId: common.String(f.opt.Compartment),
}
var resp objectstorage.ListBucketsResponse
for {
@@ -569,12 +569,12 @@ func (f *Fs) makeBucket(ctx context.Context, bucketName string) error {
}
return f.cache.Create(bucketName, func() error {
details := objectstorage.CreateBucketDetails{
Name: new(bucketName),
CompartmentId: new(f.opt.Compartment),
Name: common.String(bucketName),
CompartmentId: common.String(f.opt.Compartment),
PublicAccessType: objectstorage.CreateBucketDetailsPublicAccessTypeNopublicaccess,
}
req := objectstorage.CreateBucketRequest{
NamespaceName: new(f.opt.Namespace),
NamespaceName: common.String(f.opt.Namespace),
CreateBucketDetails: details,
}
err := f.pacer.Call(func() (bool, error) {
@@ -601,8 +601,8 @@ func (f *Fs) makeBucket(ctx context.Context, bucketName string) error {
// NB this can return incorrect results if called immediately after bucket deletion
func (f *Fs) bucketExists(ctx context.Context, bucketName string) (bool, error) {
req := objectstorage.HeadBucketRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucketName),
}
err := f.pacer.Call(func() (bool, error) {
resp, err := f.srv.HeadBucket(ctx, req)
@@ -627,8 +627,8 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
}
return f.cache.Remove(bucketName, func() error {
req := objectstorage.DeleteBucketRequest{
NamespaceName: new(f.opt.Namespace),
BucketName: new(bucketName),
NamespaceName: common.String(f.opt.Namespace),
BucketName: common.String(bucketName),
}
err := f.pacer.Call(func() (bool, error) {
resp, err := f.srv.DeleteBucket(ctx, req)
@@ -646,7 +646,7 @@ func (f *Fs) abortMultiPartUpload(ctx context.Context, bucketName, bucketPath, u
return nil
}
request := objectstorage.AbortMultipartUploadRequest{
NamespaceName: new(f.opt.Namespace),
NamespaceName: common.String(f.opt.Namespace),
BucketName: bucketName,
ObjectName: bucketPath,
UploadId: uploadID,
+5 -10
View File
@@ -1,6 +1,7 @@
package pikpak
import (
"bytes"
"context"
"crypto/md5"
"crypto/sha1"
@@ -22,7 +23,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/rest"
)
@@ -307,9 +307,7 @@ func readGcid(in io.Reader, size, threshold int64) (gcid string, out io.Reader,
cleanup = func() {}
// don't cache small files on disk to reduce wear of the disk
//
// files of unknown size go to disk as they may not fit in memory
if size < 0 || size > threshold {
if size > threshold {
var tempFile *os.File
// create the cache file
@@ -342,16 +340,13 @@ func readGcid(in io.Reader, size, threshold int64) (gcid string, out io.Reader,
// replace the already read source with a reader of our cached file
out = tempFile
} else {
rw := multipart.NewRW()
cleanup = func() {
_ = rw.Close()
}
teeReader := io.TeeReader(in, rw)
buf := &bytes.Buffer{}
teeReader := io.TeeReader(in, buf)
if gcid, err = calcGcid(teeReader, size); err != nil {
return
}
out = rw
out = buf
}
return
}
-46
View File
@@ -1,46 +0,0 @@
package pikpak
import (
"bytes"
"io"
"os"
"testing"
"github.com/rclone/rclone/lib/pool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestReadGcid checks readGcid hashes and replays its input from a pooled
// buffer for small known sizes, and from a temp file for large or unknown
// sizes, releasing the buffer on cleanup.
func TestReadGcid(t *testing.T) {
content := bytes.Repeat([]byte("pikpak"), 1024)
want, err := calcGcid(bytes.NewReader(content), int64(len(content)))
require.NoError(t, err)
for _, test := range []struct {
name string
size int64
threshold int64
wantFile bool
}{
{"memory", int64(len(content)), int64(len(content)), false},
{"file", int64(len(content)), int64(len(content)) - 1, true},
{"unknown size", -1, int64(len(content)), true},
} {
t.Run(test.name, func(t *testing.T) {
inUse := pool.Global().InUse()
gcid, out, cleanup, err := readGcid(bytes.NewReader(content), test.size, test.threshold)
require.NoError(t, err)
assert.Equal(t, want, gcid)
_, isFile := out.(*os.File)
assert.Equal(t, test.wantFile, isFile, "expected temp file %v", test.wantFile)
got, err := io.ReadAll(out)
require.NoError(t, err)
assert.Equal(t, content, got)
cleanup()
assert.Equal(t, inUse, pool.Global().InUse(), "buffer should be returned to the pool")
})
}
}
+30 -2
View File
@@ -7,6 +7,7 @@ import (
"sort"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
@@ -17,11 +18,38 @@ import (
"github.com/rclone/rclone/fs/chunksize"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/atexit"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"golang.org/x/sync/errgroup"
)
const (
bufferSize = 1024 * 1024 // default size of the pages used in the reader
bufferCacheSize = 64 // max number of buffers to keep in cache
bufferCacheFlushTime = 5 * time.Second // flush the cached buffers after this long
)
// bufferPool is a global pool of buffers
var (
bufferPool *pool.Pool
bufferPoolOnce sync.Once
)
// get a buffer pool
func getPool() *pool.Pool {
bufferPoolOnce.Do(func() {
ci := fs.GetConfig(context.Background())
// Initialise the buffer pool when used
bufferPool = pool.New(bufferCacheFlushTime, bufferSize, bufferCacheSize, ci.UseMmap)
})
return bufferPool
}
// NewRW gets a pool.RW using the multipart pool
func NewRW() *pool.RW {
return pool.NewRW(getPool())
}
// Upload does a multipart upload in parallel
func (w *pikpakChunkWriter) Upload(ctx context.Context) (err error) {
// make concurrency machinery
@@ -52,7 +80,7 @@ func (w *pikpakChunkWriter) Upload(ctx context.Context) (err error) {
for partNum := int64(0); !finished; partNum++ {
// Get a block of memory from the pool and token which limits concurrency.
tokens.Get()
rw := multipart.NewRW()
rw := NewRW()
if acc != nil {
rw.SetAccounting(acc.AccountRead)
}
+3 -2
View File
@@ -224,7 +224,7 @@ Fill in for rclone to use a non root folder as its starting point.
Advanced: true,
}, {
Name: "hash_memory_limit",
Help: "Files bigger than this will be cached on disk to calculate hash if required.\n\nFiles of unknown size are always cached on disk.",
Help: "Files bigger than this will be cached on disk to calculate hash if required.",
Default: fs.SizeSuffix(10 * 1024 * 1024),
Advanced: true,
}, {
@@ -433,7 +433,8 @@ func (f *Fs) shouldRetry(ctx context.Context, resp *http.Response, err error) (b
// traceback to possible api.Error wrapped in err, and re-authorize if necessary
// "unauthenticated" (16): when access_token is invalid, but should be handled by oauthutil
if terr, ok := errors.AsType[*oauth2.RetrieveError](err); ok {
var terr *oauth2.RetrieveError
if errors.As(err, &terr) {
apiErr := new(api.Error)
if err := json.Unmarshal(terr.Body, apiErr); err == nil {
if apiErr.Reason == "invalid_grant" {
+1 -1
View File
@@ -213,7 +213,7 @@ func (f *Fs) put(
// exist yet
params.Set("make_parents", "true")
return node, f.pacer.CallNoRetry(func() (bool, error) {
return node, f.pacer.Call(func() (bool, error) {
resp, err := f.srv.CallJSON(
ctx,
&rest.Opts{
+5 -4
View File
@@ -262,7 +262,8 @@ func shouldRetry(ctx context.Context, err error) (bool, error) {
if err == nil {
return false, nil
}
if apiErr, ok := errors.AsType[*proton.APIError](err); ok {
var apiErr *proton.APIError
if errors.As(err, &apiErr) {
// Code 200501 is a generic Drive operation-failure code. Proton also
// returns it with an HTTP 422 for permanent validation failures (for
// example a content key packet that cannot be verified, or an upload
@@ -455,9 +456,9 @@ func isDecimalString(value string) bool {
// and is captured by --log-file.
type protonLogger struct{ f *Fs }
func (l protonLogger) Errorf(format string, v ...any) { fs.Errorf(l.f, format, v...) }
func (l protonLogger) Warnf(format string, v ...any) { fs.Logf(l.f, format, v...) }
func (l protonLogger) Debugf(format string, v ...any) { fs.Debugf(l.f, format, v...) }
func (l protonLogger) Errorf(format string, v ...interface{}) { fs.Errorf(l.f, format, v...) }
func (l protonLogger) Warnf(format string, v ...interface{}) { fs.Logf(l.f, format, v...) }
func (l protonLogger) Debugf(format string, v ...interface{}) { fs.Debugf(l.f, format, v...) }
func newProtonDrive(ctx context.Context, f *Fs, opt *Options, m configmap.Mapper) (*protonDriveAPI.ProtonDrive, error) {
config := protonDriveAPI.NewDefaultConfig()
@@ -86,7 +86,7 @@ func TestShouldRetry(t *testing.T) {
{"rate limit Status=429 (handled by SDK, not retried here)", ctx, apiErr(429, 0), false},
{"client error Status=400", ctx, apiErr(400, 0), false},
{"client error Status=404", ctx, apiErr(404, 0), false},
{"wrapped API error retried via errors.As", ctx, fmt.Errorf("wrapped: %w", apiErr(500, 0)), true},
{"wrapped API error retried via errors.As", ctx, fmt.Errorf("wrapped: %w", &proton.APIError{Status: 500}), true},
{"non-API error falls back to fserrors.ShouldRetry", ctx, errors.New("plain error"), false},
} {
t.Run(tc.name, func(t *testing.T) {
+5 -32
View File
@@ -21,7 +21,6 @@ import (
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/random"
@@ -331,31 +330,17 @@ func (f *Fs) sendUpload(ctx context.Context, location string, size int64, in io.
}
var clientOffset int64
var offsetMismatch bool
buf := make([]byte, defaultChunkSize)
for clientOffset < size {
chunkSize := min(size-clientOffset, int64(defaultChunkSize))
chunk := readers.NewRepeatableLimitReaderBuffer(in, buf, chunkSize)
chunkStart := clientOffset
reqSize := chunkSize
transferOffset := clientOffset
fs.Debugf(f, "chunkStart: %d, reqSize: %d", chunkStart, reqSize)
// Buffer the chunk in memory from the global pool so reads are
// repeatable for retries
rw := multipart.NewRW()
_, err = io.CopyN(rw, in, chunkSize)
if err != nil {
_ = rw.Close()
if err == io.EOF {
err = fmt.Errorf("short read of chunk at %d: %w", chunkStart, io.ErrUnexpectedEOF)
}
return
}
// Transfer the chunk
err = f.pacer.Call(func() (bool, error) {
_, err = rw.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
if offsetMismatch {
// Get file offset and seek to the position
offset, err := f.getServerOffset(ctx, location)
@@ -364,7 +349,7 @@ func (f *Fs) sendUpload(ctx context.Context, location string, size int64, in io.
}
sentBytes := offset - chunkStart
fs.Debugf(f, "sentBytes: %d", sentBytes)
_, err = rw.Seek(sentBytes, io.SeekStart)
_, err = chunk.Seek(sentBytes, io.SeekStart)
if err != nil {
return shouldRetry(ctx, err)
}
@@ -374,7 +359,7 @@ func (f *Fs) sendUpload(ctx context.Context, location string, size int64, in io.
}
fs.Debugf(f, "Sending chunk. transferOffset: %d length: %d", transferOffset, reqSize)
var serverOffset int64
serverOffset, fileID, err = f.transferChunk(ctx, location, transferOffset, rw, reqSize)
serverOffset, fileID, err = f.transferChunk(ctx, location, transferOffset, chunk, reqSize)
if cerr, ok := err.(*statusCodeError); ok && cerr.response.StatusCode == 409 {
offsetMismatch = true
return true, err
@@ -385,13 +370,9 @@ func (f *Fs) sendUpload(ctx context.Context, location string, size int64, in io.
}
return shouldRetry(ctx, err)
})
closeErr := rw.Close()
if err != nil {
return
}
if closeErr != nil {
return 0, closeErr
}
clientOffset += chunkSize
}
@@ -455,19 +436,11 @@ func (f *Fs) makeUploadHeadRequest(ctx context.Context, location string) (*http.
return req, nil
}
// makeUploadPatchRequest makes the tus PATCH request sending length bytes
// of in at offset.
//
// The body is wrapped in readers.NoCloser so the transport can't upgrade it
// to an io.Closer and close it after each attempt — the chunk buffer is
// pool-backed, so an early close would free its pages and a retry would then
// read a dead buffer. The upload loop owns the buffer's lifetime.
func (f *Fs) makeUploadPatchRequest(ctx context.Context, location string, in io.Reader, offset, length int64) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, "PATCH", location, readers.NoCloser(in))
req, err := http.NewRequestWithContext(ctx, "PATCH", location, in)
if err != nil {
return nil, err
}
req.ContentLength = length
req.Header.Set("tus-resumable", "1.0.0")
req.Header.Set("upload-offset", strconv.FormatInt(offset, 10))
req.Header.Set("content-length", strconv.FormatInt(length, 10))
+24 -37
View File
@@ -4,6 +4,7 @@ package s3
//go:generate go run gen_setfrom.go -o setfrom.go
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
@@ -1278,7 +1279,8 @@ func (f *Fs) shouldRetry(ctx context.Context, err error) (bool, error) {
}
// https://github.com/aws/aws-sdk-go-v2/blob/main/CHANGELOG.md#error-handling
// If this is an awserr object, try and extract more useful information to determine if we should retry
if awsError, ok := errors.AsType[smithy.APIError](err); ok {
var awsError smithy.APIError
if errors.As(err, &awsError) {
// Simple case, check the original embedded error in case it's generically retryable
if fserrors.ShouldRetry(awsError) {
return true, err
@@ -2505,7 +2507,8 @@ func (f *Fs) list(ctx context.Context, opt listOpt, fn listFn) error {
listBucket.URLEncodeListings(urlEncodeListings)
resp, versionIDs, err = listBucket.List(ctx)
if err != nil && !urlEncodeListings {
if _, ok := errors.AsType[*xml.SyntaxError](err); ok {
var xmlErr *xml.SyntaxError
if errors.As(err, &xmlErr) {
// Retry the listing with URL encoding as there were characters that XML can't encode
urlEncodeListings = true
fs.Debugf(f, "Retrying listing because of characters which can't be XML encoded")
@@ -2942,7 +2945,8 @@ func (f *Fs) makeBucket(ctx context.Context, bucket string) error {
if err == nil {
fs.Infof(f, "Bucket %q created with ACL %q", bucket, f.opt.BucketACL)
}
if awsErr, ok := errors.AsType[smithy.APIError](err); ok {
var awsErr smithy.APIError
if errors.As(err, &awsErr) {
switch awsErr.ErrorCode() {
case "BucketAlreadyOwnedByYou":
err = nil
@@ -4421,7 +4425,8 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
resp, err = o.fs.c.GetObject(ctx, &req, s3.WithAPIOptions(APIOptions...))
return o.fs.shouldRetry(ctx, err)
})
if awsError, ok := errors.AsType[smithy.APIError](err); ok {
var awsError smithy.APIError
if errors.As(err, &awsError) {
if awsError.ErrorCode() == "InvalidObjectState" {
return nil, fmt.Errorf("Object in GLACIER, restore first: bucket=%q, key=%q", bucket, bucketPath)
}
@@ -4761,36 +4766,27 @@ func (o *Object) uploadMultipart(ctx context.Context, src fs.ObjectInfo, in io.R
}
// bufferForObjectLockMD5 buffers the body and computes Content-MD5 when
// Object Lock parameters are set on the request and Content-MD5 isn't
// already known from the source. AWS S3 requires Content-MD5 for
// PutObject with Object Lock params and cannot compute it automatically
// Object Lock parameters are set on the request. AWS S3 requires Content-MD5
// for PutObject with Object Lock params and cannot compute it automatically
// from a non-seekable io.Reader.
// See: https://github.com/aws/aws-sdk-go-v2/discussions/2960
//
// The returned body must not be closed by the transport and cleanup must
// be called once the upload has finished with it.
func bufferForObjectLockMD5(req *s3.PutObjectInput, in io.Reader) (body io.Reader, cleanup func(), err error) {
cleanup = func() {}
if req.ContentMD5 != nil || (req.ObjectLockMode == "" && req.ObjectLockRetainUntilDate == nil && req.ObjectLockLegalHoldStatus == "") {
return in, cleanup, nil
func bufferForObjectLockMD5(req *s3.PutObjectInput, in io.Reader) (io.Reader, error) {
if req.ObjectLockMode == "" && req.ObjectLockRetainUntilDate == nil && req.ObjectLockLegalHoldStatus == "" {
return in, nil
}
rw := multipart.NewRW()
cleanup = func() {
_ = rw.Close()
buf, err := io.ReadAll(in)
if err != nil {
return nil, fmt.Errorf("failed to read body for Content-MD5: %w", err)
}
hasher := md5.New()
if _, err = io.Copy(rw, io.TeeReader(in, hasher)); err != nil {
return nil, cleanup, fmt.Errorf("failed to read body for Content-MD5: %w", err)
}
md5base64 := base64.StdEncoding.EncodeToString(hasher.Sum(nil))
md5sum := md5.Sum(buf)
md5base64 := base64.StdEncoding.EncodeToString(md5sum[:])
req.ContentMD5 = &md5base64
return rw, cleanup, nil
return bytes.NewReader(buf), nil
}
// Upload a single part using PutObject
func (o *Object) uploadSinglepartPutObject(ctx context.Context, req *s3.PutObjectInput, size int64, in io.Reader) (etag string, lastModified time.Time, versionID *string, err error) {
in, cleanup, err := bufferForObjectLockMD5(req, in)
defer cleanup()
in, err = bufferForObjectLockMD5(req, in)
if err != nil {
return etag, lastModified, nil, err
}
@@ -4825,8 +4821,7 @@ func (o *Object) uploadSinglepartPutObject(ctx context.Context, req *s3.PutObjec
// Upload a single part using a presigned request
func (o *Object) uploadSinglepartPresignedRequest(ctx context.Context, req *s3.PutObjectInput, size int64, in io.Reader) (etag string, lastModified time.Time, versionID *string, err error) {
// Content-MD5 must be set before signing so it's included in the presigned URL.
in, cleanup, err := bufferForObjectLockMD5(req, in)
defer cleanup()
in, err = bufferForObjectLockMD5(req, in)
if err != nil {
return etag, lastModified, nil, err
}
@@ -4841,9 +4836,8 @@ func (o *Object) uploadSinglepartPresignedRequest(ctx context.Context, req *s3.P
in = nil
}
// create the vanilla http request, making sure the transport can't
// close a pooled body
httpReq, err := http.NewRequestWithContext(ctx, "PUT", putReq.URL, readers.NoCloser(in))
// create the vanilla http request
httpReq, err := http.NewRequestWithContext(ctx, "PUT", putReq.URL, in)
if err != nil {
return etag, lastModified, nil, fmt.Errorf("s3 upload: new request: %w", err)
}
@@ -4851,13 +4845,6 @@ func (o *Object) uploadSinglepartPresignedRequest(ctx context.Context, req *s3.P
// set the headers we signed and the length
httpReq.Header = putReq.SignedHeader
httpReq.ContentLength = size
// let the client resend a seekable body when following a redirect
if seeker, ok := in.(io.Seeker); ok {
httpReq.GetBody = func() (io.ReadCloser, error) {
_, err := seeker.Seek(0, io.SeekStart)
return io.NopCloser(readers.NoCloser(in)), err
}
}
var resp *http.Response
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
+2 -49
View File
@@ -5,10 +5,8 @@ import (
"compress/gzip"
"context"
"crypto/md5"
"encoding/base64"
"errors"
"fmt"
"io"
"path"
"strings"
"testing"
@@ -24,7 +22,6 @@ import (
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/version"
"github.com/stretchr/testify/assert"
@@ -526,9 +523,10 @@ func (f *Fs) InternalTestVersions(t *testing.T) {
return f.shouldRetry(ctx, err)
})
var errString string
var awsError smithy.APIError
if err == nil {
errString = "No Error"
} else if awsError, ok := errors.AsType[smithy.APIError](err); ok {
} else if errors.As(err, &awsError) {
errString = awsError.ErrorCode()
} else {
assert.Fail(t, "Unknown error %T %v", err, err)
@@ -846,48 +844,3 @@ func (f *Fs) InternalTest(t *testing.T) {
}
var _ fstests.InternalTester = (*Fs)(nil)
func TestBufferForObjectLockMD5(t *testing.T) {
content := []byte("object lock body")
md5sum := md5.Sum(content)
wantMD5 := base64.StdEncoding.EncodeToString(md5sum[:])
t.Run("NoObjectLock", func(t *testing.T) {
req := &s3.PutObjectInput{}
in := bytes.NewReader(content)
body, cleanup, err := bufferForObjectLockMD5(req, in)
defer cleanup()
require.NoError(t, err)
assert.Equal(t, io.Reader(in), body, "body should be passed through untouched")
assert.Nil(t, req.ContentMD5)
})
t.Run("SourceMD5", func(t *testing.T) {
req := &s3.PutObjectInput{
ObjectLockMode: types.ObjectLockModeCompliance,
ContentMD5: aws.String(wantMD5),
}
in := bytes.NewReader(content)
body, cleanup, err := bufferForObjectLockMD5(req, in)
defer cleanup()
require.NoError(t, err)
assert.Equal(t, io.Reader(in), body, "body should not be buffered when the MD5 is known")
assert.Equal(t, wantMD5, *req.ContentMD5)
})
t.Run("Buffered", func(t *testing.T) {
inUse := pool.Global().InUse()
req := &s3.PutObjectInput{
ObjectLockLegalHoldStatus: types.ObjectLockLegalHoldStatusOn,
}
body, cleanup, err := bufferForObjectLockMD5(req, bytes.NewReader(content))
require.NoError(t, err)
require.NotNil(t, req.ContentMD5)
assert.Equal(t, wantMD5, *req.ContentMD5)
got, err := io.ReadAll(body)
require.NoError(t, err)
assert.Equal(t, content, got)
cleanup()
assert.Equal(t, inUse, pool.Global().InUse(), "pool buffers leaked")
})
}
+20 -14
View File
@@ -88,22 +88,28 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
// But for unknown-sized objects (indicated by src.Size() == -1), Upload should either
// return an error or update the object properly (rather than e.g. calling panic).
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
uploadLink, err := o.fs.getUploadLink(ctx, o.libraryID)
if err != nil {
return err
}
// The upload sometimes return a temporary 500 error
// We cannot use the pacer to retry uploading the file as the upload link is single use only
for retry := 0; retry <= 3; retry++ {
uploadLink, err := o.fs.getUploadLink(ctx, o.libraryID)
if err != nil {
return err
}
// The upload can't be retried here as the input stream can't be re-read and
// the upload link is single use, so upload returns a retry
// error for the caller to retry with a fresh stream.
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
if err != nil {
return err
}
// Set the properties from the upload back to the object
o.size = uploaded.Size
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
if err == ErrorInternalDuringUpload {
// This is a temporary error, try again with a new upload link
continue
}
if err != nil {
return err
}
// Set the properties from the upload back to the object
o.size = uploaded.Size
return nil
return nil
}
return ErrorInternalDuringUpload
}
// Remove this object
+2 -3
View File
@@ -13,7 +13,6 @@ import (
"github.com/rclone/rclone/backend/seafile/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
)
@@ -722,8 +721,8 @@ func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath stri
return nil, fs.ErrorPermissionDenied
}
if resp.StatusCode == 500 {
// This is a temporary error - the caller will get a new upload link when it retries
return nil, fserrors.RetryError(ErrorInternalDuringUpload)
// This is a temporary error - we will get a new upload link before retrying
return nil, ErrorInternalDuringUpload
}
}
return nil, fmt.Errorf("failed to upload file: %w", err)
-42
View File
@@ -390,28 +390,6 @@ Normally rclone uses concurrent writes to upload files. This improves
the performance greatly, especially for distant servers.
This option disables concurrent writes should that be necessary.
`,
Advanced: true,
}, {
Name: "multithread_upload",
Default: false,
Help: `Set this to use multi-thread (multi-connection) uploads.
Normally rclone uploads a single large file over one SFTP connection.
With this set rclone uploads large files over several SFTP connections
at once (one per chunk), which greatly improves throughput on high
latency links, the same way multi-thread downloads already work. Each
connection writes a different, non-overlapping byte range of the file,
so this requires a server that allows several handles to the same file
with writes at arbitrary offsets, which OpenSSH does.
This is off by default because many SFTP servers only accept sequential
writes (for example some object storage backed SFTP gateways) and would
fail large uploads with "truncate failed" or "invalid offset" style
errors.
This is ignored (uploads stay single-threaded) when
--sftp-disable-concurrent-writes or --sftp-connections is in use.
`,
Advanced: true,
}, {
@@ -670,7 +648,6 @@ type Options struct {
UseFstat bool `config:"use_fstat"`
DisableConcurrentReads bool `config:"disable_concurrent_reads"`
DisableConcurrentWrites bool `config:"disable_concurrent_writes"`
MultithreadUpload bool `config:"multithread_upload"`
IdleTimeout fs.Duration `config:"idle_timeout"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
Concurrency int `config:"concurrency"`
@@ -1617,24 +1594,6 @@ func NewFsWithConnection(ctx context.Context, f *Fs, name string, root string, m
// Disable server side copy unless --sftp-copy-is-hardlink is set
f.features.Copy = nil
}
// Multi-thread uploads open one write handle per connection. They are off
// by default (many SFTP servers only take sequential writes) and turned on
// with --sftp-multithread-upload. Even when asked for, fall back to
// single-connection uploads when concurrent writes are disabled (a server
// that can't take out-of-order packets on one handle won't take several
// handles writing at arbitrary offsets either) or when connections are
// capped (the per-file fan-out would deadlock waiting on the pool, and a
// user limiting connections doesn't want it anyway).
switch {
case !opt.MultithreadUpload:
f.features.OpenWriterAt = nil
case opt.DisableConcurrentWrites:
fs.Logf(f, "Disabling multi-thread uploads because --sftp-disable-concurrent-writes is set")
f.features.OpenWriterAt = nil
case opt.Connections > 0:
fs.Logf(f, "Disabling multi-thread uploads because --sftp-connections is set")
f.features.OpenWriterAt = nil
}
// Make a connection and pool it to return errors early
c, err := f.getSftpConnection(ctx)
if err != nil {
@@ -2886,7 +2845,6 @@ var (
_ fs.PutStreamer = &Fs{}
_ fs.Mover = &Fs{}
_ fs.Copier = &Fs{}
_ fs.OpenWriterAter = &Fs{}
_ fs.DirMover = &Fs{}
_ fs.DirSetModTimer = &Fs{}
_ fs.Abouter = &Fs{}
+4 -4
View File
@@ -428,7 +428,7 @@ func TestHostKeyCallbackRefusesAtCap(t *testing.T) {
opt: Options{PinHostKey: true},
hostKeys: map[string][][]byte{},
}
for i := range maxHostKeys {
for i := 0; i < maxHostKeys; i++ {
algo := fmt.Sprintf("test-algo-%d", i)
f.hostKeys[algo] = [][]byte{{byte(i)}}
}
@@ -480,7 +480,7 @@ func TestHostKeyCallbackPinHostKeyRace(t *testing.T) {
const N = 16
pendings := make([]*pendingKey, N)
wg.Add(N)
for i := range N {
for i := 0; i < N; i++ {
go func(i int) {
defer wg.Done()
cb := f.hostKeyCallback(&pendings[i])
@@ -489,7 +489,7 @@ func TestHostKeyCallbackPinHostKeyRace(t *testing.T) {
}(i)
}
wg.Wait()
for i := range N {
for i := 0; i < N; i++ {
require.NotNil(t, pendings[i], "dial %d should have stashed its own key", i)
assert.Equal(t, keyBytes, pendings[i].marshalled)
}
@@ -631,7 +631,7 @@ func TestCommitHostKeyConcurrent(t *testing.T) {
keys := makeTestKeys(t, N)
var wg sync.WaitGroup
wg.Add(N)
for i := range N {
for i := 0; i < N; i++ {
go func(i int) {
defer wg.Done()
f.commitHostKey(&pendingKey{
-137
View File
@@ -1,137 +0,0 @@
//go:build !plan9
package sftp
import (
"context"
"errors"
"fmt"
"os"
"sync"
"github.com/pkg/sftp"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/filepool"
)
// poolFile is a pooled write handle together with the connection it lives on.
type poolFile struct {
file *sftp.File
c *conn
}
// openPoolFile opens a fresh write handle on its own connection for path. The
// file must already exist: the handle opens O_WRONLY only, so it never races
// another handle to create or truncate.
func (f *Fs) openPoolFile(path string) func(context.Context) (*poolFile, error) {
return func(ctx context.Context) (*poolFile, error) {
c, err := f.getSftpConnection(ctx)
if err != nil {
return nil, err
}
file, err := c.sftpClient.OpenFile(path, os.O_WRONLY)
if err != nil {
f.putSftpConnection(&c, err)
return nil, err
}
return &poolFile{file: file, c: c}, nil
}
}
// releasePoolFile closes a pooled handle and returns its connection.
func (f *Fs) releasePoolFile(pf *poolFile, err error) error {
closeErr := pf.file.Close()
if err == nil {
err = closeErr
}
f.putSftpConnection(&pf.c, err)
return closeErr
}
// sftpWriterAt is the fs.WriterAtCloser used by the core's multi-thread copy.
// WriteAt is called concurrently at non-overlapping offsets, each borrowing its
// own handle from the pool.
type sftpWriterAt struct {
fs *Fs
pool *filepool.Pool[*poolFile]
closeMu sync.Mutex
closed bool
wg sync.WaitGroup
}
// WriteAt writes p at offset off using a handle borrowed from the pool.
func (w *sftpWriterAt) WriteAt(p []byte, off int64) (int, error) {
w.closeMu.Lock()
if w.closed {
w.closeMu.Unlock()
return 0, errors.New("sftp: WriteAt on closed writer")
}
w.wg.Add(1)
w.closeMu.Unlock()
defer w.wg.Done()
pf, err := w.pool.Get()
if err != nil {
return 0, err
}
n, writeErr := pf.file.WriteAt(p, off)
w.pool.Put(pf, writeErr)
if writeErr != nil {
return n, fmt.Errorf("failed to write at offset %d: %w", off, writeErr)
}
return n, nil
}
// Close waits for outstanding writes then closes every pooled handle.
func (w *sftpWriterAt) Close() error {
w.closeMu.Lock()
if w.closed {
w.closeMu.Unlock()
return nil
}
w.closed = true
w.closeMu.Unlock()
w.wg.Wait()
err := w.pool.Drain()
w.fs.removeSession()
return err
}
// OpenWriterAt opens remote for random-access writes, truncating any existing
// object, and pre-sizes it to size (if known) so every chunk offset is valid.
//
// The file is created and truncated once here, on a single connection, so the
// pooled handles open O_WRONLY and never race to truncate each other's data.
func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.WriterAtCloser, error) {
err := f.mkParentDir(ctx, remote)
if err != nil {
return nil, fmt.Errorf("OpenWriterAt: %w", err)
}
path := f.remotePath(remote)
c, err := f.getSftpConnection(ctx)
if err != nil {
return nil, fmt.Errorf("OpenWriterAt: %w", err)
}
file, err := c.sftpClient.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
if err != nil {
f.putSftpConnection(&c, err)
return nil, fmt.Errorf("OpenWriterAt: create failed: %w", err)
}
if size > 0 {
if truncErr := file.Truncate(size); truncErr != nil {
_ = file.Close()
f.putSftpConnection(&c, truncErr)
return nil, fmt.Errorf("OpenWriterAt: truncate failed (the server may not support multi-thread uploads; try without --sftp-multithread-upload): %w", truncErr)
}
}
if closeErr := file.Close(); closeErr != nil {
f.putSftpConnection(&c, closeErr)
return nil, fmt.Errorf("OpenWriterAt: close failed: %w", closeErr)
}
f.putSftpConnection(&c, nil)
f.addSession()
return &sftpWriterAt{fs: f, pool: filepool.New(ctx, f.openPoolFile(path), f.releasePoolFile)}, nil
}
+11 -12
View File
@@ -3,6 +3,7 @@
package shade
import (
"bytes"
"context"
"fmt"
"io"
@@ -154,15 +155,17 @@ func (s *shadeChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, read
return 0, err
}
// Find the chunk size
n, err := reader.Seek(0, io.SeekEnd)
if err != nil {
return 0, fmt.Errorf("failed to read chunk: %w", err)
}
// Read chunk
var chunk bytes.Buffer
n, err := io.Copy(&chunk, reader)
if n == 0 {
return 0, nil
}
if err != nil {
return 0, fmt.Errorf("failed to read chunk: %w", err)
}
// Get presigned URL for this part
var partURL api.PartURL
@@ -198,18 +201,14 @@ func (s *shadeChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, read
}
err = s.f.pacer.Call(func() (bool, error) {
// Rewind the chunk so each attempt sends it in full
_, err = reader.Seek(0, io.SeekStart)
if err != nil {
return false, err
}
opts.Body = reader
// Use a fresh reader for each attempt so retries resend the whole chunk
opts.Body = bytes.NewReader(chunk.Bytes())
uploadRes, err = s.f.srv.Call(ctx, &opts)
return shouldRetry(ctx, uploadRes, err)
})
if err != nil {
return 0, fmt.Errorf("failed to upload part %d: %w", chunkNumber+1, err)
return 0, fmt.Errorf("failed to upload part %d: %w", chunk, err)
}
if uploadRes.StatusCode != http.StatusOK && uploadRes.StatusCode != http.StatusCreated {
-65
View File
@@ -1,65 +0,0 @@
package shade
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newTestChunkWriter returns a chunk writer pointed at server, which must
// answer the part URL request with a URL back to itself and the part PUT.
func newTestChunkWriter(t *testing.T, server *httptest.Server) *shadeChunkWriter {
ctx := context.Background()
f := &Fs{
srv: rest.NewClient(server.Client()),
endpoint: server.URL,
drive: "drive",
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(time.Millisecond), pacer.MaxSleep(time.Millisecond))),
token: "token",
tokenExp: time.Now().Add(time.Hour),
}
return &shadeChunkWriter{initToken: "init", f: f}
}
// partServer returns a test server which hands out a part URL pointing at
// itself and passes part PUTs to put.
func partServer(t *testing.T, put func(w http.ResponseWriter, body []byte)) *httptest.Server {
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "/upload/multipart/part/") {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"url":%q}`, server.URL+"/put")
return
}
body, err := io.ReadAll(r.Body)
require.NoError(t, err)
put(w, body)
}))
return server
}
// TestWriteChunkError checks that a part which keeps failing reports the
// part number in the error.
func TestWriteChunkError(t *testing.T) {
server := partServer(t, func(w http.ResponseWriter, body []byte) {
w.WriteHeader(http.StatusInternalServerError)
})
defer server.Close()
s := newTestChunkWriter(t, server)
_, err := s.WriteChunk(context.Background(), 2, bytes.NewReader([]byte("shade")))
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to upload part 3:")
}
+99
View File
@@ -0,0 +1,99 @@
package smb
import (
"context"
"fmt"
"os"
"sync"
"github.com/cloudsoda/go-smb2"
"golang.org/x/sync/errgroup"
)
// FsInterface defines the methods that filePool needs from Fs
type FsInterface interface {
getConnection(ctx context.Context, share string) (*conn, error)
putConnection(pc **conn, err error)
removeSession()
}
type file struct {
*smb2.File
c *conn
}
type filePool struct {
ctx context.Context
fs FsInterface
share string
path string
mu sync.Mutex
pool []*file
}
func newFilePool(ctx context.Context, fs FsInterface, share, path string) *filePool {
return &filePool{
ctx: ctx,
fs: fs,
share: share,
path: path,
}
}
func (p *filePool) get() (*file, error) {
p.mu.Lock()
if len(p.pool) > 0 {
f := p.pool[len(p.pool)-1]
p.pool = p.pool[:len(p.pool)-1]
p.mu.Unlock()
return f, nil
}
p.mu.Unlock()
c, err := p.fs.getConnection(p.ctx, p.share)
if err != nil {
return nil, err
}
fl, err := c.smbShare.OpenFile(p.path, os.O_WRONLY, 0o644)
if err != nil {
p.fs.putConnection(&c, err)
return nil, fmt.Errorf("failed to open: %w", err)
}
return &file{File: fl, c: c}, nil
}
func (p *filePool) put(f *file, err error) {
if f == nil {
return
}
if err != nil {
_ = f.Close()
p.fs.putConnection(&f.c, err)
return
}
p.mu.Lock()
p.pool = append(p.pool, f)
p.mu.Unlock()
}
func (p *filePool) drain() error {
p.mu.Lock()
files := p.pool
p.pool = nil
p.mu.Unlock()
g, _ := errgroup.WithContext(p.ctx)
for _, f := range files {
g.Go(func() error {
err := f.Close()
p.fs.putConnection(&f.c, err)
return err
})
}
return g.Wait()
}
+228
View File
@@ -0,0 +1,228 @@
package smb
import (
"context"
"errors"
"sync"
"testing"
"github.com/cloudsoda/go-smb2"
"github.com/stretchr/testify/assert"
)
// Mock Fs that implements FsInterface
type mockFs struct {
mu sync.Mutex
putConnectionCalled bool
putConnectionErr error
getConnectionCalled bool
getConnectionErr error
getConnectionResult *conn
removeSessionCalled bool
}
func (m *mockFs) putConnection(pc **conn, err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.putConnectionCalled = true
m.putConnectionErr = err
}
func (m *mockFs) getConnection(ctx context.Context, share string) (*conn, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.getConnectionCalled = true
if m.getConnectionErr != nil {
return nil, m.getConnectionErr
}
if m.getConnectionResult != nil {
return m.getConnectionResult, nil
}
return &conn{}, nil
}
func (m *mockFs) removeSession() {
m.mu.Lock()
defer m.mu.Unlock()
m.removeSessionCalled = true
}
func (m *mockFs) isPutConnectionCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.putConnectionCalled
}
func (m *mockFs) getPutConnectionErr() error {
m.mu.Lock()
defer m.mu.Unlock()
return m.putConnectionErr
}
func (m *mockFs) isGetConnectionCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.getConnectionCalled
}
func newMockFs() *mockFs {
return &mockFs{}
}
// Helper function to create a mock file
func newMockFile() *file {
return &file{
File: &smb2.File{},
c: &conn{},
}
}
// Test filePool creation
func TestNewFilePool(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
share := "testshare"
path := "/test/path"
pool := newFilePool(ctx, fs, share, path)
assert.NotNil(t, pool)
assert.Equal(t, ctx, pool.ctx)
assert.Equal(t, fs, pool.fs)
assert.Equal(t, share, pool.share)
assert.Equal(t, path, pool.path)
assert.Empty(t, pool.pool)
}
// Test getting file from pool when pool has files
func TestFilePool_Get_FromPool(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
// Add a mock file to the pool
mockFile := newMockFile()
pool.pool = append(pool.pool, mockFile)
// Get file from pool
f, err := pool.get()
assert.NoError(t, err)
assert.NotNil(t, f)
assert.Equal(t, mockFile, f)
assert.Empty(t, pool.pool)
}
// Test getting file when pool is empty
func TestFilePool_Get_EmptyPool(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
// Set up the mock to return an error from getConnection
// This tests that the pool calls getConnection when empty
fs.getConnectionErr = errors.New("connection failed")
pool := newFilePool(ctx, fs, "testshare", "test/path")
// This should call getConnection and return the error
f, err := pool.get()
assert.Error(t, err)
assert.Nil(t, f)
assert.True(t, fs.isGetConnectionCalled())
assert.Equal(t, "connection failed", err.Error())
}
// Test putting file successfully
func TestFilePool_Put_Success(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
mockFile := newMockFile()
pool.put(mockFile, nil)
assert.Len(t, pool.pool, 1)
assert.Equal(t, mockFile, pool.pool[0])
}
// Test putting file with error
func TestFilePool_Put_WithError(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
mockFile := newMockFile()
pool.put(mockFile, errors.New("write error"))
// Should call putConnection with error
assert.True(t, fs.isPutConnectionCalled())
assert.Equal(t, errors.New("write error"), fs.getPutConnectionErr())
assert.Empty(t, pool.pool)
}
// Test putting nil file
func TestFilePool_Put_NilFile(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
// Should not panic
pool.put(nil, nil)
pool.put(nil, errors.New("some error"))
assert.Empty(t, pool.pool)
}
// Test draining pool with files
func TestFilePool_Drain_WithFiles(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
// Add mock files to pool
mockFile1 := newMockFile()
mockFile2 := newMockFile()
pool.pool = append(pool.pool, mockFile1, mockFile2)
// Before draining
assert.Len(t, pool.pool, 2)
_ = pool.drain()
assert.Empty(t, pool.pool)
}
// Test concurrent access to pool
func TestFilePool_ConcurrentAccess(t *testing.T) {
ctx := context.Background()
fs := newMockFs()
pool := newFilePool(ctx, fs, "testshare", "/test/path")
const numGoroutines = 10
for range numGoroutines {
mockFile := newMockFile()
pool.pool = append(pool.pool, mockFile)
}
// Test concurrent get operations
done := make(chan bool, numGoroutines)
for range numGoroutines {
go func() {
defer func() { done <- true }()
f, err := pool.get()
if err == nil {
pool.put(f, nil)
}
}()
}
for range numGoroutines {
<-done
}
// Pool should be in a consistent after the concurrence access
assert.Len(t, pool.pool, numGoroutines)
}
+6 -42
View File
@@ -13,7 +13,6 @@ import (
"sync/atomic"
"time"
"github.com/cloudsoda/go-smb2"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configmap"
@@ -22,7 +21,6 @@ import (
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/env"
"github.com/rclone/rclone/lib/filepool"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/readers"
)
@@ -516,15 +514,8 @@ func (f *Fs) About(ctx context.Context) (_ *fs.Usage, err error) {
return usage, nil
}
// file is a pooled write handle together with the connection it lives on.
type file struct {
*smb2.File
c *conn
}
type smbWriterAt struct {
fs *Fs
pool *filepool.Pool[*file]
pool *filePool
closed bool
closeMu sync.Mutex
wg sync.WaitGroup
@@ -540,13 +531,13 @@ func (w *smbWriterAt) WriteAt(p []byte, off int64) (int, error) {
w.closeMu.Unlock()
defer w.wg.Done()
f, err := w.pool.Get()
f, err := w.pool.get()
if err != nil {
return 0, fmt.Errorf("failed to get file from pool: %w", err)
}
n, writeErr := f.WriteAt(p, off)
w.pool.Put(f, writeErr)
w.pool.put(f, writeErr)
if writeErr != nil {
return n, fmt.Errorf("failed to write at offset %d: %w", off, writeErr)
@@ -570,12 +561,12 @@ func (w *smbWriterAt) Close() error {
var errs []error
// Drain the pool
if err := w.pool.Drain(); err != nil {
if err := w.pool.drain(); err != nil {
errs = append(errs, fmt.Errorf("failed to drain file pool: %w", err))
}
// Remove session
w.fs.removeSession()
w.pool.fs.removeSession()
if len(errs) > 0 {
return errors.Join(errs...)
@@ -584,32 +575,6 @@ func (w *smbWriterAt) Close() error {
return nil
}
// openPoolFile opens a fresh write handle on its own connection for share/path.
func (f *Fs) openPoolFile(share, path string) func(context.Context) (*file, error) {
return func(ctx context.Context) (*file, error) {
c, err := f.getConnection(ctx, share)
if err != nil {
return nil, err
}
fl, err := c.smbShare.OpenFile(path, os.O_WRONLY, 0o644)
if err != nil {
f.putConnection(&c, err)
return nil, fmt.Errorf("failed to open: %w", err)
}
return &file{File: fl, c: c}, nil
}
}
// releasePoolFile closes a pooled handle and returns its connection.
func (f *Fs) releasePoolFile(fl *file, err error) error {
closeErr := fl.Close()
if err == nil {
err = closeErr
}
f.putConnection(&fl.c, err)
return closeErr
}
// OpenWriterAt opens with a handle for random access writes
//
// Pass in the remote desired and the size if known.
@@ -659,8 +624,7 @@ func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.Wr
o.fs.addSession()
return &smbWriterAt{
fs: o.fs,
pool: filepool.New(ctx, o.fs.openPoolFile(share, smbPath), o.fs.releasePoolFile),
pool: newFilePool(ctx, o.fs, share, smbPath),
}, nil
}
+6 -2
View File
@@ -4,7 +4,6 @@ package api
import (
"encoding/xml"
"regexp"
"slices"
"strconv"
"strings"
"sync"
@@ -108,7 +107,12 @@ func (p *Prop) StatusOK() bool {
if len(p.Status) == 0 {
return true
}
return slices.ContainsFunc(p.Status, parseStatus2XX.MatchString)
for _, statusStr := range p.Status {
if parseStatus2XX.MatchString(statusStr) {
return true
}
}
return false
}
// Hashes returns a map of all checksums - may be nil
-12
View File
@@ -1559,18 +1559,6 @@ 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,20 +3,16 @@ 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"
)
@@ -155,132 +151,3 @@ 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())
}
+4 -4
View File
@@ -103,7 +103,7 @@ func TestFolderWindowLimiterShape(t *testing.T) {
}
// Window 1: the first burst grants pass immediately...
for i := range defaultListFolderBurst {
for i := 0; i < defaultListFolderBurst; i++ {
assert.Equal(t, base, reserve(base), "burst grant %d passes immediately", i+1)
}
// ...then the paced phase spends the rest of the budget one interval apart
@@ -149,14 +149,14 @@ func TestFolderWindowLimiterIdleResume(t *testing.T) {
var grants []time.Time
g := base
// Spend window 1's full budget greedily.
for range defaultListFolderLimit {
for i := 0; i < defaultListFolderLimit; i++ {
g = lim.reserve(g)
grants = append(grants, g)
}
// Resume mid-window-2 after an idle gap and hammer across the 2->3
// boundary: a fresh burst fires on resume and again at the boundary.
g = base.Add(window + window/2)
for range defaultListFolderLimit {
for i := 0; i < defaultListFolderLimit; i++ {
g = lim.reserve(g)
grants = append(grants, g)
}
@@ -187,7 +187,7 @@ func TestFolderWindowLimiterClamps(t *testing.T) {
// burst >= limit clamps to limit-1, leaving one paced token per window.
lim = newFs(5, 99).folderListLimiter("Y")
for i := range 4 {
for i := 0; i < 4; i++ {
assert.Equal(t, base, lim.reserve(base), "clamped burst grant %d", i+1)
}
assert.Equal(t, base.Add(window), lim.reserve(base), "5th grant rolls into the next window")
+46 -9
View File
@@ -4,6 +4,8 @@ package check
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/rclone/rclone/cmd"
@@ -76,23 +78,58 @@ option for more information.`, "|", "`")
// GetCheckOpt gets the options corresponding to the check flags
func GetCheckOpt(fsrc, fdst fs.Fs) (opt *operations.CheckOpt, close func(), err error) {
closers := []io.Closer{}
opt = &operations.CheckOpt{
Fsrc: fsrc,
Fdst: fdst,
OneWay: oneway,
}
close, err = operations.OpenReportFiles(
operations.ReportFile{Name: combined, Out: &opt.Combined},
operations.ReportFile{Name: missingOnSrc, Out: &opt.MissingOnSrc},
operations.ReportFile{Name: missingOnDst, Out: &opt.MissingOnDst},
operations.ReportFile{Name: match, Out: &opt.Match},
operations.ReportFile{Name: differ, Out: &opt.Differ},
operations.ReportFile{Name: errFile, Out: &opt.Error},
)
if err != nil {
open := func(name string, pout *io.Writer) error {
if name == "" {
return nil
}
if name == "-" {
*pout = os.Stdout
return nil
}
out, err := os.Create(name)
if err != nil {
return err
}
*pout = out
closers = append(closers, out)
return nil
}
if err = open(combined, &opt.Combined); err != nil {
return nil, nil, err
}
if err = open(missingOnSrc, &opt.MissingOnSrc); err != nil {
return nil, nil, err
}
if err = open(missingOnDst, &opt.MissingOnDst); err != nil {
return nil, nil, err
}
if err = open(match, &opt.Match); err != nil {
return nil, nil, err
}
if err = open(differ, &opt.Differ); err != nil {
return nil, nil, err
}
if err = open(errFile, &opt.Error); err != nil {
return nil, nil, err
}
close = func() {
for _, closer := range closers {
err := closer.Close()
if err != nil {
fs.Errorf(nil, "Failed to close report output: %v", err)
}
}
}
return opt, close, nil
}
+2
View File
@@ -170,6 +170,8 @@ func mount(VFS *vfs.VFS, mountPath string, opt *mountlib.Options) (<-chan error,
// unmount
unmount := func() error {
// Shutdown the VFS
fsys.VFS.Shutdown()
var umountOK bool
if fsys.destroyed.Load() != 0 {
fs.Debugf(nil, "Not calling host.Unmount as mount already Destroyed")
+9 -9
View File
@@ -42,10 +42,10 @@ func TestRun_CallsCopyURL_WithExplicitFilename_Success(t *testing.T) {
tmp := t.TempDir()
dstPath := filepath.Join(tmp, "out.txt")
var called atomic.Int32
var called int32
copyURL = func(_ctx context.Context, _dst fs.Fs, dstFileName, url string, auto, header, noclobber bool) (fs.Object, error) {
called.Add(1)
atomic.AddInt32(&called, 1)
assert.Equal(t, "https://example.com/file", url)
assert.Equal(t, "out.txt", dstFileName)
assert.False(t, auto)
@@ -56,7 +56,7 @@ func TestRun_CallsCopyURL_WithExplicitFilename_Success(t *testing.T) {
err := run([]string{"https://example.com/file", dstPath})
require.NoError(t, err)
assert.Equal(t, int32(1), called.Load())
assert.Equal(t, int32(1), atomic.LoadInt32(&called))
}
func TestRun_CallsCopyURL_WithAutoFilename_AndPropagatesError(t *testing.T) {
@@ -67,10 +67,10 @@ func TestRun_CallsCopyURL_WithAutoFilename_AndPropagatesError(t *testing.T) {
autoFilename = true
want := errors.New("boom")
var called atomic.Int32
var called int32
copyURL = func(_ctx context.Context, _dst fs.Fs, dstFileName, url string, auto, header, noclobber bool) (fs.Object, error) {
called.Add(1)
atomic.AddInt32(&called, 1)
assert.Equal(t, "", dstFileName) // auto filename -> empty
assert.True(t, auto)
return nil, want
@@ -79,7 +79,7 @@ func TestRun_CallsCopyURL_WithAutoFilename_AndPropagatesError(t *testing.T) {
err := run([]string{"https://example.com/auto/name", tmp})
require.Error(t, err)
assert.Equal(t, want, err)
assert.Equal(t, int32(1), called.Load())
assert.Equal(t, int32(1), atomic.LoadInt32(&called))
}
func TestRunURLS_ErrorsWithStdoutAndWithPrintFilename(t *testing.T) {
@@ -115,12 +115,12 @@ func TestRunURLS_ProcessesCSV_ParallelCalls_AndAggregatesError(t *testing.T) {
// mock copyURL: succeed for /a and /b, fail for /c
var calls atomic.Int32
var calls int32
var mu sync.Mutex
var seen []string
copyURL = func(_ctx context.Context, _dst fs.Fs, dstFileName, url string, auto, header, noclobber bool) (fs.Object, error) {
calls.Add(1)
atomic.AddInt32(&calls, 1)
mu.Lock()
seen = append(seen, url+"|"+dstFileName)
mu.Unlock()
@@ -143,7 +143,7 @@ func TestRunURLS_ProcessesCSV_ParallelCalls_AndAggregatesError(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "not all URLs copied successfully")
// 3 lines => 3 calls
assert.Equal(t, int32(3), calls.Load())
assert.Equal(t, int32(3), atomic.LoadInt32(&calls))
// sanity: all expected URLs were seen
assert.ElementsMatch(t,
+11 -33
View File
@@ -18,7 +18,6 @@ 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
@@ -169,17 +168,14 @@ 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-annex repository in the ephemeral repo
// directory. The "global" git config it writes is ultimately scoped to the
// createGitRepo creates an empty git repository in the ephemeral repo
// directory. It makes "global" config changes that are ultimately scoped to the
// calling test thanks to runInRepo() overriding the HOME environment variable.
func (e *e2eTestingContext) createGitRepo(t *testing.T) {
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", "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")
e.runInRepo(t, "git", "init")
e.runInRepo(t, "git", "annex", "init")
}
@@ -198,13 +194,6 @@ 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 {
@@ -242,7 +231,6 @@ 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() {
@@ -259,25 +247,14 @@ func TestEndToEnd(t *testing.T) {
"rcloneremotename=MyRcloneRemote", "rcloneprefix="+testingContext.ephemeralRepoDir,
"rclonelayout="+string(mode))
// 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")
}
testingContext.runInRepo(t, "git", "annex", "testremote", "MyTestRemote")
})
}
}
// 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.
// For each layout mode, migrate a single remote from git-annex-remote-rclone to
// git-annex-remote-rclone-builtin and run `git annex testremote`.
func TestEndToEndMigration(t *testing.T) {
t.Parallel()
skipE2eTestIfNecessary(t)
if _, err := exec.LookPath("git-annex-remote-rclone"); err != nil {
@@ -326,6 +303,8 @@ func TestEndToEndMigration(t *testing.T) {
)
tc.runInRepo(t, "git", "annex", "fsck", "--from=MigratedRemote", "foo")
tc.runInRepo(t, "git", "annex", "testremote", "MigratedRemote")
})
}
}
@@ -335,7 +314,6 @@ 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 {
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff. Show more