Compare commits

...
Author SHA1 Message Date
Nick Craig-Wood fb17dd9fe7 dropbox: make shared_folders mode read-write - fixes #9221
Previously shared_folders mode blocked all write operations with
"not supported in shared files mode". This adds full read-write
support by using namespace-scoped API clients for all operations.
2026-03-13 18:13:08 +00:00
Nick Craig-Wood 14b56fa7dc dropbox: fix listing shared folder subdirectories - fixes #9221
When shared_folders was enabled and the remote was mounted at root,
listing subdirectories would return top-level shared folder names
instead of the directory contents, causing "Entry doesn't belong in
directory (too short)" errors. Opening and reading files inside shared
folders also failed with path/not_found because the API calls didn't
use the shared folder's namespace.

Now when listing a subdirectory, use the shared folder's namespace ID
to create a per-request files client and list its contents directly
via the Dropbox files API. This works for all shared folder types
including team folders.

Fix NewObject to resolve files inside shared folders using the correct
namespace. Store the namespace ID on Object so that Open/Download also
uses the correct namespace-scoped client.

Extract the common directory listing logic into a listDir helper
method to avoid code duplication between the normal and shared folder
listing paths.

Add integration tests that share a folder, then verify listing,
NewObject, and Open all work in shared_folders mode.
2026-03-13 14:50:10 +00:00
Nick Craig-Wood 5d6690eb20 list: fix nil pointer panic in Sorter when temp file creation fails
When extsort.Strings() cannot create temporary files (e.g. due to
apparmor restrictions or permission denied), it returns a nil sorter
with the error on errChan. The code then called Sort() on the nil
sorter, causing a panic.

Check for nil sorter and return the error instead of panicking.

Fixes #9244
2026-03-12 10:00:56 +00:00
Nick Craig-Wood c7b8654b17 docs: update RELEASE procedure to avoid mistakes 2026-03-11 11:26:16 +00:00
Nick Craig-Wood 906b27d8b9 Add Billy Hughes to contributors 2026-03-11 11:26:16 +00:00
Billy Hughes e233f8b0a7 accounting: Add deletedDirs stat to core/stats help output 2026-03-09 18:43:19 +00:00
Jan-Philipp ReßlerandJan-Philipp Reßler 17a547a980 docs: added text to the label showing version-introduced info
Co-authored-by: Jan-Philipp Reßler <xodarap@xodarap.de>
2026-03-09 18:35:20 +00:00
Nick Craig-Wood cdb3ecb0fb Changelog updates from Version v1.73.2 2026-03-06 20:43:59 +00:00
Nick Craig-Wood 2d7f84576a fs/log: fix data race on OutputHandler.format field
The format field was read in Handle() without synchronization while
setFormat() could write it concurrently from InitLogging(). This
caused a data race detected by the race detector, failing
TestListBucketsAuthProxy in cmd/serve/s3.

Fix by protecting all access to format with the existing mutex.
2026-03-06 14:41:23 +00:00
dependabot[bot] ab234dcfd7 build(deps): bump docker/build-push-action from 6 to 7
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 6 to 7.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v6...v7)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-06 09:49:05 +00:00
dependabot[bot] c5bcfbac8f build(deps): bump docker/setup-buildx-action from 3 to 4
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3 to 4.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-06 09:48:25 +00:00
dependabot[bot] 88ed8e2b43 build(deps): bump docker/metadata-action from 5 to 6
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-06 09:47:33 +00:00
dependabot[bot] b097454f83 build(deps): bump docker/setup-qemu-action from 3 to 4
Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 3 to 4.
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-05 12:36:44 +00:00
dependabot[bot] 2f890114b6 build(deps): bump docker/login-action from 3 to 4
Bumps [docker/login-action](https://github.com/docker/login-action) from 3 to 4.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-05 12:36:13 +00:00
nielash 78a7d9bb8e bisync: update changelog 2026-03-03 16:13:00 -05:00
nielash 72c561d209 bisync: auto-generate rc help docs
This adds a go generate ./cmd/bisync command to autogenerate the bisync rc docs,
including the list of params.
2026-03-03 16:13:00 -05:00
nielash b864c4f9c9 bisync: add more structured info to rc output
This adds a few handy bits of info, like the session name, workdir location, and
listing file paths, to the rc output.
2026-03-03 16:13:00 -05:00
nielash bb78eb8ab2 bisync: add missing rc params - fixes #7799
This adds 11 previously-missing rc params for newer bisync features.

It also makes optional parameters truly optional. (Previously, callers were
required to supply every single one, even if using the default value.)
2026-03-03 16:13:00 -05:00
Nick Craig-Wood e11a066e00 operations: multithread copy: grab memory before making go routines
This reduces the number of go routines which can get out of hand when
using large --transfers and --multi-thread-streams from potentially
--multi-thread-streams * --transfers Go routines to --max-memory /
--multi-thread-chunk-size

It serializes the memory allocator in each transfer which should be
good for performance and reduce lock contention.
2026-03-03 14:01:11 +00:00
Nick Craig-Wood f0dfe9280c b2: add server side copy real time accounting 2026-03-03 14:01:11 +00:00
Nick Craig-Wood b8d2ce8962 s3: add server side copy real time accounting 2026-03-03 14:01:11 +00:00
Nick Craig-Wood f60b09e7ab azureblob: add server side copy real time accounting 2026-03-03 14:01:11 +00:00
Nick Craig-Wood 307f1edaf4 operations: add method to real time account server side copy
Before this change server side copies would show at 0% until they were
done then show at 100%.

With support from the backend, server side copies can now be accounted
in real time. This will only work for backends which have been
modified and themselves get feedback about how copies are going.

If the transfer fails, the bytes accounted will be reversed.
2026-03-03 14:01:11 +00:00
Nick Craig-Wood a7a3bee488 Add Duncan F to contributors 2026-03-03 14:01:11 +00:00
Duncan F 8e24a21ef2 azureblob: add --azureblob-copy-total-concurrency to limit total multipart copy concurrency 2026-03-03 14:01:11 +00:00
Nick Craig-Wood 239dae97db Add razorloves to contributors 2026-03-03 14:01:11 +00:00
razorloves 7056989972 docs: fix new drive flag typo in changelog 2026-03-03 09:53:42 +01:00
Nick Craig-Wood 056adc97d6 build: update to golang.org/x/net v0.51.0 to fix CVE-2026-27141 #9220
See: https://pkg.go.dev/vuln/GO-2026-4559
2026-02-27 11:24:16 +00:00
Nick Craig-Wood c2fd08192b Add Bjoern Franke to contributors 2026-02-27 11:22:12 +00:00
Nick Craig-Wood 9e0054983c Add Brian Bockelman to contributors 2026-02-27 11:22:12 +00:00
Nick Craig-Wood 7c336fdb6f Add Romāns Potašovs to contributors 2026-02-27 11:22:12 +00:00
Nick Craig-Wood 5d07f521dc Add Adam Kasztenny to contributors 2026-02-27 11:22:11 +00:00
Nick Craig-Wood 0d759d1280 Add hxnd to contributors 2026-02-27 11:22:11 +00:00
Nick Craig-Wood 93b1c50c14 Add Bjoern Franke to contributors 2026-02-27 11:22:11 +00:00
Nick Craig-Wood d6819d9d46 Add FTCHD to contributors 2026-02-27 11:22:11 +00:00
dependabot[bot] 65f2f59734 build(deps): bump actions/upload-artifact from 6 to 7
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-27 08:25:05 +00:00
dependabot[bot] ac177f70cb build(deps): bump actions/download-artifact from 7 to 8
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 7 to 8.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v7...v8)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '8'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-27 08:23:32 +00:00
Leon Brocard 9be4fc8c2b serve http: add gzip compression
Add gzip compression for directory listings and text assets served over HTTP.

This reduces the rclone repository file listing from 40 kB to 8 kB and reduces
the rclone MANUAL.txt from 2.7 MB to 700 kB.

This makes listings and assets served across the network load faster.

The compression level of 5 should be a good balance between size and speed.
2026-02-26 17:18:52 +00:00
Brian Bockelman cf240b6c0f webdav: permit redirects on PROPFIND for metadata
The WebDAV implementation already permits redirects on PROPFIND for
listing paths in the `listAll` method but does not permit this for
metadata in `readMetaDataForPath`.  This results in a strange experience
for endpoints that heavily use redirects -

```
rclone lsl endpoint:
```

functions and lists `hello_world.txt` in its output but

```
rclone lsl endpoint:hello_world.txt
```

Fails with a HTTP 307.

The git history for this setting indicates this was done to avoid
an issue where redirects cause a verb change to GET in the Go HTTP
client; it does not appear to be problematic with HTTP 307.

To fix, a new `CheckRedirect` function is added in the `rest` library
to force the client to use the same verb across redirects, forcing this
for the PROPFIND case.
2026-02-26 16:23:52 +00:00
Romāns Potašovs 6159ea9cf5 webdav: add missing headers for CORS
fix #7492
2026-02-26 16:23:07 +00:00
Adam Kasztenny be1fb99aee docs: Document unsupported S3 object keys with double slashes
Fixes #5063 by documenting that S3 object keys containing
consecutive forward slashes (//) are not supported by rclone.

The issue occurs because rclone normalizes paths like "a//b" to "a/b",
causing "object not found" errors when trying to access the original
object. This documentation addition explicitly warns users about this
limitation and provides workarounds.

Changes:
- Added new subsection "Important note about double slashes (//)"
  under "Restricted filename characters" in S3 documentation
- Explains the normalization behavior and its consequences
- Provides clear examples and workarounds

AI Model/Tool Attribution:
- Implemented using opencode AI assistant
- Issue analysis and documentation update performed by AI tools

Resolves: #5063
2026-02-26 16:21:56 +00:00
Prakhar Chhalotre 01095a539b touch: add metadata when using --metadata-set 2026-02-26 16:20:24 +00:00
hxnd 6578f0ad08 s3: ionos: updated regions & endpoints 2026-02-26 12:41:24 +00:00
Bjoern FrankeandBjoern Franke f4ffa54952 s3: scaleway: ONEZONE_IA is available in all zones, GLACIER only in FR-PAR
Co-authored-by: Bjoern Franke <bjo@schafweide.org>
2026-02-26 12:38:22 +00:00
Prakhar Chhalotre abed695720 drive: add integration test for handling folder names with single quotes 2026-02-26 12:37:10 +00:00
FTCHD 77892a8289 http: dark mode for browser 2026-02-26 12:29:40 +00:00
Nick Craig-Wood 9f9569ad6f docs: note that --use-server-modtime only works on some backends
Closes #6977
2026-02-26 12:00:56 +00:00
Nick Craig-Wood 80cdc4dd06 Add a1pcm to contributors 2026-02-26 12:00:56 +00:00
Nick Craig-Wood 216c9de2c4 Add Leon Brocard to contributors 2026-02-26 12:00:56 +00:00
Nick Craig-Wood 7952910e40 Add Dark Dragon to contributors 2026-02-26 12:00:56 +00:00
jzunigax2 7eed0b6825 internxt: fix Entry doesn't belong in directory errors on windows 2026-02-26 11:13:16 +00:00
a1pcm c7da3ab77f drime: fix chunk-uploaded files ignoring workspace ID
When specifying --drime-workspace-id, a file greater than the limit at
which file uploads get chunked would ignore the specified ID and get put
into the default workspace instead.

Completes the fix described in commit 2360e65 by properly closing the
chunkwriter by providing the workspace ID to the Drime API call.
2026-02-26 10:58:13 +00:00
Leon Brocard 879913da41 s3: add new Fastly Object Storage regions
Add AU East 1, EU South 1, JP Central 1, UK East 1, and US Central 1
regions and endpoints for Fastly Object Storage.

Also sort the entries alphabetically.
2026-02-26 09:02:27 +00:00
Dark Dragon 576e6145fc docs: Fix headers hierarchy for mount.md
Similar to "Mounting on macOS", "Mounting on Linux" needs to move one layer down. This also fixes the missing anchor overlay on hover.
2026-02-25 14:47:30 +01:00
Leon Brocard be73a72f93 serve http: add fallback embedded favicon
Browsers make a request to /favicon.ico when visiting pages generated
by the HTTP server.

Previously, if remotes did not have a /favicon.ico then the server
responded with a 404, causing browsers to show a default icon.

This adds a tiny fallback embedded PNG rclone favicon to help users
identify the rclone browser tab.
2026-02-25 12:48:17 +00:00
Leon Brocard 36913cda94 graphics: optimise images losslessly with ImageOptim
All PNG and JPEG images in the graphics/ and docs/static/img/
directories have been run through ImageOptim with lossless compression.
This reduces the checkout size and the size of logo files served,
without any change in visual quality.

```bash
git diff --cached --stat
docs/static/img/ncw-bitcoin-address.png                                  | Bin 1100 -> 404 bytes
docs/static/img/rclone-1200x630.png                                      | Bin 36503 -> 24220 bytes
docs/static/img/rclone-32x32.png                                         | Bin 1106 -> 704 bytes
graphics/cover.jpg                                                       | Bin 9986330 -> 8998666 bytes
graphics/logo/favicon/favicon_16px.png                                   | Bin 559 -> 389 bytes
graphics/logo/favicon/favicon_32px.png                                   | Bin 1106 -> 704 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_color_128px.png      | Bin 10651 -> 6655 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_color_256px.png      | Bin 22388 -> 14378 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_color_32px.png       | Bin 2656 -> 1650 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_color_64px.png       | Bin 5284 -> 3245 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_mono_128px.png       | Bin 9875 -> 5790 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_mono_256px.png       | Bin 21247 -> 10809 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_mono_32px.png        | Bin 2234 -> 1406 bytes
graphics/logo/logo_on_dark/logo_on_dark__horizontal_mono_64px.png        | Bin 4622 -> 2751 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_color_128px.png        | Bin 3946 -> 2444 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_color_256px.png        | Bin 8234 -> 5134 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_color_512px.png        | Bin 17223 -> 10797 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_color_64px.png         | Bin 1979 -> 1271 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_mono_128px.png         | Bin 3490 -> 2104 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_mono_256px.png         | Bin 7372 -> 4630 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_mono_512px.png         | Bin 16451 -> 8358 bytes
graphics/logo/logo_on_dark/logo_on_dark__vertical_mono_64px.png          | Bin 1684 -> 1049 bytes
graphics/logo/logo_on_dark/logo_symbol_on_dark_mono_128px.png            | Bin 3889 -> 2239 bytes
graphics/logo/logo_on_dark/logo_symbol_on_dark_mono_256px.png            | Bin 8843 -> 4917 bytes
graphics/logo/logo_on_dark/logo_symbol_on_dark_mono_512px.png            | Bin 19071 -> 9074 bytes
graphics/logo/logo_on_dark/logo_symbol_on_dark_mono_64px.png             | Bin 1731 -> 1130 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_color_128px.png    | Bin 10621 -> 6860 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_color_256px.png    | Bin 22317 -> 14747 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_color_32px.png     | Bin 2594 -> 1655 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_color_64px.png     | Bin 5184 -> 3316 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_mono_128px.png     | Bin 8839 -> 5907 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_mono_256px.png     | Bin 19305 -> 11010 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_mono_32px.png      | Bin 2092 -> 1422 bytes
graphics/logo/logo_on_light/logo_on_light__horizontal_mono_64px.png      | Bin 4198 -> 2835 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_color_128px.png      | Bin 3856 -> 2446 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_color_256px.png      | Bin 8083 -> 5179 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_color_512px.png      | Bin 16804 -> 11148 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_color_64px.png       | Bin 1932 -> 1258 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_color_800px_2to1.png | Bin 23388 -> 12019 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_mono_128px.png       | Bin 3139 -> 2106 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_mono_256px.png       | Bin 6347 -> 4630 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_mono_512px.png       | Bin 14138 -> 8358 bytes
graphics/logo/logo_on_light/logo_on_light__vertical_mono_64px.png        | Bin 1522 -> 1038 bytes
graphics/logo/logo_on_light/logo_symbol_on_light_mono_128px.png          | Bin 3193 -> 2241 bytes
graphics/logo/logo_on_light/logo_symbol_on_light_mono_256px.png          | Bin 6992 -> 4917 bytes
graphics/logo/logo_on_light/logo_symbol_on_light_mono_512px.png          | Bin 16638 -> 9074 bytes
graphics/logo/logo_on_light/logo_symbol_on_light_mono_64px.png           | Bin 1568 -> 1127 bytes
graphics/logo/logo_symbol/logo_symbol_color_128px.png                    | Bin 4468 -> 2783 bytes
graphics/logo/logo_symbol/logo_symbol_color_16px.png                     | Bin 1787 -> 391 bytes
graphics/logo/logo_symbol/logo_symbol_color_256px.png                    | Bin 9362 -> 5835 bytes
graphics/logo/logo_symbol/logo_symbol_color_512px.png                    | Bin 19898 -> 12946 bytes
graphics/logo/logo_symbol/logo_symbol_color_600px_spaced.png             | Bin 18775 -> 13537 bytes
graphics/logo/logo_symbol/logo_symbol_color_64px.png                     | Bin 2235 -> 1380 bytes
```
2026-02-25 12:45:49 +00:00
Nick Craig-Wood 699e4cfb23 docs: update sponsors 2026-02-23 13:05:33 +00:00
Nick Craig-Wood bc5cad8792 Add Jan-Philipp Reßler to contributors 2026-02-23 13:05:25 +00:00
Nick Craig-Wood 9024962fc4 Add Chris to contributors 2026-02-23 13:05:25 +00:00
Nick Craig-Wood aa1f4ace64 Add Shlomi Avihou to contributors 2026-02-23 13:05:25 +00:00
Nick Craig-Wood dd1d750c55 Add Jan-Philipp Reßler to contributors 2026-02-23 13:05:25 +00:00
Nick Craig-Wood 5a2564c6e2 Add Varun Chawla to contributors 2026-02-23 13:05:24 +00:00
Nick Craig-Wood 82cc80cc6f Add Prakhar Chhalotre to contributors 2026-02-23 13:05:24 +00:00
Chris 7d0a8bf850 s3: add Object Lock support
Add support for S3 Object Lock with the following new options:

- --s3-object-lock-mode: set retention mode (GOVERNANCE/COMPLIANCE/copy)
- --s3-object-lock-retain-until-date: set retention date (RFC3339/duration/copy)
- --s3-object-lock-legal-hold-status: set legal hold (ON/OFF/copy)
- --s3-bypass-governance-retention: bypass GOVERNANCE lock on delete
- --s3-bucket-object-lock-enabled: enable Object Lock on bucket creation
- --s3-object-lock-set-after-upload: apply lock via separate API calls

The special value "copy" preserves the source object's setting when used
with --metadata flag, enabling scenarios like cloning objects from
COMPLIANCE to GOVERNANCE mode while preserving the original retention date.

Includes integration tests that create a temporary Object Lock bucket covering:
- Retention Mode and Date
- Legal Hold
- Apply settings after upload
- Override protections using bypass-governance flag
The tests are gracefully skipped on providers that do not support Object Lock.

Fixes #4683
Closes #7894 #7893 #8866
2026-02-20 16:40:24 +00:00
Varun Chawla fd8b28d36d webdav: escape reserved characters in URL path segments
Use URLPathEscapeAll instead of URLPathEscape for path encoding.

URLPathEscape relies on Go's url.URL.String() which only minimally
escapes paths - reserved sub-delimiter characters like semicolons and
equals signs pass through unescaped. Per RFC 3986 section 3.3, these
characters must be percent-encoded when used as literal values in
path segments.

Some WebDAV servers (notably dCache/Jetty) interpret unescaped
semicolons as path parameter delimiters, which truncates filenames
at the semicolon position. URLPathEscapeAll encodes everything
except [A-Za-z0-9/], which is safe for all servers.

Fixes #9082
2026-02-20 16:30:15 +00:00
Shlomi Avihou c63ecace41 s3: add Zadara Object Storage provider 2026-02-20 16:27:17 +00:00
Jan-Philipp ReßlerandJan-Philipp Reßler 0c8c3d8fb9 bisync: add group Sync to the bisync command
Co-authored-by: Jan-Philipp Reßler <xodarap@xodarap.de>
2026-02-20 16:21:48 +00:00
Varun Chawla 5042f360f0 archive: extract: strip "./" prefix from tar entry paths
Tar files created from the current directory (e.g. tar -czf archive.tar.gz .)
produce entries prefixed with "./". When extracting, rclone's character
encoding replaces the "." with a full-width dot (U+FF0E), creating a
spurious directory instead of merging into the destination root.

Strip the leading "./" from NameInArchive before processing. Only "./"
is stripped specifically to avoid enabling path traversal attacks via
"../".

Fixes #9168
2026-02-20 11:46:53 +00:00
Prakhar Chhalotre 9601dbce87 accounting: update String method output format for clarity in transfer rate representation - fixes #9129 2026-02-18 15:19:47 +00:00
Nick Craig-Wood e06f0b0595 docs: add instructions on how to update Go version 2026-02-18 12:38:50 +00:00
Nick Craig-Wood b2866f0291 build: modernize Go code with go fix for go1.25 2026-02-18 12:11:52 +00:00
Nick Craig-Wood cf97f250df build: update all dependencies
Could not update github.com/coreos/go-systemd as the new version doesn't build under freebsd

See: https://github.com/coreos/go-systemd/issues/509
2026-02-18 11:33:48 +00:00
Nick Craig-Wood 627b763d4b lib/rest: remove go1.24 workaround now go1.25 is the minimum 2026-02-18 11:33:48 +00:00
Nick Craig-Wood f14945f9c1 build: update to go1.26 and make go1.25 the minimum required version 2026-02-18 11:33:48 +00:00
Nick Craig-Wood 391661fdb4 Add Jack Kelly to contributors 2026-02-18 11:33:48 +00:00
Nick Craig-Wood faffd0a6f1 Changelog updates from Version v1.73.1 2026-02-17 18:22:21 +00:00
Nick Craig-Wood 6cc3356f8e build: fix build using go 1.26.0 instead of go 1.25.7
In the actions config use Go ~1.25.7 to pin the go version to 1.25.x,
x >= 7.

Before this it was choosing Go 1.26.0 which isn't what we want.
2026-02-17 17:05:45 +00:00
Nick Craig-Wood 07e76419c9 fs/march: fix runtime: program exceeds 10000-thread limit
Before this change when doing a sync with `--no-traverse` and
`--files-from` we could call `NewObject` a total of `--checkers` *
`--checkers` times simultaneously.

With `--checkers 128` this can exceed the 10,000 thread limit and
fails when run on a local to local transfer because `NewObject` calls
`lstat` which is a syscall which needs an OS thread of its own.

This patch uses a weighted semaphore to limit the number of
simultaneous calls to `NewObject` to `--checkers` instead which won't
blow the 10,000 thread limit and is far more sensible use of OS
resources.

Fixes #9073
2026-02-17 12:27:17 +00:00
Nick Craig-Wood 60c4f35b56 accounting: fix missing server side stats from core/stats rc
These stats weren't being updated in the global stats read by rc
core/stats:

- transferQueue
- deletesSize
- serverSideCopies
- serverSideCopyBytes
- serverSideMoves
- serverSideMoveBytes
2026-02-17 12:27:17 +00:00
Nick Craig-Wood 15a9c0fd36 pacer: re-read the sleep time as it may be stale
Before this change we read sleepTime before acquiring the pacer token
and uses that possibly stale value to schedule the token return. When
many goroutines enter while sleepTime is high (e.g., 10s), each
goroutine caches this 10s value. Even if successful calls rapidly
decay the pacer state to 0, the queued goroutines still schedule 10s
token returns, so the queue drains at 1 req/10s for the entire herd.
This can create multi‑minute delays even after the pacer has dropped
to 0.

After this change we refresh the sleep time after getting the token.

This problem was introduced by the desire to skip reading the pacer
token entirely when sleepTime is 0 in high performance backends (eg
s3, azure blob).
2026-02-17 12:27:17 +00:00
Nick Craig-Wood 8b85ffbf03 pacer: fix deadlock between pacer token and --max-connections
It was possible in the presence of --max-connections and recursive
calls to the pacer to deadlock it leaving all connections waiting on
either a max connection token or a pacer token.

This fixes the problem by making sure we return the pacer token on
schedule if we take it.

This also short circuits the pacer token if sleepTime is 0.
2026-02-17 12:27:17 +00:00
Nick Craig-Wood 26fb659fe4 test_all: increase retries for Internxt eventual consistency 2026-02-17 12:27:17 +00:00
Nick Craig-Wood 7aa3d8a32f build: fix CVE-2025-68121 by updating go to 1.25.7 or later - fixes #9167 2026-02-17 12:27:17 +00:00
Nick Craig-Wood b7ebec865b drime: fix files and directories being created in the default workspace
Before this change directories and files were created in the default
workspace, not the workspace specified by --drime-workspace-id.
2026-02-17 12:27:17 +00:00
Nick Craig-Wood a60d09c43d docs: update sponsors 2026-02-17 12:27:04 +00:00
Nick Craig-Wood 14a47937c0 Add kingston125 to contributors 2026-02-17 12:22:11 +00:00
Jack Kelly 64d6916161 copyurl: Extend copyurl docs with an example of CSV FILENAMEs starting with a path. 2026-02-17 11:46:37 +00:00
kingston125 ae778f1413 filelu: migrate API calls to lib/rest 2026-02-16 17:45:42 +00:00
José Zúniga 33859568d6 internxt: implement re-login under refresh logic, improve retry logic - fixes #9174 2026-02-13 19:18:51 +00:00
Nick Craig-Wood 4b3aa5aea0 docs: add ExchangeRate-API as a sponsor 2026-02-12 14:08:20 +00:00
Nick Craig-Wood 349487bb7f Add Cohinem to contributors 2026-02-12 14:08:20 +00:00
Nick Craig-Wood b70b2fff16 Add Leon Brocard to contributors 2026-02-12 14:08:20 +00:00
Leon Brocard 32307e9226 s3: remove StackPath Object Storage provider
StackPath's object storage service no longer exists and all S3
endpoints are no longer operational.

Before this change, users could select StackPath as an S3 provider
during configuration, but connections would fail as the endpoints no
longer respond and the service has been discontinued.

After this change, StackPath is removed from the list of supported
S3 providers, preventing users from attempting to configure a
non-functional service.

Fixes #9148
2026-02-11 23:12:35 +01:00
Cohinem 2bd6630c2e drime: implement About 2026-02-11 14:06:31 +00:00
albertony 54c2078f25 build: bump github.com/go-chi/chi/v5 from 5.2.3 to 5.2.5 to fix GO-2026-4316 2026-02-11 11:34:29 +01:00
kingston125 4f284614a4 Set list_version to 2 for FileLu S3 configuration 2026-02-11 11:32:11 +01:00
kingston125 eef0b39a2c filelu: add multipart upload support with configurable cutoff 2026-02-05 13:09:16 +00:00
kingston125 37f6336636 filelu: add multipart init response type 2026-02-05 13:09:16 +00:00
kingston125 1049f88a1d filelu: add comment for response body wrapping 2026-02-05 13:09:16 +00:00
kingston125 327ca25a4d filelu: avoid buffering entire file in memory
Avoid buffering the entire file in memory during download, especially
for large files.
2026-02-05 13:09:16 +00:00
Nick Craig-Wood 673e24a60f docs: update sponsor logos 2026-02-05 12:27:51 +00:00
Leon Brocard 43db4c5dc7 s3: add Fastly Object Storage provider
- Add new Fastly provider with US East, US West, and EU Central regions
- Add `etag_is_not_md5` quirk for providers with mandatory encryption
- Disable server-side copy for Fastly (not supported)
2026-02-05 12:10:53 +00:00
Enduriel 88b484722a filen: fix potential panic in case of error during upload 2026-02-05 12:08:20 +00:00
Enduriel ed5bd327c0 filen: fix 32 bit targets not being able to list directories Fixes #9142
or do pretty much anything,
this was caused by timestamps not being read to 64 bit integers
2026-02-05 12:06:20 +00:00
wiserain 341ce61a2a pikpak: support custom filenames for addurl backend command - fixes #9111
Extended the addurl backend command to accept an optional filename parameter, 
enabling customized naming for downloaded files.
2026-02-03 08:13:03 +09:00
Nick Craig-Wood 9abf9d38c0 Start v1.74.0-DEV development 2026-01-30 22:19:04 +00:00
169 changed files with 4386 additions and 1202 deletions

No files matched your search

+11 -11
View File
@@ -29,12 +29,12 @@ jobs:
strategy:
fail-fast: false
matrix:
job_name: ['linux', 'linux_386', 'mac_amd64', 'mac_arm64', 'windows', 'other_os', 'go1.24']
job_name: ['linux', 'linux_386', 'mac_amd64', 'mac_arm64', 'windows', 'other_os', 'go1.25']
include:
- job_name: linux
os: ubuntu-latest
go: '>=1.25.0-rc.1'
go: '~1.26.0'
gotags: cmount
build_flags: '-include "^linux/"'
check: true
@@ -45,14 +45,14 @@ jobs:
- job_name: linux_386
os: ubuntu-latest
go: '>=1.25.0-rc.1'
go: '~1.26.0'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '>=1.25.0-rc.1'
go: '~1.26.0'
gotags: 'cmount'
build_flags: '-include "^darwin/amd64" -cgo'
quicktest: true
@@ -61,14 +61,14 @@ jobs:
- job_name: mac_arm64
os: macos-latest
go: '>=1.25.0-rc.1'
go: '~1.26.0'
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.25.0-rc.1'
go: '~1.26.0'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -78,14 +78,14 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '>=1.25.0-rc.1'
go: '~1.26.0'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
- job_name: go1.24
- job_name: go1.25
os: ubuntu-latest
go: '1.24'
go: '~1.25.7'
quicktest: true
racequicktest: true
@@ -224,7 +224,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v6
with:
go-version: '>=1.24.0-rc.1'
go-version: '~1.26.0'
check-latest: true
cache: false
@@ -315,7 +315,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '>=1.25.0-rc.1'
go-version: '~1.26.0'
- name: Set global environment variables
run: |
@@ -100,7 +100,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v6
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: manifest,manifest-descriptor # Important for digest annotation (used by Github packages)
with:
@@ -122,10 +122,10 @@ jobs:
type=raw,value=beta,enable={{is_default_branch}}
- name: Setup QEMU
uses: docker/setup-qemu-action@v3
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Load Go Build Cache for Docker
id: go-cache
@@ -148,7 +148,7 @@ jobs:
skip-extraction: ${{ steps.go-cache.outputs.cache-hit }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
uses: docker/login-action@v4
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
@@ -159,7 +159,7 @@ jobs:
- name: Build and Publish Image Digest
id: build
uses: docker/build-push-action@v6
uses: docker/build-push-action@v7
with:
file: Dockerfile
context: .
@@ -183,7 +183,7 @@ jobs:
touch "/tmp/digests/${digest#sha256:}"
- name: Upload Image Digest
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: digests-${{ env.PLATFORM }}
path: /tmp/digests/*
@@ -198,7 +198,7 @@ jobs:
steps:
- name: Download Image Digests
uses: actions/download-artifact@v7
uses: actions/download-artifact@v8
with:
path: /tmp/digests
pattern: digests-*
@@ -210,7 +210,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v6
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
with:
@@ -261,16 +261,16 @@ jobs:
env.write(f"ANNOTATIONS={annotations_string}\n")
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Login to Docker Hub
uses: docker/login-action@v3
uses: docker/login-action@v4
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
uses: docker/login-action@v4
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
+1
View File
@@ -146,6 +146,7 @@ MANUAL.txt: MANUAL.md
commanddocs: rclone
go generate ./lib/transform
go generate ./cmd/bisync
-@rmdir -p '$$HOME/.config/rclone'
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs --config=/notfound docs/content/
@[ ! -e '$$HOME' ] || (echo 'Error: created unwanted directory named $$HOME' && exit 1)
+2 -1
View File
@@ -44,6 +44,7 @@ directories to and from different cloud storage providers.
- Dropbox [:page_facing_up:](https://rclone.org/dropbox/)
- Enterprise File Fabric [:page_facing_up:](https://rclone.org/filefabric/)
- Exaba [:page_facing_up:](https://rclone.org/s3/#exaba)
- Fastly Object Storage [:page_facing_up:](https://rclone.org/s3/#fastly)
- Fastmail Files [:page_facing_up:](https://rclone.org/webdav/#fastmail-files)
- FileLu [:page_facing_up:](https://rclone.org/filelu/)
- Filen [:page_facing_up:](https://rclone.org/filen/)
@@ -117,7 +118,6 @@ directories to and from different cloud storage providers.
- Shade [:page_facing_up:](https://rclone.org/shade/)
- SMB / CIFS [:page_facing_up:](https://rclone.org/smb/)
- Spectra Logic [:page_facing_up:](https://rclone.org/s3/#spectralogic)
- StackPath [:page_facing_up:](https://rclone.org/s3/#stackpath)
- Storj [:page_facing_up:](https://rclone.org/storj/)
- SugarSync [:page_facing_up:](https://rclone.org/sugarsync/)
- Synology C2 Object Storage [:page_facing_up:](https://rclone.org/s3/#synology-c2)
@@ -126,6 +126,7 @@ directories to and from different cloud storage providers.
- Wasabi [:page_facing_up:](https://rclone.org/s3/#wasabi)
- WebDAV [:page_facing_up:](https://rclone.org/webdav/)
- Yandex Disk [:page_facing_up:](https://rclone.org/yandex/)
- Zadara Object Storage [:page_facing_up:](https://rclone.org/s3/#zadara)
- Zoho WorkDrive [:page_facing_up:](https://rclone.org/zoho/)
- Zata.ai [:page_facing_up:](https://rclone.org/s3/#Zata)
- The local filesystem [:page_facing_up:](https://rclone.org/local/)
+55 -1
View File
@@ -32,10 +32,11 @@ This file describes how to make the various kinds of releases
- make sign_upload
- make check_sign
- make upload
- make upload_test_website # check sponsors are correct/unchanged
- make upload_website
- make upload_github
- make startdev # make startstable for stable branch
- \# announce with forum post, twitter post, patreon post
- \# announce with forum post, twitter post, and post to annoucements list
## Update dependencies
@@ -109,6 +110,59 @@ go run github.com/icholy/gomajor@latest list -major
Expect API breakage when updating major versions.
## Updating Go
When a new Go stable is released update to it. We support the current
stable Go and the previous release which is in line with the rest of
the Go ecosystem.
These files will need editing:
- `.github/workflows/build.yml` - change current and previous Go versions
- `docs/content/install.md` - change minimum Go version required
- `fs/versioncheck.go` - update minimum Go version required
- `go.mod` - update minimum Go version required
Check it builds
- `make GOTAGS=cmount`
- `make compiletest`
Assuming `go1.XX` is current and `go1.YY` is previous version:
Use `git grep go1.YY` and `git grep go1.YY` to look for opportunities
to remove build tags we no longer need.
Commit with message like this:
```text
build: update to go1.YY and make go1.YY the minimum required version
```
Send to CI and if it passes, merge.
### gofix
Updating the minimum required version of Go is a good opportunity to
run the `go fix` command to modernize Go usage.
This needs to be run for all architectures.
```console
GOOS=linux go fix -tags cmount ./...
GOOS=freebsd go fix -tags cmount ./...
GOOS=windows go fix -tags cmount ./...
GOOS=darwin go fix -tags cmount ./...
```
Examine the diff carefully.
Commit with message
```text
build: modernize Go code with go fix for go1.YY
```
## Tidy beta
At some point after the release run
+1 -1
View File
@@ -1 +1 @@
v1.73.0
v1.74.0
+45 -29
View File
@@ -14,6 +14,7 @@ import (
"errors"
"fmt"
"io"
"maps"
"net/http"
"path"
"slices"
@@ -46,6 +47,7 @@ import (
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/transferaccounter"
"golang.org/x/sync/errgroup"
)
@@ -184,6 +186,16 @@ In tests, copy speed increases almost linearly with copy
concurrency.`,
Default: 512,
Advanced: true,
}, {
Name: "copy_total_concurrency",
Help: `Global concurrency limit for multipart copy chunks.
This limits the total number of multipart copy chunks running at once
across all files.
Set to 0 to disable this limiter.`,
Default: 0,
Advanced: true,
}, {
Name: "use_copy_blob",
Help: `Whether to use the Copy Blob API when copying to the same storage account.
@@ -345,21 +357,22 @@ rclone does if you know the container exists already.
// Options defines the configuration for this backend
type Options struct {
auth.Options
ChunkSize fs.SizeSuffix `config:"chunk_size"`
CopyCutoff fs.SizeSuffix `config:"copy_cutoff"`
CopyConcurrency int `config:"copy_concurrency"`
UseCopyBlob bool `config:"use_copy_blob"`
UploadConcurrency int `config:"upload_concurrency"`
ListChunkSize uint `config:"list_chunk"`
AccessTier string `config:"access_tier"`
ArchiveTierDelete bool `config:"archive_tier_delete"`
DisableCheckSum bool `config:"disable_checksum"`
Enc encoder.MultiEncoder `config:"encoding"`
PublicAccess string `config:"public_access"`
DirectoryMarkers bool `config:"directory_markers"`
NoCheckContainer bool `config:"no_check_container"`
NoHeadObject bool `config:"no_head_object"`
DeleteSnapshots string `config:"delete_snapshots"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
CopyCutoff fs.SizeSuffix `config:"copy_cutoff"`
CopyConcurrency int `config:"copy_concurrency"`
CopyTotalConcurrency int `config:"copy_total_concurrency"`
UseCopyBlob bool `config:"use_copy_blob"`
UploadConcurrency int `config:"upload_concurrency"`
ListChunkSize uint `config:"list_chunk"`
AccessTier string `config:"access_tier"`
ArchiveTierDelete bool `config:"archive_tier_delete"`
DisableCheckSum bool `config:"disable_checksum"`
Enc encoder.MultiEncoder `config:"encoding"`
PublicAccess string `config:"public_access"`
DirectoryMarkers bool `config:"directory_markers"`
NoCheckContainer bool `config:"no_check_container"`
NoHeadObject bool `config:"no_head_object"`
DeleteSnapshots string `config:"delete_snapshots"`
}
// Fs represents a remote azure server
@@ -381,6 +394,7 @@ type Fs struct {
cache *bucket.Cache // cache for container creation status
pacer *fs.Pacer // To pace and retry the API calls
uploadToken *pacer.TokenDispenser // control concurrency
copyToken *pacer.TokenDispenser // global multipart copy concurrency limiter
publicAccess container.PublicAccessType // Container Public Access Level
// user delegation cache
@@ -586,6 +600,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
ci: ci,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
copyToken: pacer.NewTokenDispenser(opt.CopyTotalConcurrency),
cache: bucket.NewCache(),
cntSVCcache: make(map[string]*container.Client, 1),
}
@@ -729,8 +744,8 @@ func parseXMsTags(s string) (map[string]string, error) {
return map[string]string{}, nil
}
out := make(map[string]string)
parts := strings.Split(s, ",")
for _, p := range parts {
parts := strings.SplitSeq(s, ",")
for p := range parts {
p = strings.TrimSpace(p)
if p == "" {
continue
@@ -893,9 +908,7 @@ func assembleCopyParams(ctx context.Context, f *Fs, src fs.Object, srcProps *blo
if meta == nil {
meta = make(map[string]*string, len(userMeta))
}
for k, v := range userMeta {
meta[k] = v
}
maps.Copy(meta, userMeta)
}
// Apply tags if any
if len(mappedTags) > 0 {
@@ -992,9 +1005,7 @@ func (o *Object) applyMappedMetadata(ctx context.Context, src fs.ObjectInfo, ui
if o.tags == nil {
o.tags = make(map[string]string, len(tags))
}
for k, v := range tags {
o.tags[k] = v
}
maps.Copy(o.tags, tags)
}
if mappedModTime != nil {
@@ -1745,18 +1756,26 @@ func (f *Fs) copyMultipart(ctx context.Context, remote, dstContainer, dstPath st
blockIDs = make([]string, numParts) // list of blocks for finalize
g, gCtx = errgroup.WithContext(ctx)
checker = newCheckForInvalidBlockOrBlob("copy", o)
account = transferaccounter.Get(ctx)
)
g.SetLimit(f.opt.CopyConcurrency)
fs.Debugf(o, "Starting multipart copy with %d parts of size %v", numParts, fs.SizeSuffix(partSize))
account.Start()
for partNum := uint64(0); partNum < uint64(numParts); partNum++ {
// Fail fast, in case an errgroup managed function returns an error
// gCtx is cancelled. There is no point in uploading all the other parts.
if gCtx.Err() != nil {
break
}
if f.opt.CopyTotalConcurrency > 0 {
f.copyToken.Get()
}
partNum := partNum // for closure
g.Go(func() error {
if f.opt.CopyTotalConcurrency > 0 {
defer f.copyToken.Put()
}
blockID := bic.newBlockID(partNum)
options := blockblob.StageBlockFromURLOptions{
Range: blob.HTTPRange{
@@ -1790,6 +1809,7 @@ func (f *Fs) copyMultipart(ctx context.Context, remote, dstContainer, dstPath st
return fmt.Errorf("multipart copy: failed to copy chunk %d with %v bytes: %w", partNum+1, -1, err)
}
blockIDs[partNum] = blockID
account.Add(options.Range.Count)
return nil
})
}
@@ -1859,9 +1879,7 @@ func (f *Fs) copySinglepart(ctx context.Context, remote, dstContainer, dstPath s
// Apply tags and post-copy headers only when mapping requested changes
if len(tags) > 0 {
options.BlobTags = make(map[string]string, len(tags))
for k, v := range tags {
options.BlobTags[k] = v
}
maps.Copy(options.BlobTags, tags)
}
if hadMapping {
// Only set metadata explicitly when mapping was requested; otherwise
@@ -2062,9 +2080,7 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
// Merge user metadata (already lower-cased keys)
metadataMu.Lock()
for k, v := range o.meta {
m[k] = v
}
maps.Copy(m, o.meta)
metadataMu.Unlock()
return m, nil
+7 -7
View File
@@ -287,13 +287,13 @@ type StartLargeFileRequest struct {
// StartLargeFileResponse is the response to StartLargeFileRequest
type StartLargeFileResponse struct {
ID string `json:"fileId"` // The unique identifier for this version of this file. Used with b2_get_file_info, b2_download_file_by_id, and b2_delete_file_version.
Name string `json:"fileName"` // The name of this file, which can be used with b2_download_file_by_name.
AccountID string `json:"accountId"` // The identifier for the account.
BucketID string `json:"bucketId"` // The unique ID of the bucket.
ContentType string `json:"contentType"` // The MIME type of the file.
Info map[string]string `json:"fileInfo"` // The custom information that was uploaded with the file. This is a JSON object, holding the name/value pairs that were uploaded with the file.
UploadTimestamp Timestamp `json:"uploadTimestamp,omitempty"` // This is a UTC time when this file was uploaded.
ID string `json:"fileId"` // The unique identifier for this version of this file. Used with b2_get_file_info, b2_download_file_by_id, and b2_delete_file_version.
Name string `json:"fileName"` // The name of this file, which can be used with b2_download_file_by_name.
AccountID string `json:"accountId"` // The identifier for the account.
BucketID string `json:"bucketId"` // The unique ID of the bucket.
ContentType string `json:"contentType"` // The MIME type of the file.
Info map[string]string `json:"fileInfo"` // The custom information that was uploaded with the file. This is a JSON object, holding the name/value pairs that were uploaded with the file.
UploadTimestamp Timestamp `json:"uploadTimestamp"` // This is a UTC time when this file was uploaded.
}
// GetUploadPartURLRequest is passed to b2_get_upload_part_url
+8 -1
View File
@@ -22,6 +22,7 @@ import (
"github.com/rclone/rclone/lib/atexit"
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/rest"
"github.com/rclone/rclone/lib/transferaccounter"
"golang.org/x/sync/errgroup"
)
@@ -499,10 +500,12 @@ func (up *largeUpload) Copy(ctx context.Context) (err error) {
defer atexit.OnError(&err, func() { _ = up.Abort(ctx) })()
fs.Debugf(up.o, "Starting %s of large file in %d chunks (id %q)", up.what, up.parts, up.id)
var (
account = transferaccounter.Get(ctx)
g, gCtx = errgroup.WithContext(ctx)
remaining = up.size
)
g.SetLimit(up.f.opt.UploadConcurrency)
account.Start()
for part := range up.parts {
// Fail fast, in case an errgroup managed function returns an error
// gCtx is cancelled. There is no point in copying all the other parts.
@@ -514,7 +517,11 @@ func (up *largeUpload) Copy(ctx context.Context) (err error) {
part := part // for the closure
g.Go(func() (err error) {
return up.copyChunk(gCtx, part, reqSize)
err = up.copyChunk(gCtx, part, reqSize)
if err == nil {
account.Add(reqSize)
}
return err
})
remaining -= reqSize
}
+10
View File
@@ -173,6 +173,7 @@ type MultiPartCreateRequest struct {
Extension string `json:"extension"`
ParentID json.Number `json:"parent_id"`
RelativePath string `json:"relativePath"`
WorkspaceID string `json:"workspaceId,omitempty"`
}
// MultiPartCreateResponse is returned by POST /s3/multipart/create
@@ -223,6 +224,7 @@ type MultiPartEntriesRequest struct {
ClientExtension string `json:"clientExtension"`
ParentID json.Number `json:"parent_id"`
RelativePath string `json:"relativePath"`
WorkspaceID string `json:"workspaceId,omitempty"`
}
// MultiPartEntriesResponse is the result of POST /s3/entries
@@ -235,3 +237,11 @@ type MultiPartAbort struct {
UploadID string `json:"uploadId"`
Key string `json:"key"`
}
// SpaceUsageResponse is returned by GET /user/space-usage
type SpaceUsageResponse struct {
Used int64 `json:"used"`
Available int64 `json:"available"`
Status string `json:"status"`
SEO any `json:"seo"`
}
+59 -8
View File
@@ -476,8 +476,12 @@ func (f *Fs) createDir(ctx context.Context, pathID, leaf string, modTime time.Ti
var resp *http.Response
var result api.CreateFolderResponse
opts := rest.Opts{
Method: "POST",
Path: "/folders",
Method: "POST",
Path: "/folders",
Parameters: url.Values{},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
}
mkdir := api.CreateFolderRequest{
Name: f.opt.Enc.FromStandardName(leaf),
@@ -779,8 +783,12 @@ func (f *Fs) patch(ctx context.Context, id, attribute string, value string) (ite
}
var result api.UpdateItemResponse
opts := rest.Opts{
Method: "PUT",
Path: "/file-entries/" + id,
Method: "PUT",
Path: "/file-entries/" + id,
Parameters: url.Values{},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
}
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
@@ -807,8 +815,12 @@ func (f *Fs) move(ctx context.Context, id, newDirID string) (err error) {
}
var result api.MoveResponse
opts := rest.Opts{
Method: "POST",
Path: "/file-entries/move",
Method: "POST",
Path: "/file-entries/move",
Parameters: url.Values{},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
}
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
@@ -945,8 +957,12 @@ func (f *Fs) copy(ctx context.Context, id, newDirID string) (item *api.Item, err
}
var result api.CopyResponse
opts := rest.Opts{
Method: "POST",
Path: "/file-entries/duplicate",
Method: "POST",
Path: "/file-entries/duplicate",
Parameters: url.Values{},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
}
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, &request, &result)
@@ -1114,6 +1130,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
Extension: strings.TrimPrefix(path.Ext(leaf), `.`),
ParentID: json.Number(directoryID),
RelativePath: f.opt.Enc.FromStandardPath(path.Join(f.root, remote)),
WorkspaceID: f.opt.WorkspaceID,
}
var resp api.MultiPartCreateResponse
@@ -1297,6 +1314,7 @@ func (s *drimeChunkWriter) Close(ctx context.Context) error {
ClientExtension: s.extension,
ParentID: s.parentID,
RelativePath: s.relativePath,
WorkspaceID: s.f.opt.WorkspaceID,
}
entriesOpts := rest.Opts{
@@ -1344,6 +1362,37 @@ func (s *drimeChunkWriter) Abort(ctx context.Context) error {
return nil
}
// About gets quota information
func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
opts := rest.Opts{
Method: "GET",
Path: "/user/space-usage",
Parameters: url.Values{},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
}
var resp *http.Response
var result api.SpaceUsageResponse
var err error
err = f.pacer.Call(func() (bool, error) {
resp, err = f.srv.CallJSON(ctx, &opts, nil, &result)
return shouldRetry(ctx, resp, err)
})
if err != nil {
return nil, fmt.Errorf("failed to get Drime Quota: %w", err)
}
usage := &fs.Usage{
Total: fs.NewUsageValue(result.Available),
Used: fs.NewUsageValue(result.Used),
Free: fs.NewUsageValue(result.Available - result.Used),
}
return usage, nil
}
// ------------------------------------------------------------
// Fs returns the parent Fs
@@ -1509,6 +1558,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
MultipartParams: url.Values{
"parentId": {directoryID},
"relativePath": {encodedLeaf},
"workspaceId": {o.fs.opt.WorkspaceID},
},
MultipartContentName: "file",
MultipartFileName: encodedLeaf,
@@ -1555,6 +1605,7 @@ var (
_ fs.Mover = (*Fs)(nil)
_ fs.DirMover = (*Fs)(nil)
_ fs.DirCacheFlusher = (*Fs)(nil)
_ fs.Abouter = (*Fs)(nil)
_ fs.OpenChunkWriter = (*Fs)(nil)
_ fs.Object = (*Object)(nil)
_ fs.IDer = (*Object)(nil)
+39
View File
@@ -643,6 +643,44 @@ func (f *Fs) InternalTestAgeQuery(t *testing.T) {
assert.Contains(t, subFs.lastQuery, timeQuery)
}
// TestIntegration/FsMkdir/FsPutFiles/Internal/SingleQuoteFolder
func (f *Fs) InternalTestSingleQuoteFolder(t *testing.T) {
ctx := context.Background()
// Test various folder names containing single quotes
for _, name := range []string{
"'",
"''",
"'a'",
"it's a test",
} {
t.Run(name, func(t *testing.T) {
dir := "singleQuoteTest/" + name
err := f.Mkdir(ctx, dir)
require.NoError(t, err)
defer func() {
err := f.Rmdir(ctx, dir)
assert.NoError(t, err)
}()
entries, err := f.List(ctx, "singleQuoteTest")
require.NoError(t, err)
found := false
for _, entry := range entries {
if entry.Remote() == dir {
found = true
break
}
}
assert.True(t, found, "directory %q not found in listing", name)
})
}
err := f.Rmdir(ctx, "singleQuoteTest")
assert.NoError(t, err)
}
func (f *Fs) InternalTest(t *testing.T) {
// These tests all depend on each other so run them as nested tests
t.Run("DocumentImport", func(t *testing.T) {
@@ -662,6 +700,7 @@ func (f *Fs) InternalTest(t *testing.T) {
t.Run("CopyOrMoveID", f.InternalTestCopyOrMoveID)
t.Run("Query", f.InternalTestQuery)
t.Run("AgeQuery", f.InternalTestAgeQuery)
t.Run("SingleQuoteFolder", f.InternalTestSingleQuoteFolder)
t.Run("ShouldRetry", f.InternalTestShouldRetry)
}
+603 -139
View File
@@ -29,6 +29,7 @@ import (
"path"
"regexp"
"strings"
"sync"
"time"
"unicode/utf8"
@@ -222,17 +223,17 @@ All other operations will be disabled.`,
}, {
Name: "shared_folders",
Help: `Instructs rclone to work on shared folders.
When this flag is used with no path only the List operation is supported and
all available shared folders will be listed. If you specify a path the first part
will be interpreted as the name of shared folder. Rclone will then try to mount this
shared to the root namespace. On success shared folder rclone proceeds normally.
The shared folder is now pretty much a normal folder and all normal operations
are supported.
Note that we don't unmount the shared folder afterwards so the
--dropbox-shared-folders can be omitted after the first use of a particular
shared folder.
When this flag is used with no path only the List operation is supported and
all available shared folders will be listed. If you specify a path the first part
will be interpreted as the name of shared folder and rclone will list and access
files within it using the shared folder's namespace. This works for all shared
folder types including team folders.
Write operations (upload, delete, mkdir, copy, move) are supported within
shared folders. Server-side copy and move operations only work within the
same shared folder - cross-shared-folder operations will fall back to
upload/download.
See also --dropbox-root-namespace for an alternative way to work with shared
folders.`,
@@ -320,22 +321,25 @@ type Options struct {
// Fs represents a remote dropbox server
type Fs struct {
name string // name of this remote
root string // the path we are working on
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv files.Client // the connection to the dropbox server
svc files.Client // the connection to the dropbox server (unauthorized)
sharing sharing.Client // as above, but for generating sharing links
users users.Client // as above, but for accessing user information
team team.Client // for the Teams API
slashRoot string // root with "/" prefix, lowercase
slashRootSlash string // root with "/" prefix and postfix, lowercase
pacer *fs.Pacer // To pace the API calls
ns string // The namespace we are using or "" for none
batcher *batcher.Batcher[*files.UploadSessionFinishArg, *files.FileMetadata]
exportExts []exportExtension
name string // name of this remote
root string // the path we are working on
opt Options // parsed options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
srv files.Client // the connection to the dropbox server
svc files.Client // the connection to the dropbox server (unauthorized)
sharing sharing.Client // as above, but for generating sharing links
users users.Client // as above, but for accessing user information
team team.Client // for the Teams API
slashRoot string // root with "/" prefix, lowercase
slashRootSlash string // root with "/" prefix and postfix, lowercase
pacer *fs.Pacer // To pace the API calls
ns string // The namespace we are using or "" for none
batcher *batcher.Batcher[*files.UploadSessionFinishArg, *files.FileMetadata]
exportExts []exportExtension
cfg dropbox.Config // SDK config for creating per-namespace clients
sharedFolderMu sync.Mutex // protects sharedFolderIDs
sharedFolderIDs map[string]string // cache of shared folder name → namespace ID
}
type exportType int
@@ -358,11 +362,50 @@ type Object struct {
bytes int64 // size of the object
modTime time.Time // time it was last modified
hash string // content_hash of the object
nsID string // shared folder namespace ID, if applicable
exportType exportType
exportAPIFormat exportAPIFormat
}
// fileSrv returns the files client to use for this object.
// If the object belongs to a shared folder, it returns a
// namespace-scoped client; otherwise it returns the default client.
func (o *Object) fileSrv() files.Client {
if o.nsID != "" {
nsCfg := o.fs.cfg.WithNamespaceID(o.nsID)
return files.New(nsCfg)
}
return o.fs.srv
}
// sharedFolderSrvAndPath resolves an rclone path in shared_folders mode
// to a namespace-scoped files client and the API path within that namespace.
// The rclone path format is "SharedFolderName/sub/path/file.txt".
func (f *Fs) sharedFolderSrvAndPath(ctx context.Context, rclonePath string) (srv files.Client, apiPath string, nsID string, err error) {
firstDir, subPath, _ := strings.Cut(rclonePath, "/")
nsID, err = f.findSharedFolder(ctx, firstDir)
if err != nil {
return nil, "", "", err
}
srv = files.New(f.cfg.WithNamespaceID(nsID))
if subPath != "" {
apiPath = f.opt.Enc.FromStandardPath("/" + subPath)
}
return srv, apiPath, nsID, nil
}
// nsPath returns the encoded API path for use with namespace-scoped clients.
// In shared_folders mode the object's remote is "SharedFolder/sub/file.txt"
// but the API path within the namespace is just "/sub/file.txt".
func (o *Object) nsPath() string {
if o.nsID != "" {
_, subPath, _ := strings.Cut(o.remote, "/")
return o.fs.opt.Enc.FromStandardPath("/" + subPath)
}
return o.fs.opt.Enc.FromStandardPath(o.remotePath())
}
// Name of the remote (as passed into NewFs)
func (f *Fs) Name() string {
return f.name
@@ -537,6 +580,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
cfg.AsMemberID = memberIDs[0].MemberInfo.Profile.MemberProfile.TeamMemberId
}
f.cfg = cfg
f.srv = files.New(cfg)
f.svc = files.New(ucfg)
f.sharing = sharing.New(cfg)
@@ -564,7 +608,8 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if f.opt.SharedFolders {
f.setRoot(root)
if f.root == "" {
return f, nil // our root it empty so we probably want to list shared folders
f.features.Fill(ctx, f)
return f, nil // our root is empty so we probably want to list shared folders
}
dir := path.Dir(f.root)
@@ -830,9 +875,53 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
if f.opt.SharedFiles {
return f.findSharedFile(ctx, remote)
}
if f.opt.SharedFolders {
return f.newSharedFolderObject(ctx, remote)
}
return f.newObjectWithInfo(ctx, remote, nil)
}
// newSharedFolderObject finds an Object inside a shared folder by
// using the shared folder's namespace ID to resolve the path.
func (f *Fs) newSharedFolderObject(ctx context.Context, remote string) (fs.Object, error) {
firstDir, subPath, ok := strings.Cut(remote, "/")
if !ok {
return nil, fs.ErrorObjectNotFound
}
id, err := f.findSharedFolder(ctx, firstDir)
if err != nil {
return nil, err
}
nsCfg := f.cfg.WithNamespaceID(id)
nsSrv := files.New(nsCfg)
filePath := f.opt.Enc.FromStandardPath("/" + subPath)
var entry files.IsMetadata
err = f.pacer.Call(func() (bool, error) {
entry, err = nsSrv.GetMetadata(&files.GetMetadataArg{Path: filePath})
return shouldRetry(ctx, err)
})
if err != nil {
switch e := err.(type) {
case files.GetMetadataAPIError:
if e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.LookupErrorNotFound {
return nil, fs.ErrorObjectNotFound
}
}
return nil, err
}
fileInfo, ok := entry.(*files.FileMetadata)
if !ok {
return nil, fs.ErrorObjectNotFound
}
o, err := f.newObjectWithInfo(ctx, remote, fileInfo)
if err != nil {
return nil, err
}
o.(*Object).nsID = id
return o, nil
}
// listSharedFolders lists all available shared folders mounted and not mounted
// we'll need the id later so we have to return them in original format
func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) error) (err error) {
@@ -879,24 +968,128 @@ func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) e
return nil
}
// listDir lists the contents of a directory using the given files client.
// root is the Dropbox API path to list, dir is the rclone directory prefix for results.
// nsID is the shared folder namespace ID to set on created objects (empty for normal listings).
func (f *Fs) listDir(ctx context.Context, srv files.Client, root string, dir string, nsID string, list *list.Helper) (err error) {
started := false
var res *files.ListFolderResult
for {
if !started {
arg := files.NewListFolderArg(f.opt.Enc.FromStandardPath(root))
arg.Recursive = false
arg.Limit = 1000
if root == "/" || root == "" {
arg.Path = "" // Specify root folder as empty string
}
err = f.pacer.Call(func() (bool, error) {
res, err = srv.ListFolder(arg)
return shouldRetry(ctx, err)
})
if err != nil {
switch e := err.(type) {
case files.ListFolderAPIError:
if e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.LookupErrorNotFound {
err = fs.ErrorDirNotFound
}
}
return err
}
started = true
} else {
arg := files.ListFolderContinueArg{
Cursor: res.Cursor,
}
err = f.pacer.Call(func() (bool, error) {
res, err = srv.ListFolderContinue(&arg)
return shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("list continue: %w", err)
}
}
for _, entry := range res.Entries {
var fileInfo *files.FileMetadata
var folderInfo *files.FolderMetadata
var metadata *files.Metadata
switch info := entry.(type) {
case *files.FolderMetadata:
folderInfo = info
metadata = &info.Metadata
case *files.FileMetadata:
fileInfo = info
metadata = &info.Metadata
default:
fs.Errorf(f, "Unknown type %T", entry)
continue
}
// Only the last element is reliably cased in PathDisplay
entryPath := metadata.PathDisplay
leaf := f.opt.Enc.ToStandardName(path.Base(entryPath))
remote := path.Join(dir, leaf)
if folderInfo != nil {
d := fs.NewDir(remote, time.Time{}).SetID(folderInfo.Id)
err = list.Add(d)
if err != nil {
return err
}
} else if fileInfo != nil {
o, err := f.newObjectWithInfo(ctx, remote, fileInfo)
if err != nil {
return err
}
o.(*Object).nsID = nsID
if o.(*Object).exportType.listable() {
err = list.Add(o)
if err != nil {
return err
}
}
}
}
if !res.HasMore {
break
}
}
return list.Flush()
}
// findSharedFolder find the id for a given shared folder name
// somewhat annoyingly there is no endpoint to query a shared folder by it's name
// so our only option is to iterate over all shared folders
//
// Results are cached for the lifetime of the Fs.
func (f *Fs) findSharedFolder(ctx context.Context, name string) (id string, err error) {
errFoundFile := errors.New("found file")
err = f.listSharedFolders(ctx, func(entry fs.DirEntry) error {
if entry.(*fs.Dir).Remote() == name {
id = entry.(*fs.Dir).ID()
return errFoundFile
f.sharedFolderMu.Lock()
if f.sharedFolderIDs != nil {
if cachedID, ok := f.sharedFolderIDs[name]; ok {
f.sharedFolderMu.Unlock()
return cachedID, nil
}
}
f.sharedFolderMu.Unlock()
// Not cached - list all shared folders and populate the cache
found := make(map[string]string)
err = f.listSharedFolders(ctx, func(entry fs.DirEntry) error {
d := entry.(*fs.Dir)
found[d.Remote()] = d.ID()
return nil
})
if errors.Is(err, errFoundFile) {
return id, nil
} else if err != nil {
if err != nil {
return "", err
}
return "", fs.ErrorDirNotFound
f.sharedFolderMu.Lock()
f.sharedFolderIDs = found
f.sharedFolderMu.Unlock()
id, ok := found[name]
if !ok {
return "", fs.ErrorDirNotFound
}
return id, nil
}
// mountSharedFolder mount a shared folder to the root namespace
@@ -1018,99 +1211,34 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
return list.Flush()
}
if f.opt.SharedFolders {
err := f.listSharedFolders(ctx, list.Add)
if dir == "" {
err := f.listSharedFolders(ctx, list.Add)
if err != nil {
return err
}
return list.Flush()
}
// For subdirectories, use the shared folder's namespace
// to list its contents via the files API.
firstDir, subDir, _ := strings.Cut(dir, "/")
id, err := f.findSharedFolder(ctx, firstDir)
if err != nil {
return err
}
return list.Flush()
nsCfg := f.cfg.WithNamespaceID(id)
nsSrv := files.New(nsCfg)
root := ""
if subDir != "" {
root = "/" + subDir
}
return f.listDir(ctx, nsSrv, root, dir, id, list)
}
root := f.slashRoot
if dir != "" {
root += "/" + dir
}
started := false
var res *files.ListFolderResult
for {
if !started {
arg := files.NewListFolderArg(f.opt.Enc.FromStandardPath(root))
arg.Recursive = false
arg.Limit = 1000
if root == "/" {
arg.Path = "" // Specify root folder as empty string
}
err = f.pacer.Call(func() (bool, error) {
res, err = f.srv.ListFolder(arg)
return shouldRetry(ctx, err)
})
if err != nil {
switch e := err.(type) {
case files.ListFolderAPIError:
if e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.LookupErrorNotFound {
err = fs.ErrorDirNotFound
}
}
return err
}
started = true
} else {
arg := files.ListFolderContinueArg{
Cursor: res.Cursor,
}
err = f.pacer.Call(func() (bool, error) {
res, err = f.srv.ListFolderContinue(&arg)
return shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("list continue: %w", err)
}
}
for _, entry := range res.Entries {
var fileInfo *files.FileMetadata
var folderInfo *files.FolderMetadata
var metadata *files.Metadata
switch info := entry.(type) {
case *files.FolderMetadata:
folderInfo = info
metadata = &info.Metadata
case *files.FileMetadata:
fileInfo = info
metadata = &info.Metadata
default:
fs.Errorf(f, "Unknown type %T", entry)
continue
}
// Only the last element is reliably cased in PathDisplay
entryPath := metadata.PathDisplay
leaf := f.opt.Enc.ToStandardName(path.Base(entryPath))
remote := path.Join(dir, leaf)
if folderInfo != nil {
d := fs.NewDir(remote, time.Time{}).SetID(folderInfo.Id)
err = list.Add(d)
if err != nil {
return err
}
} else if fileInfo != nil {
o, err := f.newObjectWithInfo(ctx, remote, fileInfo)
if err != nil {
return err
}
if o.(*Object).exportType.listable() {
err = list.Add(o)
if err != nil {
return err
}
}
}
}
if !res.HasMore {
break
}
}
return list.Flush()
return f.listDir(ctx, f.srv, root, dir, "", list)
}
// Put the object
@@ -1119,7 +1247,7 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
//
// The new object may have been created if an error is returned
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
if f.opt.SharedFiles || f.opt.SharedFolders {
if f.opt.SharedFiles {
return nil, errNotSupportedInSharedMode
}
// Temporary Object under construction
@@ -1127,6 +1255,17 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
fs: f,
remote: src.Remote(),
}
if f.opt.SharedFolders {
firstDir, _, ok := strings.Cut(src.Remote(), "/")
if !ok {
return nil, errors.New("can't upload to shared folder root")
}
nsID, err := f.findSharedFolder(ctx, firstDir)
if err != nil {
return nil, err
}
o.nsID = nsID
}
return o, o.Update(ctx, in, src, options...)
}
@@ -1137,9 +1276,12 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
// Mkdir creates the container if it doesn't exist
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
if f.opt.SharedFiles || f.opt.SharedFolders {
if f.opt.SharedFiles {
return errNotSupportedInSharedMode
}
if f.opt.SharedFolders {
return f.mkdirSharedFolder(ctx, dir)
}
root := path.Join(f.slashRoot, dir)
// can't create or run metadata on root
@@ -1170,6 +1312,48 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
return err
}
// mkdirSharedFolder creates a directory within a shared folder.
// Creating shared folders themselves is not supported.
func (f *Fs) mkdirSharedFolder(ctx context.Context, dir string) error {
if dir == "" {
return nil // root of shared folders listing - nothing to create
}
if !strings.Contains(dir, "/") {
// This is just a shared folder name - it already exists
// (you can't create shared folders via the files API)
_, err := f.findSharedFolder(ctx, dir)
return err
}
srv, apiPath, _, err := f.sharedFolderSrvAndPath(ctx, dir)
if err != nil {
return err
}
if apiPath == "" {
return nil // root of shared folder already exists
}
// Check if directory exists by trying to get metadata
var entry files.IsMetadata
err = f.pacer.Call(func() (bool, error) {
entry, err = srv.GetMetadata(&files.GetMetadataArg{Path: apiPath})
return shouldRetry(ctx, err)
})
if err == nil {
if _, ok := entry.(*files.FolderMetadata); ok {
return nil // directory exists already
}
}
// Create it
arg := files.CreateFolderArg{Path: apiPath}
if cErr := checkPathLength(arg.Path); cErr != nil {
return cErr
}
err = f.pacer.Call(func() (bool, error) {
_, err = srv.CreateFolderV2(&arg)
return shouldRetry(ctx, err)
})
return err
}
// purgeCheck removes the root directory, if check is set then it
// refuses to do so if it has anything in
func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error) {
@@ -1219,12 +1403,73 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error)
//
// Returns an error if it isn't empty
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
if f.opt.SharedFiles || f.opt.SharedFolders {
if f.opt.SharedFiles {
return errNotSupportedInSharedMode
}
if f.opt.SharedFolders {
return f.rmdirSharedFolder(ctx, dir)
}
return f.purgeCheck(ctx, dir, true)
}
// rmdirSharedFolder removes a directory within a shared folder.
// Removing the shared folder itself (top-level dir) is not allowed.
func (f *Fs) rmdirSharedFolder(ctx context.Context, dir string) error {
if dir == "" || !strings.Contains(dir, "/") {
return errors.New("can't remove shared folder itself - only subdirectories within it")
}
return f.purgeCheckSharedFolder(ctx, dir, true)
}
// purgeCheckSharedFolder removes a directory within a shared folder.
// If check is true, it verifies the directory is empty first.
func (f *Fs) purgeCheckSharedFolder(ctx context.Context, dir string, check bool) error {
if dir == "" || !strings.Contains(dir, "/") {
return errors.New("can't remove shared folder itself - only subdirectories within it")
}
srv, apiPath, _, err := f.sharedFolderSrvAndPath(ctx, dir)
if err != nil {
return err
}
if apiPath == "" {
return errors.New("can't remove shared folder root")
}
if check {
// Check directory exists
var entry files.IsMetadata
err = f.pacer.Call(func() (bool, error) {
entry, err = srv.GetMetadata(&files.GetMetadataArg{Path: apiPath})
return shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("Rmdir: %w", err)
}
if _, ok := entry.(*files.FolderMetadata); !ok {
return fmt.Errorf("Rmdir: %w", fs.ErrorIsFile)
}
// Check directory is empty
arg := files.NewListFolderArg(apiPath)
arg.Recursive = false
var res *files.ListFolderResult
err = f.pacer.Call(func() (bool, error) {
res, err = srv.ListFolder(arg)
return shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("Rmdir: %w", err)
}
if len(res.Entries) != 0 {
return errors.New("directory not empty")
}
}
// Remove it
err = f.pacer.Call(func() (bool, error) {
_, err = srv.DeleteV2(&files.DeleteArg{Path: apiPath})
return shouldRetry(ctx, err)
})
return err
}
// Precision returns the precision
func (f *Fs) Precision() time.Duration {
return time.Second
@@ -1246,6 +1491,10 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
return nil, fs.ErrorCantCopy
}
if f.opt.SharedFolders {
return f.copySharedFolder(ctx, srcObj, remote)
}
// Find and remove existing object
cleanup, err := operations.RemoveExisting(ctx, f, remote, "server side copy")
if err != nil {
@@ -1288,12 +1537,76 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
return dstObj, nil
}
// copySharedFolder copies an object within shared folders.
// Both source and destination must be in the same shared folder namespace.
func (f *Fs) copySharedFolder(ctx context.Context, srcObj *Object, remote string) (fs.Object, error) {
srcFirstDir, _, _ := strings.Cut(srcObj.remote, "/")
dstFirstDir, _, ok := strings.Cut(remote, "/")
if !ok {
return nil, fs.ErrorCantCopy
}
srcNsID, err := f.findSharedFolder(ctx, srcFirstDir)
if err != nil {
return nil, fs.ErrorCantCopy
}
dstNsID, err := f.findSharedFolder(ctx, dstFirstDir)
if err != nil {
return nil, fs.ErrorCantCopy
}
if srcNsID != dstNsID {
return nil, fs.ErrorCantCopy
}
srv := files.New(f.cfg.WithNamespaceID(srcNsID))
// Find and remove existing object
cleanup, err := operations.RemoveExisting(ctx, f, remote, "server side copy")
if err != nil {
return nil, err
}
defer cleanup(&err)
dstObj := &Object{
fs: f,
remote: remote,
nsID: srcNsID,
}
_, srcSubPath, _ := strings.Cut(srcObj.remote, "/")
_, dstSubPath, _ := strings.Cut(remote, "/")
arg := files.RelocationArg{
RelocationPath: files.RelocationPath{
FromPath: f.opt.Enc.FromStandardPath("/" + srcSubPath),
ToPath: f.opt.Enc.FromStandardPath("/" + dstSubPath),
},
}
var result *files.RelocationResult
err = f.pacer.Call(func() (bool, error) {
result, err = srv.CopyV2(&arg)
return shouldRetry(ctx, err)
})
if err != nil {
return nil, fmt.Errorf("copy failed: %w", err)
}
fileInfo, ok := result.Metadata.(*files.FileMetadata)
if !ok {
return nil, fs.ErrorNotAFile
}
err = dstObj.setMetadataFromEntry(fileInfo)
if err != nil {
return nil, fmt.Errorf("copy failed: %w", err)
}
return dstObj, nil
}
// Purge deletes all the files and the container
//
// Optional interface: Only implement this if you have a way of
// deleting all the files quicker than just running Remove() on the
// result of List()
func (f *Fs) Purge(ctx context.Context, dir string) (err error) {
if f.opt.SharedFolders {
return f.purgeCheckSharedFolder(ctx, dir, false)
}
return f.purgeCheck(ctx, dir, false)
}
@@ -1313,6 +1626,10 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return nil, fs.ErrorCantMove
}
if f.opt.SharedFolders {
return f.moveSharedFolder(ctx, srcObj, remote)
}
// Temporary Object under construction
dstObj := &Object{
fs: f,
@@ -1358,6 +1675,67 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return dstObj, nil
}
// moveSharedFolder moves an object within shared folders.
// Both source and destination must be in the same shared folder namespace.
func (f *Fs) moveSharedFolder(ctx context.Context, srcObj *Object, remote string) (fs.Object, error) {
srcFirstDir, _, _ := strings.Cut(srcObj.remote, "/")
dstFirstDir, _, ok := strings.Cut(remote, "/")
if !ok {
return nil, fs.ErrorCantMove
}
srcNsID, err := f.findSharedFolder(ctx, srcFirstDir)
if err != nil {
return nil, fs.ErrorCantMove
}
dstNsID, err := f.findSharedFolder(ctx, dstFirstDir)
if err != nil {
return nil, fs.ErrorCantMove
}
if srcNsID != dstNsID {
return nil, fs.ErrorCantMove
}
srv := files.New(f.cfg.WithNamespaceID(srcNsID))
dstObj := &Object{
fs: f,
remote: remote,
nsID: srcNsID,
}
_, srcSubPath, _ := strings.Cut(srcObj.remote, "/")
_, dstSubPath, _ := strings.Cut(remote, "/")
arg := files.RelocationArg{
RelocationPath: files.RelocationPath{
FromPath: f.opt.Enc.FromStandardPath("/" + srcSubPath),
ToPath: f.opt.Enc.FromStandardPath("/" + dstSubPath),
},
}
var result *files.RelocationResult
err = f.pacer.Call(func() (bool, error) {
result, err = srv.MoveV2(&arg)
switch e := err.(type) {
case files.MoveV2APIError:
if e.EndpointError != nil && e.EndpointError.FromLookup != nil && e.EndpointError.FromLookup.Tag == files.LookupErrorNotFound {
fs.Debugf(srcObj, "Retrying move on %v error", err)
return true, err
}
}
return shouldRetry(ctx, err)
})
if err != nil {
return nil, fmt.Errorf("move failed: %w", err)
}
fileInfo, ok := result.Metadata.(*files.FileMetadata)
if !ok {
return nil, fs.ErrorNotAFile
}
err = dstObj.setMetadataFromEntry(fileInfo)
if err != nil {
return nil, fmt.Errorf("move failed: %w", err)
}
return dstObj, nil
}
// PublicLink adds a "readable by anyone with link" permission on the given file or folder.
func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration, unlink bool) (link string, err error) {
absPath := f.opt.Enc.FromStandardPath(path.Join(f.slashRoot, remote))
@@ -1445,6 +1823,11 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
fs.Debugf(srcFs, "Can't move directory - not same remote type")
return fs.ErrorCantDirMove
}
if f.opt.SharedFolders {
return f.dirMoveSharedFolder(ctx, srcFs, srcRemote, dstRemote)
}
srcPath := path.Join(srcFs.slashRoot, srcRemote)
dstPath := path.Join(f.slashRoot, dstRemote)
@@ -1477,6 +1860,57 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
return nil
}
// dirMoveSharedFolder moves a directory within shared folders.
// Both source and destination must be in the same shared folder namespace.
func (f *Fs) dirMoveSharedFolder(ctx context.Context, srcFs *Fs, srcRemote, dstRemote string) error {
srcFirstDir, srcSubPath, _ := strings.Cut(srcRemote, "/")
dstFirstDir, dstSubPath, _ := strings.Cut(dstRemote, "/")
if srcSubPath == "" || dstSubPath == "" {
return errors.New("can't move shared folder itself - only subdirectories within it")
}
srcNsID, err := srcFs.findSharedFolder(ctx, srcFirstDir)
if err != nil {
return fs.ErrorCantDirMove
}
dstNsID, err := f.findSharedFolder(ctx, dstFirstDir)
if err != nil {
return fs.ErrorCantDirMove
}
if srcNsID != dstNsID {
return fs.ErrorCantDirMove
}
srv := files.New(f.cfg.WithNamespaceID(srcNsID))
// Check if destination exists
dstAPIPath := f.opt.Enc.FromStandardPath("/" + dstSubPath)
var entry files.IsMetadata
err = f.pacer.Call(func() (bool, error) {
entry, err = srv.GetMetadata(&files.GetMetadataArg{Path: dstAPIPath})
return shouldRetry(ctx, err)
})
if err == nil {
if _, ok := entry.(*files.FolderMetadata); ok {
return fs.ErrorDirExists
}
}
// Do the move
arg := files.RelocationArg{
RelocationPath: files.RelocationPath{
FromPath: f.opt.Enc.FromStandardPath("/" + srcSubPath),
ToPath: dstAPIPath,
},
}
err = f.pacer.Call(func() (bool, error) {
_, err = srv.MoveV2(&arg)
return shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("MoveDir failed: %w", err)
}
return nil
}
// About gets quota information
func (f *Fs) About(ctx context.Context) (usage *fs.Usage, err error) {
var q *users.SpaceUsage
@@ -1741,7 +2175,7 @@ func (o *Object) ID() string {
// Hash returns the dropbox special hash
func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
if o.fs.opt.SharedFiles {
return "", errNotSupportedInSharedMode
}
if t != DbHashType {
@@ -1802,6 +2236,29 @@ func (o *Object) setMetadataFromEntry(info *files.FileMetadata) error {
// Reads the entry for a file from dropbox
func (o *Object) readEntry(ctx context.Context) (*files.FileMetadata, error) {
if o.nsID != "" {
srv := o.fileSrv()
var entry files.IsMetadata
var err error
err = o.fs.pacer.Call(func() (bool, error) {
entry, err = srv.GetMetadata(&files.GetMetadataArg{Path: o.nsPath()})
return shouldRetry(ctx, err)
})
if err != nil {
switch e := err.(type) {
case files.GetMetadataAPIError:
if e.EndpointError != nil && e.EndpointError.Path != nil && e.EndpointError.Path.Tag == files.LookupErrorNotFound {
return nil, fs.ErrorObjectNotFound
}
}
return nil, err
}
fileInfo, ok := entry.(*files.FileMetadata)
if !ok {
return nil, fs.ErrorNotAFile
}
return fileInfo, nil
}
return o.fs.getFileMetadata(ctx, o.remotePath())
}
@@ -1868,8 +2325,9 @@ func (o *Object) export(ctx context.Context) (in io.ReadCloser, err error) {
arg := files.ExportArg{Path: o.id, ExportFormat: string(o.exportAPIFormat)}
var exportResult *files.ExportResult
srv := o.fileSrv()
err = o.fs.pacer.Call(func() (bool, error) {
exportResult, in, err = o.fs.srv.Export(&arg)
exportResult, in, err = srv.Export(&arg)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1910,8 +2368,9 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
Path: o.id,
ExtraHeaders: headers,
}
srv := o.fileSrv()
err = o.fs.pacer.Call(func() (bool, error) {
_, in, err = o.fs.srv.Download(&arg)
_, in, err = srv.Download(&arg)
return shouldRetry(ctx, err)
})
@@ -1931,11 +2390,11 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
// Will introduce two additional network requests to start and finish the session.
// If the size is unknown (i.e. -1) the method incurs one additional
// request to the Dropbox API that does not carry a payload to close the append session.
func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *files.CommitInfo, size int64) (entry *files.FileMetadata, err error) {
func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, srv files.Client, commitInfo *files.CommitInfo, size int64, useBatching bool) (entry *files.FileMetadata, err error) {
// start upload
var res *files.UploadSessionStartResult
err = o.fs.pacer.Call(func() (bool, error) {
res, err = o.fs.srv.UploadSessionStart(&files.UploadSessionStartArg{}, nil)
res, err = srv.UploadSessionStart(&files.UploadSessionStartArg{}, nil)
return shouldRetry(ctx, err)
})
if err != nil {
@@ -1972,7 +2431,7 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
if _, err = chunk.Seek(skip, io.SeekStart); err != nil {
return false, err
}
err = o.fs.srv.UploadSessionAppendV2(&appendArg, chunk)
err = srv.UploadSessionAppendV2(&appendArg, chunk)
// after session is started, we retry everything
if err != nil {
// Check for incorrect offset error and retry with new offset
@@ -2026,12 +2485,12 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
}
// If we are batching then we should have written all the data now
// store the commit info now for a batch commit
if o.fs.batcher.Batching() {
if useBatching {
return o.fs.batcher.Commit(ctx, o.remote, args)
}
err = o.fs.pacer.Call(func() (bool, error) {
entry, err = o.fs.srv.UploadSessionFinish(args, nil)
entry, err = srv.UploadSessionFinish(args, nil)
if retry, err := shouldRetryExclude(ctx, err); !retry {
return retry, err
}
@@ -2075,14 +2534,15 @@ func checkPathLength(name string) (err error) {
//
// The new object may have been created if an error is returned
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
if o.fs.opt.SharedFiles {
return errNotSupportedInSharedMode
}
uploadPath := o.nsPath()
remote := o.remotePath()
if ignoredFiles.MatchString(remote) {
return fserrors.NoRetryError(fmt.Errorf("file name %q is disallowed - not uploading", path.Base(remote)))
}
commitInfo := files.NewCommitInfo(o.fs.opt.Enc.FromStandardPath(o.remotePath()))
commitInfo := files.NewCommitInfo(uploadPath)
commitInfo.Mode.Tag = "overwrite"
// The Dropbox API only accepts timestamps in UTC with second precision.
clientModified := src.ModTime(ctx).UTC().Round(time.Second)
@@ -2092,14 +2552,17 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return cErr
}
srv := o.fileSrv()
size := src.Size()
// Disable batching for shared folder objects since the batch commit uses f.srv
useBatching := o.fs.batcher.Batching() && o.nsID == ""
var err error
var entry *files.FileMetadata
if size > int64(o.fs.opt.ChunkSize) || size < 0 || o.fs.batcher.Batching() {
entry, err = o.uploadChunked(ctx, in, commitInfo, size)
if size > int64(o.fs.opt.ChunkSize) || size < 0 || useBatching {
entry, err = o.uploadChunked(ctx, in, srv, commitInfo, size, useBatching)
} else {
err = o.fs.pacer.CallNoRetry(func() (bool, error) {
entry, err = o.fs.srv.Upload(&files.UploadArg{CommitInfo: *commitInfo}, in)
entry, err = srv.Upload(&files.UploadArg{CommitInfo: *commitInfo}, in)
return shouldRetry(ctx, err)
})
}
@@ -2120,12 +2583,13 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Remove an object
func (o *Object) Remove(ctx context.Context) (err error) {
if o.fs.opt.SharedFiles || o.fs.opt.SharedFolders {
if o.fs.opt.SharedFiles {
return errNotSupportedInSharedMode
}
srv := o.fileSrv()
err = o.fs.pacer.Call(func() (bool, error) {
_, err = o.fs.srv.DeleteV2(&files.DeleteArg{
Path: o.fs.opt.Enc.FromStandardPath(o.remotePath()),
_, err = srv.DeleteV2(&files.DeleteArg{
Path: o.nsPath(),
})
return shouldRetry(ctx, err)
})
+308
View File
@@ -1,13 +1,19 @@
package dropbox
import (
"bytes"
"context"
"io"
"strings"
"testing"
"time"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/async"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/files"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/sharing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest/fstests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -95,8 +101,310 @@ func (f *Fs) InternalTestPaperExport(t *testing.T) {
require.Contains(t, text, excerpt)
}
}
// InternalTestSharedFolder tests both read and write operations on shared folders.
// It uses a single shared folder setup to avoid re-sharing between subtests
// (Dropbox has eventual consistency issues with share/unshare cycles).
func (f *Fs) InternalTestSharedFolder(t *testing.T) {
ctx := context.Background()
testDir := f.slashRoot
// Share the test root folder
folderName := f.opt.Enc.ToStandardName(strings.TrimPrefix(testDir, "/"))
shareArg := sharing.NewShareFolderArg(testDir)
var sharedFolderID string
var shareLaunch *sharing.ShareFolderLaunch
var err error
err = f.pacer.Call(func() (bool, error) {
shareLaunch, err = f.sharing.ShareFolder(shareArg)
return shouldRetry(ctx, err)
})
if err != nil {
sharedFolderID, err = f.findSharedFolder(ctx, folderName)
require.NoError(t, err, "ShareFolder failed and couldn't find existing share")
} else {
switch shareLaunch.Tag {
case sharing.ShareFolderLaunchComplete:
sharedFolderID = shareLaunch.Complete.SharedFolderId
case sharing.ShareFolderLaunchAsyncJobId:
pollArg := async.PollArg{AsyncJobId: shareLaunch.AsyncJobId}
for range 30 {
time.Sleep(time.Second)
var status *sharing.ShareFolderJobStatus
err = f.pacer.Call(func() (bool, error) {
status, err = f.sharing.CheckShareJobStatus(&pollArg)
return shouldRetry(ctx, err)
})
require.NoError(t, err)
if status.Tag == sharing.ShareFolderJobStatusComplete {
sharedFolderID = status.Complete.SharedFolderId
break
}
}
require.NotEmpty(t, sharedFolderID, "share folder job did not complete")
}
}
require.NotEmpty(t, sharedFolderID)
defer func() {
unshareArg := sharing.NewUnshareFolderArg(sharedFolderID)
unshareArg.LeaveACopy = true
_ = f.pacer.Call(func() (bool, error) {
_, err = f.sharing.UnshareFolder(unshareArg)
return shouldRetry(ctx, err)
})
}()
sf := *f //nolint:govet // intentional copy; mutex is zero-valued and unused before this point
sf.opt.SharedFolders = true
sf.features = (&fs.Features{
CaseInsensitive: true,
ReadMimeType: false,
CanHaveEmptyDirectories: true,
}).Fill(ctx, &sf)
sharedFs := &sf
// Upload a test file using the normal API for listing tests
testFileName := "shared-folder-test-file.txt"
testFilePath := testDir + "/" + testFileName
content := "hello shared folder"
uploadArg := files.NewUploadArg(testFilePath)
uploadArg.Mode = &files.WriteMode{Tagged: dropbox.Tagged{Tag: files.WriteModeOverwrite}}
err = f.pacer.Call(func() (bool, error) {
_, err = f.srv.Upload(uploadArg, strings.NewReader(content))
return shouldRetry(ctx, err)
})
require.NoError(t, err)
defer func() {
_, _ = f.srv.DeleteV2(files.NewDeleteArg(testFilePath))
}()
t.Run("List", func(t *testing.T) {
// listing root should include the shared folder
var rootEntries fs.DirEntries
err = sharedFs.ListP(ctx, "", func(entries fs.DirEntries) error {
rootEntries = append(rootEntries, entries...)
return nil
})
require.NoError(t, err)
found := false
for _, entry := range rootEntries {
if entry.Remote() == folderName {
found = true
break
}
}
assert.True(t, found, "shared folder %q not found in root listing (have %v)", folderName, rootEntries)
// listing the shared folder should show its contents
var dirEntries fs.DirEntries
err = sharedFs.ListP(ctx, folderName, func(entries fs.DirEntries) error {
dirEntries = append(dirEntries, entries...)
return nil
})
require.NoError(t, err)
foundFile := false
expectedRemote := folderName + "/" + testFileName
for _, entry := range dirEntries {
if entry.Remote() == expectedRemote {
foundFile = true
break
}
}
assert.True(t, foundFile, "file %q not found in shared folder listing (have %v)", expectedRemote, dirEntries)
})
t.Run("NewObject", func(t *testing.T) {
expectedRemote := folderName + "/" + testFileName
obj, err := sharedFs.NewObject(ctx, expectedRemote)
require.NoError(t, err, "NewObject failed for shared folder file")
assert.Equal(t, expectedRemote, obj.Remote())
assert.Equal(t, int64(len(content)), obj.Size())
})
t.Run("Open", func(t *testing.T) {
expectedRemote := folderName + "/" + testFileName
obj, err := sharedFs.NewObject(ctx, expectedRemote)
require.NoError(t, err)
rc, err := obj.Open(ctx)
require.NoError(t, err, "Open failed for shared folder file")
buf, err := io.ReadAll(rc)
require.NoError(t, rc.Close())
require.NoError(t, err)
assert.Equal(t, content, string(buf))
})
t.Run("Put", func(t *testing.T) {
// Upload a file via Put
content := "hello from shared folder put"
remote := folderName + "/test-put-file.txt"
src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(content)), true, nil, nil)
obj, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
assert.Equal(t, remote, obj.Remote())
assert.Equal(t, int64(len(content)), obj.Size())
// Verify we can read back the content
rc, err := obj.Open(ctx)
require.NoError(t, err)
buf, err := io.ReadAll(rc)
require.NoError(t, rc.Close())
require.NoError(t, err)
assert.Equal(t, content, string(buf))
// Clean up
require.NoError(t, obj.Remove(ctx))
})
t.Run("Hash", func(t *testing.T) {
// Upload a file and check its hash
content := "hash test content"
remote := folderName + "/test-hash-file.txt"
src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(content)), true, nil, nil)
obj, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
defer func() { _ = obj.Remove(ctx) }()
hash, err := obj.Hash(ctx, DbHashType)
require.NoError(t, err)
assert.NotEmpty(t, hash, "hash should not be empty")
})
t.Run("Mkdir", func(t *testing.T) {
// Create a subdirectory within the shared folder
subDir := folderName + "/test-mkdir-subdir"
err := sharedFs.Mkdir(ctx, subDir)
require.NoError(t, err)
// Verify it appears in the listing
var entries fs.DirEntries
err = sharedFs.ListP(ctx, folderName, func(e fs.DirEntries) error {
entries = append(entries, e...)
return nil
})
require.NoError(t, err)
found := false
for _, entry := range entries {
if entry.Remote() == subDir {
found = true
break
}
}
assert.True(t, found, "subdirectory %q not found in listing", subDir)
// Clean up
require.NoError(t, sharedFs.Rmdir(ctx, subDir))
})
t.Run("Rmdir", func(t *testing.T) {
// Create and then remove a subdirectory
subDir := folderName + "/test-rmdir-subdir"
require.NoError(t, sharedFs.Mkdir(ctx, subDir))
require.NoError(t, sharedFs.Rmdir(ctx, subDir))
// Verify it's gone
var entries fs.DirEntries
err := sharedFs.ListP(ctx, folderName, func(e fs.DirEntries) error {
entries = append(entries, e...)
return nil
})
require.NoError(t, err)
for _, entry := range entries {
assert.NotEqual(t, subDir, entry.Remote(), "subdirectory should have been removed")
}
})
t.Run("RmdirSharedFolderRoot", func(t *testing.T) {
// Removing a shared folder itself should fail
err := sharedFs.Rmdir(ctx, folderName)
assert.Error(t, err, "should not be able to remove shared folder itself")
})
t.Run("Remove", func(t *testing.T) {
// Upload and then delete a file
content := "file to remove"
remote := folderName + "/test-remove-file.txt"
src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(content)), true, nil, nil)
obj, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
err = obj.Remove(ctx)
require.NoError(t, err)
// Verify it's gone
_, err = sharedFs.NewObject(ctx, remote)
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
})
t.Run("Copy", func(t *testing.T) {
// Upload a file, then server-side copy it within the same shared folder
content := "file to copy"
srcRemote := folderName + "/test-copy-src.txt"
dstRemote := folderName + "/test-copy-dst.txt"
src := object.NewStaticObjectInfo(srcRemote, time.Now(), int64(len(content)), true, nil, nil)
srcObj, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
defer func() { _ = srcObj.Remove(ctx) }()
dstObj, err := sharedFs.Copy(ctx, srcObj, dstRemote)
require.NoError(t, err)
defer func() { _ = dstObj.Remove(ctx) }()
assert.Equal(t, dstRemote, dstObj.Remote())
assert.Equal(t, int64(len(content)), dstObj.Size())
// Verify content
rc, err := dstObj.Open(ctx)
require.NoError(t, err)
buf, err := io.ReadAll(rc)
require.NoError(t, rc.Close())
require.NoError(t, err)
assert.Equal(t, content, string(buf))
})
t.Run("Move", func(t *testing.T) {
// Upload a file, then server-side move it within the same shared folder
content := "file to move"
srcRemote := folderName + "/test-move-src.txt"
dstRemote := folderName + "/test-move-dst.txt"
src := object.NewStaticObjectInfo(srcRemote, time.Now(), int64(len(content)), true, nil, nil)
srcObj, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
dstObj, err := sharedFs.Move(ctx, srcObj, dstRemote)
require.NoError(t, err)
defer func() { _ = dstObj.Remove(ctx) }()
assert.Equal(t, dstRemote, dstObj.Remote())
// Source should be gone
_, err = sharedFs.NewObject(ctx, srcRemote)
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
})
t.Run("Purge", func(t *testing.T) {
// Create a subdir with a file, then purge
subDir := folderName + "/test-purge-subdir"
require.NoError(t, sharedFs.Mkdir(ctx, subDir))
content := "file in purge dir"
remote := subDir + "/file.txt"
src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(content)), true, nil, nil)
_, err := sharedFs.Put(ctx, bytes.NewReader([]byte(content)), src)
require.NoError(t, err)
err = sharedFs.Purge(ctx, subDir)
require.NoError(t, err)
})
}
func (f *Fs) InternalTest(t *testing.T) {
t.Run("PaperExport", f.InternalTestPaperExport)
t.Run("SharedFolder", f.InternalTestSharedFolder)
}
var _ fstests.InternalTester = (*Fs)(nil)
+13
View File
@@ -3,6 +3,19 @@ package api
import "encoding/json"
// MultipartInitResponse represents the response from multipart/init.
type MultipartInitResponse struct {
Status int `json:"status"`
Msg string `json:"msg"`
Result struct {
UploadID string `json:"upload_id"`
SessID string `json:"sess_id"`
Server string `json:"server"`
FolderID int64 `json:"folder_id"`
ObjectPath string `json:"object_path"`
} `json:"result"`
}
// CreateFolderResponse represents the response for creating a folder.
type CreateFolderResponse struct {
Status int `json:"status"`
+24 -19
View File
@@ -21,6 +21,11 @@ import (
"github.com/rclone/rclone/lib/rest"
)
const (
defaultUploadCutoff = fs.SizeSuffix(500 * 1024 * 1024)
defaultChunkSize = fs.SizeSuffix(64 * 1024 * 1024)
)
// Register the backend with Rclone
func init() {
fs.Register(&fs.RegInfo{
@@ -33,6 +38,17 @@ func init() {
Required: true,
Sensitive: true,
},
{
Name: "upload_cutoff",
Help: "Cutoff for switching to chunked upload. Any files larger than this will be uploaded in chunks of chunk_size.",
Default: defaultUploadCutoff,
Advanced: true,
}, {
Name: "chunk_size",
Help: "Chunk size to use for uploading. Used for multipart uploads.",
Default: defaultChunkSize,
Advanced: true,
},
{
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
@@ -72,8 +88,10 @@ func init() {
// Options defines the configuration for the FileLu backend
type Options struct {
Key string `config:"key"`
Enc encoder.MultiEncoder `config:"encoding"`
Key string `config:"key"`
Enc encoder.MultiEncoder `config:"encoding"`
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
}
// Fs represents the FileLu file system
@@ -189,7 +207,6 @@ func (f *Fs) Purge(ctx context.Context, dir string) error {
return f.deleteFolder(ctx, fullPath)
}
// List returns a list of files and folders
// List returns a list of files and folders for the given directory
func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
// Compose full path for API call
@@ -250,23 +267,11 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
// Put uploads a file directly to the destination folder in the FileLu storage system.
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
if src.Size() == 0 {
return nil, fs.ErrorCantUploadEmptyFiles
o := &Object{
fs: f,
remote: src.Remote(),
}
err := f.uploadFile(ctx, in, src.Remote())
if err != nil {
return nil, err
}
newObject := &Object{
fs: f,
remote: src.Remote(),
size: src.Size(),
modTime: src.ModTime(ctx),
}
fs.Infof(f, "Put: Successfully uploaded new file %q", src.Remote())
return newObject, nil
return o, o.Update(ctx, in, src, options...)
}
// Move moves the file to the specified location
+127 -153
View File
@@ -1,9 +1,7 @@
package filelu
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
@@ -16,40 +14,82 @@ import (
"github.com/rclone/rclone/lib/rest"
)
// multipartInit starts a new multipart upload and returns server details.
func (f *Fs) multipartInit(ctx context.Context, folderPath, filename string) (*api.MultipartInitResponse, error) {
opts := rest.Opts{
Method: "GET",
Path: "/multipart/init",
Parameters: url.Values{
"key": {f.opt.Key},
"filename": {filename},
"folder_path": {folderPath},
},
}
var result api.MultipartInitResponse
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
return fserrors.ShouldRetry(err), err
})
if err != nil {
return nil, err
}
if result.Status != 200 {
return nil, fmt.Errorf("multipart init error: %s", result.Msg)
}
return &result, nil
}
// completeMultipart finalizes the multipart upload on the file server.
func (f *Fs) completeMultipart(ctx context.Context, server string, uploadID string, sessID string, objectPath string) error {
req, err := http.NewRequestWithContext(ctx, "POST", server, nil)
if err != nil {
return err
}
req.Header.Set("X-RC-Upload-Id", uploadID)
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 != 202 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("completeMultipart failed %d: %s", resp.StatusCode, string(body))
}
return nil
}
// createFolder creates a folder at the specified path.
func (f *Fs) createFolder(ctx context.Context, dirPath string) (*api.CreateFolderResponse, error) {
encodedDir := f.fromStandardPath(dirPath)
apiURL := fmt.Sprintf("%s/folder/create?folder_path=%s&key=%s",
f.endpoint,
url.QueryEscape(encodedDir),
url.QueryEscape(f.opt.Key), // assuming f.opt.Key is the correct field
)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
opts := rest.Opts{
Method: "GET",
Path: "/folder/create",
Parameters: url.Values{
"folder_path": {encodedDir},
"key": {f.opt.Key},
},
}
var resp *http.Response
result := api.CreateFolderResponse{}
err = f.pacer.Call(func() (bool, error) {
var innerErr error
resp, innerErr = f.client.Do(req)
return fserrors.ShouldRetry(innerErr), innerErr
var result api.CreateFolderResponse
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
return fserrors.ShouldRetry(err), err
})
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, fmt.Errorf("error decoding response: %w", err)
}
if result.Status != 200 {
return nil, fmt.Errorf("error: %s", result.Msg)
}
@@ -61,44 +101,29 @@ func (f *Fs) createFolder(ctx context.Context, dirPath string) (*api.CreateFolde
// getFolderList List both files and folders in a directory.
func (f *Fs) getFolderList(ctx context.Context, path string) (*api.FolderListResponse, error) {
encodedDir := f.fromStandardPath(path)
apiURL := fmt.Sprintf("%s/folder/list?folder_path=%s&key=%s",
f.endpoint,
url.QueryEscape(encodedDir),
url.QueryEscape(f.opt.Key),
)
var body []byte
opts := rest.Opts{
Method: "GET",
Path: "/folder/list",
Parameters: url.Values{
"folder_path": {encodedDir},
"key": {f.opt.Key},
},
}
var response api.FolderListResponse
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := f.client.Do(req)
_, err := f.srv.CallJSON(ctx, &opts, nil, &response)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to list directory: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
body, err = io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("error reading response body: %w", err)
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
if err != nil {
return nil, err
}
var response api.FolderListResponse
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&response); err != nil {
return nil, fmt.Errorf("error decoding response: %w", err)
}
if response.Status != 200 {
if strings.Contains(response.Msg, "Folder not found") {
return nil, fs.ErrorDirNotFound
@@ -115,42 +140,28 @@ func (f *Fs) getFolderList(ctx context.Context, path string) (*api.FolderListRes
}
return &response, nil
}
// deleteFolder deletes a folder at the specified path.
func (f *Fs) deleteFolder(ctx context.Context, fullPath string) error {
fullPath = f.fromStandardPath(fullPath)
deleteURL := fmt.Sprintf("%s/folder/delete?folder_path=%s&key=%s",
f.endpoint,
url.QueryEscape(fullPath),
url.QueryEscape(f.opt.Key),
)
opts := rest.Opts{
Method: "GET",
Path: "/folder/delete",
Parameters: url.Values{
"folder_path": {fullPath},
"key": {f.opt.Key},
},
}
delResp := api.DeleteFolderResponse{}
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", deleteURL, nil)
if err != nil {
return false, err
}
resp, err := f.client.Do(req)
_, err := f.srv.CallJSON(ctx, &opts, nil, &delResp)
if err != nil {
return fserrors.ShouldRetry(err), err
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
if err := json.Unmarshal(body, &delResp); err != nil {
return false, fmt.Errorf("error decoding delete response: %w", err)
}
if delResp.Status != 200 {
return false, fmt.Errorf("delete error: %s", delResp.Msg)
}
@@ -167,38 +178,27 @@ func (f *Fs) deleteFolder(ctx context.Context, fullPath string) error {
// getDirectLink of file from FileLu to download.
func (f *Fs) getDirectLink(ctx context.Context, filePath string) (string, int64, error) {
filePath = f.fromStandardPath(filePath)
apiURL := fmt.Sprintf("%s/file/direct_link?file_path=%s&key=%s",
f.endpoint,
url.QueryEscape(filePath),
url.QueryEscape(f.opt.Key),
)
opts := rest.Opts{
Method: "GET",
Path: "/file/direct_link",
Parameters: url.Values{
"file_path": {filePath},
"key": {f.opt.Key},
},
}
result := api.FileDirectLinkResponse{}
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := f.client.Do(req)
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to fetch direct link: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, fmt.Errorf("error decoding response: %w", err)
}
if result.Status != 200 {
return false, fmt.Errorf("API error: %s", result.Msg)
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
if err != nil {
return "", 0, err
@@ -210,39 +210,31 @@ func (f *Fs) getDirectLink(ctx context.Context, filePath string) (string, int64,
// deleteFile deletes a file based on filePath
func (f *Fs) deleteFile(ctx context.Context, filePath string) error {
filePath = f.fromStandardPath(filePath)
apiURL := fmt.Sprintf("%s/file/remove?file_path=%s&key=%s",
f.endpoint,
url.QueryEscape(filePath),
url.QueryEscape(f.opt.Key),
)
opts := rest.Opts{
Method: "GET",
Path: "/file/remove",
Parameters: url.Values{
"file_path": {filePath},
"key": {f.opt.Key},
},
}
result := api.DeleteFileResponse{}
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := f.client.Do(req)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to fetch direct link: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, fmt.Errorf("error decoding response: %w", err)
return shouldRetry(err), fmt.Errorf("failed to delete file: %w", err)
}
if result.Status != 200 {
return false, fmt.Errorf("API error: %s", result.Msg)
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
return err
}
@@ -275,46 +267,28 @@ func (f *Fs) getAccountInfo(ctx context.Context) (*api.AccountInfoResponse, erro
// getFileInfo retrieves file information based on file code
func (f *Fs) getFileInfo(ctx context.Context, fileCode string) (*api.FileInfoResponse, error) {
u, _ := url.Parse(f.endpoint + "/file/info2")
q := u.Query()
q.Set("file_code", fileCode) // raw path — Go handles escaping properly here
q.Set("key", f.opt.Key)
u.RawQuery = q.Encode()
apiURL := f.endpoint + "/file/info2?" + u.RawQuery
opts := rest.Opts{
Method: "GET",
Path: "/file/info2",
Parameters: url.Values{
"file_code": {fileCode},
"key": {f.opt.Key},
},
}
result := api.FileInfoResponse{}
var body []byte
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := f.client.Do(req)
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to fetch file info: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
body, err = io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("error reading response body: %w", err)
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
if err != nil {
return nil, err
}
result := api.FileInfoResponse{}
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&result); err != nil {
return nil, fmt.Errorf("error decoding response: %w", err)
}
if result.Status != 200 || len(result.Result) == 0 {
return nil, fs.ErrorObjectNotFound
+115 -23
View File
@@ -1,6 +1,7 @@
package filelu
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -13,8 +14,108 @@ import (
"strings"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/rest"
)
// multipartUpload uploads a file in fixed-size chunks using the multipart API.
func (f *Fs) multipartUpload(ctx context.Context, in io.Reader, remote string) error {
dir := path.Dir(remote)
if dir == "." {
dir = ""
}
if dir != "" {
_ = f.Mkdir(ctx, dir)
}
folder := strings.Trim(dir, "/")
if folder != "" {
folder = "/" + folder
}
file := path.Base(remote)
initResp, err := f.multipartInit(ctx, folder, file)
if err != nil {
return fmt.Errorf("multipart init failed: %w", err)
}
uploadID := initResp.Result.UploadID
sessID := initResp.Result.SessID
server := initResp.Result.Server
objectPath := initResp.Result.ObjectPath
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 {
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 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)
if err != nil {
return fmt.Errorf("complete multipart failed: %w", err)
}
return nil
}
// 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
}
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
func (f *Fs) uploadFile(ctx context.Context, fileContent io.Reader, fileFullPath string) error {
directory := path.Dir(fileFullPath)
@@ -68,9 +169,15 @@ func (f *Fs) uploadFile(ctx context.Context, fileContent io.Reader, fileFullPath
return nil
}
// getUploadServer gets the upload server URL with proper key authentication
func (f *Fs) getUploadServer(ctx context.Context) (string, string, error) {
apiURL := fmt.Sprintf("%s/upload/server?key=%s", f.endpoint, url.QueryEscape(f.opt.Key))
opts := rest.Opts{
Method: "GET",
Path: "/upload/server",
Parameters: url.Values{
"key": {f.opt.Key},
},
}
var result struct {
Status int `json:"status"`
@@ -80,36 +187,21 @@ func (f *Fs) getUploadServer(ctx context.Context) (string, string, error) {
}
err := f.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
resp, err := f.client.Do(req)
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to get upload server: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, fmt.Errorf("error decoding response: %w", err)
}
if result.Status != 200 {
return false, fmt.Errorf("API error: %s", result.Msg)
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
if err != nil {
return "", "", err
}
if result.Status != 200 {
return "", "", fmt.Errorf("API error: %s", result.Msg)
}
return result.Result, result.SessID, nil
}
+44 -38
View File
@@ -1,9 +1,7 @@
package filelu
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
@@ -16,6 +14,7 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/rest"
)
// Object describes a FileLu object
@@ -88,6 +87,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
}
}
// Wrap the response body to handle offset and count
var reader io.ReadCloser
err = o.fs.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", directLink, nil)
@@ -109,22 +109,25 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
return false, fmt.Errorf("failed to download file: HTTP %d", resp.StatusCode)
}
// Wrap the response body to handle offset and count
currentContents, err := io.ReadAll(resp.Body)
if err != nil {
return false, fmt.Errorf("failed to read response body: %w", err)
if offset > 0 {
_, err = io.CopyN(io.Discard, resp.Body, offset)
if err != nil {
_ = resp.Body.Close()
return false, fmt.Errorf("failed to skip offset: %w", err)
}
}
if offset > 0 {
if offset > int64(len(currentContents)) {
return false, fmt.Errorf("offset %d exceeds file size %d", offset, len(currentContents))
if count > 0 {
reader = struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(resp.Body, count),
Closer: resp.Body,
}
currentContents = currentContents[offset:]
} else {
reader = resp.Body
}
if count > 0 && count < int64(len(currentContents)) {
currentContents = currentContents[:count]
}
reader = io.NopCloser(bytes.NewReader(currentContents))
return false, nil
})
@@ -137,15 +140,23 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
// Update updates the object with new data
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
if src.Size() <= 0 {
return fs.ErrorCantUploadEmptyFiles
size := src.Size()
if size <= int64(o.fs.opt.UploadCutoff) {
err := o.fs.uploadFile(ctx, in, o.remote)
if err != nil {
return err
}
} else {
fullPath := path.Join(o.fs.root, o.remote)
err := o.fs.multipartUpload(ctx, in, fullPath)
if err != nil {
return fmt.Errorf("failed to upload file: %w", err)
}
}
err := o.fs.uploadFile(ctx, in, o.remote)
if err != nil {
return fmt.Errorf("failed to upload file: %w", err)
}
o.size = src.Size()
o.size = size
o.modTime = src.ModTime(ctx)
return nil
}
@@ -183,8 +194,14 @@ func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
return "", fmt.Errorf("no valid file code found in the remote path")
}
apiURL := fmt.Sprintf("%s/file/info?file_code=%s&key=%s",
o.fs.endpoint, url.QueryEscape(fileCode), url.QueryEscape(o.fs.opt.Key))
opts := rest.Opts{
Method: "GET",
Path: "/file/info",
Parameters: url.Values{
"file_code": {fileCode},
"key": {o.fs.opt.Key},
},
}
var result struct {
Status int `json:"status"`
@@ -193,29 +210,18 @@ func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
Hash string `json:"hash"`
} `json:"result"`
}
err := o.fs.pacer.Call(func() (bool, error) {
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, err
}
resp, err := o.fs.client.Do(req)
_, err := o.fs.srv.CallJSON(ctx, &opts, nil, &result)
if err != nil {
return shouldRetry(err), err
}
defer func() {
if err := resp.Body.Close(); err != nil {
fs.Logf(nil, "Failed to close response body: %v", err)
}
}()
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return false, err
}
return shouldRetryHTTP(resp.StatusCode), nil
return false, nil
})
if err != nil {
return "", err
}
if result.Status != 200 || len(result.Result) == 0 {
return "", fmt.Errorf("error: unable to fetch hash: %s", result.Msg)
}
+10 -10
View File
@@ -355,19 +355,19 @@ type chunkWriter struct {
chunkSize int64
chunksLock sync.Mutex
knownChunks map[int][]byte // known chunks to be hashed
nextChunkToHash int
knownChunks map[int64][]byte // known chunks to be hashed
nextChunkToHash int64
sizeLock sync.Mutex
size int64
}
func (cw *chunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader io.ReadSeeker) (bytesWritten int64, err error) {
realChunkNumber := int(int64(chunkNumber) * (cw.chunkSize) / sdk.ChunkSize)
realChunkNumber := int64(chunkNumber) * (cw.chunkSize) / sdk.ChunkSize
chunk := make([]byte, sdk.ChunkSize, sdk.ChunkSize+cw.EncryptionKey.Cipher.Overhead())
totalWritten := int64(0)
for sliceStart := 0; sliceStart < int(cw.chunkSize); sliceStart += sdk.ChunkSize {
for sliceStart := int64(0); sliceStart < cw.chunkSize; sliceStart += sdk.ChunkSize {
chunk = chunk[:sdk.ChunkSize]
chunkRead := 0
for {
@@ -415,13 +415,13 @@ func (cw *chunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader i
return totalWritten, err
}
resp, err := cw.filen.UploadChunk(ctx, &cw.FileUpload, realChunkNumber, chunkReadSlice)
if err != nil {
return totalWritten, err
}
select { // only care about getting this once
case cw.bucketAndRegion <- *resp:
default:
}
if err != nil {
return totalWritten, err
}
totalWritten += int64(len(chunkReadSlice))
realChunkNumber++
}
@@ -496,7 +496,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
filen: f.filen,
chunkSize: chunkSize,
bucketAndRegion: make(chan client.V3UploadResponse, 1),
knownChunks: make(map[int][]byte),
knownChunks: make(map[int64][]byte),
nextChunkToHash: 0,
size: 0,
}, nil
@@ -1122,8 +1122,8 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
return nil, err
}
total := int64(userInfo.MaxStorage)
used := int64(userInfo.UsedStorage)
total := userInfo.MaxStorage
used := userInfo.UsedStorage
free := total - used
return &fs.Usage{
Total: &total,
+2 -2
View File
@@ -116,8 +116,8 @@ type Date struct {
type DateFilter struct {
Dates []Date `json:"dates,omitempty"`
Ranges []struct {
StartDate Date `json:"startDate,omitempty"`
EndDate Date `json:"endDate,omitempty"`
StartDate Date `json:"startDate"`
EndDate Date `json:"endDate"`
} `json:"ranges,omitempty"`
}
+2 -4
View File
@@ -583,9 +583,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
entriesMu.Unlock()
}
for range checkers {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for remote := range in {
file := &Object{
fs: f,
@@ -601,7 +599,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
fs.Debugf(remote, "skipping because of error: %v", err)
}
}
}()
})
}
for _, name := range names {
isDir := name[len(name)-1] == '/'
+4 -4
View File
@@ -599,7 +599,7 @@ type UpdateFileInfo struct {
Signature string `json:"signature,omitempty"`
Size int64 `json:"size,omitempty"`
WrappingKey string `json:"wrapping_key,omitempty"`
} `json:"data,omitempty"`
} `json:"data"`
DocumentID string `json:"document_id"`
FileFlags FileFlags `json:"file_flags"`
Mtime int64 `json:"mtime"`
@@ -849,10 +849,10 @@ type DriveItem struct {
NumberOfItems int64 `json:"numberOfItems"`
Status string `json:"status"`
Extension string `json:"extension,omitempty"`
DateModified time.Time `json:"dateModified,omitempty"`
DateChanged time.Time `json:"dateChanged,omitempty"`
DateModified time.Time `json:"dateModified"`
DateChanged time.Time `json:"dateChanged"`
Size int64 `json:"size,omitempty"`
LastOpenTime time.Time `json:"lastOpenTime,omitempty"`
LastOpenTime time.Time `json:"lastOpenTime"`
Urls struct {
URLDownload string `json:"url_download"`
} `json:"urls"`
+101 -1
View File
@@ -13,8 +13,12 @@ import (
"github.com/golang-jwt/jwt/v5"
internxtauth "github.com/internxt/rclone-adapter/auth"
internxtconfig "github.com/internxt/rclone-adapter/config"
sdkerrors "github.com/internxt/rclone-adapter/errors"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/lib/oauthutil"
"golang.org/x/oauth2"
)
@@ -101,7 +105,6 @@ func jwtToOAuth2Token(jwtString string) (*oauth2.Token, error) {
}
// computeBasicAuthHeader creates the BasicAuthHeader for bucket operations
// Following the pattern from SDK's auth/access.go:96-102
func computeBasicAuthHeader(bridgeUser, userID string) string {
sum := sha256.Sum256([]byte(userID))
hexPass := hex.EncodeToString(sum[:])
@@ -144,3 +147,100 @@ func refreshJWTToken(ctx context.Context, name string, m configmap.Mapper) error
fs.Debugf(name, "Token refreshed successfully, new expiry: %v", token.Expiry)
return nil
}
// reLogin performs a full re-login using stored email+password credentials.
// Returns the AccessResponse on success, or an error if 2FA is required or login fails.
func (f *Fs) reLogin(ctx context.Context) (*internxtauth.AccessResponse, error) {
password, err := obscure.Reveal(f.opt.Pass)
if err != nil {
return nil, fmt.Errorf("couldn't decrypt password: %w", err)
}
cfg := internxtconfig.NewDefaultToken("")
cfg.HTTPClient = fshttp.NewClient(ctx)
loginResp, err := internxtauth.Login(ctx, cfg, f.opt.Email)
if err != nil {
return nil, fmt.Errorf("re-login check failed: %w", err)
}
if loginResp.TFA {
return nil, errors.New("account requires 2FA - please run: rclone config reconnect " + f.name + ":")
}
resp, err := internxtauth.DoLogin(ctx, cfg, f.opt.Email, password, "")
if err != nil {
return nil, fmt.Errorf("re-login failed: %w", err)
}
return resp, nil
}
// refreshOrReLogin tries to refresh the JWT token first; if that fails with 401,
// it falls back to a full re-login using stored credentials.
func (f *Fs) refreshOrReLogin(ctx context.Context) error {
refreshErr := refreshJWTToken(ctx, f.name, f.m)
if refreshErr == nil {
newToken, err := oauthutil.GetToken(f.name, f.m)
if err != nil {
return fmt.Errorf("failed to get refreshed token: %w", err)
}
f.cfg.Token = newToken.AccessToken
f.cfg.BasicAuthHeader = computeBasicAuthHeader(f.bridgeUser, f.userID)
fs.Debugf(f, "Token refresh succeeded")
return nil
}
var httpErr *sdkerrors.HTTPError
if !errors.As(refreshErr, &httpErr) || httpErr.StatusCode() != 401 {
if fserrors.ShouldRetry(refreshErr) {
return refreshErr
}
return refreshErr
}
fs.Debugf(f, "Token refresh returned 401, attempting re-login with stored credentials")
resp, err := f.reLogin(ctx)
if err != nil {
return fmt.Errorf("re-login fallback failed: %w", err)
}
oauthToken, err := jwtToOAuth2Token(resp.NewToken)
if err != nil {
return fmt.Errorf("failed to parse re-login token: %w", err)
}
err = oauthutil.PutToken(f.name, f.m, oauthToken, true)
if err != nil {
return fmt.Errorf("failed to save re-login token: %w", err)
}
f.cfg.Token = oauthToken.AccessToken
f.bridgeUser = resp.User.BridgeUser
f.userID = resp.User.UserID
f.cfg.BasicAuthHeader = computeBasicAuthHeader(f.bridgeUser, f.userID)
f.cfg.Bucket = resp.User.Bucket
f.cfg.RootFolderID = resp.User.RootFolderID
fs.Debugf(f, "Re-login succeeded, new token expiry: %v", oauthToken.Expiry)
return nil
}
// reAuthorize is called after getting 401 from the server.
// It serializes re-auth attempts and uses a circuit-breaker to avoid infinite loops.
func (f *Fs) reAuthorize(ctx context.Context) error {
f.authMu.Lock()
defer f.authMu.Unlock()
if f.authFailed {
return errors.New("re-authorization permanently failed")
}
err := f.refreshOrReLogin(ctx)
if err != nil {
f.authFailed = true
return err
}
return nil
}
+119 -71
View File
@@ -9,8 +9,8 @@ import (
"io"
"net"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/internxt/rclone-adapter/auth"
@@ -41,16 +41,34 @@ const (
decayConstant = 2 // bigger for slower decay, exponential
)
// shouldRetry determines if an error should be retried
func shouldRetry(ctx context.Context, err error) (bool, error) {
// shouldRetry determines if an error should be retried.
// On 401, it attempts to re-authorize before retrying.
// On 429, it honours the server's rate limit retry delay.
func (f *Fs) shouldRetry(ctx context.Context, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
var httpErr *sdkerrors.HTTPError
if errors.As(err, &httpErr) && httpErr.StatusCode() == 401 {
return true, err
if errors.As(err, &httpErr) {
switch httpErr.StatusCode() {
case 401:
if !f.authFailed {
authErr := f.reAuthorize(ctx)
if authErr != nil {
fs.Debugf(f, "Re-authorization failed: %v", authErr)
return false, err
}
return true, err
}
return false, err
case 429:
delay := httpErr.RetryAfter()
if delay <= 0 {
delay = time.Second
}
return true, pacer.RetryAfterError(err, delay)
}
}
return fserrors.ShouldRetry(err), err
}
@@ -184,6 +202,7 @@ type Fs struct {
name string
root string
opt Options
m configmap.Mapper
dirCache *dircache.DirCache
cfg *config.Config
features *fs.Features
@@ -191,6 +210,8 @@ type Fs struct {
tokenRenewer *oauthutil.Renew
bridgeUser string
userID string
authMu sync.Mutex
authFailed bool
}
// Object holds the data for a remote file object
@@ -263,45 +284,62 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
cfg.SkipHashValidation = opt.SkipHashValidation
cfg.HTTPClient = fshttp.NewClient(ctx)
userInfo, err := getUserInfo(ctx, &userInfoConfig{Token: cfg.Token})
if err != nil {
return nil, fmt.Errorf("failed to fetch user info: %w", err)
}
cfg.RootFolderID = userInfo.RootFolderID
cfg.Bucket = userInfo.Bucket
cfg.BasicAuthHeader = computeBasicAuthHeader(userInfo.BridgeUser, userInfo.UserID)
f := &Fs{
name: name,
root: strings.Trim(root, "/"),
opt: *opt,
cfg: cfg,
bridgeUser: userInfo.BridgeUser,
userID: userInfo.UserID,
name: name,
root: strings.Trim(root, "/"),
opt: *opt,
m: m,
cfg: cfg,
}
f.pacer = fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant)))
var userInfo *userInfo
const maxRetries = 3
for attempt := 1; attempt <= maxRetries; attempt++ {
userInfo, err = getUserInfo(ctx, &userInfoConfig{Token: f.cfg.Token})
if err == nil {
break
}
var httpErr *sdkerrors.HTTPError
if errors.As(err, &httpErr) && httpErr.StatusCode() == 401 {
fs.Debugf(f, "getUserInfo returned 401, attempting re-auth")
authErr := f.refreshOrReLogin(ctx)
if authErr != nil {
return nil, fmt.Errorf("failed to fetch user info (re-auth failed): %w", err)
}
userInfo, err = getUserInfo(ctx, &userInfoConfig{Token: f.cfg.Token})
if err == nil {
break
}
return nil, fmt.Errorf("failed to fetch user info after re-auth: %w", err)
}
if fserrors.ShouldRetry(err) && attempt < maxRetries {
fs.Debugf(f, "getUserInfo transient error (attempt %d/%d): %v", attempt, maxRetries, err)
time.Sleep(time.Duration(attempt) * time.Second)
continue
}
return nil, fmt.Errorf("failed to fetch user info: %w", err)
}
f.cfg.RootFolderID = userInfo.RootFolderID
f.cfg.Bucket = userInfo.Bucket
f.cfg.BasicAuthHeader = computeBasicAuthHeader(userInfo.BridgeUser, userInfo.UserID)
f.bridgeUser = userInfo.BridgeUser
f.userID = userInfo.UserID
f.features = (&fs.Features{
CanHaveEmptyDirectories: true,
}).Fill(ctx, f)
if ts != nil {
f.tokenRenewer = oauthutil.NewRenew(f.String(), ts, func() error {
err := refreshJWTToken(ctx, name, m)
if err != nil {
return err
}
newToken, err := oauthutil.GetToken(name, m)
if err != nil {
return fmt.Errorf("failed to get refreshed token: %w", err)
}
f.cfg.Token = newToken.AccessToken
f.cfg.BasicAuthHeader = computeBasicAuthHeader(f.bridgeUser, f.userID)
return nil
f.authMu.Lock()
defer f.authMu.Unlock()
return f.refreshOrReLogin(ctx)
})
f.tokenRenewer.Start()
}
@@ -312,9 +350,19 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if err != nil {
// Assume it might be a file
newRoot, remote := dircache.SplitPath(f.root)
tempF := *f
tempF.dirCache = dircache.New(newRoot, f.cfg.RootFolderID, &tempF)
tempF.root = newRoot
tempF := &Fs{
name: f.name,
root: newRoot,
opt: f.opt,
m: f.m,
cfg: f.cfg,
features: f.features,
pacer: f.pacer,
tokenRenewer: f.tokenRenewer,
bridgeUser: f.bridgeUser,
userID: f.userID,
}
tempF.dirCache = dircache.New(newRoot, f.cfg.RootFolderID, tempF)
err = tempF.dirCache.FindRoot(ctx, false)
if err != nil {
@@ -367,7 +415,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
err = f.pacer.Call(func() (bool, error) {
var err error
childFolders, err = folders.ListAllFolders(ctx, f.cfg, id)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return err
@@ -380,7 +428,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
err = f.pacer.Call(func() (bool, error) {
var err error
childFiles, err = folders.ListAllFiles(ctx, f.cfg, id)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return err
@@ -395,7 +443,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
if err != nil && strings.Contains(err.Error(), "404") {
return false, fs.ErrorDirNotFound
}
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return err
@@ -412,7 +460,7 @@ func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (string, bool, e
err := f.pacer.Call(func() (bool, error) {
var err error
entries, err = folders.ListAllFolders(ctx, f.cfg, pathID)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return "", false, err
@@ -437,7 +485,7 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (string, error)
err := f.pacer.CallNoRetry(func() (bool, error) {
var err error
resp, err = folders.CreateFolder(ctx, f.cfg, request)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
// If folder already exists (409 conflict), try to find it
@@ -459,8 +507,8 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (string, error)
func (f *Fs) preUploadCheck(ctx context.Context, leaf, directoryID string) (*folders.File, error) {
// Parse name and extension from the leaf
baseName := f.opt.Encoding.FromStandardName(leaf)
name := strings.TrimSuffix(baseName, filepath.Ext(baseName))
ext := strings.TrimPrefix(filepath.Ext(baseName), ".")
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
checkResult, err := files.CheckFilesExistence(ctx, f.cfg, directoryID, []files.FileExistenceCheck{
{
@@ -525,20 +573,20 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
err = f.pacer.Call(func() (bool, error) {
var err error
foldersList, err = folders.ListAllFolders(ctx, f.cfg, dirID)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
}
for _, e := range foldersList {
remote := filepath.Join(dir, f.opt.Encoding.ToStandardName(e.PlainName))
remote := path.Join(dir, f.opt.Encoding.ToStandardName(e.PlainName))
out = append(out, fs.NewDir(remote, e.ModificationTime))
}
var filesList []folders.File
err = f.pacer.Call(func() (bool, error) {
var err error
filesList, err = folders.ListAllFiles(ctx, f.cfg, dirID)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
@@ -548,7 +596,7 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
if len(e.Type) > 0 {
remote += "." + e.Type
}
remote = filepath.Join(dir, f.opt.Encoding.ToStandardName(remote))
remote = path.Join(dir, f.opt.Encoding.ToStandardName(remote))
out = append(out, newObjectWithFile(f, remote, &e))
}
return out, nil
@@ -616,7 +664,7 @@ func (f *Fs) Remove(ctx context.Context, remote string) error {
}
err = f.pacer.Call(func() (bool, error) {
err := folders.DeleteFolder(ctx, f.cfg, dirID)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return err
@@ -627,7 +675,7 @@ func (f *Fs) Remove(ctx context.Context, remote string) error {
// NewObject creates a new object
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
parentDir := filepath.Dir(remote)
parentDir := path.Dir(remote)
if parentDir == "." {
parentDir = ""
@@ -642,12 +690,12 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
err = f.pacer.Call(func() (bool, error) {
var err error
files, err = folders.ListAllFiles(ctx, f.cfg, dirID)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
}
targetName := filepath.Base(remote)
targetName := path.Base(remote)
for _, e := range files {
name := e.PlainName
if len(e.Type) > 0 {
@@ -720,7 +768,7 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
err := f.pacer.Call(func() (bool, error) {
var err error
internxtLimit, err = users.GetLimit(ctx, f.cfg)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
@@ -730,7 +778,7 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
err = f.pacer.Call(func() (bool, error) {
var err error
internxtUsage, err = users.GetUsage(ctx, f.cfg)
return shouldRetry(ctx, err)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
@@ -776,7 +824,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
err := o.f.pacer.Call(func() (bool, error) {
var err error
stream, err = buckets.DownloadFileStream(ctx, o.f.cfg, o.id, rangeValue)
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
@@ -788,9 +836,9 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
remote := o.remote
origBaseName := filepath.Base(remote)
origName := strings.TrimSuffix(origBaseName, filepath.Ext(origBaseName))
origType := strings.TrimPrefix(filepath.Ext(origBaseName), ".")
origBaseName := path.Base(remote)
origName := strings.TrimSuffix(origBaseName, path.Ext(origBaseName))
origType := strings.TrimPrefix(path.Ext(origBaseName), ".")
// Create directory if it doesn't exist
_, dirID, err := o.f.dirCache.FindPath(ctx, remote, true)
@@ -808,9 +856,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// Step 1: If file exists, rename to backup (preserves old file during upload)
if oldUUID != "" {
// Generate unique backup name
baseName := filepath.Base(remote)
name := strings.TrimSuffix(baseName, filepath.Ext(baseName))
ext := strings.TrimPrefix(filepath.Ext(baseName), ".")
baseName := path.Base(remote)
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
backupSuffix := fmt.Sprintf(".rclone-backup-%s", random.String(8))
backupName = o.f.opt.Encoding.FromStandardName(name + backupSuffix)
@@ -826,7 +874,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return false, nil
}
}
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("failed to rename existing file to backup: %w", err)
@@ -842,12 +890,12 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
meta, err = buckets.UploadFileStreamAuto(ctx,
o.f.cfg,
dirID,
o.f.opt.Encoding.FromStandardName(filepath.Base(remote)),
o.f.opt.Encoding.FromStandardName(path.Base(remote)),
in,
src.Size(),
src.ModTime(ctx),
)
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
if err != nil && isEmptyFileLimitError(err) {
@@ -885,7 +933,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
}
}
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
if err != nil {
fs.Errorf(o.f, "Failed to delete backup file %s.%s (UUID: %s): %v. This may leave an orphaned backup file.",
@@ -932,18 +980,18 @@ func (o *Object) recoverFromTimeoutConflict(ctx context.Context, uploadErr error
return nil, uploadErr
}
baseName := filepath.Base(remote)
baseName := path.Base(remote)
encodedName := o.f.opt.Encoding.FromStandardName(baseName)
var meta *buckets.CreateMetaResponse
checkErr := o.f.pacer.Call(func() (bool, error) {
existingFile, err := o.f.preUploadCheck(ctx, encodedName, dirID)
if err != nil {
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
}
if existingFile != nil {
name := strings.TrimSuffix(baseName, filepath.Ext(baseName))
ext := strings.TrimPrefix(filepath.Ext(baseName), ".")
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
meta = &buckets.CreateMetaResponse{
UUID: existingFile.UUID,
@@ -978,7 +1026,7 @@ func (o *Object) restoreBackupFile(ctx context.Context, backupUUID, origName, or
_ = o.f.pacer.Call(func() (bool, error) {
err := files.RenameFile(ctx, o.f.cfg, backupUUID,
o.f.opt.Encoding.FromStandardName(origName), origType)
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
}
@@ -986,6 +1034,6 @@ func (o *Object) restoreBackupFile(ctx context.Context, backupUUID, origName, or
func (o *Object) Remove(ctx context.Context) error {
return o.f.pacer.Call(func() (bool, error) {
err := files.DeleteFile(ctx, o.f.cfg, o.uuid)
return shouldRetry(ctx, err)
return o.f.shouldRetry(ctx, err)
})
}
+2 -4
View File
@@ -33,12 +33,10 @@ func TestRemove(t *testing.T) {
assert.True(t, exists())
// close the file in the background
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
time.Sleep(250 * time.Millisecond)
require.NoError(t, fd.Close())
}()
})
// delete the open file
err = remove(name)
require.NoError(t, err)
+1 -1
View File
@@ -14,7 +14,7 @@ import (
func remove(name string) (err error) {
const maxTries = 10
var sleepTime = 1 * time.Millisecond
for i := 0; i < maxTries; i++ {
for i := range maxTries {
err = os.Remove(name)
if err == nil {
break
+2 -2
View File
@@ -112,7 +112,7 @@ type ListItem struct {
Count struct {
Folders int `json:"folders"`
Files int `json:"files"`
} `json:"count,omitempty"`
} `json:"count"`
Kind string `json:"kind"`
Type string `json:"type"`
Name string `json:"name"`
@@ -154,7 +154,7 @@ type FolderInfoResponse struct {
Type string `json:"type"`
Home string `json:"home"`
List []ListItem `json:"list"`
} `json:"body,omitempty"`
} `json:"body"`
Time int64 `json:"time"`
Status int `json:"status"`
Email string `json:"email"`
+12 -12
View File
@@ -50,12 +50,12 @@ type Identity struct {
// to represent a set of identities associated with various events for
// an item, such as created by or last modified by.
type IdentitySet struct {
User Identity `json:"user,omitempty"`
Application Identity `json:"application,omitempty"`
Device Identity `json:"device,omitempty"`
Group Identity `json:"group,omitempty"`
SiteGroup Identity `json:"siteGroup,omitempty"` // The SharePoint group associated with this action. Optional.
SiteUser Identity `json:"siteUser,omitempty"` // The SharePoint user associated with this action. Optional.
User Identity `json:"user"`
Application Identity `json:"application"`
Device Identity `json:"device"`
Group Identity `json:"group"`
SiteGroup Identity `json:"siteGroup"` // The SharePoint group associated with this action. Optional.
SiteUser Identity `json:"siteUser"` // The SharePoint user associated with this action. Optional.
}
// Quota groups storage space quota-related information on OneDrive into a single structure.
@@ -155,8 +155,8 @@ type FileFacet struct {
// facet can be used to specify the last modified date or created date
// of the item as it was on the local device.
type FileSystemInfoFacet struct {
CreatedDateTime Timestamp `json:"createdDateTime,omitempty"` // The UTC date and time the file was created on a client.
LastModifiedDateTime Timestamp `json:"lastModifiedDateTime,omitempty"` // The UTC date and time the file was last modified on a client.
CreatedDateTime Timestamp `json:"createdDateTime"` // The UTC date and time the file was created on a client.
LastModifiedDateTime Timestamp `json:"lastModifiedDateTime"` // The UTC date and time the file was last modified on a client.
}
// DeletedFacet indicates that the item on OneDrive has been
@@ -175,10 +175,10 @@ type PackageFacet struct {
// SharedType indicates a DriveItem has been shared with others. The resource includes information about how the item is shared.
// If a Driveitem has a non-null shared facet, the item has been shared.
type SharedType struct {
Owner IdentitySet `json:"owner,omitempty"` // The identity of the owner of the shared item. Read-only.
Scope string `json:"scope,omitempty"` // Indicates the scope of how the item is shared: anonymous, organization, or users. Read-only.
SharedBy IdentitySet `json:"sharedBy,omitempty"` // The identity of the user who shared the item. Read-only.
SharedDateTime Timestamp `json:"sharedDateTime,omitempty"` // The UTC date and time when the item was shared. Read-only.
Owner IdentitySet `json:"owner"` // The identity of the owner of the shared item. Read-only.
Scope string `json:"scope,omitempty"` // Indicates the scope of how the item is shared: anonymous, organization, or users. Read-only.
SharedBy IdentitySet `json:"sharedBy"` // The identity of the user who shared the item. Read-only.
SharedDateTime Timestamp `json:"sharedDateTime"` // The UTC date and time when the item was shared. Read-only.
}
// SharingInvitationType groups invitation-related data items into a single structure.
+18 -18
View File
@@ -75,8 +75,8 @@ type ErrorDetails struct {
Type string `json:"@type,omitempty"`
Reason string `json:"reason,omitempty"`
Domain string `json:"domain,omitempty"`
Metadata struct{} `json:"metadata,omitempty"` // TODO: undiscovered yet
Locale string `json:"locale,omitempty"` // e.g. "en"
Metadata struct{} `json:"metadata"` // TODO: undiscovered yet
Locale string `json:"locale,omitempty"` // e.g. "en"
Message string `json:"message,omitempty"`
StackEntries []any `json:"stack_entries,omitempty"` // TODO: undiscovered yet
Detail string `json:"detail,omitempty"`
@@ -189,8 +189,8 @@ type File struct {
Apps []*FileApp `json:"apps,omitempty"`
Audit *FileAudit `json:"audit,omitempty"`
Collection string `json:"collection,omitempty"` // TODO
CreatedTime Time `json:"created_time,omitempty"`
DeleteTime Time `json:"delete_time,omitempty"`
CreatedTime Time `json:"created_time"`
DeleteTime Time `json:"delete_time"`
FileCategory string `json:"file_category,omitempty"` // "AUDIO", "VIDEO"
FileExtension string `json:"file_extension,omitempty"`
FolderType string `json:"folder_type,omitempty"`
@@ -202,7 +202,7 @@ type File struct {
Md5Checksum string `json:"md5_checksum,omitempty"`
Medias []*Media `json:"medias,omitempty"`
MimeType string `json:"mime_type,omitempty"`
ModifiedTime Time `json:"modified_time,omitempty"` // updated when renamed or moved
ModifiedTime Time `json:"modified_time"` // updated when renamed or moved
Name string `json:"name,omitempty"`
OriginalFileIndex int `json:"original_file_index,omitempty"` // TODO
OriginalURL string `json:"original_url,omitempty"`
@@ -221,7 +221,7 @@ type File struct {
ThumbnailLink string `json:"thumbnail_link,omitempty"`
Trashed bool `json:"trashed,omitempty"`
UserID string `json:"user_id,omitempty"`
UserModifiedTime Time `json:"user_modified_time,omitempty"`
UserModifiedTime Time `json:"user_modified_time"`
WebContentLink string `json:"web_content_link,omitempty"`
Writable bool `json:"writable,omitempty"`
}
@@ -252,7 +252,7 @@ type Media struct {
AudioCodec string `json:"audio_codec,omitempty"` // "pcm_bluray", "aac"
VideoType string `json:"video_type,omitempty"` // "mpegts"
HdrType string `json:"hdr_type,omitempty"`
} `json:"video,omitempty"`
} `json:"video"`
Link *Link `json:"link,omitempty"`
NeedMoreQuota bool `json:"need_more_quota,omitempty"`
VipTypes []any `json:"vip_types,omitempty"` // TODO maybe list of something?
@@ -290,11 +290,11 @@ type FileApp struct {
NeedMoreQuota bool `json:"need_more_quota,omitempty"`
IconLink string `json:"icon_link,omitempty"`
IsDefault bool `json:"is_default,omitempty"`
Params struct{} `json:"params,omitempty"` // TODO
Params struct{} `json:"params"` // TODO
CategoryIDs []any `json:"category_ids,omitempty"`
AdSceneType int `json:"ad_scene_type,omitempty"`
Space string `json:"space,omitempty"`
Links struct{} `json:"links,omitempty"` // TODO
Links struct{} `json:"links"` // TODO
}
// ------------------------------------------------------------
@@ -320,8 +320,8 @@ type Task struct {
FileName string `json:"file_name,omitempty"`
FileSize string `json:"file_size,omitempty"`
Message string `json:"message,omitempty"` // e.g. "Saving"
CreatedTime Time `json:"created_time,omitempty"`
UpdatedTime Time `json:"updated_time,omitempty"`
CreatedTime Time `json:"created_time"`
UpdatedTime Time `json:"updated_time"`
ThirdTaskID string `json:"third_task_id,omitempty"` // TODO
Phase string `json:"phase,omitempty"` // e.g. "PHASE_TYPE_RUNNING"
Progress int `json:"progress,omitempty"`
@@ -368,7 +368,7 @@ type ResumableParams struct {
AccessKeySecret string `json:"access_key_secret,omitempty"`
Bucket string `json:"bucket,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Expiration Time `json:"expiration,omitempty"`
Expiration Time `json:"expiration"`
Key string `json:"key,omitempty"`
SecurityToken string `json:"security_token,omitempty"`
}
@@ -409,7 +409,7 @@ type About struct {
Kind string `json:"kind,omitempty"` // "drive#about"
Quota *Quota `json:"quota,omitempty"`
ExpiresAt string `json:"expires_at,omitempty"`
Quotas struct{} `json:"quotas,omitempty"` // maybe []*Quota?
Quotas struct{} `json:"quotas"` // maybe []*Quota?
}
// Quota informs drive quota
@@ -445,8 +445,8 @@ type User struct {
PhoneNumber string `json:"phone_number,omitempty"`
Password string `json:"password,omitempty"` // "SET" if configured
Status string `json:"status,omitempty"` // "ACTIVE"
CreatedAt Time `json:"created_at,omitempty"`
PasswordUpdatedAt Time `json:"password_updated_at,omitempty"`
CreatedAt Time `json:"created_at"`
PasswordUpdatedAt Time `json:"password_updated_at"`
}
// UserProvider details third-party authentication
@@ -464,11 +464,11 @@ type VIP struct {
Message string `json:"message,omitempty"`
RedirectURI string `json:"redirect_uri,omitempty"`
Data struct {
Expire Time `json:"expire,omitempty"`
Expire Time `json:"expire"`
Status string `json:"status,omitempty"` // "invalid" or "ok"
Type string `json:"type,omitempty"` // "novip" or "platinum"
UserID string `json:"user_id,omitempty"` // same as User.Sub
} `json:"data,omitempty"`
} `json:"data"`
}
// DecompressResult is a response to RequestDecompress
@@ -538,7 +538,7 @@ type CaptchaToken struct {
CaptchaToken string `json:"captcha_token"`
ExpiresIn int64 `json:"expires_in"` // currently 300s
// API doesn't provide Expiry field and thus it should be populated from ExpiresIn on retrieval
Expiry time.Time `json:"expiry,omitempty"`
Expiry time.Time `json:"expiry"`
URL string `json:"url,omitempty"` // a link for users to solve captcha
}
+14 -3
View File
@@ -1608,7 +1608,7 @@ func (f *Fs) UserInfo(ctx context.Context) (userInfo map[string]string, err erro
// ------------------------------------------------------------
// add offline download task for url
func (f *Fs) addURL(ctx context.Context, url, path string) (*api.Task, error) {
func (f *Fs) addURL(ctx context.Context, url, name, path string) (*api.Task, error) {
req := api.RequestNewTask{
Kind: api.KindOfFile,
UploadType: "UPLOAD_TYPE_URL",
@@ -1617,6 +1617,9 @@ func (f *Fs) addURL(ctx context.Context, url, path string) (*api.Task, error) {
},
FolderType: "DOWNLOAD",
}
if name != "" {
req.Name = f.opt.Enc.FromStandardName(name)
}
if parentID, err := f.dirCache.FindDir(ctx, path, false); err == nil {
req.ParentID = parentIDForRequest(parentID)
req.FolderType = ""
@@ -1681,14 +1684,18 @@ var commandHelp = []fs.CommandHelp{{
Short: "Add offline download task for url.",
Long: `This command adds offline download task for url.
Usage example:
Usage examples:
` + "```console" + `
rclone backend addurl pikpak:dirpath url
rclone backend addurl pikpak:dirpath url -o name=custom_filename.zip
` + "```" + `
Downloads will be stored in 'dirpath'. If 'dirpath' is invalid,
download will fallback to default 'My Pack' folder.`,
Opts: map[string]string{
"name": "Custom filename for the downloaded file.",
},
}, {
Name: "decompress",
Short: "Request decompress of a file/files in a folder.",
@@ -1732,7 +1739,11 @@ func (f *Fs) Command(ctx context.Context, name string, arg []string, opt map[str
if len(arg) != 1 {
return nil, errors.New("need exactly 1 argument")
}
return f.addURL(ctx, arg[0], "")
filename := ""
if name, ok := opt["name"]; ok {
filename = name
}
return f.addURL(ctx, arg[0], filename, "")
case "decompress":
filename := ""
if len(arg) > 0 {
+1
View File
@@ -170,6 +170,7 @@ In `backend/s3/provider/YourProvider.yaml`
UseUnsignedPayload *bool `yaml:"use_unsigned_payload,omitempty"`
UseXID *bool `yaml:"use_x_id,omitempty"`
SignAcceptEncoding *bool `yaml:"sign_accept_encoding,omitempty"`
EtagIsNotMD5 *bool `yaml:"etag_is_not_md5,omitempty"`
CopyCutoff *int64 `yaml:"copy_cutoff,omitempty"`
MaxUploadParts *int `yaml:"max_upload_parts,omitempty"`
MinChunkSize *int64 `yaml:"min_chunk_size,omitempty"`
+26
View File
@@ -0,0 +1,26 @@
name: Fastly
description: Fastly Object Storage
region:
au-east-1: AU East 1
eu-central: EU Central
eu-south-1: EU South 1
jp-central-1: JP Central 1
uk-east-1: UK East 1
us-central-1: US Central 1
us-east: US East
us-west: US West
endpoint:
au-east-1.object.fastlystorage.app: AU East 1
eu-central.object.fastlystorage.app: EU Central
eu-south-1.object.fastlystorage.app: EU South 1
jp-central-1.object.fastlystorage.app: JP Central 1
uk-east-1.object.fastlystorage.app: UK East 1
us-central-1.object.fastlystorage.app: US Central 1
us-east.object.fastlystorage.app: US East
us-west.object.fastlystorage.app: US West
quirks:
force_path_style: true
use_already_exists: false
use_multipart_etag: false
use_multipart_uploads: false
etag_is_not_md5: true
+1 -1
View File
@@ -15,7 +15,7 @@ endpoint:
acl: {}
bucket_acl: true
quirks:
list_version: 1
list_version: 2
force_path_style: true
list_url_encode: false
use_multipart_etag: false
+9 -3
View File
@@ -3,11 +3,17 @@ description: IONOS Cloud
region:
de: Frankfurt, Germany
eu-central-2: Berlin, Germany
eu-central-3: Berlin, Germany
eu-central-4: Frankfurt, Germany
eu-south-2: Logrono, Spain
us-central-1: Lenexa, USA
endpoint:
s3-eu-central-1.ionoscloud.com: Frankfurt, Germany
s3-eu-central-2.ionoscloud.com: Berlin, Germany
s3-eu-south-2.ionoscloud.com: Logrono, Spain
s3.eu-central-1.ionoscloud.com: Frankfurt, Germany
s3.eu-central-2.ionoscloud.com: Berlin, Germany
s3.eu-central-3.ionoscloud.com: Berlin, Germany
s3.eu-central-4.ionoscloud.com: Frankfurt, Germany
s3.eu-south-2.ionoscloud.com: Logrono, Spain
s3.us-central-1.ionoscloud.com: Lenexa, USA
acl: {}
bucket_acl: true
quirks:
+2 -2
View File
@@ -18,11 +18,11 @@ storage_class:
GLACIER: |-
Archived storage.
Prices are lower, but it needs to be restored first to be accessed.
Available in FR-PAR and NL-AMS regions.
Available in the FR-PAR region only.
ONEZONE_IA: |-
One Zone - Infrequent Access.
A good choice for storing secondary backup copies or easily re-creatable data.
Available in the FR-PAR region only.
Available in all regions.
bucket_acl: true
quirks:
max_upload_parts: 1000
-14
View File
@@ -1,14 +0,0 @@
name: StackPath
description: StackPath Object Storage
region: {}
endpoint:
s3.us-east-2.stackpathstorage.com: US East Endpoint
s3.us-west-1.stackpathstorage.com: US West Endpoint
s3.eu-central-1.stackpathstorage.com: EU Endpoint
acl: {}
bucket_acl: true
quirks:
list_version: 1
force_path_style: true
list_url_encode: false
use_already_exists: false
+9
View File
@@ -0,0 +1,9 @@
name: Zadara
description: Zadara Object Storage
region:
us-east-1: |-
The default region.
Leave location constraint empty.
endpoint: {}
quirks:
force_path_style: true
+1
View File
@@ -32,6 +32,7 @@ type Quirks struct {
UseUnsignedPayload *bool `yaml:"use_unsigned_payload,omitempty"`
UseXID *bool `yaml:"use_x_id,omitempty"`
SignAcceptEncoding *bool `yaml:"sign_accept_encoding,omitempty"`
EtagIsNotMD5 *bool `yaml:"etag_is_not_md5,omitempty"`
CopyCutoff *int64 `yaml:"copy_cutoff,omitempty"`
MaxUploadParts *int `yaml:"max_upload_parts,omitempty"`
MinChunkSize *int64 `yaml:"min_chunk_size,omitempty"`
+389 -5
View File
@@ -63,6 +63,7 @@ import (
"github.com/rclone/rclone/lib/pool"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/lib/rest"
"github.com/rclone/rclone/lib/transferaccounter"
"github.com/rclone/rclone/lib/version"
)
@@ -828,6 +829,107 @@ use |-vv| to see the debug level logs.
}, {
Name: "ibm_resource_instance_id",
Help: "IBM service instance id",
}, {
Name: "object_lock_mode",
Help: `Object Lock mode to apply when uploading or copying objects.
Set this to apply Object Lock retention mode to objects.
If not set, no Object Lock mode is applied (even with --metadata).
Note: To enable Object Lock retention, you must set BOTH object_lock_mode
AND object_lock_retain_until_date. Setting only one has no effect.
- GOVERNANCE: Set Object Lock mode to GOVERNANCE
- COMPLIANCE: Set Object Lock mode to COMPLIANCE
- copy: Copy the mode from the source object (requires --metadata)
See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html`,
Advanced: true,
Examples: []fs.OptionExample{{
Value: "GOVERNANCE",
Help: "Set Object Lock mode to GOVERNANCE",
}, {
Value: "COMPLIANCE",
Help: "Set Object Lock mode to COMPLIANCE",
}, {
Value: "copy",
Help: "Copy from source object (requires --metadata)",
}},
}, {
Name: "object_lock_retain_until_date",
Help: `Object Lock retention until date to apply when uploading or copying objects.
Set this to apply Object Lock retention date to objects.
If not set, no retention date is applied (even with --metadata).
Note: To enable Object Lock retention, you must set BOTH object_lock_mode
AND object_lock_retain_until_date. Setting only one has no effect.
Accepts:
- RFC 3339 format: 2030-01-02T15:04:05Z
- Duration from now: 365d, 1y, 6M (days, years, months)
- copy: Copy the date from the source object (requires --metadata)
See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html`,
Advanced: true,
Examples: []fs.OptionExample{{
Value: "copy",
Help: "Copy from source object (requires --metadata)",
}, {
Value: "2030-01-01T00:00:00Z",
Help: "Set specific date (RFC 3339 format)",
}, {
Value: "365d",
Help: "Set retention for 365 days from now",
}, {
Value: "1y",
Help: "Set retention for 1 year from now",
}},
}, {
Name: "object_lock_legal_hold_status",
Help: `Object Lock legal hold status to apply when uploading or copying objects.
Set this to apply Object Lock legal hold to objects.
If not set, no legal hold is applied (even with --metadata).
Note: Legal hold is independent of retention and can be set separately.
- ON: Enable legal hold
- OFF: Disable legal hold
- copy: Copy the legal hold status from the source object (requires --metadata)
See: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html`,
Advanced: true,
Examples: []fs.OptionExample{{
Value: "ON",
Help: "Enable legal hold",
}, {
Value: "OFF",
Help: "Disable legal hold",
}, {
Value: "copy",
Help: "Copy from source object (requires --metadata)",
}},
}, {
Name: "bypass_governance_retention",
Help: `Allow deleting or modifying objects locked with GOVERNANCE mode.`,
Default: false,
Advanced: true,
}, {
Name: "bucket_object_lock_enabled",
Help: `Enable Object Lock when creating new buckets.`,
Default: false,
}, {
Name: "object_lock_set_after_upload",
Help: `Set Object Lock via separate API calls after upload.
Use this for S3-compatible providers that don't support setting Object Lock
headers during PUT operations. When enabled, Object Lock is set via separate
PutObjectRetention and PutObjectLegalHold API calls after the upload completes.
This adds extra API calls per object, so only enable if your provider requires it.`,
Default: false,
Advanced: true,
},
}}))
}
@@ -922,6 +1024,21 @@ var systemMetadataInfo = map[string]fs.MetadataHelp{
Example: "2006-01-02T15:04:05.999999999Z07:00",
ReadOnly: true,
},
"object-lock-mode": {
Help: "Object Lock mode: GOVERNANCE or COMPLIANCE",
Type: "string",
Example: "GOVERNANCE",
},
"object-lock-retain-until-date": {
Help: "Object Lock retention until date",
Type: "RFC 3339",
Example: "2030-01-02T15:04:05Z",
},
"object-lock-legal-hold-status": {
Help: "Object Lock legal hold status: ON or OFF",
Type: "string",
Example: "OFF",
},
}
// Options defines the configuration for this backend
@@ -992,6 +1109,12 @@ type Options struct {
IBMInstanceID string `config:"ibm_resource_instance_id"`
UseXID fs.Tristate `config:"use_x_id"`
SignAcceptEncoding fs.Tristate `config:"sign_accept_encoding"`
ObjectLockMode string `config:"object_lock_mode"`
ObjectLockRetainUntilDate string `config:"object_lock_retain_until_date"`
ObjectLockLegalHoldStatus string `config:"object_lock_legal_hold_status"`
BypassGovernanceRetention bool `config:"bypass_governance_retention"`
BucketObjectLockEnabled bool `config:"bucket_object_lock_enabled"`
ObjectLockSetAfterUpload bool `config:"object_lock_set_after_upload"`
}
// Fs represents a remote s3 server
@@ -1036,6 +1159,11 @@ type Object struct {
contentDisposition *string // Content-Disposition: header
contentEncoding *string // Content-Encoding: header
contentLanguage *string // Content-Language: header
// Object Lock metadata
objectLockMode *string // Object Lock mode: GOVERNANCE or COMPLIANCE
objectLockRetainUntilDate *time.Time // Object Lock retention until date
objectLockLegalHoldStatus *string // Object Lock legal hold: ON or OFF
}
// safely dereference the pointer, returning a zero T if nil
@@ -1056,6 +1184,21 @@ func getHTTPStatusCode(err error) int {
return -1
}
// parseRetainUntilDate parses a retain until date from a string.
// It accepts RFC 3339 format or duration strings like "365d", "1y", "6m".
func parseRetainUntilDate(s string) (time.Time, error) {
// First try RFC 3339 format
if t, err := time.Parse(time.RFC3339, s); err == nil {
return t, nil
}
// Try as a duration from now
d, err := fs.ParseDuration(s)
if err != nil {
return time.Time{}, fmt.Errorf("can't parse %q as RFC 3339 date or duration: %w", s, err)
}
return time.Now().Add(d), nil
}
// ------------------------------------------------------------
// Name of the remote (as passed into NewFs)
@@ -1664,6 +1807,10 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
// MD5 digest of their object data.
f.etagIsNotMD5 = true
}
if provider.Quirks.EtagIsNotMD5 != nil && *provider.Quirks.EtagIsNotMD5 {
// Provider always returns ETags that are not MD5 (e.g., mandatory encryption)
f.etagIsNotMD5 = true
}
if opt.DirectoryBucket {
// Objects uploaded to directory buckets appear to have random ETags
//
@@ -1688,6 +1835,9 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if opt.Provider == "AWS" {
f.features.DoubleSlash = true
}
if opt.Provider == "Fastly" {
f.features.Copy = nil
}
if opt.Provider == "Rabata" {
f.features.Copy = nil
}
@@ -2642,8 +2792,9 @@ func (f *Fs) makeBucket(ctx context.Context, bucket string) error {
}
return f.cache.Create(bucket, func() error {
req := s3.CreateBucketInput{
Bucket: &bucket,
ACL: types.BucketCannedACL(f.opt.BucketACL),
Bucket: &bucket,
ACL: types.BucketCannedACL(f.opt.BucketACL),
ObjectLockEnabledForBucket: &f.opt.BucketObjectLockEnabled,
}
if f.opt.LocationConstraint != "" {
req.CreateBucketConfiguration = &types.CreateBucketConfiguration{
@@ -2762,6 +2913,24 @@ func (f *Fs) copy(ctx context.Context, req *s3.CopyObjectInput, dstBucket, dstPa
req.StorageClass = types.StorageClass(f.opt.StorageClass)
}
// Apply Object Lock options via headers (unless ObjectLockSetAfterUpload is set)
// "copy" means: keep the value from source (passed via req from prepareUpload/setFrom functions)
if !f.opt.ObjectLockSetAfterUpload {
if f.opt.ObjectLockMode != "" && !strings.EqualFold(f.opt.ObjectLockMode, "copy") {
req.ObjectLockMode = types.ObjectLockMode(strings.ToUpper(f.opt.ObjectLockMode))
}
if f.opt.ObjectLockRetainUntilDate != "" && !strings.EqualFold(f.opt.ObjectLockRetainUntilDate, "copy") {
retainDate, err := parseRetainUntilDate(f.opt.ObjectLockRetainUntilDate)
if err != nil {
return fmt.Errorf("invalid object_lock_retain_until_date: %w", err)
}
req.ObjectLockRetainUntilDate = &retainDate
}
if f.opt.ObjectLockLegalHoldStatus != "" && !strings.EqualFold(f.opt.ObjectLockLegalHoldStatus, "copy") {
req.ObjectLockLegalHoldStatus = types.ObjectLockLegalHoldStatus(strings.ToUpper(f.opt.ObjectLockLegalHoldStatus))
}
}
if src.bytes >= int64(f.opt.CopyCutoff) {
return f.copyMultipart(ctx, req, dstBucket, dstPath, srcBucket, srcPath, src)
}
@@ -2838,6 +3007,8 @@ func (f *Fs) copyMultipart(ctx context.Context, copyReq *s3.CopyObjectInput, dst
numParts := (srcSize-1)/partSize + 1
fs.Debugf(src, "Starting multipart copy with %d parts", numParts)
account := transferaccounter.Get(ctx)
account.Start()
var (
parts = make([]types.CompletedPart, numParts)
@@ -2872,6 +3043,11 @@ func (f *Fs) copyMultipart(ctx context.Context, copyReq *s3.CopyObjectInput, dst
PartNumber: &partNum,
ETag: uout.CopyPartResult.ETag,
}
copied := partSize
if int64(partNum) == numParts {
copied = srcSize - (numParts-1)*partSize
}
account.Add(copied)
return nil
})
}
@@ -2944,7 +3120,15 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
setFrom_s3CopyObjectInput_s3PutObjectInput(&req, ui.req)
if ci.Metadata {
// Use REPLACE directive if metadata is being modified, otherwise S3 ignores our values
// This is needed when:
// 1. --metadata flag is set
// 2. Any Object Lock option is set (to override or explicitly copy)
needsReplace := ci.Metadata ||
f.opt.ObjectLockMode != "" ||
f.opt.ObjectLockRetainUntilDate != "" ||
f.opt.ObjectLockLegalHoldStatus != ""
if needsReplace {
req.MetadataDirective = types.MetadataDirectiveReplace
}
@@ -2952,7 +3136,21 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
if err != nil {
return nil, err
}
return f.NewObject(ctx, remote)
dstObj, err := f.NewObject(ctx, remote)
if err != nil {
return nil, err
}
// Set Object Lock via separate API calls if requested
if f.opt.ObjectLockSetAfterUpload {
if dstObject, ok := dstObj.(*Object); ok {
if err := dstObject.setObjectLockAfterUpload(ctx, srcObj); err != nil {
return nil, err
}
}
}
return dstObj, nil
}
// Hashes returns the supported hash sets.
@@ -3831,6 +4029,19 @@ func (o *Object) setMetaData(resp *s3.HeadObjectOutput) {
o.contentEncoding = stringClonePointer(removeAWSChunked(resp.ContentEncoding))
o.contentLanguage = stringClonePointer(resp.ContentLanguage)
// Set Object Lock metadata
if resp.ObjectLockMode != "" {
mode := string(resp.ObjectLockMode)
o.objectLockMode = &mode
}
if resp.ObjectLockRetainUntilDate != nil {
o.objectLockRetainUntilDate = resp.ObjectLockRetainUntilDate
}
if resp.ObjectLockLegalHoldStatus != "" {
status := string(resp.ObjectLockLegalHoldStatus)
o.objectLockLegalHoldStatus = &status
}
// If decompressing then size and md5sum are unknown
if o.fs.opt.Decompress && deref(o.contentEncoding) == "gzip" {
o.bytes = -1
@@ -4549,6 +4760,26 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
case "btime":
// write as metadata since we can't set it
ui.req.Metadata[k] = v
case "object-lock-mode":
// Only apply if option is set to "copy" and not using after-upload API
if strings.EqualFold(o.fs.opt.ObjectLockMode, "copy") && !o.fs.opt.ObjectLockSetAfterUpload {
ui.req.ObjectLockMode = types.ObjectLockMode(v)
}
case "object-lock-retain-until-date":
// Only apply if option is set to "copy" and not using after-upload API
if strings.EqualFold(o.fs.opt.ObjectLockRetainUntilDate, "copy") && !o.fs.opt.ObjectLockSetAfterUpload {
retainDate, err := time.Parse(time.RFC3339, v)
if err != nil {
fs.Debugf(o, "failed to parse object-lock-retain-until-date %q: %v", v, err)
} else {
ui.req.ObjectLockRetainUntilDate = &retainDate
}
}
case "object-lock-legal-hold-status":
// Only apply if option is set to "copy" and not using after-upload API
if strings.EqualFold(o.fs.opt.ObjectLockLegalHoldStatus, "copy") && !o.fs.opt.ObjectLockSetAfterUpload {
ui.req.ObjectLockLegalHoldStatus = types.ObjectLockLegalHoldStatus(v)
}
default:
ui.req.Metadata[k] = v
}
@@ -4614,6 +4845,25 @@ func (o *Object) prepareUpload(ctx context.Context, src fs.ObjectInfo, options [
if o.fs.opt.StorageClass != "" {
ui.req.StorageClass = types.StorageClass(o.fs.opt.StorageClass)
}
// Apply Object Lock options via headers (unless ObjectLockSetAfterUpload is set)
// "copy" means: keep the value from metadata (already applied above in the switch)
if !o.fs.opt.ObjectLockSetAfterUpload {
if o.fs.opt.ObjectLockMode != "" && !strings.EqualFold(o.fs.opt.ObjectLockMode, "copy") {
ui.req.ObjectLockMode = types.ObjectLockMode(strings.ToUpper(o.fs.opt.ObjectLockMode))
}
if o.fs.opt.ObjectLockRetainUntilDate != "" && !strings.EqualFold(o.fs.opt.ObjectLockRetainUntilDate, "copy") {
retainDate, err := parseRetainUntilDate(o.fs.opt.ObjectLockRetainUntilDate)
if err != nil {
return ui, fmt.Errorf("invalid object_lock_retain_until_date %q: %w", o.fs.opt.ObjectLockRetainUntilDate, err)
}
ui.req.ObjectLockRetainUntilDate = &retainDate
}
if o.fs.opt.ObjectLockLegalHoldStatus != "" && !strings.EqualFold(o.fs.opt.ObjectLockLegalHoldStatus, "copy") {
ui.req.ObjectLockLegalHoldStatus = types.ObjectLockLegalHoldStatus(strings.ToUpper(o.fs.opt.ObjectLockLegalHoldStatus))
}
}
// Apply upload options
for _, option := range options {
key, value := option.Header()
@@ -4737,6 +4987,14 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
fs.Debugf(o, "Multipart upload Etag: %s OK", wantETag)
}
// Set Object Lock via separate API calls if requested
if o.fs.opt.ObjectLockSetAfterUpload {
if err := o.setObjectLockAfterUpload(ctx, src); err != nil {
return err
}
}
return err
}
@@ -4754,6 +5012,9 @@ func (o *Object) Remove(ctx context.Context) error {
if o.fs.opt.RequesterPays {
req.RequestPayer = types.RequestPayerRequester
}
if o.fs.opt.BypassGovernanceRetention {
req.BypassGovernanceRetention = &o.fs.opt.BypassGovernanceRetention
}
err := o.fs.pacer.Call(func() (bool, error) {
_, err := o.fs.c.DeleteObject(ctx, &req)
return o.fs.shouldRetry(ctx, err)
@@ -4761,6 +5022,120 @@ func (o *Object) Remove(ctx context.Context) error {
return err
}
// setObjectRetention sets Object Lock retention on an object via PutObjectRetention API
//
// Note: We use smithyhttp.AddContentChecksumMiddleware to ensure Content-MD5 is
// calculated for the request body. The AWS SDK v2 switched from MD5 to CRC32 as
// the default checksum algorithm, but some S3-compatible providers (e.g. MinIO)
// still require Content-MD5 for PutObjectRetention requests.
// See: https://github.com/aws/aws-sdk-go-v2/discussions/2960
func (o *Object) setObjectRetention(ctx context.Context, mode types.ObjectLockRetentionMode, retainUntilDate time.Time) error {
bucket, bucketPath := o.split()
req := s3.PutObjectRetentionInput{
Bucket: &bucket,
Key: &bucketPath,
VersionId: o.versionID,
Retention: &types.ObjectLockRetention{
Mode: mode,
RetainUntilDate: &retainUntilDate,
},
}
if o.fs.opt.RequesterPays {
req.RequestPayer = types.RequestPayerRequester
}
if o.fs.opt.BypassGovernanceRetention {
req.BypassGovernanceRetention = &o.fs.opt.BypassGovernanceRetention
}
return o.fs.pacer.Call(func() (bool, error) {
_, err := o.fs.c.PutObjectRetention(ctx, &req,
s3.WithAPIOptions(smithyhttp.AddContentChecksumMiddleware))
return o.fs.shouldRetry(ctx, err)
})
}
// setObjectLegalHold sets Object Lock legal hold on an object via PutObjectLegalHold API
//
// Note: We use smithyhttp.AddContentChecksumMiddleware to ensure Content-MD5 is
// calculated for the request body. The AWS SDK v2 switched from MD5 to CRC32 as
// the default checksum algorithm, but some S3-compatible providers (e.g. MinIO)
// still require Content-MD5 for PutObjectLegalHold requests.
// See: https://github.com/aws/aws-sdk-go-v2/discussions/2960
func (o *Object) setObjectLegalHold(ctx context.Context, status types.ObjectLockLegalHoldStatus) error {
bucket, bucketPath := o.split()
req := s3.PutObjectLegalHoldInput{
Bucket: &bucket,
Key: &bucketPath,
VersionId: o.versionID,
LegalHold: &types.ObjectLockLegalHold{
Status: status,
},
}
if o.fs.opt.RequesterPays {
req.RequestPayer = types.RequestPayerRequester
}
return o.fs.pacer.Call(func() (bool, error) {
_, err := o.fs.c.PutObjectLegalHold(ctx, &req,
s3.WithAPIOptions(smithyhttp.AddContentChecksumMiddleware))
return o.fs.shouldRetry(ctx, err)
})
}
// setObjectLockAfterUpload sets Object Lock via separate API calls after upload
// This is for S3 providers that don't support Object Lock headers during PUT
func (o *Object) setObjectLockAfterUpload(ctx context.Context, src fs.ObjectInfo) error {
// Determine the mode
var mode types.ObjectLockRetentionMode
modeOpt := o.fs.opt.ObjectLockMode
if strings.EqualFold(modeOpt, "copy") {
if srcObj, ok := src.(*Object); ok && srcObj.objectLockMode != nil {
mode = types.ObjectLockRetentionMode(*srcObj.objectLockMode)
}
} else if modeOpt != "" {
mode = types.ObjectLockRetentionMode(strings.ToUpper(modeOpt))
}
// Determine the retain until date
var retainUntilDate time.Time
dateOpt := o.fs.opt.ObjectLockRetainUntilDate
if strings.EqualFold(dateOpt, "copy") {
if srcObj, ok := src.(*Object); ok && srcObj.objectLockRetainUntilDate != nil {
retainUntilDate = *srcObj.objectLockRetainUntilDate
}
} else if dateOpt != "" {
var err error
retainUntilDate, err = parseRetainUntilDate(dateOpt)
if err != nil {
return fmt.Errorf("invalid object_lock_retain_until_date %q: %w", dateOpt, err)
}
}
// Set retention if both mode and date are set
if mode != "" && !retainUntilDate.IsZero() {
if err := o.setObjectRetention(ctx, mode, retainUntilDate); err != nil {
return fmt.Errorf("failed to set object retention: %w", err)
}
}
// Determine and set legal hold
var legalHold types.ObjectLockLegalHoldStatus
legalHoldOpt := o.fs.opt.ObjectLockLegalHoldStatus
if strings.EqualFold(legalHoldOpt, "copy") {
if srcObj, ok := src.(*Object); ok && srcObj.objectLockLegalHoldStatus != nil {
legalHold = types.ObjectLockLegalHoldStatus(*srcObj.objectLockLegalHoldStatus)
}
} else if legalHoldOpt != "" {
legalHold = types.ObjectLockLegalHoldStatus(strings.ToUpper(legalHoldOpt))
}
if legalHold != "" {
if err := o.setObjectLegalHold(ctx, legalHold); err != nil {
return fmt.Errorf("failed to set legal hold: %w", err)
}
}
return nil
}
// MimeType of an Object if known, "" otherwise
func (o *Object) MimeType(ctx context.Context) string {
err := o.readMetaData(ctx)
@@ -4804,7 +5179,7 @@ func (o *Object) Metadata(ctx context.Context) (metadata fs.Metadata, err error)
if err != nil {
return nil, err
}
metadata = make(fs.Metadata, len(o.meta)+7)
metadata = make(fs.Metadata, len(o.meta)+10)
for k, v := range o.meta {
switch k {
case metaMtime:
@@ -4839,6 +5214,15 @@ func (o *Object) Metadata(ctx context.Context) (metadata fs.Metadata, err error)
setMetadata("content-disposition", o.contentDisposition)
setMetadata("content-encoding", o.contentEncoding)
setMetadata("content-language", o.contentLanguage)
// Set Object Lock metadata
setMetadata("object-lock-mode", o.objectLockMode)
if o.objectLockRetainUntilDate != nil {
formatted := o.objectLockRetainUntilDate.Format(time.RFC3339)
setMetadata("object-lock-retain-until-date", &formatted)
}
setMetadata("object-lock-legal-hold-status", o.objectLockLegalHoldStatus)
metadata["tier"] = o.GetTier()
return metadata, nil
+226
View File
@@ -498,10 +498,236 @@ func (f *Fs) InternalTestVersions(t *testing.T) {
// Purge gets tested later
}
func (f *Fs) InternalTestObjectLock(t *testing.T) {
ctx := context.Background()
// Create a temporary bucket with Object Lock enabled to test on.
// This exercises our BucketObjectLockEnabled option and isolates
// the test from the main test bucket.
lockBucket := f.rootBucket + "-object-lock-" + random.String(8)
lockBucket = strings.ToLower(lockBucket)
// Try to create bucket with Object Lock enabled
objectLockEnabled := true
req := s3.CreateBucketInput{
Bucket: &lockBucket,
ACL: types.BucketCannedACL(f.opt.BucketACL),
ObjectLockEnabledForBucket: &objectLockEnabled,
}
if f.opt.LocationConstraint != "" {
req.CreateBucketConfiguration = &types.CreateBucketConfiguration{
LocationConstraint: types.BucketLocationConstraint(f.opt.LocationConstraint),
}
}
err := f.pacer.Call(func() (bool, error) {
_, err := f.c.CreateBucket(ctx, &req)
return f.shouldRetry(ctx, err)
})
if err != nil {
t.Skipf("Object Lock not supported by this provider: CreateBucket with Object Lock failed: %v", err)
}
// Verify Object Lock is actually enabled on the new bucket.
// Some S3-compatible servers (e.g. rclone serve s3) accept the
// ObjectLockEnabledForBucket flag but don't actually implement Object Lock.
var lockCfg *s3.GetObjectLockConfigurationOutput
err = f.pacer.Call(func() (bool, error) {
var err error
lockCfg, err = f.c.GetObjectLockConfiguration(ctx, &s3.GetObjectLockConfigurationInput{
Bucket: &lockBucket,
})
return f.shouldRetry(ctx, err)
})
if err != nil || lockCfg.ObjectLockConfiguration == nil ||
lockCfg.ObjectLockConfiguration.ObjectLockEnabled != types.ObjectLockEnabledEnabled {
_ = f.pacer.Call(func() (bool, error) {
_, err := f.c.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: &lockBucket})
return f.shouldRetry(ctx, err)
})
t.Skipf("Object Lock not functional on this provider (GetObjectLockConfiguration: %v)", err)
}
// Switch f to use the Object Lock bucket for this test
oldBucket := f.rootBucket
oldRoot := f.root
oldRootDir := f.rootDirectory
f.rootBucket = lockBucket
f.root = lockBucket
f.rootDirectory = ""
defer func() {
f.rootBucket = oldBucket
f.root = oldRoot
f.rootDirectory = oldRootDir
}()
// Helper to remove an object with Object Lock protection
removeLocked := func(t *testing.T, obj fs.Object) {
t.Helper()
o := obj.(*Object)
// Remove legal hold if present
_ = o.setObjectLegalHold(ctx, types.ObjectLockLegalHoldStatusOff)
// Enable bypass governance retention for deletion
o.fs.opt.BypassGovernanceRetention = true
err := obj.Remove(ctx)
o.fs.opt.BypassGovernanceRetention = false
assert.NoError(t, err)
}
// Clean up the temporary bucket after all sub-tests
defer func() {
// List and remove all object versions
var objectVersions []types.ObjectIdentifier
listReq := &s3.ListObjectVersionsInput{Bucket: &lockBucket}
for {
var resp *s3.ListObjectVersionsOutput
err := f.pacer.Call(func() (bool, error) {
var err error
resp, err = f.c.ListObjectVersions(ctx, listReq)
return f.shouldRetry(ctx, err)
})
if err != nil {
t.Logf("Failed to list object versions for cleanup: %v", err)
break
}
for _, v := range resp.Versions {
objectVersions = append(objectVersions, types.ObjectIdentifier{
Key: v.Key,
VersionId: v.VersionId,
})
}
for _, m := range resp.DeleteMarkers {
objectVersions = append(objectVersions, types.ObjectIdentifier{
Key: m.Key,
VersionId: m.VersionId,
})
}
if !aws.ToBool(resp.IsTruncated) {
break
}
listReq.KeyMarker = resp.NextKeyMarker
listReq.VersionIdMarker = resp.NextVersionIdMarker
}
if len(objectVersions) > 0 {
bypass := true
_ = f.pacer.Call(func() (bool, error) {
_, err := f.c.DeleteObjects(ctx, &s3.DeleteObjectsInput{
Bucket: &lockBucket,
BypassGovernanceRetention: &bypass,
Delete: &types.Delete{
Objects: objectVersions,
Quiet: aws.Bool(true),
},
})
return f.shouldRetry(ctx, err)
})
}
_ = f.pacer.Call(func() (bool, error) {
_, err := f.c.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: &lockBucket})
return f.shouldRetry(ctx, err)
})
}()
retainUntilDate := time.Now().UTC().Add(24 * time.Hour).Truncate(time.Second)
t.Run("Retention", func(t *testing.T) {
// Set Object Lock options for this test
f.opt.ObjectLockMode = "GOVERNANCE"
f.opt.ObjectLockRetainUntilDate = retainUntilDate.Format(time.RFC3339)
defer func() {
f.opt.ObjectLockMode = ""
f.opt.ObjectLockRetainUntilDate = ""
}()
// Upload an object with Object Lock retention
contents := random.String(100)
item := fstest.NewItem("test-object-lock-retention", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
removeLocked(t, obj)
}()
// Read back metadata and verify Object Lock settings
o := obj.(*Object)
gotMetadata, err := o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "GOVERNANCE", gotMetadata["object-lock-mode"])
gotRetainDate, err := time.Parse(time.RFC3339, gotMetadata["object-lock-retain-until-date"])
require.NoError(t, err)
assert.WithinDuration(t, retainUntilDate, gotRetainDate, time.Second)
})
t.Run("LegalHold", func(t *testing.T) {
// Set Object Lock legal hold option
f.opt.ObjectLockLegalHoldStatus = "ON"
defer func() {
f.opt.ObjectLockLegalHoldStatus = ""
}()
// Upload an object with legal hold
contents := random.String(100)
item := fstest.NewItem("test-object-lock-legal-hold", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
removeLocked(t, obj)
}()
// Verify legal hold is ON
o := obj.(*Object)
gotMetadata, err := o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "ON", gotMetadata["object-lock-legal-hold-status"])
// Set legal hold to OFF
err = o.setObjectLegalHold(ctx, types.ObjectLockLegalHoldStatusOff)
require.NoError(t, err)
// Clear cached metadata and re-read
o.meta = nil
gotMetadata, err = o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "OFF", gotMetadata["object-lock-legal-hold-status"])
})
t.Run("SetAfterUpload", func(t *testing.T) {
// Test the post-upload API path (PutObjectRetention + PutObjectLegalHold)
f.opt.ObjectLockSetAfterUpload = true
f.opt.ObjectLockMode = "GOVERNANCE"
f.opt.ObjectLockRetainUntilDate = retainUntilDate.Format(time.RFC3339)
f.opt.ObjectLockLegalHoldStatus = "ON"
defer func() {
f.opt.ObjectLockSetAfterUpload = false
f.opt.ObjectLockMode = ""
f.opt.ObjectLockRetainUntilDate = ""
f.opt.ObjectLockLegalHoldStatus = ""
}()
// Upload an object - lock applied AFTER upload via separate API calls
contents := random.String(100)
item := fstest.NewItem("test-object-lock-after-upload", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
removeLocked(t, obj)
}()
// Verify all Object Lock settings were applied
o := obj.(*Object)
gotMetadata, err := o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "GOVERNANCE", gotMetadata["object-lock-mode"])
gotRetainDate, err := time.Parse(time.RFC3339, gotMetadata["object-lock-retain-until-date"])
require.NoError(t, err)
assert.WithinDuration(t, retainUntilDate, gotRetainDate, time.Second)
assert.Equal(t, "ON", gotMetadata["object-lock-legal-hold-status"])
})
}
func (f *Fs) InternalTest(t *testing.T) {
t.Run("Metadata", f.InternalTestMetadata)
t.Run("NoHead", f.InternalTestNoHead)
t.Run("Versions", f.InternalTestVersions)
t.Run("ObjectLock", f.InternalTestObjectLock)
}
var _ fstests.InternalTester = (*Fs)(nil)
+85
View File
@@ -5,6 +5,7 @@ import (
"context"
"net/http"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/rclone/rclone/fs"
@@ -92,3 +93,87 @@ var (
_ fstests.SetUploadCutoffer = (*Fs)(nil)
_ fstests.SetCopyCutoffer = (*Fs)(nil)
)
func TestParseRetainUntilDate(t *testing.T) {
now := time.Now()
tests := []struct {
name string
input string
wantErr bool
checkFunc func(t *testing.T, result time.Time)
}{
{
name: "RFC3339 date",
input: "2030-01-15T10:30:00Z",
wantErr: false,
checkFunc: func(t *testing.T, result time.Time) {
expected, _ := time.Parse(time.RFC3339, "2030-01-15T10:30:00Z")
assert.Equal(t, expected, result)
},
},
{
name: "RFC3339 date with timezone",
input: "2030-06-15T10:30:00+02:00",
wantErr: false,
checkFunc: func(t *testing.T, result time.Time) {
expected, _ := time.Parse(time.RFC3339, "2030-06-15T10:30:00+02:00")
assert.Equal(t, expected, result)
},
},
{
name: "duration days",
input: "365d",
wantErr: false,
checkFunc: func(t *testing.T, result time.Time) {
expected := now.Add(365 * 24 * time.Hour)
diff := result.Sub(expected)
assert.Less(t, diff.Abs(), 2*time.Second, "result should be ~365 days from now")
},
},
{
name: "duration hours",
input: "24h",
wantErr: false,
checkFunc: func(t *testing.T, result time.Time) {
expected := now.Add(24 * time.Hour)
diff := result.Sub(expected)
assert.Less(t, diff.Abs(), 2*time.Second, "result should be ~24 hours from now")
},
},
{
name: "duration minutes",
input: "30m",
wantErr: false,
checkFunc: func(t *testing.T, result time.Time) {
expected := now.Add(30 * time.Minute)
diff := result.Sub(expected)
assert.Less(t, diff.Abs(), 2*time.Second, "result should be ~30 minutes from now")
},
},
{
name: "invalid input",
input: "not-a-date",
wantErr: true,
},
{
name: "empty input",
input: "",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := parseRetainUntilDate(tt.input)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
if tt.checkFunc != nil {
tt.checkFunc(t, result)
}
})
}
}
+2 -2
View File
@@ -163,7 +163,7 @@ func (f *Fs) refreshJWTToken(ctx context.Context) (string, error) {
if err != nil {
return "", fmt.Errorf("invalid token received from server")
}
var claims map[string]interface{}
var claims map[string]any
if err := json.Unmarshal(payload, &claims); err != nil {
return "", err
}
@@ -182,7 +182,7 @@ func (f *Fs) refreshJWTToken(ctx context.Context) (string, error) {
return f.token, nil
}
func (f *Fs) callAPI(ctx context.Context, method, path string, response interface{}) (*http.Response, error) {
func (f *Fs) callAPI(ctx context.Context, method, path string, response any) (*http.Response, error) {
token, err := f.refreshJWTToken(ctx)
if err != nil {
return nil, err
+2 -3
View File
@@ -7,6 +7,7 @@ import (
"context"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"path"
@@ -203,9 +204,7 @@ func (s *shadeChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, read
var uploadRes *http.Response
if len(partURL.Headers) > 0 {
opts.ExtraHeaders = make(map[string]string)
for k, v := range partURL.Headers {
opts.ExtraHeaders[k] = v
}
maps.Copy(opts.ExtraHeaders, partURL.Headers)
}
err = s.f.pacer.Call(func() (bool, error) {
+2 -2
View File
@@ -27,8 +27,8 @@ type Item struct {
FileCount int32 `json:"FileCount,omitempty"`
Name string `json:"Name,omitempty"`
FileName string `json:"FileName,omitempty"`
CreatedAt time.Time `json:"CreationDate,omitempty"`
ModifiedAt time.Time `json:"ClientModifiedDate,omitempty"`
CreatedAt time.Time `json:"CreationDate"`
ModifiedAt time.Time `json:"ClientModifiedDate"`
IsHidden bool `json:"IsHidden,omitempty"`
Size int64 `json:"FileSizeBytes,omitempty"`
Type string `json:"odata.type,omitempty"`
+3 -3
View File
@@ -348,7 +348,7 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string, depth string)
ExtraHeaders: map[string]string{
"Depth": depth,
},
NoRedirect: true,
CheckRedirect: rest.PreserveMethodRedirectFn,
}
if f.hasOCMD5 || f.hasOCSHA1 {
opts.Body = bytes.NewBuffer(owncloudProps)
@@ -423,7 +423,7 @@ func (f *Fs) filePath(file string) string {
if f.opt.Enc != encoder.EncodeZero {
subPath = f.opt.Enc.FromStandardPath(subPath)
}
return rest.URLPathEscape(subPath)
return rest.URLPathEscapeAll(subPath)
}
// dirPath returns a directory path (f.root, dir)
@@ -610,7 +610,7 @@ func (f *Fs) findHeader(headers fs.CommaSepList, find string) bool {
// fetch the bearer token and set it if successful
func (f *Fs) fetchAndSetBearerToken() error {
_, err, _ := f.authSingleflight.Do("bearerToken", func() (interface{}, error) {
_, err, _ := f.authSingleflight.Do("bearerToken", func() (any, error) {
if len(f.opt.BearerTokenCommand) == 0 {
return nil, nil
}
+32
View File
@@ -80,3 +80,35 @@ func TestHeaders(t *testing.T) {
_, err := f.Features().About(context.Background())
require.NoError(t, err)
}
// TestReservedCharactersInPathAreEscaped verifies that reserved characters
// like semicolons and equals signs in file paths are percent-encoded in
// HTTP requests to the WebDAV server (RFC 3986 compliance).
func TestReservedCharactersInPathAreEscaped(t *testing.T) {
var capturedPath string
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
capturedPath = r.RequestURI
// Return a 404 so the NewObject call fails cleanly
w.WriteHeader(http.StatusNotFound)
})
ts := httptest.NewServer(handler)
defer ts.Close()
configfile.Install()
m := configmap.Simple{
"type": "webdav",
"url": ts.URL,
}
f, err := webdav.NewFs(context.Background(), remoteName, "", m)
require.NoError(t, err)
// Try to access a file with a semicolon in the name.
// We expect the request to fail (404), but the path should be escaped.
_, _ = f.NewObject(context.Background(), "my;test")
// The semicolon must be percent-encoded as %3B
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")
}
+1 -1
View File
@@ -256,7 +256,7 @@ type WriteMultiMetadataRequest struct {
// WriteMetadata is used to write item metadata
type WriteMetadata struct {
Attributes WriteAttributes `json:"attributes,omitempty"`
Attributes WriteAttributes `json:"attributes"`
ID string `json:"id,omitempty"`
Type string `json:"type"`
}
+10
View File
@@ -147,6 +147,16 @@ func ArchiveExtract(ctx context.Context, dst fs.Fs, dstDir string, src fs.Fs, sr
// extract files
err = ex.Extract(ctx, in, func(ctx context.Context, f archives.FileInfo) error {
remote := f.NameInArchive
// Strip leading "./" from archive paths. Tar files created with
// relative paths (e.g. "tar -czf archive.tar.gz .") use "./" prefixed
// entries. Without stripping, rclone encodes the "." as a full-width
// dot character creating a spurious directory. We only strip "./"
// specifically to avoid enabling path traversal attacks via "../".
remote = strings.TrimPrefix(remote, "./")
// If the entry was exactly "./" (the root dir), skip it
if remote == "" && f.IsDir() {
return nil
}
if dstDir != "" {
remote = path.Join(dstDir, remote)
}
+62
View File
@@ -0,0 +1,62 @@
//go:build !plan9
package extract
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStripDotSlashPrefix(t *testing.T) {
tests := []struct {
name string
input string
expected string
}{
{
name: "strip leading dot-slash from file",
input: "./file.txt",
expected: "file.txt",
},
{
name: "strip leading dot-slash from nested path",
input: "./subdir/file.txt",
expected: "subdir/file.txt",
},
{
name: "no prefix unchanged",
input: "file.txt",
expected: "file.txt",
},
{
name: "nested path unchanged",
input: "dir/file.txt",
expected: "dir/file.txt",
},
{
name: "dot-dot-slash NOT stripped (path traversal safety)",
input: "../etc/passwd",
expected: "../etc/passwd",
},
{
name: "dot-slash directory entry becomes empty",
input: "./",
expected: "",
},
{
name: "only single leading dot-slash stripped",
input: "././file.txt",
expected: "./file.txt",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
// This mirrors the stripping logic in ArchiveExtract
got := strings.TrimPrefix(tc.input, "./")
assert.Equal(t, tc.expected, got)
})
}
}
+2 -2
View File
@@ -92,10 +92,10 @@ func TestCountWriterConcurrent(t *testing.T) {
var wg sync.WaitGroup
wg.Add(goroutines)
for g := 0; g < goroutines; g++ {
for range goroutines {
go func() {
defer wg.Done()
for i := 0; i < loops; i++ {
for range loops {
n, err := cw.Write(data)
assert.NoError(t, err)
assert.Equal(t, chunkSize, n)
+5 -4
View File
@@ -127,14 +127,14 @@ func init() {
// and the Command line syntax section of docs/content/bisync.md (it doesn't update automatically)
flags.BoolVarP(cmdFlags, &Opt.Resync, "resync", "1", Opt.Resync, "Performs the resync run. Equivalent to --resync-mode path1. Consider using --verbose or --dry-run first.", "")
flags.FVarP(cmdFlags, &Opt.ResyncMode, "resync-mode", "", "During resync, prefer the version that is: path1, path2, newer, older, larger, smaller (default: path1 if --resync, otherwise none for no resync.)", "")
flags.BoolVarP(cmdFlags, &Opt.CheckAccess, "check-access", "", Opt.CheckAccess, makeHelp("Ensure expected {CHECKFILE} files are found on both Path1 and Path2 filesystems, else abort."), "")
flags.StringVarP(cmdFlags, &Opt.CheckFilename, "check-filename", "", Opt.CheckFilename, makeHelp("Filename for --check-access (default: {CHECKFILE})"), "")
flags.BoolVarP(cmdFlags, &Opt.CheckAccess, "check-access", "", Opt.CheckAccess, MakeHelp("Ensure expected {CHECKFILE} files are found on both Path1 and Path2 filesystems, else abort."), "")
flags.StringVarP(cmdFlags, &Opt.CheckFilename, "check-filename", "", Opt.CheckFilename, MakeHelp("Filename for --check-access (default: {CHECKFILE})"), "")
flags.BoolVarP(cmdFlags, &Opt.Force, "force", "", Opt.Force, "Bypass --max-delete safety check and run the sync. Consider using with --verbose", "")
flags.FVarP(cmdFlags, &Opt.CheckSync, "check-sync", "", "Controls comparison of final listings: true|false|only (default: true)", "")
flags.BoolVarP(cmdFlags, &Opt.CreateEmptySrcDirs, "create-empty-src-dirs", "", Opt.CreateEmptySrcDirs, "Sync creation and deletion of empty directories. (Not compatible with --remove-empty-dirs)", "")
flags.BoolVarP(cmdFlags, &Opt.RemoveEmptyDirs, "remove-empty-dirs", "", Opt.RemoveEmptyDirs, "Remove ALL empty directories at the final cleanup step.", "")
flags.StringVarP(cmdFlags, &Opt.FiltersFile, "filters-file", "", Opt.FiltersFile, "Read filtering patterns from a file", "")
flags.StringVarP(cmdFlags, &Opt.Workdir, "workdir", "", Opt.Workdir, makeHelp("Use custom working dir - useful for testing. (default: {WORKDIR})"), "")
flags.StringVarP(cmdFlags, &Opt.Workdir, "workdir", "", Opt.Workdir, MakeHelp("Use custom working dir - useful for testing. (default: {WORKDIR})"), "")
flags.StringVarP(cmdFlags, &Opt.BackupDir1, "backup-dir1", "", Opt.BackupDir1, "--backup-dir for Path1. Must be a non-overlapping path on the same remote.", "")
flags.StringVarP(cmdFlags, &Opt.BackupDir2, "backup-dir2", "", Opt.BackupDir2, "--backup-dir for Path2. Must be a non-overlapping path on the same remote.", "")
flags.StringVarP(cmdFlags, &Opt.DebugName, "debugname", "", Opt.DebugName, "Debug by tracking one file at various points throughout a bisync run (when -v or -vv)", "")
@@ -153,6 +153,7 @@ func init() {
flags.StringVarP(cmdFlags, &Opt.ConflictSuffixFlag, "conflict-suffix", "", Opt.ConflictSuffixFlag, "Suffix to use when renaming a --conflict-loser. Can be either one string or two comma-separated strings to assign different suffixes to Path1/Path2. (default: 'conflict')", "")
_ = cmdFlags.MarkHidden("debugname")
_ = cmdFlags.MarkHidden("localtime")
addRC()
}
// bisync command definition
@@ -162,7 +163,7 @@ var commandDefinition = &cobra.Command{
Long: longHelp,
Annotations: map[string]string{
"versionIntroduced": "v1.58",
"groups": "Filter,Copy,Important",
"groups": "Filter,Copy,Important,Sync",
},
RunE: func(command *cobra.Command, args []string) error {
// NOTE: avoid putting too much handling here, as it won't apply to the rc.
+65 -53
View File
@@ -1,65 +1,77 @@
package bisync
//go:build none
// Create the help text for the rc
//
// Run with go generate ./cmd/bisync (defined in rc.go)
package main
import (
"strconv"
"fmt"
"os"
"strings"
"github.com/muesli/reflow/wordwrap"
"github.com/rclone/rclone/cmd"
"github.com/rclone/rclone/cmd/bisync"
"github.com/rclone/rclone/fs"
"github.com/spf13/pflag"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func makeHelp(help string) string {
replacer := strings.NewReplacer(
"|", "`",
"{MAXDELETE}", strconv.Itoa(DefaultMaxDelete),
"{CHECKFILE}", DefaultCheckFilename,
// "{WORKDIR}", DefaultWorkdir,
)
return replacer.Replace(help)
// Output the help to stdout
func main() {
out := os.Stdout
if len(os.Args) > 1 {
var err error
out, err = os.Create(os.Args[1])
if err != nil {
fs.Fatalf(nil, "Open output failed: %v", err)
}
defer out.Close()
}
fmt.Fprintf(out, "<!--- Docs generated by help.go - use go generate to rebuild - DO NOT EDIT --->\n\n")
fmt.Fprint(out, RcHelp())
}
var shortHelp = `Perform bidirectional synchronization between two paths.`
var rcHelp = makeHelp(`This takes the following parameters
- path1 - a remote directory string e.g. |drive:path1|
- path2 - a remote directory string e.g. |drive:path2|
- dryRun - dry-run mode
- resync - performs the resync run
- checkAccess - abort if {CHECKFILE} files are not found on both filesystems
- checkFilename - file name for checkAccess (default: {CHECKFILE})
- maxDelete - abort sync if percentage of deleted files is above
this threshold (default: {MAXDELETE})
- force - Bypass maxDelete safety check and run the sync
- checkSync - |true| by default, |false| disables comparison of final listings,
|only| will skip sync, only compare listings from the last run
- createEmptySrcDirs - Sync creation and deletion of empty directories.
(Not compatible with --remove-empty-dirs)
- removeEmptyDirs - remove empty directories at the final cleanup step
- filtersFile - read filtering patterns from a file
- ignoreListingChecksum - Do not use checksums for listings
- resilient - Allow future runs to retry after certain less-serious errors, instead of requiring resync.
- workdir - server directory for history files (default: |~/.cache/rclone/bisync|)
- backupdir1 - --backup-dir for Path1. Must be a non-overlapping path on the same remote.
- backupdir2 - --backup-dir for Path2. Must be a non-overlapping path on the same remote.
- noCleanup - retain working files
// RcHelp returns the rc help
func RcHelp() string {
return wordwrap.String(bisync.MakeHelp(`This takes the following parameters:
- path1 (required) - (string) a remote directory string e.g. ||drive:path1||
- path2 (required) - (string) a remote directory string e.g. ||drive:path2||
- dryRun - (bool) dry-run mode
`+GenerateParams()+`
See [bisync command help](https://rclone.org/commands/rclone_bisync/)
and [full bisync description](https://rclone.org/bisync/)
for more information.`)
for more information.
`), 76)
}
var longHelp = shortHelp + makeHelp(`
// example: "create-empty-src-dirs" -> "createEmptySrcDirs"
func toCamel(s string) string {
split := strings.Split(s, "-")
builder := strings.Builder{}
for i, word := range split {
if i == 0 { // first word always all lowercase
builder.WriteString(strings.ToLower(word))
continue
}
builder.WriteString(cases.Title(language.AmericanEnglish).String(word))
}
return builder.String()
}
[Bisync](https://rclone.org/bisync/) provides a
bidirectional cloud sync solution in rclone.
It retains the Path1 and Path2 filesystem listings from the prior run.
On each successive run it will:
- list files on Path1 and Path2, and check for changes on each side.
Changes include |New|, |Newer|, |Older|, and |Deleted| files.
- Propagate changes on Path1 to Path2, and vice-versa.
Bisync is considered an **advanced command**, so use with care.
Make sure you have read and understood the entire [manual](https://rclone.org/bisync)
(especially the [Limitations](https://rclone.org/bisync/#limitations) section)
before using, or data loss can result. Questions can be asked in the
[Rclone Forum](https://forum.rclone.org/).
See [full bisync description](https://rclone.org/bisync/) for details.`)
// GenerateParams automatically generates the param list from commandDefinition.Flags
func GenerateParams() string {
builder := strings.Builder{}
fn := func(flag *pflag.Flag) {
if flag.Hidden {
return
}
builder.WriteString(fmt.Sprintf("- %s - (%s) %s \n", toCamel(flag.Name), flag.Value.Type(), flag.Usage))
}
commandDefinition, _, _ := cmd.Root.Find([]string{"bisync"})
commandDefinition.Flags().VisitAll(fn)
return builder.String()
}
+2 -4
View File
@@ -128,9 +128,7 @@ func (b *bisyncRun) startLockRenewal() func() {
}
stopLockRenewal := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
ticker := time.NewTicker(time.Duration(b.opt.MaxLock) - time.Minute)
for {
select {
@@ -141,7 +139,7 @@ func (b *bisyncRun) startLockRenewal() func() {
return
}
}
}()
})
return func() {
close(stopLockRenewal)
wg.Wait()
+124 -25
View File
@@ -1,16 +1,22 @@
//go:generate go run help.go rc.md
package bisync
import (
"context"
_ "embed"
"errors"
"log"
"path/filepath"
"strconv"
"strings"
"github.com/rclone/rclone/cmd/bisync/bilib"
"github.com/rclone/rclone/fs"
fslog "github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/rc"
)
func init() {
func addRC() {
rc.Add(rc.Call{
Path: "sync/bisync",
AuthRequired: true,
@@ -20,6 +26,42 @@ func init() {
})
}
//go:embed rc.md
var rcHelp string
var shortHelp = `Perform bidirectional synchronization between two paths.`
var longHelp = shortHelp + MakeHelp(`
[Bisync](https://rclone.org/bisync/) provides a
bidirectional cloud sync solution in rclone.
It retains the Path1 and Path2 filesystem listings from the prior run.
On each successive run it will:
- list files on Path1 and Path2, and check for changes on each side.
Changes include ||New||, ||Newer||, ||Older||, and ||Deleted|| files.
- Propagate changes on Path1 to Path2, and vice-versa.
Bisync is considered an **advanced command**, so use with care.
Make sure you have read and understood the entire [manual](https://rclone.org/bisync)
(especially the [Limitations](https://rclone.org/bisync/#limitations) section)
before using, or data loss can result. Questions can be asked in the
[Rclone Forum](https://forum.rclone.org/).
See [full bisync description](https://rclone.org/bisync/) for details.
`)
// MakeHelp replaces some dynamic variables for the help docs
func MakeHelp(help string) string {
replacer := strings.NewReplacer(
"||", "`",
"{MAXDELETE}", strconv.Itoa(DefaultMaxDelete),
"{CHECKFILE}", DefaultCheckFilename,
"{WORKDIR}", DefaultWorkdir,
)
return replacer.Replace(help)
}
func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
opt := &Options{}
octx, ci := fs.AddConfig(ctx)
@@ -41,56 +83,86 @@ func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
}
if opt.Resync, err = in.GetBool("resync"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("resync", "optional parameter is missing. using default value: %v", opt.Resync)
}
if opt.CheckAccess, err = in.GetBool("checkAccess"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("checkAccess", "optional parameter is missing. using default value: %v", opt.CheckAccess)
}
if opt.Force, err = in.GetBool("force"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("force", "optional parameter is missing. using default value: %v", opt.Force)
}
if opt.CreateEmptySrcDirs, err = in.GetBool("createEmptySrcDirs"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("createEmptySrcDirs", "optional parameter is missing. using default value: %v", opt.CreateEmptySrcDirs)
}
if opt.RemoveEmptyDirs, err = in.GetBool("removeEmptyDirs"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("removeEmptyDirs", "optional parameter is missing. using default value: %v", opt.RemoveEmptyDirs)
}
if opt.NoCleanup, err = in.GetBool("noCleanup"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("noCleanup", "optional parameter is missing. using default value: %v", opt.NoCleanup)
}
if opt.IgnoreListingChecksum, err = in.GetBool("ignoreListingChecksum"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("ignoreListingChecksum", "optional parameter is missing. using default value: %v", opt.IgnoreListingChecksum)
}
if opt.Resilient, err = in.GetBool("resilient"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("resilient", "optional parameter is missing. using default value: %v", opt.Resilient)
}
if opt.CheckFilename, err = in.GetString("checkFilename"); rc.NotErrParamNotFound(err) {
return
opt.CheckFilename = DefaultCheckFilename
fs.Debugf("checkFilename", "optional parameter is missing. using default value: %v", opt.CheckFilename)
}
if opt.FiltersFile, err = in.GetString("filtersFile"); rc.NotErrParamNotFound(err) {
return
fs.Debugf("filtersFile", "optional parameter is missing. using default value: %v", opt.FiltersFile)
}
if opt.Workdir, err = in.GetString("workdir"); rc.NotErrParamNotFound(err) {
return
// "" sets correct default later
fs.Debugf("workdir", "optional parameter is missing. using default value: %v", opt.Workdir)
}
if opt.BackupDir1, err = in.GetString("backupdir1"); rc.NotErrParamNotFound(err) {
return
if opt.BackupDir1, err = in.GetString("backupDir1"); rc.NotErrParamNotFound(err) {
// we accept an alternate capitalization here for backward compatibility.
if opt.BackupDir1, err = in.GetString("backupdir1"); rc.NotErrParamNotFound(err) {
fs.Debugf("backupDir1", "optional parameter is missing. using default value: %v", opt.BackupDir1)
}
}
if opt.BackupDir2, err = in.GetString("backupdir2"); rc.NotErrParamNotFound(err) {
return
if opt.BackupDir2, err = in.GetString("backupDir2"); rc.NotErrParamNotFound(err) {
// we accept an alternate capitalization here for backward compatibility.
if opt.BackupDir2, err = in.GetString("backupdir2"); rc.NotErrParamNotFound(err) {
fs.Debugf("backupDir2", "optional parameter is missing. using default value: %v", opt.BackupDir2)
}
}
checkSync, err := in.GetString("checkSync")
if rc.NotErrParamNotFound(err) {
if err = setEnum(in, "checkSync", "true", opt.CheckSync.Set); err != nil {
return nil, err
}
if checkSync == "" {
checkSync = "true"
}
if err := opt.CheckSync.Set(checkSync); err != nil {
if err = setEnum(in, "resyncMode", opt.ResyncMode.String(), opt.ResyncMode.Set); err != nil {
return nil, err
}
if err = setEnum(in, "conflictResolve", opt.ConflictResolve.String(), opt.ConflictResolve.Set); err != nil {
return nil, err
}
if err = setEnum(in, "conflictLoser", opt.ConflictLoser.String(), opt.ConflictLoser.Set); err != nil {
return nil, err
}
if opt.ConflictSuffixFlag, err = in.GetString("conflictSuffix"); rc.NotErrParamNotFound(err) {
fs.Debugf("conflictSuffix", "optional parameter is missing. using default value: %v", opt.ConflictSuffixFlag)
}
if opt.Recover, err = in.GetBool("recover"); rc.NotErrParamNotFound(err) {
fs.Debugf("recover", "optional parameter is missing. using default value: %v", opt.Recover)
}
if opt.CompareFlag, err = in.GetString("compare"); rc.NotErrParamNotFound(err) {
fs.Debugf("compare", "optional parameter is missing. using default value: %v", opt.CompareFlag)
}
if opt.Compare.NoSlowHash, err = in.GetBool("noSlowHash"); rc.NotErrParamNotFound(err) {
fs.Debugf("noSlowHash", "optional parameter is missing. using default value: %v", opt.Compare.NoSlowHash)
}
if opt.Compare.SlowHashSyncOnly, err = in.GetBool("slowHashSyncOnly"); rc.NotErrParamNotFound(err) {
fs.Debugf("slowHashSyncOnly", "optional parameter is missing. using default value: %v", opt.Compare.SlowHashSyncOnly)
}
if opt.Compare.DownloadHash, err = in.GetBool("downloadHash"); rc.NotErrParamNotFound(err) {
fs.Debugf("downloadHash", "optional parameter is missing. using default value: %v", opt.Compare.DownloadHash)
}
if opt.MaxLock, err = in.GetFsDuration("maxLock"); rc.NotErrParamNotFound(err) {
opt.MaxLock = 0
fs.Debugf("maxLock", "optional parameter is missing. using default value: %v", opt.MaxLock)
}
fs1, err := rc.GetFsNamed(octx, in, "path1")
if err != nil {
@@ -105,6 +177,33 @@ func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
output := bilib.CaptureOutput(func() {
err = Bisync(octx, fs1, fs2, opt)
})
workDir, _ := filepath.Abs(DefaultWorkdir)
if opt.Workdir != "" {
workDir, _ = filepath.Abs(opt.Workdir)
}
basePath := bilib.BasePath(ctx, workDir, fs1, fs2)
_, _ = log.Writer().Write(output)
return rc.Params{"output": string(output)}, err
return rc.Params{
"output": string(output),
"session": bilib.SessionName(fs1, fs2),
"workDir": workDir,
"basePath": basePath,
"listing1": basePath + ".path1.lst",
"listing2": basePath + ".path2.lst",
"logFile": fslog.Opt.File,
}, err
}
func setEnum(in rc.Params, name string, defaultVal string, set func(s string) error) error {
v, err := in.GetString(name)
if rc.NotErrParamNotFound(err) || v == "" {
v = defaultVal
fs.Debugf(name, "optional parameter is missing. using default value: %v", v)
}
if err := set(v); err != nil {
return err
}
return nil
}
+61
View File
@@ -0,0 +1,61 @@
<!--- Docs generated by help.go - use go generate to rebuild - DO NOT EDIT --->
This takes the following parameters:
- path1 (required) - (string) a remote directory string e.g. `drive:path1`
- path2 (required) - (string) a remote directory string e.g. `drive:path2`
- dryRun - (bool) dry-run mode
- backupDir1 - (string) --backup-dir for Path1. Must be a non-overlapping path on
the same remote.
- backupDir2 - (string) --backup-dir for Path2. Must be a non-overlapping path on
the same remote.
- checkAccess - (bool) Ensure expected RCLONE_TEST files are found on both
Path1 and Path2 filesystems, else abort.
- checkFilename - (string) Filename for --check-access (default: RCLONE_TEST)
- checkSync - (string) Controls comparison of final listings: true|false|only
(default: true)
- compare - (string) Comma-separated list of bisync-specific compare options ex.
'size,modtime,checksum' (default: 'size,modtime')
- conflictLoser - (ConflictLoserAction) Action to take on the loser of a sync
conflict (when there is a winner) or on both files (when there is no
winner): , num, pathname, delete (default: num)
- conflictResolve - (string) Automatically resolve conflicts by preferring the
version that is: none, path1, path2, newer, older, larger, smaller (default:
none)
- conflictSuffix - (string) Suffix to use when renaming a --conflict-loser. Can
be either one string or two comma-separated strings to assign different
suffixes to Path1/Path2. (default: 'conflict')
- createEmptySrcDirs - (bool) Sync creation and deletion of empty directories.
(Not compatible with --remove-empty-dirs)
- downloadHash - (bool) Compute hash by downloading when otherwise
unavailable. (warning: may be slow and use lots of data!)
- filtersFile - (string) Read filtering patterns from a file
- force - (bool) Bypass --max-delete safety check and run the sync. Consider
using with --verbose
- ignoreListingChecksum - (bool) Do not use checksums for listings (add --ignore-
checksum to additionally skip post-copy checksum checks)
- maxLock - (Duration) Consider lock files older than this to be expired
(default: 0 (never expire)) (minimum: 2m)
- noCleanup - (bool) Retain working files (useful for troubleshooting and
testing).
- noSlowHash - (bool) Ignore listing checksums only on backends where they are
slow
- recover - (bool) Automatically recover from interruptions without requiring --
resync.
- removeEmptyDirs - (bool) Remove ALL empty directories at the final cleanup
step.
- resilient - (bool) Allow future runs to retry after certain less-serious
errors, instead of requiring --resync.
- resync - (bool) Performs the resync run. Equivalent to --resync-mode path1.
Consider using --verbose or --dry-run first.
- resyncMode - (string) During resync, prefer the version that is: path1,
path2, newer, older, larger, smaller (default: path1 if --resync, otherwise
none for no resync.)
- slowHashSyncOnly - (bool) Ignore slow checksums for listings and deltas, but
still consider them during sync calls.
- workdir - (string) Use custom working dir - useful for testing. (default:
~/.cache/rclone/bisync)
See [bisync command help](https://rclone.org/commands/rclone_bisync/)
and [full bisync description](https://rclone.org/bisync/)
for more information.
+2 -4
View File
@@ -361,9 +361,7 @@ func StartStats() func() {
}
stopStats := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
ticker := time.NewTicker(*statsInterval)
for {
select {
@@ -374,7 +372,7 @@ func StartStats() func() {
return
}
}
}()
})
return func() {
close(stopStats)
wg.Wait()
+1 -1
View File
@@ -108,7 +108,7 @@ func mountOptions(VFS *vfs.VFS, device string, mountpoint string, opt *mountlib.
func waitFor(fn func() bool) (ok bool) {
const totalWait = 10 * time.Second
const individualWait = 10 * time.Millisecond
for i := 0; i < int(totalWait/individualWait); i++ {
for range int(totalWait / individualWait) {
ok = fn()
if ok {
return ok
+9
View File
@@ -70,6 +70,15 @@ Note that |--stdout| and |--print-filename| are incompatible with |--urls|.
This will do |--transfers| copies in parallel. Note that if |--auto-filename|
is desired for all URLs then a file with only URLs and no filename can be used.
Each FILENAME in the CSV file can start with a relative path which will be appended
to the destination path provided at the command line. For example, running the command
shown above with the following CSV file will write two files to the destination:
|remote:dir/local/path/bar.json| and |remote:dir/another/local/directory/qux.json|
|||csv
https://example.org/foo/bar.json,local/path/bar.json
https://example.org/qux/baz.json,another/local/directory/qux.json
|||
### Troubleshooting
If you can't get |rclone copyurl| to work then here are some things you can try:
+1 -1
View File
@@ -324,7 +324,7 @@ full new copy of the file.
When mounting with `--read-only`, attempts to write to files will fail *silently*
as opposed to with a clear warning as in macFUSE.
## Mounting on Linux
### Mounting on Linux
On newer versions of Ubuntu, you may encounter the following error when running
`rclone mount`:
+2 -4
View File
@@ -41,9 +41,7 @@ func startProgress() func() {
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
progressInterval := defaultProgressInterval
if ShowStats() && *statsInterval > 0 {
progressInterval = *statsInterval
@@ -65,7 +63,7 @@ func startProgress() func() {
return
}
}
}()
})
return func() {
close(stopStats)
wg.Wait()
Binary file not shown.

After

Width:  |  Height:  |  Size: 704 B

+27
View File
@@ -3,6 +3,7 @@ package http
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
@@ -57,6 +58,9 @@ var DefaultOpt = Options{
// Opt is options set by command line flags
var Opt = DefaultOpt
//go:embed favicon.png
var faviconData []byte
func init() {
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "http", Opt: &Opt, Options: OptionsInfo})
}
@@ -198,9 +202,11 @@ func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Opt
router := s.server.Router()
router.Use(
middleware.Compress(5),
middleware.SetHeader("Accept-Ranges", "bytes"),
middleware.SetHeader("Server", "rclone/"+fs.Version),
)
router.Get("/favicon.ico", s.serveFavicon)
router.Get("/*", s.handler)
router.Head("/*", s.handler)
@@ -225,6 +231,27 @@ func (s *HTTP) Shutdown() error {
return s.server.Shutdown()
}
// serveFavicon serves the remote's favicon.ico if it exists, otherwise
// the rclone favicon
func (s *HTTP) serveFavicon(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
VFS, err := s.getVFS(ctx)
if err == nil {
node, err := VFS.Stat("favicon.ico")
if err == nil && node.IsFile() {
// Remote has favicon.ico, serve it as a regular file
s.serveFile(w, r, "favicon.ico")
return
}
}
// Serve the embedded rclone favicon
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "max-age=86400")
if _, err := w.Write(faviconData); err != nil {
fs.Debugf(nil, "Failed to write favicon: %v", err)
}
}
// handler reads incoming requests and dispatches them
func (s *HTTP) handler(w http.ResponseWriter, r *http.Request) {
isDir := strings.HasSuffix(r.URL.Path, "/")
+111
View File
@@ -1,6 +1,7 @@
package http
import (
"compress/gzip"
"context"
"flag"
"io"
@@ -297,6 +298,116 @@ func TestAuthProxy(t *testing.T) {
testGET(t, true)
}
func TestFavicon(t *testing.T) {
ctx := context.Background()
doGet := func(testURL, path string) *http.Response {
req, err := http.NewRequest("GET", testURL+path, nil)
require.NoError(t, err)
req.SetBasicAuth(testUser, testPass)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
return resp
}
t.Run("fallback", func(t *testing.T) {
// testdata/files has no favicon.ico, so the embedded fallback is served
f, err := fs.NewFs(ctx, "testdata/files")
require.NoError(t, err)
s, testURL := start(ctx, t, f)
defer func() { assert.NoError(t, s.server.Shutdown()) }()
resp := doGet(testURL, "favicon.ico")
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "image/png", resp.Header.Get("Content-Type"))
assert.Equal(t, "max-age=86400", resp.Header.Get("Cache-Control"))
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, faviconData, body)
})
t.Run("remote override", func(t *testing.T) {
// Start a server on a temp dir that already contains a custom favicon.ico,
// so the VFS sees it at init time and serves it instead of the fallback.
dir := t.TempDir()
customFavicon := []byte("custom favicon data")
require.NoError(t, os.WriteFile(filepath.Join(dir, "favicon.ico"), customFavicon, 0666))
f, err := fs.NewFs(ctx, dir)
require.NoError(t, err)
s, testURL := start(ctx, t, f)
defer func() { assert.NoError(t, s.server.Shutdown()) }()
resp := doGet(testURL, "favicon.ico")
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, customFavicon, body)
})
}
func TestCompressedDirectoryListing(t *testing.T) {
ctx := context.Background()
require.NoError(t, setAllModTimes("testdata/files", expectedTime))
f, err := fs.NewFs(ctx, "testdata/files")
require.NoError(t, err)
s, testURL := start(ctx, t, f)
defer func() { assert.NoError(t, s.server.Shutdown()) }()
req, err := http.NewRequest("GET", testURL, nil)
require.NoError(t, err)
req.SetBasicAuth(testUser, testPass)
req.Header.Set("Accept-Encoding", "gzip")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
gr, err := gzip.NewReader(resp.Body)
require.NoError(t, err)
defer func() { _ = gr.Close() }()
body, err := io.ReadAll(gr)
require.NoError(t, err)
assert.Contains(t, string(body), "Directory listing of /")
}
func TestCompressedTextFile(t *testing.T) {
ctx := context.Background()
require.NoError(t, setAllModTimes("testdata/files", expectedTime))
f, err := fs.NewFs(ctx, "testdata/files")
require.NoError(t, err)
s, testURL := start(ctx, t, f)
defer func() { assert.NoError(t, s.server.Shutdown()) }()
req, err := http.NewRequest("GET", testURL+"two.txt", nil)
require.NoError(t, err)
req.SetBasicAuth(testUser, testPass)
req.Header.Set("Accept-Encoding", "gzip")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
gr, err := gzip.NewReader(resp.Body)
require.NoError(t, err)
defer func() { _ = gr.Close() }()
body, err := io.ReadAll(gr)
require.NoError(t, err)
assert.Equal(t, "0123456789\n", string(body))
}
func TestRc(t *testing.T) {
servetest.TestRc(t, rc.Params{
"type": "http",
+4 -8
View File
@@ -66,11 +66,9 @@ func testCacheCRUD(t *testing.T, h *Handler, c Cache, fileName string) {
func testCacheThrashDifferent(t *testing.T, h *Handler, c Cache) {
var wg sync.WaitGroup
for i := range 100 {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
testCacheCRUD(t, h, c, fmt.Sprintf("file-%d", i))
}()
})
}
wg.Wait()
}
@@ -79,9 +77,7 @@ func testCacheThrashDifferent(t *testing.T, h *Handler, c Cache) {
func testCacheThrashSame(t *testing.T, h *Handler, c Cache) {
var wg sync.WaitGroup
for range 100 {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
// Write a handle
splitPath := []string{"file"}
@@ -108,7 +104,7 @@ func testCacheThrashSame(t *testing.T, h *Handler, c Cache) {
require.Error(t, err)
assert.Equal(t, errStaleHandle, err)
}
}()
})
}
wg.Wait()
}
+9 -4
View File
@@ -61,7 +61,11 @@ time instead of the current time. Times may be specified as one of:
- 'YYYY-MM-DDTHH:MM:SS.SSS' - e.g. 2006-01-02T15:04:05.123456789
Note that value of ` + "`--timestamp`" + ` is in UTC. If you want local time
then add the ` + "`--localtime`" + ` flag.`,
then add the ` + "`--localtime`" + ` flag.
Metadata can be added when creating a new file with ` + "`--metadata-set`" + `.
For example:
rclone touch remote:path -M --metadata-set key=value`,
Annotations: map[string]string{
"versionIntroduced": "v1.39",
"groups": "Filter,Listing,Important",
@@ -123,10 +127,10 @@ func timeOfTouch() (time.Time, error) {
}
// createEmptyObject creates an empty object (file) with specified timestamp
func createEmptyObject(ctx context.Context, remote string, modTime time.Time, f fs.Fs) error {
func createEmptyObject(ctx context.Context, remote string, modTime time.Time, f fs.Fs, options []fs.OpenOption) error {
var buffer []byte
src := object.NewStaticObjectInfo(remote, modTime, int64(len(buffer)), true, nil, f)
_, err := f.Put(ctx, bytes.NewBuffer(buffer), src)
_, err := f.Put(ctx, bytes.NewBuffer(buffer), src, options...)
return err
}
@@ -163,7 +167,8 @@ func Touch(ctx context.Context, f fs.Fs, remote string) error {
return nil
}
fs.Debugf(f, "Touching (creating) %q", remote)
if err = createEmptyObject(ctx, remote, t, f); err != nil {
options := fs.MetadataAsOpenOptions(ctx)
if err = createEmptyObject(ctx, remote, t, f, options); err != nil {
return fmt.Errorf("failed to touch (create): %w", err)
}
}
+29
View File
@@ -150,3 +150,32 @@ func TestRecursiveTouchDirWithFiles(t *testing.T) {
require.NoError(t, err)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1, file2, file3}, []string{"a", "a/b", "a/b/c"}, fs.ModTimeNotSupported)
}
func TestTouchWithMetadata(t *testing.T) {
r := fstest.NewRun(t)
ctx := context.Background()
features := r.Fremote.Features()
if !features.UserMetadata {
t.Skip("Skipping metadata test; backend does not support user metadata")
}
ci := fs.GetConfig(ctx)
origMetadata := ci.Metadata
origMetadataSet := ci.MetadataSet
t.Cleanup(func() {
ci.Metadata = origMetadata
ci.MetadataSet = origMetadataSet
})
ci.Metadata = true
ci.MetadataSet = fs.Metadata{
"testkey": "testvalue",
}
err := Touch(ctx, r.Fremote, "metaFile")
require.NoError(t, err)
o, err := r.Fremote.NewObject(ctx, "metaFile")
require.NoError(t, err)
fstest.CheckEntryMetadata(ctx, t, r.Fremote, o, ci.MetadataSet)
}
+2 -1
View File
@@ -133,6 +133,7 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Dropbox" home="https://www.dropbox.com/" config="/dropbox/" >}}
{{< provider name="Enterprise File Fabric" home="https://storagemadeeasy.com/about/" config="/filefabric/" >}}
{{< provider name="Exaba" home="https://exaba.com/" config="/s3/#exaba" >}}
{{< provider name="Fastly Object Storage" home="https://www.fastly.com/products/storage" config="/s3/#fastly" >}}
{{< provider name="Fastmail Files" home="https://www.fastmail.com/" config="/webdav/#fastmail-files" >}}
{{< provider name="FileLu Cloud Storage" home="https://filelu.com/" config="/filelu/" >}}
{{< provider name="FileLu S5 (S3-Compatible Object Storage)" home="https://s5lu.com/" config="/s3/#filelu-s5" >}}
@@ -210,7 +211,6 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Sia" home="https://sia.tech/" config="/sia/" >}}
{{< provider name="SMB / CIFS" home="https://en.wikipedia.org/wiki/Server_Message_Block" config="/smb/" >}}
{{< provider name="Spectra Logic" home="https://spectralogic.com/blackpearl-nearline-object-gateway/" config="/s3/#spectralogic" >}}
{{< provider name="StackPath" home="https://www.stackpath.com/products/object-storage/" config="/s3/#stackpath" >}}
{{< provider name="Storj" home="https://storj.io/" config="/storj/" >}}
{{< provider name="Synology" home="https://c2.synology.com/en-global/object-storage/overview" config="/s3/#synology-c2" >}}
{{< provider name="SugarSync" home="https://sugarsync.com/" config="/sugarsync/" >}}
@@ -219,6 +219,7 @@ WebDAV or S3, that work out of the box.)
{{< provider name="Wasabi" home="https://wasabi.com/" config="/s3/#wasabi" >}}
{{< provider name="WebDAV" home="https://en.wikipedia.org/wiki/WebDAV" config="/webdav/" >}}
{{< provider name="Yandex Disk" home="https://disk.yandex.com/" config="/yandex/" >}}
{{< provider name="Zadara Object Storage" home="https://www.zadara.com" config="/s3/#zadara" >}}
{{< provider name="Zoho WorkDrive" home="https://www.zoho.com/workdrive/" config="/zoho/" >}}
{{< provider name="Zata" home="https://zata.ai/" config="/s3/#Zata" end="true" >}}
{{< provider name="The local filesystem" home="/local/" config="/local/" end="true">}}
+23 -1
View File
@@ -978,7 +978,7 @@ put them back in again. -->
- Nathanael Demacon <7271496+quantumsheep@users.noreply.github.com>
- ahxxm <ahxxm@users.noreply.github.com>
- Flora Thiebaut <johann.thiebaut@gmail.com>
- kingston125 <support@filelu.com>
- kingston125 <support@filelu.com> <kingston125@github.com>
- Ser-Bul <30335009+Ser-Bul@users.noreply.github.com>
- jinjingroad <jinjingroad@sina.com>
- necaran <55765083+necaran@users.noreply.github.com>
@@ -1073,3 +1073,25 @@ put them back in again. -->
- jzunigax2 <125698953+jzunigax2@users.noreply.github.com>
- lullius <lullius@users.noreply.github.com>
- StarHack <StarHack@users.noreply.github.com>
- Leon Brocard <acme@astray.com>
- Cohinem <143964778+Cohinem@users.noreply.github.com>
- Jack Kelly <jack@OpenClimateFix.org>
- Prakhar Chhalotre <chhalotreprakhar00@gmail.com>
- Varun Chawla <34209028+veeceey@users.noreply.github.com>
- Jan-Philipp Reßler <75355263+TabError@users.noreply.github.com>
- Shlomi Avihou <shlomi@zadarastorage.com>
- Chris <238498929+chris081519-crypto@users.noreply.github.com>
- Jan-Philipp Reßler <xodarap@xodarap.de>
- Dark Dragon <darkdragon-001@web.de>
- Leon Brocard <lbrocard@fastly.com>
- a1pcm <a1pcm@users.noreply.github.com>
- FTCHD <144691102+FTCHD@users.noreply.github.com>
- Bjoern Franke <bjo+git@schafweide.org>
- hxnd <callmehxnd@outlook.de>
- Adam Kasztenny <adamkasztenny@gmail.com>
- Romāns Potašovs <justgook@gmail.com>
- Brian Bockelman <bbockelman@morgridge.org>
- Bjoern Franke <bjo@schafweide.org>
- razorloves <razorloves@gmail.com>
- Duncan F <131309315+duncanaf@users.noreply.github.com>
- Billy Hughes <w.g.h.hughes@gmail.com>
+6
View File
@@ -1897,6 +1897,12 @@ about *Unison* and synchronization in general.
## Changelog
### `v1.74`
- Added several missing `rc` parameters.
- Optional `rc` parameters are now truly optional.
- `rc` output now provides more structured information.
### `v1.71`
- `bisync` is now officially released from beta.
+53 -1
View File
@@ -6,6 +6,58 @@ description: "Rclone Changelog"
# Changelog
## v1.73.2 - 2026-03-06
[See commits](https://github.com/rclone/rclone/compare/v1.73.1...v1.73.2)
- Bug Fixes
- build
- Update to go 1.25.8 to fix CVE-2026-27137 CVE-2026-27138 CVE-2026-25679 CVE-2026-27142 (Nick Craig-Wood)
- Update github.com/cloudflare/circl to v1.6.3 to fix CVE-2026-1229 (Nick Craig-Wood)
- Update to golang.org/x/net v0.51.0 to fix CVE-2026-27141 (Nick Craig-Wood)
- docs fixes:
- bisync: Add group Sync to the bisync command (Jan-Philipp Reßler)
- Note that --use-server-modtime only works on some backends (Nick Craig-Wood)
- Document unsupported S3 object keys with double slashes (Adam Kasztenny)
- Fix headers hierarchy for mount.md (Dark Dragon)
- Fix new drive flag typo in changelog (razorloves)
- Archive
- Extract: fix extraction with "./" prefix from tar entry paths (Varun Chawla)
- Drime
- Fix chunk-uploaded files ignoring workspace ID (a1pcm)
- Internxt
- Fix Entry doesn't belong in directory errors on windows (jzunigax2)
- WebDAV
- Escape reserved characters in URL path segments (Varun Chawla)
- Add missing headers for CORS (Romāns Potašovs)
## v1.73.1 - 2026-02-17
[See commits](https://github.com/rclone/rclone/compare/v1.73.0...v1.73.1)
- Bug Fixes
- accounting: Fix missing server side stats from core/stats rc (Nick Craig-Wood)
- build
- Fix CVE-2025-68121 by updating go to 1.25.7 or later (Nick Craig-Wood)
- Bump github.com/go-chi/chi/v5 from 5.2.3 to 5.2.5 to fix GO-2026-4316 (albertony)
- docs: Extend copyurl docs with an example of CSV FILENAMEs starting with a path. (Jack Kelly)
- march: Fix runtime: program exceeds 10000-thread limit (Nick Craig-Wood)
- pacer
- Fix deadlock between pacer token and --max-connections (Nick Craig-Wood)
- Re-read the sleep time as it may be stale (Nick Craig-Wood)
- Drime
- Fix files and directories being created in the default workspace (Nick Craig-Wood)
- Filelu
- Avoid buffering entire file in memory (kingston125)
- Add multipart upload support with configurable cutoff (kingston125)
- Filen
- Fix 32 bit targets not being able to list directories (Enduriel)
- Fix potential panic in case of error during upload (Enduriel)
- Internxt
- Implement re-login under refresh logic, improve retry logic (José Zúniga)
-S3
- Set list_version to 2 for FileLu S3 configuration (kingston125)
## v1.73.0 - 2026-01-30
[See commits](https://github.com/rclone/rclone/compare/v1.72.0...v1.73.0)
@@ -36,7 +88,7 @@ description: "Rclone Changelog"
- B2
- Support authentication with new bucket restricted application keys (DianaNites)
- Drive
- Add `--drive-metadata-force-expansive-access` flag (Nick Craig-Wood)
- Add `--drive-metadata-enforce-expansive-access` flag (Nick Craig-Wood)
- Fix crash when trying to creating shortcut to a Google doc (Nick Craig-Wood)
- FTP
- Add http proxy authentication support (Nicolas Dessart)
+4
View File
@@ -2961,6 +2961,10 @@ knowing the local file is newer than the time it was last uploaded to the
remote is sufficient. In those cases, this flag can speed up the process and
reduce the number of API calls necessary.
This flag is only supported on certain backends and will be silently
ignored on unsupported backends. Supported backends include
`azureblob`, `oracleobjectstorage`, `s3`, `swift`.
Using this flag on a sync operation without also using `--update` would cause
all files modified at any time other than the last upload time to be uploaded
again, which is probably not what you want.
+1 -1
View File
@@ -380,7 +380,7 @@ not the rclone developers so it may be out of date. Its current version is as be
## Source installation {#source}
Make sure you have git and [Go](https://golang.org/) installed.
Go version 1.24 or newer is required, the latest release is recommended.
Go version 1.25 or newer is required, the latest release is recommended.
You can get it from your package manager, or download it from
[golang.org/dl](https://golang.org/dl/). Then you can run the following:
+282 -31
View File
@@ -23,6 +23,7 @@ The S3 backend can be used with a number of different providers:
{{< provider name="DigitalOcean Spaces" home="https://www.digitalocean.com/products/object-storage/" config="/s3/#digitalocean-spaces" >}}
{{< provider name="Dreamhost" home="https://www.dreamhost.com/cloud/storage/" config="/s3/#dreamhost" >}}
{{< provider name="Exaba" home="https://exaba.com/" config="/s3/#exaba" >}}
{{< provider name="Fastly Object Storage" home="https://www.fastly.com/products/storage" config="/s3/#fastly" >}}
{{< provider name="FileLu S5 (S3-Compatible Object Storage)" home="https://s5lu.com/" config="/s3/#filelu-s5" >}}
{{< provider name="GCS" home="https://cloud.google.com/storage/docs" config="/s3/#google-cloud-storage" >}}
{{< provider name="Hetzner" home="https://www.hetzner.com/storage/object-storage/" config="/s3/#hetzner" >}}
@@ -51,11 +52,11 @@ The S3 backend can be used with a number of different providers:
{{< provider name="Selectel" home="https://selectel.ru/services/cloud/storage/" config="/s3/#selectel" >}}
{{< provider name="Servercore Object Storage" home="https://servercore.com/services/object-storage/" config="/s3/#servercore" >}}
{{< provider name="Spectra Logic" home="https://spectralogic.com/blackpearl-nearline-object-gateway" config="/s3/#spectralogic" >}}
{{< provider name="StackPath" home="https://www.stackpath.com/products/object-storage/" config="/s3/#stackpath" >}}
{{< provider name="Storj" home="https://storj.io/" config="/s3/#storj" >}}
{{< provider name="Synology C2 Object Storage" home="https://c2.synology.com/en-global/object-storage/overview" config="/s3/#synology-c2" >}}
{{< provider name="Tencent Cloud Object Storage (COS)" home="https://intl.cloud.tencent.com/product/cos" config="/s3/#tencent-cos" >}}
{{< provider name="Wasabi" home="https://wasabi.com/" config="/s3/#wasabi" end="true" >}}
{{< provider name="Wasabi" home="https://wasabi.com/" config="/s3/#wasabi" >}}
{{< provider name="Zadara Object Storage" home="https://www.zadara.com" config="/s3/#zadara" >}}
{{< provider name="Zata" home="https://zata.ai/" config="/s3/#Zata" end="true" >}}
{{< /provider_list >}}
@@ -670,6 +671,20 @@ work with the SDK properly:
| . | . |
| .. | .. |
#### Important note about double slashes (`//`)
Object keys containing consecutive forward slashes (`//`) are **not supported** by rclone.
When rclone encounters an object key with `//` (e.g., `a//b`), it will normalize the path to use a single slash (e.g., `a/b`). This normalization can cause "object not found" errors when trying to access the original object, as rclone will look for the normalized path instead of the actual object key.
**Example:**
- Original S3 object key: `folder//file.txt`
- rclone interprets it as: `folder/file.txt`
- Result: "object not found" error when trying to access `folder//file.txt`
**Workaround:**
Avoid using consecutive forward slashes (`//`) in S3 object keys when using rclone. If you have existing objects with `//` in their keys, you will need to rename them to use single slashes or access them through other means.
### Multipart uploads
rclone supports multipart uploads with S3 which means that it can
@@ -903,10 +918,52 @@ section, small files that are not uploaded as multipart, use a different tag, ca
the upload to fail. A simple solution is to set the `--s3-upload-cutoff 0` and force
all the files to be uploaded as multipart.
#### Setting Object Lock retention
Rclone supports setting Object Lock retention on uploaded objects with
the following options:
- `--s3-object-lock-mode` - Set the Object Lock mode (GOVERNANCE or COMPLIANCE)
- `--s3-object-lock-retain-until-date` - Set the retention date (RFC3339 format or duration like `365d`, `24h`)
- `--s3-object-lock-legal-hold-status` - Set legal hold (ON or OFF)
Example - upload files with 1 year GOVERNANCE retention:
rclone copy local:/data remote:bucket \
--s3-object-lock-mode GOVERNANCE \
--s3-object-lock-retain-until-date 365d
#### Copying Object Lock settings from source
When using `--metadata`, you can use the special value `copy` to preserve
the source object's Object Lock settings:
rclone copy source:bucket dest:bucket \
--metadata \
--s3-object-lock-mode copy \
--s3-object-lock-retain-until-date copy
You can also mix copied and explicit values. For example, to change the
mode from COMPLIANCE to GOVERNANCE while preserving the original retention date:
rclone copy source:bucket dest:bucket \
--metadata \
--s3-object-lock-mode GOVERNANCE \
--s3-object-lock-retain-until-date copy
#### Additional Object Lock options
- `--s3-bypass-governance-retention` - Required to delete or overwrite objects
with GOVERNANCE mode retention before the retention date expires
- `--s3-bucket-object-lock-enabled` - Enable Object Lock when creating a new
bucket with `rclone mkdir`
- `--s3-object-lock-set-after-upload` - Set Object Lock via separate API calls
after upload (for providers that don't support Object Lock headers during PUT)
<!-- autogenerated options start - DO NOT EDIT - instead edit fs.RegInfo in backend/s3/s3.go and run make backenddocs to verify --> <!-- markdownlint-disable-line line-length -->
### Standard options
Here are the Standard options specific to s3 (Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, BizflyCloud, Ceph, ChinaMobile, Cloudflare, Cubbit, DigitalOcean, Dreamhost, Exaba, FileLu, FlashBlade, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, Intercolo, IONOS, Leviia, Liara, Linode, LyveCloud, Magalu, Mega, Minio, Netease, Outscale, OVHcloud, Petabox, Qiniu, Rabata, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Servercore, SpectraLogic, StackPath, Storj, Synology, TencentCOS, Wasabi, Zata, Other).
Here are the Standard options specific to s3 (Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, BizflyCloud, Ceph, ChinaMobile, Cloudflare, Cubbit, DigitalOcean, Dreamhost, Exaba, FileLu, FlashBlade, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, Intercolo, IONOS, Leviia, Liara, Linode, LyveCloud, Magalu, Mega, Minio, Netease, Outscale, OVHcloud, Petabox, Qiniu, Rabata, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Servercore, SpectraLogic, Storj, Synology, TencentCOS, Wasabi, Zata, Other).
#### --s3-provider
@@ -999,8 +1056,6 @@ Properties:
- Servercore Object Storage
- "SpectraLogic"
- Spectra Logic Black Pearl
- "StackPath"
- StackPath Object Storage
- "Storj"
- Storj (S3 Compatible Gateway)
- "Synology"
@@ -1068,7 +1123,7 @@ Properties:
- Config: region
- Env Var: RCLONE_S3_REGION
- Provider: AWS,BizflyCloud,Ceph,Cloudflare,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,Intercolo,IONOS,Leviia,LyveCloud,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,Rabata,RackCorp,Scaleway,SeaweedFS,Selectel,Servercore,StackPath,Synology,Wasabi,Zata,Other
- Provider: AWS,BizflyCloud,Ceph,Cloudflare,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,Intercolo,IONOS,Leviia,LyveCloud,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,Rabata,RackCorp,Scaleway,SeaweedFS,Selectel,Servercore,Synology,Wasabi,Zata,Other
- Type: string
- Required: false
- Examples:
@@ -1186,11 +1241,11 @@ Properties:
- ""
- Use this if unsure.
- Will use v4 signatures and an empty region.
- Provider: Ceph,DigitalOcean,Dreamhost,Exaba,GCS,IBMCOS,Leviia,LyveCloud,Minio,Netease,SeaweedFS,StackPath,Wasabi,Other
- Provider: Ceph,DigitalOcean,Dreamhost,Exaba,GCS,IBMCOS,Leviia,LyveCloud,Minio,Netease,SeaweedFS,Wasabi,Other
- "other-v2-signature"
- Use this only if v4 signatures don't work.
- E.g. pre Jewel/v10 CEPH.
- Provider: Ceph,DigitalOcean,Dreamhost,Exaba,GCS,IBMCOS,Leviia,LyveCloud,Minio,Netease,SeaweedFS,StackPath,Wasabi,Other
- Provider: Ceph,DigitalOcean,Dreamhost,Exaba,GCS,IBMCOS,Leviia,LyveCloud,Minio,Netease,SeaweedFS,Wasabi,Other
- "auto"
- R2 buckets are automatically distributed across Cloudflare's data centers for low latency.
- Provider: Cloudflare
@@ -1504,7 +1559,7 @@ Properties:
- Config: endpoint
- Env Var: RCLONE_S3_ENDPOINT
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cloudflare,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,FlashBlade,GCS,Hetzner,HuaweiOBS,IBMCOS,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Mega,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,Rabata,RackCorp,Rclone,Scaleway,SeaweedFS,Selectel,Servercore,SpectraLogic,StackPath,Storj,Synology,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cloudflare,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,FlashBlade,GCS,Hetzner,HuaweiOBS,IBMCOS,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Mega,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,Rabata,RackCorp,Rclone,Scaleway,SeaweedFS,Selectel,Servercore,SpectraLogic,Storj,Synology,TencentCOS,Wasabi,Zata,Other
- Type: string
- Required: false
- Examples:
@@ -2292,15 +2347,6 @@ Properties:
- "s3.kz-1.srvstorage.kz"
- Almaty, Kazakhstan
- Provider: Servercore
- "s3.us-east-2.stackpathstorage.com"
- US East Endpoint
- Provider: StackPath
- "s3.us-west-1.stackpathstorage.com"
- US West Endpoint
- Provider: StackPath
- "s3.eu-central-1.stackpathstorage.com"
- EU Endpoint
- Provider: StackPath
- "gateway.storjshare.io"
- Global Hosted Gateway
- Provider: Storj
@@ -2810,36 +2856,36 @@ Properties:
- Config: acl
- Env Var: RCLONE_S3_ACL
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- Type: string
- Required: false
- Examples:
- "private"
- Owner gets FULL_CONTROL.
- No one else has access rights (default).
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,Wasabi,Zata,Other
- "public-read"
- Owner gets FULL_CONTROL.
- The AllUsers group gets READ access.
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- "public-read-write"
- Owner gets FULL_CONTROL.
- The AllUsers group gets READ and WRITE access.
- Granting this on a bucket is generally not recommended.
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- "authenticated-read"
- Owner gets FULL_CONTROL.
- The AuthenticatedUsers group gets READ access.
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- "bucket-owner-read"
- Object owner gets FULL_CONTROL.
- Bucket owner gets READ access.
- If you specify this canned ACL when creating a bucket, Amazon S3 ignores it.
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- "bucket-owner-full-control"
- Both the object owner and the bucket owner get FULL_CONTROL over the object.
- If you specify this canned ACL when creating a bucket, Amazon S3 ignores it.
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,TencentCOS,Wasabi,Zata,Other
- "private"
- Owner gets FULL_CONTROL.
- No one else has access rights (default).
@@ -3004,7 +3050,7 @@ Properties:
### Advanced options
Here are the Advanced options specific to s3 (Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, BizflyCloud, Ceph, ChinaMobile, Cloudflare, Cubbit, DigitalOcean, Dreamhost, Exaba, FileLu, FlashBlade, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, Intercolo, IONOS, Leviia, Liara, Linode, LyveCloud, Magalu, Mega, Minio, Netease, Outscale, OVHcloud, Petabox, Qiniu, Rabata, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Servercore, SpectraLogic, StackPath, Storj, Synology, TencentCOS, Wasabi, Zata, Other).
Here are the Advanced options specific to s3 (Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, BizflyCloud, Ceph, ChinaMobile, Cloudflare, Cubbit, DigitalOcean, Dreamhost, Exaba, FileLu, FlashBlade, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, Intercolo, IONOS, Leviia, Liara, Linode, LyveCloud, Magalu, Mega, Minio, Netease, Outscale, OVHcloud, Petabox, Qiniu, Rabata, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Servercore, SpectraLogic, Storj, Synology, TencentCOS, Wasabi, Zata, Other).
#### --s3-bucket-acl
@@ -3023,7 +3069,7 @@ Properties:
- Config: bucket_acl
- Env Var: RCLONE_S3_BUCKET_ACL
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Mega,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,Servercore,StackPath,TencentCOS,Wasabi,Zata,Other
- Provider: AWS,Alibaba,ArvanCloud,BizflyCloud,Ceph,ChinaMobile,Cubbit,DigitalOcean,Dreamhost,Exaba,FileLu,GCS,Hetzner,HuaweiOBS,IBMCOS,IDrive,Intercolo,IONOS,Leviia,Liara,Linode,LyveCloud,Magalu,Mega,Minio,Netease,Outscale,OVHcloud,Petabox,Qiniu,RackCorp,Scaleway,SeaweedFS,Servercore,TencentCOS,Wasabi,Zata,Other
- Type: string
- Required: false
- Examples:
@@ -4992,7 +5038,7 @@ Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
...
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, Ceph, China Mobile, Cloudflare, ArvanCloud, DigitalOcean, Dreamhost, Huawei OBS, IBM COS, Lyve Cloud, Minio, Magalu, Netease, RackCorp, Scaleway, SeaweedFS, StackPath, Storj, Synology, Tencent COS and Wasabi
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, Ceph, China Mobile, Cloudflare, ArvanCloud, DigitalOcean, Dreamhost, Huawei OBS, IBM COS, Lyve Cloud, Minio, Magalu, Netease, RackCorp, Scaleway, SeaweedFS, Storj, Synology, Tencent COS and Wasabi
\ (s3)
...
Storage> s3
@@ -5279,6 +5325,92 @@ secret_access_key = XXX
endpoint = http://127.0.0.1:9000/
```
### Fastly Object Storage {#fastly}
[Fastly Object Storage](https://www.fastly.com/products/storage) is an
S3-compatible object storage service from Fastly. It provides three
regions (US East, US West, and EU Central) with mandatory server-side
encryption.
Here is an example of making a configuration. First run:
```console
rclone config
```
This will guide you through an interactive setup process.
```text
No remotes found, make a new one?
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n
Enter name for new remote.
name> fastly
Option Storage.
Type of storage to configure.
Storage> s3
Option provider.
Choose your S3 provider.
provider> Fastly
Option env_auth.
Get AWS credentials from runtime (environment variables or EC2/ECS meta data if no env vars).
Only applies if access_key_id and secret_access_key is blank.
env_auth> false
Option access_key_id.
AWS Access Key ID.
access_key_id> YOUR_ACCESS_KEY
Option secret_access_key.
AWS Secret Access Key (password).
secret_access_key> YOUR_SECRET_KEY
Option region.
Region where your bucket will be created and your data stored.
region> us-east
Option endpoint.
Endpoint for S3 API.
endpoint> us-east.object.fastlystorage.app
Edit advanced config?
y) Yes
n) No (default)
y/n> n
Configuration complete.
Options:
- type: s3
- provider: Fastly
- access_key_id: YOUR_ACCESS_KEY
- secret_access_key: YOUR_SECRET_KEY
- region: us-east
- endpoint: us-east.object.fastlystorage.app
Keep this "fastly" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y
```
The resulting configuration file should look like:
```ini
[fastly]
type = s3
provider = Fastly
access_key_id = YOUR_ACCESS_KEY
secret_access_key = YOUR_SECRET_KEY
region = us-east
endpoint = us-east.object.fastlystorage.app
```
### Google Cloud Storage
[GoogleCloudStorage](https://cloud.google.com/storage/docs) is an
@@ -5330,7 +5462,7 @@ Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
[snip]
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, StackPath, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, GCS, Hetzner, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
\ (s3)
[snip]
Storage> s3
@@ -7112,7 +7244,7 @@ Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
[...]
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, GCS, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, OVHcloud, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, StackPath, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
XX / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, GCS, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, OVHcloud, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
\ (s3)
[...]
Storage> s3
@@ -7486,7 +7618,7 @@ Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
[snip]
4 / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, FlashBlade, GCS, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, StackPath, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
4 / Amazon S3 Compliant Storage Providers including AWS, Alibaba, ArvanCloud, Ceph, ChinaMobile, Cloudflare, DigitalOcean, Dreamhost, FlashBlade, GCS, HuaweiOBS, IBMCOS, IDrive, IONOS, LyveCloud, Leviia, Liara, Linode, Magalu, Minio, Netease, Outscale, Petabox, RackCorp, Rclone, Scaleway, SeaweedFS, Selectel, Storj, Synology, TencentCOS, Wasabi, Qiniu and others
\ (s3)
[snip]
Storage> s3
@@ -9099,6 +9231,125 @@ server_side_encryption =
storage_class =
```
### Zadara Object Storage {#zadara}
[Zadara Object Storage](https://www.zadara.com) is a fully-managed,
enterprise-grade, S3-compatible storage solution that provides scalable,
multi-tenant object storage with flexible deployment options (on-prem,
hybrid, or cloud).
Zadara Object Storage can be configured using `rclone config` with `s3` as
the type and `Zadara` as the provider name. Here is an example
run of the configurator.
Authentication and endpoint information, including the region field,
should be fetched from Zadara’s Object Storage management interface
To configure access to Zadara Object Storage, first run:
```console
rclone config
```
```text
This will guide you through an interactive setup process:
No remotes found, make a new one\?
n) New remote
s) Set configuration password
n/s> n
Enter name for new remote.
name> Zadara-Object-Storage
Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
XX / Amazon S3 Compliant Storage Providers including AWS ...
\ (s3)
Storage> s3
Option provider.
Choose your S3 provider.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
XX / Zadara Object Storage
\ (Zadara)
provider> Zadara
Option env_auth.
Get AWS credentials from runtime (environment variables or EC2/ECS meta data if no env vars).
Only applies if access_key_id and secret_access_key is blank.
Choose a number from below, or type in your own boolean value (true or false).
Press Enter for the default (false).
1 / Enter AWS credentials in the next step.
\ (false)
2 / Get AWS credentials from the environment (env vars or IAM).
\ (true)
env_auth>
Option access_key_id.
AWS Access Key ID.
Leave blank for anonymous access or runtime credentials.
Enter a value. Press Enter to leave empty.
access_key_id> S3_ACCESS_KEY
Option secret_access_key.
AWS Secret Access Key (password).
Leave blank for anonymous access or runtime credentials.
Enter a value. Press Enter to leave empty.
secret_access_key> S3_SECRET_KEY
Option region.
Region to connect to.
Leave blank if you are using an S3 clone and you don't have a region.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
/ The default region.
1 | Leave location constraint empty.
\ (us-east-1)
region>
Option endpoint.
Endpoint for S3 API.
Required when using an S3 clone.
Enter a value. Press Enter to leave empty.
endpoint> https://vsa-00000001-public-zadara-cloud-01.zadarazios.com
Edit advanced config?
y) Yes
n) No (default)
y/n>
Configuration complete.
Options:
- type: s3
- provider: Zadara
- access_key_id: S3_ACCESS_KEY
- secret_access_key: S3_SECRET_KEY
- endpoint: https://vsa-00000001-public-zadara-cloud-01.zadarazios.com
Keep this "Zadara-Object-Storage" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y
```
This will leave the config file looking like this.
```ini
[Zadara-Object-Storage]
type = s3
provider = Zadara
access_key_id = S3_ACCESS_KEY
secret_access_key = S3_SECRET_KEY
endpoint = https://vsa-00000001-public-zadara-cloud-01.zadarazios.com
```
### Zata Object Storage {#Zata}
[Zata Object Storage](https://zata.ai/) provides a secure, S3-compatible cloud
+3 -1
View File
@@ -16,16 +16,18 @@ Thank you to our sponsors:
{{< sponsor src="/img/logos/rabata.svg" width="300" height="200" title="Visit our sponsor Rabata.io" link="https://rabata.io/?utm_source=banner&utm_medium=rclone&utm_content=general">}}
{{< sponsor src="/img/logos/idrive_e2.svg" width="300" height="200" title="Visit our sponsor IDrive e2" link="https://www.idrive.com/e2/?refer=rclone">}}
{{< sponsor src="/img/logos/filescom-enterprise-grade-workflows.png" width="300" height="200" title="Start Your Free Trial Today" link="https://files.com/?utm_source=rclone&utm_medium=referral&utm_campaign=banner&utm_term=rclone">}}
{{< sponsor src="/img/logos/internxt.jpg" width="300" height="200" title="Visit rclone's sponsor Internxt" link="https://internxt.com/specialoffer/rclone">}}
{{< sponsor src="/img/logos/mega-s4.svg" width="300" height="200" title="MEGA S4: New S3 compatible object storage. High scale. Low cost. Free egress." link="https://mega.io/objectstorage?utm_source=rclone&utm_medium=referral&utm_campaign=rclone-mega-s4&mct=rclonepromo">}}
{{< sponsor src="/img/logos/sia.svg" width="200" height="200" title="Visit our sponsor sia" link="https://sia.tech">}}
{{< sponsor src="/img/logos/route4me.svg" width="400" height="200" title="Visit our sponsor Route4Me" link="https://route4me.com/">}}
{{< sponsor src="/img/logos/rcloneview-banner.svg" width="300" height="200" title="Visit our sponsor RcloneView" link="https://rcloneview.com/">}}
{{< sponsor src="/img/logos/rcloneview.svg" width="300" height="200" title="Visit our sponsor RcloneView" link="https://rcloneview.com/">}}
{{< sponsor src="/img/logos/rcloneui.svg" width="300" height="200" title="Visit our sponsor RcloneUI" link="https://github.com/rclone-ui/rclone-ui">}}
{{< sponsor src="/img/logos/shade.svg" width="300" height="200" title="Visit our sponsor Shade" link="https://shade.inc">}}
{{< sponsor src="/img/logos/filelu-rclone.svg" width="300" height="200" title="Visit our sponsor FileLu" link="https://filelu.com/">}}
{{< sponsor src="/img/logos/torbox.png" width="200" height="200" title="Visit our sponsor TORBOX" link="https://www.torbox.app/">}}
{{< sponsor src="/img/logos/spectra-logic.svg" width="300" height="200" title="Visit our sponsor Spectra Logic" link="https://spectralogic.com/">}}
{{< sponsor src="/img/logos/servercore.svg" width="300" height="200" title="Visit our sponsor servercore" link="https://servercore.com/services/object-storage/?utm_source=rclone.org&utm_medium=referral&utm_campaign=cloud-s3_rclone_231025_paid">}}
{{< sponsor src="/img/logos/exchangerate-api.png" width="300" height="200" title="Visit our sponsor ExchangeRate-API" link="https://www.exchangerate-api.com/">}}
<!-- markdownlint-restore -->
+1
View File
@@ -12,6 +12,7 @@ security: High
virtual: false
remote: 'TestDrime:'
features:
- About
- CanHaveEmptyDirectories
- Copy
- DirCacheFlush
+1 -1
View File
@@ -36,7 +36,7 @@
"beta" "This feature is currently in beta must be used with care."
}}
{{ if .Params.versionIntroduced }}<span class="badge badge-pill badge-secondary float-right" style="margin-top: 30px; font-size: 100%" title="This feature needs Rclone {{ .Params.versionIntroduced }} or later.">{{ .Params.versionIntroduced }}</span>{{ end }}
{{ if .Params.versionIntroduced }}<span class="badge badge-pill badge-secondary float-right" style="margin-top: 30px; font-size: 100%" title="This feature needs Rclone {{ .Params.versionIntroduced }} or later.">added in {{ .Params.versionIntroduced }}</span>{{ end }}
{{ with .Params.status | lower }}
{{ $statusCode := . }}
+1 -14
View File
@@ -12,7 +12,7 @@
<div class="card">
<div class="card-header">Platinum Sponso⁠r</div>
<div class="card-body">
<a href="https://rabata.io/?utm_source=banner&utm_medium=rclone&utm_content=general" target="_blank" rel="noopener" title="Visit rclone's sponsor Rabata.io"><img src="/img/logos/rabata.svg"></a><br />
<a href="https://internxt.com/specialoffer/rclone" target="_blank" rel="noopener" title="Visit rclone's sponsor Internxt"><img style="max-width: 100%; height: auto;" src="/img/logos/internxt.jpg"></a><br />
</div>
</div>
@@ -30,13 +30,6 @@
</div>
</div>
<div class="card">
<div class="card-header">Gold Sponso⁠r</div>
<div class="card-body">
<a href="https://internxt.com/?utm_source=rclone" target="_blank" rel="noopener" title="Visit rclone's sponsor Internxt"><img style="max-width: 100%; height: auto;" src="/img/logos/internxt.jpg"></a><br />
</div>
</div>
{{if .IsHome}}
<div class="card">
<div class="card-header">Silver Sponso⁠r</div>
@@ -44,12 +37,6 @@
<a href="https://rcloneview.com/?utm_source=rclone" target="_blank" rel="noopener" title="Visit rclone's sponsor RcloneView"><img src="/img/logos/rcloneview.svg"></a><br />
</div>
</div>
<div class="card">
<div class="card-header">Silver Sponso⁠r</div>
<div class="card-body">
<a href="https://rcloneui.com" target="_blank" rel="noopener" title="Visit rclone's sponsor rclone UI"><img src="/img/logos/rcloneui.svg"></a><br />
</div>
</div>
<div class="card">
<div class="card-header">Silver Sponso⁠r</div>
<div class="card-body">
+1 -1
View File
@@ -1 +1 @@
v1.73.0
v1.74.0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 404 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 704 B

+28 -4
View File
@@ -11,6 +11,7 @@ import (
"unicode/utf8"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/lib/transferaccounter"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/asyncreader"
@@ -312,6 +313,15 @@ func (acc *Account) serverSideEnd(n int64) {
}
}
// NewServerSideCopyAccounter returns a TransferAccounter for a server
// side copy and a new ctx with it embedded
func (acc *Account) NewServerSideCopyAccounter(ctx context.Context) (context.Context, *transferaccounter.TransferAccounter) {
return transferaccounter.New(ctx, func(n int64) {
acc.stats.AddServerSideCopyBytes(n)
acc.accountReadNoNetwork(n)
})
}
// ServerSideCopyEnd accounts for a read of n bytes in a server-side copy
func (acc *Account) ServerSideCopyEnd(n int64) {
acc.stats.AddServerSideCopy(n)
@@ -363,6 +373,17 @@ func (acc *Account) accountRead(n int) {
acc.limitPerFileBandwidth(n)
}
// Account the read if not using network (eg for server side copies)
func (acc *Account) accountReadNoNetwork(n int64) {
// Update Stats
acc.values.mu.Lock()
acc.values.lpBytes += n
acc.values.bytes += n
acc.values.mu.Unlock()
acc.stats.BytesNoNetwork(n)
}
// read bytes from the io.Reader passed in and account them
func (acc *Account) read(in io.Reader, p []byte) (n int, err error) {
bytesUntilLimit, err := acc.checkReadBefore()
@@ -575,8 +596,11 @@ func (acc *Account) String() string {
}
}
var displaySpeedString string
if acc.ci.DataRateUnit == "bits" {
cur *= 8
displaySpeedString = fs.SizeSuffix(cur * 8).BitRateUnit()
} else {
displaySpeedString = fs.SizeSuffix(cur).ByteRateUnit()
}
percentageDone := 0
@@ -584,12 +608,12 @@ func (acc *Account) String() string {
percentageDone = int(100 * float64(a) / float64(b))
}
return fmt.Sprintf("%*s:%3d%% /%s, %s/s, %s",
return fmt.Sprintf("%*s:%3d%% / %s, %s, %s",
acc.ci.StatsFileNameLength,
shortenName(acc.name, acc.ci.StatsFileNameLength),
percentageDone,
fs.SizeSuffix(b),
fs.SizeSuffix(cur),
fs.SizeSuffix(b).ByteUnit(),
displaySpeedString,
etas,
)
}
+2 -2
View File
@@ -183,14 +183,14 @@ func TestAccountString(t *testing.T) {
// FIXME not an exhaustive test!
assert.Equal(t, "test: 0% /3, 0/s, -", strings.TrimSpace(acc.String()))
assert.Equal(t, "test: 0% / 3 B, 0 B/s, -", strings.TrimSpace(acc.String()))
var buf = make([]byte, 2)
n, err := acc.Read(buf)
assert.NoError(t, err)
assert.Equal(t, 2, n)
assert.Equal(t, "test: 66% /3, 0/s, -", strings.TrimSpace(acc.String()))
assert.Equal(t, "test: 66% / 3 B, 0 B/s, -", strings.TrimSpace(acc.String()))
assert.NoError(t, acc.Close())
}
+7
View File
@@ -960,6 +960,13 @@ func (s *StatsInfo) AddServerSideMove(n int64) {
s.mu.Unlock()
}
// AddServerSideCopyBytes adds bytes for a server side copy
func (s *StatsInfo) AddServerSideCopyBytes(n int64) {
s.mu.Lock()
s.serverSideCopyBytes += n
s.mu.Unlock()
}
// AddServerSideCopy counts a server side copy
func (s *StatsInfo) AddServerSideCopy(n int64) {
s.mu.Lock()
+7
View File
@@ -89,6 +89,7 @@ Returns the following values:
{
"bytes": total transferred bytes since the start of the group,
"checks": number of files checked,
"deletedDirs": number of directories deleted,
"deletes" : number of files deleted,
"elapsedTime": time in floating point seconds since rclone was started,
"errors": number of errors,
@@ -385,12 +386,14 @@ func (sg *statsGroups) sum(ctx context.Context) *StatsInfo {
sum.checkQueueSize += stats.checkQueueSize
sum.transfers += stats.transfers
sum.transferring.merge(stats.transferring)
sum.transferQueue += stats.transferQueue
sum.transferQueueSize += stats.transferQueueSize
sum.listed += stats.listed
sum.renames += stats.renames
sum.renameQueue += stats.renameQueue
sum.renameQueueSize += stats.renameQueueSize
sum.deletes += stats.deletes
sum.deletesSize += stats.deletesSize
sum.deletedDirs += stats.deletedDirs
sum.inProgress.merge(stats.inProgress)
sum.startedTransfers = append(sum.startedTransfers, stats.startedTransfers...)
@@ -399,6 +402,10 @@ func (sg *statsGroups) sum(ctx context.Context) *StatsInfo {
stats.average.mu.Lock()
sum.average.speed += stats.average.speed
stats.average.mu.Unlock()
sum.serverSideCopies += stats.serverSideCopies
sum.serverSideCopyBytes += stats.serverSideCopyBytes
sum.serverSideMoves += stats.serverSideMoves
sum.serverSideMoveBytes += stats.serverSideMoveBytes
}
stats.mu.RUnlock()
}
+1 -1
View File
@@ -19,7 +19,7 @@ type TransferSnapshot struct {
Checked bool `json:"checked"`
What string `json:"what"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at,omitempty"`
CompletedAt time.Time `json:"completed_at"`
Error error `json:"-"`
Group string `json:"group"`
SrcFs string `json:"srcFs,omitempty"`
+2 -4
View File
@@ -265,9 +265,7 @@ func testAsyncReaderClose(t *testing.T, writeto bool) {
var copyErr error
var wg sync.WaitGroup
started := make(chan struct{})
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
close(started)
if writeto {
// exercise the WriteTo path
@@ -284,7 +282,7 @@ func testAsyncReaderClose(t *testing.T, writeto bool) {
}
}
}
}()
})
// Do some copying
<-started
time.Sleep(100 * time.Millisecond)
+1 -1
View File
@@ -163,7 +163,7 @@ type Item struct {
// struct, otherwise they will be embedded as they are.
func Items(opt any) (items []Item, err error) {
def := reflect.ValueOf(opt)
if def.Kind() != reflect.Ptr {
if def.Kind() != reflect.Pointer {
return nil, errors.New("argument must be a pointer")
}
def = def.Elem() // indirect the pointer
+13
View File
@@ -50,6 +50,7 @@ type Sorter struct {
errChan <-chan error // for getting errors from the ext sort
sorter *extsort.StringSorter // external string sort
errs *errcount.ErrCount // accumulate errors
tempDir string // directory for temp files (empty for default)
}
// KeyFn turns an entry into a sort key
@@ -144,6 +145,7 @@ func (ls *Sorter) startExtSort() (err error) {
ChanBuffSize: 1024, // small effect
SortedChanBuffSize: 1024, // makes a lot of difference
ChunkSize: 32 * 1024, // tuned for 50 char records (UUID sized)
TempFilesDir: ls.tempDir,
// Defaults
// ChunkSize: int(1e6), // amount of records to store in each chunk which will be written to disk
// NumWorkers: 2, // maximum number of workers to use for parallel sorting
@@ -152,6 +154,17 @@ func (ls *Sorter) startExtSort() (err error) {
// TempFilesDir: "", // empty for use OS default ex: /tmp
}
ls.sorter, ls.outputChan, ls.errChan = extsort.Strings(ls.inputChan, &opt)
if ls.sorter == nil {
// extsort.Strings returns nil when it can't create temp
// files (e.g. due to permissions or apparmor restrictions).
// The error will be on errChan.
select {
case err = <-ls.errChan:
default:
err = errors.New("failed to initialise on-disk sort")
}
return fmt.Errorf("sorter: %w", err)
}
go ls.sorter.Sort(ls.ctx)
// Show we are extsorting now
+48
View File
@@ -4,6 +4,9 @@ import (
"cmp"
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
@@ -231,6 +234,51 @@ func TestSorterExt(t *testing.T) {
}
}
// Test that startExtSort returns an error instead of panicking when
// temp file creation fails (e.g. due to permissions or apparmor).
// See: https://github.com/rclone/rclone/issues/9244
func TestSorterExtTempFileError(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.ListCutoff = 1 // force ext sort on first Add
callback := func(entries fs.DirEntries) error {
return nil
}
ls, err := NewSorter(ctx, nil, callback, nil)
require.NoError(t, err)
defer ls.CleanUp()
// Override tempDir to a path where os.MkdirAll will fail,
// simulating apparmor or permission denial. This makes
// extsort.Strings return a nil sorter.
if runtime.GOOS == "windows" {
// On Windows, create a regular file and use a child path.
// os.MkdirAll fails because an intermediate component is a file.
// Windows stat returns ERROR_PATH_NOT_FOUND (treated as
// IsNotExist) so the extsort library won't fall back to a
// default directory.
blocker := filepath.Join(t.TempDir(), "notadir")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0644))
ls.tempDir = filepath.Join(blocker, "sub")
} else {
// On Unix, create a read-only parent directory. stat on the
// child returns ENOENT so the extsort library won't fall
// back, but os.MkdirAll fails with EACCES.
parent := filepath.Join(t.TempDir(), "roparent")
require.NoError(t, os.Mkdir(parent, 0o755))
require.NoError(t, os.Chmod(parent, 0o555))
t.Cleanup(func() { _ = os.Chmod(parent, 0o755) })
ls.tempDir = filepath.Join(parent, "child")
}
// Add enough entries to trigger ext sort. Before the fix this
// would panic with nil pointer dereference.
err = ls.Add(fs.DirEntries{mockobject.Object("a"), mockobject.Object("b")})
require.Error(t, err)
assert.Contains(t, err.Error(), "sorter:")
}
// benchFs implements enough of the fs.Fs interface for Sorter
type benchFs struct{}
+1 -1
View File
@@ -156,7 +156,7 @@ func Trace(o any, format string, a ...any) func(string, ...any) {
for i := range a {
// read the values of the pointed to items
typ := reflect.TypeOf(a[i])
if typ.Kind() == reflect.Ptr {
if typ.Kind() == reflect.Pointer {
value := reflect.ValueOf(a[i])
if value.IsNil() {
a[i] = nil
+41 -21
View File
@@ -125,7 +125,7 @@ type OutputHandler struct {
mu sync.Mutex
output []outputFn // log to writer if empty or the last item
outputExtra []outputExtra // log to all these additional places
format logFormat
format logFormat // protected by mu
jsonBuf bytes.Buffer
jsonHandler *slog.JSONHandler
}
@@ -139,6 +139,13 @@ type outputExtra struct {
// Define the type of the override logger
type outputFn func(level slog.Level, text string)
// getFormat returns the current log format flags under the mutex.
func (h *OutputHandler) getFormat() logFormat {
h.mu.Lock()
defer h.mu.Unlock()
return h.format
}
// NewOutputHandler creates a new OutputHandler with the specified flags.
//
// This is designed to use log/slog but produce output which is
@@ -215,16 +222,22 @@ func (h *OutputHandler) setWriter(writer io.Writer) {
// Set the format flags to that passed in.
func (h *OutputHandler) setFormat(format logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format = format
}
// clear format flags that this output type doesn't want
func (h *OutputHandler) clearFormatFlags(bitMask logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format &^= bitMask
}
// set format flags that this output type requires
func (h *OutputHandler) setFormatFlags(bitMask logFormat) {
h.mu.Lock()
defer h.mu.Unlock()
h.format |= bitMask
}
@@ -238,37 +251,37 @@ func (h *OutputHandler) Enabled(_ context.Context, level slog.Level) bool {
}
// Create a log header in Go standard log format.
func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, level slog.Level, t time.Time, object string, lineInfo string) {
func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, format logFormat, level slog.Level, t time.Time, object string, lineInfo string) {
// Add time in Go standard format if requested
if h.format&(logFormatDate|logFormatTime|logFormatMicroseconds) != 0 {
if h.format&logFormatUTC != 0 {
if format&(logFormatDate|logFormatTime|logFormatMicroseconds) != 0 {
if format&logFormatUTC != 0 {
t = t.UTC()
}
if h.format&logFormatDate != 0 {
if format&logFormatDate != 0 {
year, month, day := t.Date()
fmt.Fprintf(buf, "%04d/%02d/%02d ", year, month, day)
}
if h.format&(logFormatTime|logFormatMicroseconds) != 0 {
if format&(logFormatTime|logFormatMicroseconds) != 0 {
hour, min, sec := t.Clock()
fmt.Fprintf(buf, "%02d:%02d:%02d", hour, min, sec)
if h.format&logFormatMicroseconds != 0 {
if format&logFormatMicroseconds != 0 {
fmt.Fprintf(buf, ".%06d", t.Nanosecond()/1e3)
}
buf.WriteByte(' ')
}
}
// Add source code filename:line if requested
if h.format&(logFormatShortFile|logFormatLongFile) != 0 && lineInfo != "" {
if format&(logFormatShortFile|logFormatLongFile) != 0 && lineInfo != "" {
buf.WriteString(lineInfo)
buf.WriteByte(':')
buf.WriteByte(' ')
}
// Add PID if requested
if h.format&logFormatPid != 0 {
if format&logFormatPid != 0 {
fmt.Fprintf(buf, "[%d] ", os.Getpid())
}
// Add log level if required
if h.format&logFormatNoLevel == 0 {
if format&logFormatNoLevel == 0 {
levelStr := slogLevelToString(level)
fmt.Fprintf(buf, "%-6s: ", levelStr)
}
@@ -281,9 +294,9 @@ func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, level slog.Level,
}
// Create a log in standard Go log format into buf.
func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) error {
func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, format logFormat, r slog.Record) error {
var lineInfo string
if h.format&(logFormatShortFile|logFormatLongFile) != 0 {
if format&(logFormatShortFile|logFormatLongFile) != 0 {
lineInfo = getCaller(2)
}
@@ -296,7 +309,7 @@ func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, r slog.R
return true
})
h.formatStdLogHeader(buf, r.Level, r.Time, object, lineInfo)
h.formatStdLogHeader(buf, format, r.Level, r.Time, object, lineInfo)
buf.WriteString(r.Message)
if buf.Len() == 0 || buf.Bytes()[buf.Len()-1] != '\n' { // Ensure newline
buf.WriteByte('\n')
@@ -305,13 +318,13 @@ func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, r slog.R
}
// Create a log in JSON format into buf.
func (h *OutputHandler) jsonLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) (err error) {
func (h *OutputHandler) jsonLog(ctx context.Context, buf *bytes.Buffer, format logFormat, r slog.Record) (err error) {
// Call the JSON handler to create the JSON in buf
r.AddAttrs(
slog.String("source", getCaller(2)),
)
// Add PID if requested
if h.format&logFormatPid != 0 {
if format&logFormatPid != 0 {
r.AddAttrs(slog.Int("pid", os.Getpid()))
}
h.mu.Lock()
@@ -331,8 +344,15 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
buf *bytes.Buffer
)
// Read the format under the mutex once so it is consistent
// throughout this call. The mutex is released before calling
// jsonLog/textLog (which may re-acquire it) to avoid deadlock.
h.mu.Lock()
format := h.format
h.mu.Unlock()
// Check whether we need to build Text or JSON logs or both
needJSON := h.format&logFormatJSON != 0
needJSON := format&logFormatJSON != 0
needText := !needJSON
for _, out := range h.outputExtra {
if out.json {
@@ -345,7 +365,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
if needJSON {
var bufJSONBack [256]byte
bufJSON = bytes.NewBuffer(bufJSONBack[:0])
err = h.jsonLog(ctx, bufJSON, r)
err = h.jsonLog(ctx, bufJSON, format, r)
if err != nil {
return err
}
@@ -354,7 +374,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
if needText {
var bufTextBack [256]byte
bufText = bytes.NewBuffer(bufTextBack[:0])
err = h.textLog(ctx, bufText, r)
err = h.textLog(ctx, bufText, format, r)
if err != nil {
return err
}
@@ -364,7 +384,7 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
defer h.mu.Unlock()
// Do the log, either to the default destination or to the alternate logging system
if h.format&logFormatJSON != 0 {
if format&logFormatJSON != 0 {
buf = bufJSON
} else {
buf = bufText
@@ -390,13 +410,13 @@ func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
// WithAttrs creates a new handler with the same writer, options, and flags.
// Attributes are ignored for the output format of this specific handler.
func (h *OutputHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.format)
return NewOutputHandler(h.writer, &h.opts, h.getFormat())
}
// WithGroup creates a new handler with the same writer, options, and flags.
// Groups are ignored for the output format of this specific handler.
func (h *OutputHandler) WithGroup(name string) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.format)
return NewOutputHandler(h.writer, &h.opts, h.getFormat())
}
// Check interface
+106 -7
View File
@@ -4,9 +4,11 @@ import (
"bytes"
"context"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
"testing"
"time"
@@ -91,9 +93,9 @@ func TestFormatStdLogHeader(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
h := &OutputHandler{format: tc.format}
h := NewOutputHandler(&bytes.Buffer{}, nil, tc.format)
buf := &bytes.Buffer{}
h.formatStdLogHeader(buf, slog.LevelInfo, t0, tc.object, tc.lineInfo)
h.formatStdLogHeader(buf, tc.format, slog.LevelInfo, t0, tc.object, tc.lineInfo)
if !strings.HasPrefix(buf.String(), tc.wantPrefix) {
t.Errorf("%s: got %q; want prefix %q", tc.name, buf.String(), tc.wantPrefix)
}
@@ -114,13 +116,13 @@ func TestEnabled(t *testing.T) {
// Test clearFormatFlags and setFormatFlags bitwise ops.
func TestClearSetFormatFlags(t *testing.T) {
h := &OutputHandler{format: logFormatDate | logFormatTime}
h := NewOutputHandler(&bytes.Buffer{}, nil, logFormatDate|logFormatTime)
h.clearFormatFlags(logFormatTime)
assert.True(t, h.format&logFormatTime == 0)
assert.True(t, h.getFormat()&logFormatTime == 0)
h.setFormatFlags(logFormatMicroseconds)
assert.True(t, h.format&logFormatMicroseconds != 0)
assert.True(t, h.getFormat()&logFormatMicroseconds != 0)
}
// Test SetOutput and ResetOutput override the default writer.
@@ -231,7 +233,7 @@ func TestTextLogAndJsonLog(t *testing.T) {
// textLog
bufText := &bytes.Buffer{}
require.NoError(t, h.textLog(context.Background(), bufText, r))
require.NoError(t, h.textLog(context.Background(), bufText, h.getFormat(), r))
out := bufText.String()
if !strings.Contains(out, "WARNING") || !strings.Contains(out, "obj:") || !strings.HasSuffix(out, "\n") {
t.Errorf("textLog output = %q", out)
@@ -239,13 +241,110 @@ func TestTextLogAndJsonLog(t *testing.T) {
// jsonLog
bufJSON := &bytes.Buffer{}
require.NoError(t, h.jsonLog(context.Background(), bufJSON, r))
require.NoError(t, h.jsonLog(context.Background(), bufJSON, h.getFormat(), r))
j := bufJSON.String()
if !strings.Contains(j, `"level":"warning"`) || !strings.Contains(j, `"msg":"msg!"`) {
t.Errorf("jsonLog output = %q", j)
}
}
// Test concurrent access to the handler does not race or deadlock.
func TestOutputHandlerConcurrency(t *testing.T) {
h := NewOutputHandler(io.Discard, nil, logFormatDate|logFormatTime)
ctx := context.Background()
const goroutines = 10
const iterations = 500
var wg sync.WaitGroup
// Goroutines calling Handle (text format)
for i := 0; i < goroutines; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
r := slog.NewRecord(t0, slog.LevelInfo, "concurrent text", 0)
r.AddAttrs(slog.String("object", "obj"))
_ = h.Handle(ctx, r)
}
}()
}
// Goroutines calling setFormat (switching between text and JSON)
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
if j%2 == 0 {
h.setFormat(logFormatDate | logFormatTime)
} else {
h.setFormat(logFormatJSON)
}
}
}()
}
// Goroutines calling setFormatFlags / clearFormatFlags
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
h.setFormatFlags(logFormatPid | logFormatMicroseconds)
h.clearFormatFlags(logFormatPid | logFormatMicroseconds)
}
}()
// Goroutines calling SetLevel
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
if j%2 == 0 {
h.SetLevel(slog.LevelDebug)
} else {
h.SetLevel(slog.LevelInfo)
}
}
}()
// Goroutines calling SetOutput / ResetOutput
wg.Add(1)
go func() {
defer wg.Done()
noop := func(_ slog.Level, _ string) {}
for j := 0; j < iterations; j++ {
h.SetOutput(noop)
h.ResetOutput()
}
}()
// Goroutines calling WithAttrs / WithGroup (reads format)
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < iterations; j++ {
_ = h.WithAttrs(nil)
_ = h.WithGroup("g")
}
}()
// Use a channel with a timeout to detect deadlocks
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// success
case <-time.After(30 * time.Second):
t.Fatal("timed out waiting for concurrent goroutines — probable deadlock")
}
}
// Table-driven test for JSON vs text Handle behavior.
func TestHandleFormatFlags(t *testing.T) {
r := slog.NewRecord(t0, slog.LevelInfo, "hi", 0)
+22 -23
View File
@@ -16,6 +16,7 @@ import (
"github.com/rclone/rclone/fs/list"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/lib/transform"
"golang.org/x/sync/semaphore"
"golang.org/x/text/unicode/norm"
)
@@ -41,9 +42,10 @@ type March struct {
NoCheckDest bool // transfer all objects regardless without checking dst
NoUnicodeNormalization bool // don't normalize unicode characters in filenames
// internal state
srcListDir listDirFn // function to call to list a directory in the src
dstListDir listDirFn // function to call to list a directory in the dst
transforms []matchTransformFn
srcListDir listDirFn // function to call to list a directory in the src
dstListDir listDirFn // function to call to list a directory in the dst
transforms []matchTransformFn
newObjectSem *semaphore.Weighted // make sure we don't call too many NewObjects simultaneously
}
// Marcher is called on each match
@@ -78,6 +80,8 @@ func (m *March) init(ctx context.Context) {
if m.Fdst.Features().CaseInsensitive || ci.IgnoreCaseSync {
m.transforms = append(m.transforms, strings.ToLower)
}
// Only allow ci.Checkers simultaneous calls to NewObject
m.newObjectSem = semaphore.NewWeighted(int64(ci.Checkers))
}
// srcOrDstKey turns a directory entry into a sort key using the defined transforms.
@@ -201,9 +205,7 @@ func (m *March) Run(ctx context.Context) error {
checkers := ci.Checkers
in := make(chan listDirJob, checkers)
for range checkers {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for {
select {
case <-m.Ctx.Done():
@@ -240,7 +242,7 @@ func (m *March) Run(ctx context.Context) error {
traversing.Done()
}
}
}()
})
}
// Start the process
@@ -389,9 +391,7 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
// List the src and dst directories
if !job.noSrc {
srcChan := srcChan // duplicate this as we may override it later
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
srcListErr = m.srcListDir(job.srcRemote, func(entries fs.DirEntries) error {
for _, entry := range entries {
srcChan <- entry
@@ -399,16 +399,14 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
return nil
})
close(srcChan)
}()
})
} else {
close(srcChan)
}
startedDst := false
if !m.NoTraverse && !job.noDst {
startedDst = true
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
dstListErr = m.dstListDir(job.dstRemote, func(entries fs.DirEntries) error {
for _, entry := range entries {
dstChan <- entry
@@ -416,7 +414,7 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
return nil
})
close(dstChan)
}()
})
}
// If NoTraverse is set, then try to find a matching object
// for each item in the srcList to head dst object
@@ -451,9 +449,7 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
// Get the tasks from the queue and find a matching object.
var workerWg sync.WaitGroup
for range workers {
workerWg.Add(1)
go func() {
defer workerWg.Done()
workerWg.Go(func() {
for t := range matchTasks {
// Can't match directories with NewObject
if _, ok := t.src.(fs.Object); !ok {
@@ -461,13 +457,18 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
continue
}
leaf := path.Base(t.src.Remote())
if err := m.newObjectSem.Acquire(m.Ctx, 1); err != nil {
t.dstMatch <- nil
continue
}
dst, err := m.Fdst.NewObject(m.Ctx, path.Join(job.dstRemote, leaf))
m.newObjectSem.Release(1)
if err != nil {
dst = nil
}
t.dstMatch <- dst
}
}()
})
}
// Close dstResults when all the workers have finished
@@ -477,9 +478,7 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
}()
// Read the matches in order and send them to dstChan if found.
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for dstMatch := range dstMatches {
dst := <-dstMatch
// Note that dst may be nil here
@@ -488,7 +487,7 @@ func (m *March) processJob(job listDirJob) ([]listDirJob, error) {
}
close(srcChan)
close(dstChan)
}()
})
}
if !startedDst {
close(dstChan)
+2 -4
View File
@@ -508,9 +508,7 @@ func TestMatchListings(t *testing.T) {
}
ls, err := list.NewSorter(ctx, nil, list.SortToChan(out), key)
require.NoError(t, err)
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for i := 0; i < len(test.input); i += 2 {
entry := test.input[i+offset]
if entry != nil {
@@ -520,7 +518,7 @@ func TestMatchListings(t *testing.T) {
require.NoError(t, ls.Send())
ls.CleanUp()
close(out)
}()
})
return out
}
+10 -2
View File
@@ -151,9 +151,17 @@ func (c *copy) serverSideCopy(ctx context.Context) (actionTaken string, newDst f
}
in := c.tr.Account(ctx, nil) // account the transfer
in.ServerSideTransferStart()
newDst, err = doCopy(ctx, c.src, c.remoteForCopy)
newCtx, ta := in.NewServerSideCopyAccounter(ctx)
newDst, err = doCopy(newCtx, c.src, c.remoteForCopy)
if err == nil {
in.ServerSideCopyEnd(newDst.Size()) // account the bytes for the server-side transfer
var n int64
if !ta.Started() {
n = newDst.Size()
}
in.ServerSideCopyEnd(n) // account the bytes for the server-side transfer
} else {
// Rewind any stats counted on error
ta.Reset()
}
_ = in.Close()
if errors.Is(err, fs.ErrorCantCopy) {
+21 -16
View File
@@ -64,25 +64,15 @@ type multiThreadCopyState struct {
}
// Copy a single chunk into place
func (mc *multiThreadCopyState) copyChunk(ctx context.Context, chunk int, writer fs.ChunkWriter) (err error) {
func (mc *multiThreadCopyState) copyChunk(ctx context.Context, chunk int, writer fs.ChunkWriter, start, end, size int64, rw *pool.RW) (err error) {
defer func() {
if !mc.noBuffering {
fs.CheckClose(rw, &err)
}
if err != nil {
fs.Debugf(mc.src, "multi-thread copy: chunk %d/%d failed: %v", chunk+1, mc.numChunks, err)
}
}()
start := int64(chunk) * mc.partSize
if start >= mc.size {
return nil
}
end := min(start+mc.partSize, mc.size)
size := end - start
// Reserve the memory first so we don't open the source and wait for memory buffers for ages
var rw *pool.RW
if !mc.noBuffering {
rw = multipart.NewRW().Reserve(size)
defer fs.CheckClose(rw, &err)
}
fs.Debugf(mc.src, "multi-thread copy: chunk %d/%d (%d-%d) size %v starting", chunk+1, mc.numChunks, start, end, fs.SizeSuffix(size))
@@ -226,9 +216,24 @@ func multiThreadCopy(ctx context.Context, f fs.Fs, remote string, src fs.Object,
if gCtx.Err() != nil {
break
}
chunk := chunk
// Work out how big and where the chunk is
start := int64(chunk) * mc.partSize
if start >= mc.size {
continue
}
end := min(start+mc.partSize, mc.size)
size := end - start
// Reserve the memory first so we don't open the source and wait for memory buffers for ages
// This also avoids creating an excess of goroutines all waiting on memory.
var rw *pool.RW
if !mc.noBuffering {
rw = multipart.NewRW().Reserve(size)
}
g.Go(func() error {
return mc.copyChunk(gCtx, chunk, chunkWriter)
return mc.copyChunk(gCtx, chunk, chunkWriter, start, end, size, rw)
})
}
+4 -8
View File
@@ -570,13 +570,11 @@ func (s *syncCopyMove) startTrackRenames() {
if !s.trackRenames {
return
}
s.trackRenamesWg.Add(1)
go func() {
defer s.trackRenamesWg.Done()
s.trackRenamesWg.Go(func() {
for o := range s.trackRenamesCh {
s.renameCheck = append(s.renameCheck, o)
}
}()
})
}
// This stops the background rename collection
@@ -593,12 +591,10 @@ func (s *syncCopyMove) startDeleters() {
if s.deleteMode != fs.DeleteModeDuring && s.deleteMode != fs.DeleteModeOnly {
return
}
s.deletersWg.Add(1)
go func() {
defer s.deletersWg.Done()
s.deletersWg.Go(func() {
err := operations.DeleteFilesWithBackupDir(s.ctx, s.deleteFilesCh, s.backupDir)
s.processError(err)
}()
})
}
// This stops the background deleters
+3 -3
View File
@@ -1,7 +1,7 @@
//go:build !go1.24
//go:build !go1.25
package fs
// Upgrade to Go version 1.24 to compile rclone - latest stable go
// Upgrade to Go version 1.25 to compile rclone - latest stable go
// compiler recommended.
func init() { Go_version_1_24_required_for_compilation() }
func init() { Go_version_1_25_required_for_compilation() }
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more