Compare commits

..
Author SHA1 Message Date
Nick Craig-Wood c0f03f8ac0 Version v1.73.2 2026-03-06 18:45:23 +00:00
Nick Craig-Wood 5f149a91c4 Update to go 1.25.8 to fix multiple CVEs
This fixes the following CVEs

- CVE-2026-27137
- CVE-2026-27138
- CVE-2026-25679
- CVE-2026-27142

This disables the go1.24 build as the updates no longer build on go1.24

Fixes #9220
2026-03-06 14:12:25 +00:00
Nick Craig-Wood 41fb73c669 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-03-06 13:19:22 +00:00
razorloves 4b63e78358 docs: fix new drive flag typo in changelog 2026-03-06 13:19:22 +00:00
Romāns Potašovs 690587ebbf webdav: add missing headers for CORS
fix #7492
2026-03-06 13:19:22 +00:00
Adam Kasztenny 3821c64711 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-03-06 13:19:22 +00:00
Nick Craig-Wood dc73dba9b5 docs: note that --use-server-modtime only works on some backends
Closes #6977
2026-03-06 13:19:22 +00:00
jzunigax2 9267568fe3 internxt: fix Entry doesn't belong in directory errors on windows 2026-03-06 13:19:22 +00:00
a1pcm a285c9eeee 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-03-06 13:19:22 +00:00
Dark Dragon cf4d78e3c9 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-03-06 13:19:22 +00:00
Varun Chawla ea29edb35d 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-03-06 13:19:22 +00:00
Jan-Philipp ReßlerandJan-Philipp Reßler de93ad8744 bisync: add group Sync to the bisync command
Co-authored-by: Jan-Philipp Reßler <xodarap@xodarap.de>
2026-03-06 13:19:22 +00:00
Varun Chawla 9bfc1a7a8a 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-03-06 13:19:22 +00:00
Nick Craig-Wood d9e455d1d3 docs: add instructions on how to update Go version 2026-03-06 13:19:22 +00:00
Nick Craig-Wood 7502ec934b buid: update github.com/cloudflare/circl to v1.6.3 to fix CVE-2026-1229
Fixes #9227
2026-03-04 11:24:31 +00:00
Nick Craig-Wood bffc49742c Start v1.73.2-DEV development 2026-02-17 18:21:06 +00:00
Nick Craig-Wood c7dab94e94 Version v1.73.1 2026-02-17 16:55:43 +00:00
Nick Craig-Wood 615a6f57bb 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 16:48:52 +00:00
Nick Craig-Wood b52fab6868 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 16:35:26 +00:00
Nick Craig-Wood b740e9c299 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 16:35:26 +00:00
Nick Craig-Wood 3b63bd280c 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 16:35:26 +00:00
Nick Craig-Wood 3a902dd1a0 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 16:35:26 +00:00
Nick Craig-Wood 1e24958861 build: fix CVE-2025-68121 by updating go to 1.25.7 or later - fixes #9167 2026-02-17 16:35:26 +00:00
Nick Craig-Wood 77e0a760d8 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 16:35:26 +00:00
Nick Craig-Wood e16ac436f7 docs: update sponsors 2026-02-17 16:35:26 +00:00
Jack Kelly 1f34163857 copyurl: Extend copyurl docs with an example of CSV FILENAMEs starting with a path. 2026-02-17 16:35:26 +00:00
José Zúniga 132184a47f internxt: implement re-login under refresh logic, improve retry logic - fixes #9174 2026-02-17 16:35:26 +00:00
Nick Craig-Wood 6e78bb1c40 docs: add ExchangeRate-API as a sponsor 2026-02-17 16:35:26 +00:00
albertony d720452656 build: bump github.com/go-chi/chi/v5 from 5.2.3 to 5.2.5 to fix GO-2026-4316 2026-02-17 16:35:26 +00:00
kingston125 a8d374f068 Set list_version to 2 for FileLu S3 configuration 2026-02-17 16:35:26 +00:00
kingston125 53fbeb21c8 filelu: add multipart upload support with configurable cutoff 2026-02-17 16:35:26 +00:00
kingston125 350a9bc389 filelu: add multipart init response type 2026-02-17 16:35:25 +00:00
kingston125 6ba40cc97e filelu: add comment for response body wrapping 2026-02-17 16:35:25 +00:00
kingston125 1d2a159c6a filelu: avoid buffering entire file in memory
Avoid buffering the entire file in memory during download, especially
for large files.
2026-02-17 16:35:25 +00:00
Nick Craig-Wood 1adc3e241d docs: update sponsor logos 2026-02-17 16:35:25 +00:00
Enduriel d5483e3e93 filen: fix potential panic in case of error during upload 2026-02-17 16:35:25 +00:00
Enduriel d6bc7a69a1 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-17 16:35:25 +00:00
Nick Craig-Wood 3311b72407 Start v1.73.1-DEV development 2026-02-17 12:16:33 +00:00
299 changed files with 3906 additions and 7811 deletions

No files matched your search

+10 -16
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.25']
job_name: ['linux', 'linux_386', 'mac_amd64', 'mac_arm64', 'windows', 'other_os']
include:
- job_name: linux
os: ubuntu-latest
go: '~1.26.0'
go: '~1.25.8'
gotags: cmount
build_flags: '-include "^linux/"'
check: true
@@ -45,14 +45,14 @@ jobs:
- job_name: linux_386
os: ubuntu-latest
go: '~1.26.0'
go: '~1.25.8'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '~1.26.0'
go: '~1.25.8'
gotags: 'cmount'
build_flags: '-include "^darwin/amd64" -cgo'
quicktest: true
@@ -61,14 +61,14 @@ jobs:
- job_name: mac_arm64
os: macos-latest
go: '~1.26.0'
go: '~1.25.8'
gotags: 'cmount'
build_flags: '-include "^darwin/arm64" -cgo -macos-arch arm64 -cgo-cflags=-I/usr/local/include -cgo-ldflags=-L/usr/local/lib'
deploy: true
- job_name: windows
os: windows-latest
go: '~1.26.0'
go: '~1.25.8'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -78,17 +78,11 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '~1.26.0'
go: '~1.25.8'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
- job_name: go1.25
os: ubuntu-latest
go: '~1.25.7'
quicktest: true
racequicktest: true
name: ${{ matrix.job_name }}
runs-on: ${{ matrix.os }}
@@ -224,7 +218,7 @@ jobs:
id: setup-go
uses: actions/setup-go@v6
with:
go-version: '~1.26.0'
go-version: '~1.25.8'
check-latest: true
cache: false
@@ -283,7 +277,7 @@ jobs:
run: govulncheck ./...
- name: Check Markdown format
uses: DavidAnson/markdownlint-cli2-action@v23
uses: DavidAnson/markdownlint-cli2-action@v20
with:
globs: |
CONTRIBUTING.md
@@ -315,7 +309,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version: '~1.26.0'
go-version: '~1.25.8'
- name: Set global environment variables
run: |
@@ -100,7 +100,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
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@v4
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- 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@v4
uses: docker/login-action@v3
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@v7
uses: docker/build-push-action@v6
with:
file: Dockerfile
context: .
@@ -183,7 +183,7 @@ jobs:
touch "/tmp/digests/${digest#sha256:}"
- name: Upload Image Digest
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v6
with:
name: digests-${{ env.PLATFORM }}
path: /tmp/digests/*
@@ -198,7 +198,7 @@ jobs:
steps:
- name: Download Image Digests
uses: actions/download-artifact@v8
uses: actions/download-artifact@v7
with:
path: /tmp/digests
pattern: digests-*
@@ -210,7 +210,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
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@v4
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
+7 -7
View File
@@ -412,8 +412,8 @@ the source file in the `Help:` field:
- The `backenddocs` make target runs the Python script `bin/make_backend_docs.py`,
and you can also run this directly, optionally with the name of a backend
as argument to only update the docs for a specific backend.
- **Do not** commit the updated Markdown files. This operation is run as part
of the release process. Since any manual changes in the autogenerated sections
- **Do not** commit the updated Markdown files. This operation is run as part of
the release process. Since any manual changes in the autogenerated sections
of the Markdown files will then be lost, we have a pull request check that
reports error for any changes within the autogenerated sections. Should you
have done manual changes outside of the autogenerated sections they must be
@@ -580,8 +580,7 @@ remote or an fs.
make sure we can encode any path name and `rclone info` to help determine the
encodings needed
- `rclone purge -v TestRemote:rclone-info`
- `rclone test info --all --remote-encoding None -vv --write-json remote.json
TestRemote:rclone-info`
- `rclone test info --all --remote-encoding None -vv --write-json remote.json TestRemote:rclone-info`
- `go run cmd/test/info/internal/build_csv/main.go -o remote.csv remote.json`
- open `remote.csv` in a spreadsheet and examine
@@ -628,9 +627,10 @@ See the [testing](#testing) section for more information on integration tests.
### Backend documentation
Add your backend to the docs. Keep lists of remotes in alphabetical
order of full name of remote (e.g. `drive` is ordered as `Google
Drive`) but with the local file system last.
Add your backend to the docs - you'll need to pick an icon for it from
[fontawesome](http://fontawesome.io/icons/). Keep lists of remotes in
alphabetical order of full name of remote (e.g. `drive` is ordered as
`Google Drive`) but with the local file system last.
First add a data file about your backend in
`docs/data/backends/remote.yaml` - this is used to build the overview
+20 -20
View File
@@ -2,27 +2,27 @@
Current active maintainers of rclone are:
| Name | GitHub ID | Specific Responsibilities |
| :--------------- | :---------------- | :------------------------------------- |
| Nick Craig-Wood | @ncw | overall project health |
| Stefan Breunig | @breunigs | |
| Ishuah Kariuki | @ishuah | |
| Remus Bunduc | @remusb | cache backend |
| Fabian Möller | @B4dM4n | |
| Alex Chen | @Cnly | onedrive backend |
| Sandeep Ummadi | @sandeepkru | azureblob backend |
| Name | GitHub ID | Specific Responsibilities |
| :--------------- | :---------------- | :-------------------------- |
| Nick Craig-Wood | @ncw | overall project health |
| Stefan Breunig | @breunigs | |
| Ishuah Kariuki | @ishuah | |
| Remus Bunduc | @remusb | cache backend |
| Fabian Möller | @B4dM4n | |
| Alex Chen | @Cnly | onedrive backend |
| Sandeep Ummadi | @sandeepkru | azureblob backend |
| Sebastian Bünger | @buengese | jottacloud, yandex & compress backends |
| Ivan Andreev | @ivandeex | chunker & mailru backends |
| Max Sum | @Max-Sum | union backend |
| Fred | @creativeprojects | seafile backend |
| Caleb Case | @calebcase | storj backend |
| wiserain | @wiserain | pikpak backend |
| albertony | @albertony | |
| Chun-Hung Tseng | @henrybear327 | Proton Drive Backend |
| Hideo Aoyama | @boukendesho | snap packaging |
| nielash | @nielash | bisync |
| Dan McArdle | @dmcardle | gitannex |
| Sam Harrison | @childish-sambino | filescom |
| Ivan Andreev | @ivandeex | chunker & mailru backends |
| Max Sum | @Max-Sum | union backend |
| Fred | @creativeprojects | seafile backend |
| Caleb Case | @calebcase | storj backend |
| wiserain | @wiserain | pikpak backend |
| albertony | @albertony | |
| Chun-Hung Tseng | @henrybear327 | Proton Drive Backend |
| Hideo Aoyama | @boukendesho | snap packaging |
| nielash | @nielash | bisync |
| Dan McArdle | @dmcardle | gitannex |
| Sam Harrison | @childish-sambino | filescom |
## This is a work in progress draft
Generated
+1552 -1397
View File
File diff suppressed because it is too large. Load diff
Generated
+131 -12
View File
@@ -1,6 +1,6 @@
% rclone(1) User Manual
% Nick Craig-Wood
% Jan 30, 2026
% Mar 06, 2026
# NAME
@@ -3768,6 +3768,26 @@ Flags for anything which can copy a file
-u, --update Skip files that are newer on the destination
```
### Sync Options
Flags used for sync commands
```text
--backup-dir string Make backups into hierarchy based in DIR
--delete-after When synchronizing, delete files on destination after transferring (default)
--delete-before When synchronizing, delete files on destination before transferring
--delete-during When synchronizing, delete files during transfer
--fix-case Force rename of case insensitive dest to match source
--ignore-errors Delete even if there are I/O errors
--list-cutoff int To save memory, sort directory listings on disk above this threshold (default 1000000)
--max-delete int When synchronizing, limit the number of deletes (default -1)
--max-delete-size SizeSuffix When synchronizing, limit the total size of deletes (default off)
--suffix string Suffix to add to changed files
--suffix-keep-extension Preserve the extension when using --suffix
--track-renames When synchronizing, track file renames and do a server-side move if possible
--track-renames-strategy string Strategies to use when synchronizing using track-renames hash|modtime|leaf (default "hash")
```
### Important Options
Important flags useful for most commands
@@ -5388,12 +5408,12 @@ rclone convmv "stories/The Quick Brown Fox!.txt" --name-transform "all,command=e
```console
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{YYYYMMDD}"
// Output: stories/The Quick Brown Fox!-20260130
// Output: stories/The Quick Brown Fox!-20260306
```
```console
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{macfriendlytime}"
// Output: stories/The Quick Brown Fox!-2026-01-30 0825PM
// Output: stories/The Quick Brown Fox!-2026-03-06 0556PM
```
```console
@@ -5841,6 +5861,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:
@@ -7215,7 +7244,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`:
@@ -8657,7 +8686,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`:
@@ -19587,6 +19616,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.
@@ -24776,7 +24809,7 @@ Flags for general networking and HTTP stuff.
--tpslimit float Limit HTTP transactions per second to this
--tpslimit-burst int Max burst of transactions for --tpslimit (default 1)
--use-cookies Enable session cookiejar
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.0")
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.2")
```
@@ -25260,9 +25293,11 @@ Backend-only flags (these can be set in the config file also).
--filefabric-token-expiry string Token expiry time
--filefabric-url string URL of the Enterprise File Fabric to connect to
--filefabric-version string Version read from the file fabric
--filelu-chunk-size SizeSuffix Chunk size to use for uploading. Used for multipart uploads (default 64Mi)
--filelu-description string Description of the remote
--filelu-encoding Encoding The encoding for the backend (default Slash,LtGt,DoubleQuote,SingleQuote,BackQuote,Dollar,Colon,Question,Asterisk,Pipe,Hash,Percent,BackSlash,CrLf,Del,Ctl,LeftSpace,LeftPeriod,LeftTilde,LeftCrLfHtVt,RightSpace,RightPeriod,RightCrLfHtVt,InvalidUtf8,Dot,SquareBracket,Semicolon,Exclamation)
--filelu-key string Your FileLu Rclone key from My Account
--filelu-upload-cutoff SizeSuffix Cutoff for switching to chunked upload. Any files larger than this will be uploaded in chunks of chunk_size (default 500Mi)
--filen-api-key string API Key for your Filen account (obscured)
--filen-auth-version string Authentication Version (internal use only)
--filen-base-folder-uuid string UUID of Account Root Directory (internal use only)
@@ -27528,11 +27563,7 @@ The following backends have known issues that need more investigation:
<!--- start list_failures - DO NOT EDIT THIS SECTION - use make commanddocs --->
- `TestDropbox` (`dropbox`)
- [`TestBisyncRemoteRemote/normalization`](https://pub.rclone.org/integration-tests/current/dropbox-cmd.bisync-TestDropbox-1.txt)
- `TestSeafile` (`seafile`)
- [`TestBisyncLocalRemote/volatile`](https://pub.rclone.org/integration-tests/current/seafile-cmd.bisync-TestSeafile-1.txt)
- `TestSeafileV6` (`seafile`)
- [`TestBisyncLocalRemote/volatile`](https://pub.rclone.org/integration-tests/current/seafile-cmd.bisync-TestSeafileV6-1.txt)
- Updated: 2026-01-30-010015
- Updated: 2026-03-06-010015
<!--- end list_failures - DO NOT EDIT THIS SECTION - use make commanddocs --->
The following backends either have not been tested recently or have known issues
@@ -29649,6 +29680,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
@@ -44693,6 +44738,28 @@ Properties:
Here are the Advanced options specific to filelu (FileLu Cloud Storage).
#### --filelu-upload-cutoff
Cutoff for switching to chunked upload. Any files larger than this will be uploaded in chunks of chunk_size.
Properties:
- Config: upload_cutoff
- Env Var: RCLONE_FILELU_UPLOAD_CUTOFF
- Type: SizeSuffix
- Default: 500Mi
#### --filelu-chunk-size
Chunk size to use for uploading. Used for multipart uploads.
Properties:
- Config: chunk_size
- Env Var: RCLONE_FILELU_CHUNK_SIZE
- Type: SizeSuffix
- Default: 64Mi
#### --filelu-encoding
The encoding for the backend.
@@ -68058,6 +68125,58 @@ Options:
# 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)
@@ -68088,7 +68207,7 @@ Options:
- 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)
Generated
+150 -10
View File
@@ -1,6 +1,6 @@
rclone(1) User Manual
Nick Craig-Wood
Jan 30, 2026
Mar 06, 2026
NAME
@@ -3277,6 +3277,24 @@ Flags for anything which can copy a file
--streaming-upload-cutoff SizeSuffix Cutoff for switching to chunked upload if file size is unknown, upload starts after reaching cutoff or when file ends (default 100Ki)
-u, --update Skip files that are newer on the destination
Sync Options
Flags used for sync commands
--backup-dir string Make backups into hierarchy based in DIR
--delete-after When synchronizing, delete files on destination after transferring (default)
--delete-before When synchronizing, delete files on destination before transferring
--delete-during When synchronizing, delete files during transfer
--fix-case Force rename of case insensitive dest to match source
--ignore-errors Delete even if there are I/O errors
--list-cutoff int To save memory, sort directory listings on disk above this threshold (default 1000000)
--max-delete int When synchronizing, limit the number of deletes (default -1)
--max-delete-size SizeSuffix When synchronizing, limit the total size of deletes (default off)
--suffix string Suffix to add to changed files
--suffix-keep-extension Preserve the extension when using --suffix
--track-renames When synchronizing, track file renames and do a server-side move if possible
--track-renames-strategy string Strategies to use when synchronizing using track-renames hash|modtime|leaf (default "hash")
Important Options
Important flags useful for most commands
@@ -4607,10 +4625,10 @@ Examples:
// Output: stories/The Quick Brown Fox!.txt
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{YYYYMMDD}"
// Output: stories/The Quick Brown Fox!-20260130
// Output: stories/The Quick Brown Fox!-20260306
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{macfriendlytime}"
// Output: stories/The Quick Brown Fox!-2026-01-30 0825PM
// Output: stories/The Quick Brown Fox!-2026-03-06 0556PM
rclone convmv "stories/The Quick Brown Fox!.txt" --name-transform "all,regex=[\\.\\w]/ab"
// Output: ababababababab/ababab ababababab ababababab ababab!abababab
@@ -5032,6 +5050,15 @@ 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
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
@@ -17856,6 +17883,10 @@ server's modified time. In cases such as a local to remote sync using
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.
@@ -22962,7 +22993,7 @@ Flags for general networking and HTTP stuff.
--tpslimit float Limit HTTP transactions per second to this
--tpslimit-burst int Max burst of transactions for --tpslimit (default 1)
--use-cookies Enable session cookiejar
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.0")
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.2")
Performance
@@ -23416,9 +23447,11 @@ Backend-only flags (these can be set in the config file also).
--filefabric-token-expiry string Token expiry time
--filefabric-url string URL of the Enterprise File Fabric to connect to
--filefabric-version string Version read from the file fabric
--filelu-chunk-size SizeSuffix Chunk size to use for uploading. Used for multipart uploads (default 64Mi)
--filelu-description string Description of the remote
--filelu-encoding Encoding The encoding for the backend (default Slash,LtGt,DoubleQuote,SingleQuote,BackQuote,Dollar,Colon,Question,Asterisk,Pipe,Hash,Percent,BackSlash,CrLf,Del,Ctl,LeftSpace,LeftPeriod,LeftTilde,LeftCrLfHtVt,RightSpace,RightPeriod,RightCrLfHtVt,InvalidUtf8,Dot,SquareBracket,Semicolon,Exclamation)
--filelu-key string Your FileLu Rclone key from My Account
--filelu-upload-cutoff SizeSuffix Cutoff for switching to chunked upload. Any files larger than this will be uploaded in chunks of chunk_size (default 500Mi)
--filen-api-key string API Key for your Filen account (obscured)
--filen-auth-version string Authentication Version (internal use only)
--filen-base-folder-uuid string UUID of Account Root Directory (internal use only)
@@ -25626,11 +25659,7 @@ The following backends have known issues that need more investigation:
- TestDropbox (dropbox)
- TestBisyncRemoteRemote/normalization
- TestSeafile (seafile)
- TestBisyncLocalRemote/volatile
- TestSeafileV6 (seafile)
- TestBisyncLocalRemote/volatile
- Updated: 2026-01-30-010015
- Updated: 2026-03-06-010015
The following backends either have not been tested recently or have
known issues that are deemed unfixable for the time being:
@@ -27690,6 +27719,26 @@ 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 upload
@@ -42261,6 +42310,29 @@ Advanced options
Here are the Advanced options specific to filelu (FileLu Cloud Storage).
--filelu-upload-cutoff
Cutoff for switching to chunked upload. Any files larger than this will
be uploaded in chunks of chunk_size.
Properties:
- Config: upload_cutoff
- Env Var: RCLONE_FILELU_UPLOAD_CUTOFF
- Type: SizeSuffix
- Default: 500Mi
--filelu-chunk-size
Chunk size to use for uploading. Used for multipart uploads.
Properties:
- Config: chunk_size
- Env Var: RCLONE_FILELU_CHUNK_SIZE
- Type: SizeSuffix
- Default: 64Mi
--filelu-encoding
The encoding for the backend.
@@ -65100,6 +65172,74 @@ Options:
Changelog
v1.73.2 - 2026-03-06
See commits
- 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
- 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
@@ -65135,7 +65275,7 @@ See commits
- Support authentication with new bucket restricted application
keys (DianaNites)
- Drive
- Add --drive-metadata-force-expansive-access flag (Nick
- Add --drive-metadata-enforce-expansive-access flag (Nick
Craig-Wood)
- Fix crash when trying to creating shortcut to a Google doc (Nick
Craig-Wood)
-1
View File
@@ -146,7 +146,6 @@ 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)
+1 -3
View File
@@ -44,7 +44,6 @@ 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/)
@@ -118,16 +117,15 @@ 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)
- Tencent Cloud Object Storage (COS) [:page_facing_up:](https://rclone.org/s3/#tencent-cos)
- Uloz.to [:page_facing_up:](https://rclone.org/ulozto/)
- US3 Object Storage [:page_facing_up:](https://rclone.org/s3/#us3)
- 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/)
+1 -2
View File
@@ -32,11 +32,10 @@ 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, and post to annoucements list
- \# announce with forum post, twitter post, patreon post
## Update dependencies
+1 -1
View File
@@ -1 +1 @@
v1.74.0
v1.73.2
+29 -45
View File
@@ -14,7 +14,6 @@ import (
"errors"
"fmt"
"io"
"maps"
"net/http"
"path"
"slices"
@@ -47,7 +46,6 @@ 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"
)
@@ -186,16 +184,6 @@ 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.
@@ -357,22 +345,21 @@ 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"`
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"`
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"`
}
// Fs represents a remote azure server
@@ -394,7 +381,6 @@ 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
@@ -600,7 +586,6 @@ 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),
}
@@ -744,8 +729,8 @@ func parseXMsTags(s string) (map[string]string, error) {
return map[string]string{}, nil
}
out := make(map[string]string)
parts := strings.SplitSeq(s, ",")
for p := range parts {
parts := strings.Split(s, ",")
for _, p := range parts {
p = strings.TrimSpace(p)
if p == "" {
continue
@@ -908,7 +893,9 @@ func assembleCopyParams(ctx context.Context, f *Fs, src fs.Object, srcProps *blo
if meta == nil {
meta = make(map[string]*string, len(userMeta))
}
maps.Copy(meta, userMeta)
for k, v := range userMeta {
meta[k] = v
}
}
// Apply tags if any
if len(mappedTags) > 0 {
@@ -1005,7 +992,9 @@ func (o *Object) applyMappedMetadata(ctx context.Context, src fs.ObjectInfo, ui
if o.tags == nil {
o.tags = make(map[string]string, len(tags))
}
maps.Copy(o.tags, tags)
for k, v := range tags {
o.tags[k] = v
}
}
if mappedModTime != nil {
@@ -1756,26 +1745,18 @@ 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{
@@ -1809,7 +1790,6 @@ 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
})
}
@@ -1879,7 +1859,9 @@ 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))
maps.Copy(options.BlobTags, tags)
for k, v := range tags {
options.BlobTags[k] = v
}
}
if hadMapping {
// Only set metadata explicitly when mapping was requested; otherwise
@@ -2080,7 +2062,9 @@ func (o *Object) Metadata(ctx context.Context) (fs.Metadata, error) {
// Merge user metadata (already lower-cased keys)
metadataMu.Lock()
maps.Copy(m, o.meta)
for k, v := range o.meta {
m[k] = v
}
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"` // 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,omitempty"` // This is a UTC time when this file was uploaded.
}
// GetUploadPartURLRequest is passed to b2_get_upload_part_url
+1 -8
View File
@@ -22,7 +22,6 @@ 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"
)
@@ -500,12 +499,10 @@ 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.
@@ -517,11 +514,7 @@ func (up *largeUpload) Copy(ctx context.Context) (err error) {
part := part // for the closure
g.Go(func() (err error) {
err = up.copyChunk(gCtx, part, reqSize)
if err == nil {
account.Add(reqSize)
}
return err
return up.copyChunk(gCtx, part, reqSize)
})
remaining -= reqSize
}
-8
View File
@@ -237,11 +237,3 @@ 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"`
}
-32
View File
@@ -1362,37 +1362,6 @@ 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
@@ -1605,7 +1574,6 @@ 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,44 +643,6 @@ 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) {
@@ -700,7 +662,6 @@ 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)
}
+153 -74
View File
@@ -1,7 +1,9 @@
package filelu
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
@@ -70,26 +72,37 @@ func (f *Fs) completeMultipart(ctx context.Context, server string, uploadID stri
// 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
)
opts := rest.Opts{
Method: "GET",
Path: "/folder/create",
Parameters: url.Values{
"folder_path": {encodedDir},
"key": {f.opt.Key},
},
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
var result api.CreateFolderResponse
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
return fserrors.ShouldRetry(err), err
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
})
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)
}
@@ -101,29 +114,44 @@ 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),
)
opts := rest.Opts{
Method: "GET",
Path: "/folder/list",
Parameters: url.Values{
"folder_path": {encodedDir},
"key": {f.opt.Key},
},
}
var response api.FolderListResponse
var body []byte
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &response)
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)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to list directory: %w", err)
}
return false, nil
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
})
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
@@ -140,28 +168,42 @@ 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)
opts := rest.Opts{
Method: "GET",
Path: "/folder/delete",
Parameters: url.Values{
"folder_path": {fullPath},
"key": {f.opt.Key},
},
}
deleteURL := fmt.Sprintf("%s/folder/delete?folder_path=%s&key=%s",
f.endpoint,
url.QueryEscape(fullPath),
url.QueryEscape(f.opt.Key),
)
delResp := api.DeleteFolderResponse{}
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &delResp)
req, err := http.NewRequestWithContext(ctx, "GET", deleteURL, nil)
if err != nil {
return false, err
}
resp, err := f.client.Do(req)
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)
}
@@ -178,27 +220,38 @@ 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)
opts := rest.Opts{
Method: "GET",
Path: "/file/direct_link",
Parameters: url.Values{
"file_path": {filePath},
"key": {f.opt.Key},
},
}
apiURL := fmt.Sprintf("%s/file/direct_link?file_path=%s&key=%s",
f.endpoint,
url.QueryEscape(filePath),
url.QueryEscape(f.opt.Key),
)
result := api.FileDirectLinkResponse{}
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
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)
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 false, nil
return shouldRetryHTTP(resp.StatusCode), nil
})
if err != nil {
return "", 0, err
@@ -210,31 +263,39 @@ 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)
opts := rest.Opts{
Method: "GET",
Path: "/file/remove",
Parameters: url.Values{
"file_path": {filePath},
"key": {f.opt.Key},
},
}
apiURL := fmt.Sprintf("%s/file/remove?file_path=%s&key=%s",
f.endpoint,
url.QueryEscape(filePath),
url.QueryEscape(f.opt.Key),
)
result := api.DeleteFileResponse{}
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to delete file: %w", err)
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)
}
if result.Status != 200 {
return false, fmt.Errorf("API error: %s", result.Msg)
}
return false, nil
return shouldRetryHTTP(resp.StatusCode), nil
})
return err
}
@@ -267,28 +328,46 @@ 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()
opts := rest.Opts{
Method: "GET",
Path: "/file/info2",
Parameters: url.Values{
"file_code": {fileCode},
"key": {f.opt.Key},
},
}
result := api.FileInfoResponse{}
apiURL := f.endpoint + "/file/info2?" + u.RawQuery
var body []byte
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
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)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to fetch file info: %w", err)
}
return false, nil
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
})
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
+23 -15
View File
@@ -14,7 +14,6 @@ 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.
@@ -169,15 +168,9 @@ 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) {
opts := rest.Opts{
Method: "GET",
Path: "/upload/server",
Parameters: url.Values{
"key": {f.opt.Key},
},
}
apiURL := fmt.Sprintf("%s/upload/server?key=%s", f.endpoint, url.QueryEscape(f.opt.Key))
var result struct {
Status int `json:"status"`
@@ -187,21 +180,36 @@ func (f *Fs) getUploadServer(ctx context.Context) (string, string, error) {
}
err := f.pacer.Call(func() (bool, error) {
_, err := f.srv.CallJSON(ctx, &opts, nil, &result)
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)
if err != nil {
return shouldRetry(err), fmt.Errorf("failed to get upload server: %w", err)
}
return false, nil
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
})
if err != nil {
return "", "", err
}
if result.Status != 200 {
return "", "", fmt.Errorf("API error: %s", result.Msg)
}
return result.Result, result.SessID, nil
}
+18 -13
View File
@@ -2,6 +2,7 @@ package filelu
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
@@ -14,7 +15,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/rest"
)
// Object describes a FileLu object
@@ -194,14 +194,8 @@ func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
return "", fmt.Errorf("no valid file code found in the remote path")
}
opts := rest.Opts{
Method: "GET",
Path: "/file/info",
Parameters: url.Values{
"file_code": {fileCode},
"key": {o.fs.opt.Key},
},
}
apiURL := fmt.Sprintf("%s/file/info?file_code=%s&key=%s",
o.fs.endpoint, url.QueryEscape(fileCode), url.QueryEscape(o.fs.opt.Key))
var result struct {
Status int `json:"status"`
@@ -210,18 +204,29 @@ 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) {
_, err := o.fs.srv.CallJSON(ctx, &opts, nil, &result)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return false, err
}
resp, err := o.fs.client.Do(req)
if err != nil {
return shouldRetry(err), err
}
return false, nil
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
})
if err != nil {
return "", err
}
if result.Status != 200 || len(result.Result) == 0 {
return "", fmt.Errorf("error: unable to fetch hash: %s", result.Msg)
}
+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"`
EndDate Date `json:"endDate"`
StartDate Date `json:"startDate,omitempty"`
EndDate Date `json:"endDate,omitempty"`
} `json:"ranges,omitempty"`
}
+4 -2
View File
@@ -583,7 +583,9 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
entriesMu.Unlock()
}
for range checkers {
wg.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
for remote := range in {
file := &Object{
fs: f,
@@ -599,7 +601,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] == '/'
+5 -12
View File
@@ -118,19 +118,12 @@ func (c *Client) Authenticate(ctx context.Context) error {
fs.Debugf("icloud", "Authenticating as %s\n", c.appleID)
err := c.Session.SignIn(ctx, c.appleID, c.password)
if err != nil {
return err
}
// If 2FA is required, don't try AuthWithToken yet — the caller
// must complete 2FA first, then call AuthWithToken.
if c.Session.Requires2FA() {
return nil
}
err = c.Session.AuthWithToken(ctx)
if err == nil && c.sessionSaveCallback != nil {
c.sessionSaveCallback(c.Session)
if err == nil {
err = c.Session.AuthWithToken(ctx)
if err == nil && c.sessionSaveCallback != nil {
c.sessionSaveCallback(c.Session)
}
}
return err
}
+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"`
} `json:"data,omitempty"`
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"`
DateChanged time.Time `json:"dateChanged"`
DateModified time.Time `json:"dateModified,omitempty"`
DateChanged time.Time `json:"dateChanged,omitempty"`
Size int64 `json:"size,omitempty"`
LastOpenTime time.Time `json:"lastOpenTime"`
LastOpenTime time.Time `json:"lastOpenTime,omitempty"`
Urls struct {
URLDownload string `json:"url_download"`
} `json:"urls"`
+44 -321
View File
@@ -2,7 +2,6 @@ package api
import (
"context"
"encoding/base64"
"fmt"
"maps"
"net/http"
@@ -10,15 +9,11 @@ import (
"slices"
"strings"
"github.com/google/uuid"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/lib/rest"
)
const iCloudUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.3.1 Safari/605.1.15"
// Session represents an iCloud session
type Session struct {
SessionToken string `json:"session_token"`
@@ -27,22 +22,10 @@ type Session struct {
AccountCountry string `json:"account_country"`
TrustToken string `json:"trust_token"`
ClientID string `json:"client_id"`
AuthAttributes string `json:"auth_attributes"`
FrameID string `json:"frame_id"`
Cookies []*http.Cookie `json:"cookies"`
AccountInfo AccountInfo `json:"account_info"`
srv *rest.Client `json:"-"`
needs2FA bool `json:"-"` // set when SRP signin returns 409
}
// srpInitResponse is the server response from /auth/signin/init
type srpInitResponse struct {
Iteration int `json:"iteration"`
Salt string `json:"salt"`
Protocol string `json:"protocol"`
B string `json:"b"`
C string `json:"c"`
srv *rest.Client `json:"-"`
}
// String returns the session as a string
@@ -74,222 +57,24 @@ func (s *Session) Request(ctx context.Context, opts rest.Opts, request any, resp
if val := resp.Header.Get("scnt"); val != "" {
s.Scnt = val
}
if val := resp.Header.Get("X-Apple-Auth-Attributes"); val != "" {
s.AuthAttributes = val
}
return resp, nil
}
// Requires2FA returns true if the session requires 2FA
func (s *Session) Requires2FA() bool {
if s.needs2FA {
return true
}
return s.AccountInfo.DsInfo != nil && s.AccountInfo.DsInfo.HsaVersion == 2 && s.AccountInfo.HsaChallengeRequired
return s.AccountInfo.DsInfo.HsaVersion == 2 && s.AccountInfo.HsaChallengeRequired
}
// SignIn performs SRP-based authentication against Apple's idmsa endpoint.
// SignIn signs in the session
func (s *Session) SignIn(ctx context.Context, appleID, password string) error {
// Apple's SRP implementation expects a lowercase account name.
// The old plaintext flow didn't need this because the server normalized
// it, but SRP uses the username in client-side proof computation (M1).
appleID = strings.ToLower(appleID)
// Step 1: Initialize the auth session
if err := s.authStart(ctx); err != nil {
return fmt.Errorf("authStart: %w", err)
}
// Step 2: Federate (submit account name)
if err := s.authFederate(ctx, appleID); err != nil {
return fmt.Errorf("authFederate: %w", err)
}
// Step 3: SRP init — send client public value A, get salt + B
client := newSRPClient()
aBase64 := base64.StdEncoding.EncodeToString(client.getABytes())
initResp, err := s.authSRPInit(ctx, aBase64, appleID)
if err != nil {
return fmt.Errorf("authSRPInit: %w", err)
}
// Decode server values
serverB, err := base64.StdEncoding.DecodeString(initResp.B)
if err != nil {
return fmt.Errorf("decode B: %w", err)
}
salt, err := base64.StdEncoding.DecodeString(initResp.Salt)
if err != nil {
return fmt.Errorf("decode salt: %w", err)
}
// Step 4: Derive password key and process the SRP challenge
derivedKey, err := derivePassword(password, salt, initResp.Iteration, initResp.Protocol)
if err != nil {
return fmt.Errorf("derivePassword: %w", err)
}
client.processChallenge([]byte(appleID), derivedKey, salt, serverB)
// Step 5: Complete — send M1, M2 proofs
m1Base64 := base64.StdEncoding.EncodeToString(client.M1)
m2Base64 := base64.StdEncoding.EncodeToString(client.M2)
if err := s.authSRPComplete(ctx, appleID, m1Base64, m2Base64, initResp.C); err != nil {
return fmt.Errorf("authSRPComplete: %w", err)
}
return nil
}
// authStart initializes the SRP auth session by hitting the authorize/signin endpoint.
func (s *Session) authStart(ctx context.Context) error {
if s.FrameID == "" {
s.FrameID = strings.ToLower(uuid.New().String())
}
frameTag := "auth-" + s.FrameID
params := url.Values{}
params.Set("frame_id", frameTag)
params.Set("language", "en_US")
params.Set("skVersion", "7")
params.Set("iframeId", frameTag)
params.Set("client_id", s.ClientID)
params.Set("redirect_uri", "https://www.icloud.com")
params.Set("response_type", "code")
params.Set("response_mode", "web_message")
params.Set("state", frameTag)
params.Set("authVersion", "latest")
opts := rest.Opts{
Method: "GET",
Path: "/authorize/signin",
Parameters: params,
ExtraHeaders: map[string]string{
"Accept": "*/*",
"User-Agent": iCloudUserAgent,
},
RootURL: authEndpoint,
NoResponse: true,
}
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return err
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authStart: unexpected status %s", resp.Status)
}
if val := resp.Header.Get("X-Apple-Auth-Attributes"); val != "" {
s.AuthAttributes = val
}
if val := resp.Header.Get("scnt"); val != "" {
s.Scnt = val
}
if val := resp.Header.Get("X-Apple-ID-Session-Id"); val != "" {
s.SessionID = val
}
return nil
}
// authFederate submits the account name to Apple's federate endpoint.
func (s *Session) authFederate(ctx context.Context, accountName string) error {
values := map[string]any{
"accountName": accountName,
"rememberMe": true,
}
body, err := IntoReader(values)
if err != nil {
return err
}
opts := rest.Opts{
Method: "POST",
Path: "/federate",
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return err
}
_ = resp.Body.Close()
if val := resp.Header.Get("X-Apple-Auth-Attributes"); val != "" {
s.AuthAttributes = val
}
if val := resp.Header.Get("scnt"); val != "" {
s.Scnt = val
}
if val := resp.Header.Get("X-Apple-ID-Session-Id"); val != "" {
s.SessionID = val
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("authFederate: unexpected status %s", resp.Status)
}
return nil
}
// authSRPInit sends the client's public value A to the server and retrieves
// the salt, server public value B, iteration count, protocol, and challenge.
func (s *Session) authSRPInit(ctx context.Context, aBase64, accountName string) (*srpInitResponse, error) {
values := map[string]any{
"a": aBase64,
"accountName": accountName,
"protocols": []string{"s2k", "s2k_fo"},
}
body, err := IntoReader(values)
if err != nil {
return nil, err
}
opts := rest.Opts{
Method: "POST",
Path: "/signin/init",
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: authEndpoint,
Body: body,
}
var initResp srpInitResponse
resp, err := s.srv.CallJSON(ctx, &opts, nil, &initResp)
if err != nil {
return nil, err
}
if val := resp.Header.Get("scnt"); val != "" {
s.Scnt = val
}
if val := resp.Header.Get("X-Apple-ID-Session-Id"); val != "" {
s.SessionID = val
}
return &initResp, nil
}
// authSRPComplete sends the SRP proofs M1 and M2 to complete authentication.
// Returns nil on success (200 or 409/2FA needed).
func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2Base64, c string) error {
trustTokens := []string{}
if s.TrustToken != "" {
trustTokens = []string{s.TrustToken}
}
values := map[string]any{
"accountName": accountName,
"m1": m1Base64,
"m2": m2Base64,
"c": c,
"accountName": appleID,
"password": password,
"rememberMe": true,
"trustTokens": trustTokens,
}
@@ -297,100 +82,21 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
if err != nil {
return err
}
opts := rest.Opts{
Method: "POST",
Path: "/signin/complete",
Parameters: url.Values{"isRememberMeEnabled": {"true"}},
ExtraHeaders: s.getSRPAuthHeaders(),
Path: "/signin",
Parameters: url.Values{},
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
IgnoreStatus: true,
IgnoreStatus: true, // need to handle 409 for hsa2
NoResponse: true,
Body: body,
}
opts.Parameters.Set("isRememberMeEnabled", "true")
_, err = s.Request(ctx, opts, nil, nil)
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return err
}
_ = resp.Body.Close()
return err
// Extract updated headers
if val := resp.Header.Get("X-Apple-Auth-Attributes"); val != "" {
s.AuthAttributes = val
}
if val := resp.Header.Get("X-Apple-Session-Token"); val != "" {
s.SessionToken = val
}
if val := resp.Header.Get("scnt"); val != "" {
s.Scnt = val
}
if val := resp.Header.Get("X-Apple-ID-Session-Id"); val != "" {
s.SessionID = val
}
if val := resp.Header.Get("X-Apple-ID-Account-Country"); val != "" {
s.AccountCountry = val
}
if val := resp.Header.Get("X-Apple-TwoSV-Trust-Token"); val != "" {
s.TrustToken = val
}
switch resp.StatusCode {
case http.StatusOK:
fs.Debugf("icloud", "SRP sign in successful")
return nil
case http.StatusConflict:
// 409 = 2FA required, this is expected
fs.Debugf("icloud", "SRP sign in requires 2FA")
s.needs2FA = true
return nil
case http.StatusForbidden:
return fmt.Errorf("sign in failed: incorrect username or password")
default:
return fmt.Errorf("sign in failed: %s", resp.Status)
}
}
// getAuthOrigin returns the origin URL for auth requests.
// Supports both global (idmsa.apple.com) and China (idmsa.apple.com.cn) endpoints.
func getAuthOrigin() string {
return strings.TrimSuffix(authEndpoint, "/appleauth/auth")
}
// getSRPAuthHeaders returns headers needed for SRP auth requests.
func (s *Session) getSRPAuthHeaders() map[string]string {
frameTag := "auth-" + s.FrameID
authOrigin := getAuthOrigin()
headers := map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
"User-Agent": iCloudUserAgent,
"Origin": authOrigin,
"Referer": authOrigin + "/",
"X-Apple-Widget-Key": s.ClientID,
"X-Apple-OAuth-Client-Id": s.ClientID,
"X-Apple-OAuth-Client-Type": "firstPartyAuth",
"X-Apple-OAuth-Redirect-URI": "https://www.icloud.com",
"X-Apple-OAuth-Require-Grant-Code": "true",
"X-Apple-OAuth-Response-Mode": "web_message",
"X-Apple-OAuth-Response-Type": "code",
"X-Apple-OAuth-State": frameTag,
"X-Apple-Frame-Id": frameTag,
"X-Requested-With": "XMLHttpRequest",
"X-Apple-Mandate-Security-Upgrade": "0",
"X-Apple-I-Require-UE": "true",
"X-Apple-I-FD-Client-Info": `{"U":"` + iCloudUserAgent + `","L":"en-US","Z":"GMT-05:00","V":"1.1","F":""}`,
}
if s.AuthAttributes != "" {
headers["X-Apple-Auth-Attributes"] = s.AuthAttributes
}
if s.Scnt != "" {
headers["scnt"] = s.Scnt
}
if s.SessionID != "" {
headers["X-Apple-ID-Session-Id"] = s.SessionID
}
return headers
}
// AuthWithToken authenticates the session
@@ -429,10 +135,14 @@ func (s *Session) Validate2FACode(ctx context.Context, code string) error {
return err
}
headers := s.GetAuthHeaders(map[string]string{})
headers["scnt"] = s.Scnt
headers["X-Apple-ID-Session-Id"] = s.SessionID
opts := rest.Opts{
Method: "POST",
Path: "/verify/trusteddevice/securitycode",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
ExtraHeaders: headers,
RootURL: authEndpoint,
Body: body,
NoResponse: true,
@@ -452,10 +162,14 @@ func (s *Session) Validate2FACode(ctx context.Context, code string) error {
// TrustSession trusts the session
func (s *Session) TrustSession(ctx context.Context) error {
headers := s.GetAuthHeaders(map[string]string{})
headers["scnt"] = s.Scnt
headers["X-Apple-ID-Session-Id"] = s.SessionID
opts := rest.Opts{
Method: "GET",
Path: "/2sv/trust",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
ExtraHeaders: headers,
RootURL: authEndpoint,
NoResponse: true,
ContentLength: common.Int64(0),
@@ -487,9 +201,25 @@ func (s *Session) ValidateSession(ctx context.Context) error {
}
// GetAuthHeaders returns the authentication headers for the session.
// Used for 2FA validation and trust requests to idmsa.apple.com.
//
// It takes an `overwrite` map[string]string parameter which allows
// overwriting the default headers. It returns a map[string]string.
func (s *Session) GetAuthHeaders(overwrite map[string]string) map[string]string {
headers := s.getSRPAuthHeaders()
headers := map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
"X-Apple-OAuth-Client-Id": s.ClientID,
"X-Apple-OAuth-Client-Type": "firstPartyAuth",
"X-Apple-OAuth-Redirect-URI": "https://www.icloud.com",
"X-Apple-OAuth-Require-Grant-Code": "true",
"X-Apple-OAuth-Response-Mode": "web_message",
"X-Apple-OAuth-Response-Type": "code",
"X-Apple-OAuth-State": s.ClientID,
"X-Apple-Widget-Key": s.ClientID,
"Origin": homeEndpoint,
"Referer": fmt.Sprintf("%s/", homeEndpoint),
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:103.0) Gecko/20100101 Firefox/103.0",
}
maps.Copy(headers, overwrite)
return headers
}
@@ -518,7 +248,7 @@ func GetCommonHeaders(overwrite map[string]string) map[string]string {
"Content-Type": "application/json",
"Origin": baseEndpoint,
"Referer": fmt.Sprintf("%s/", baseEndpoint),
"User-Agent": iCloudUserAgent,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:103.0) Gecko/20100101 Firefox/103.0",
}
maps.Copy(headers, overwrite)
return headers
@@ -551,16 +281,9 @@ func GetCookiesForDomain(url *url.URL, cookies []*http.Cookie) ([]*http.Cookie,
// NewSession creates a new Session instance with default values.
func NewSession() *Session {
session := &Session{
FrameID: strings.ToLower(uuid.New().String()),
}
httpClient := fshttp.NewClient(context.Background())
if tr, ok := httpClient.Transport.(*fshttp.Transport); ok {
tr.SetRequestFilter(func(req *http.Request) {
req.Header.Set("User-Agent", iCloudUserAgent)
})
}
session.srv = rest.NewClient(httpClient).SetRoot(baseEndpoint)
session := &Session{}
session.srv = rest.NewClient(fshttp.NewClient(context.Background())).SetRoot(baseEndpoint)
//session.ClientID = "auth-" + uuid.New().String()
return session
}
-229
View File
@@ -1,229 +0,0 @@
package api
import (
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"math/big"
)
// RFC 5054 2048-bit group parameters for SRP-6a (g=2, SHA-256).
var (
srpN = mustParseBigHex(
"AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050" +
"A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50" +
"E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B8" +
"55F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773B" +
"CA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748" +
"544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB37861602790" +
"04E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8" +
"E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" +
"9E4AFF73")
srpG = big.NewInt(2)
srpNLenBytes = 2048 / 8
srpHashFunc = sha256.New
)
func mustParseBigHex(s string) *big.Int {
b, ok := new(big.Int).SetString(s, 16)
if !ok {
panic("srp: bad hex constant for N")
}
return b
}
// srpClient implements the client side of SRP-6a for Apple's iCloud auth.
type srpClient struct {
a *big.Int // client secret
A *big.Int // client public value
k *big.Int // multiplier
M1 []byte
M2 []byte
K []byte
}
// newSRPClient generates a random 32-byte secret and computes the public value A.
func newSRPClient() *srpClient {
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
panic(fmt.Sprintf("srp: rand.Read failed: %v", err))
}
a := new(big.Int).SetBytes(secret)
A := new(big.Int).Exp(srpG, a, srpN)
k := getMultiplier()
return &srpClient{
a: a,
A: A,
k: k,
}
}
// getABytes returns the padded public value A.
func (c *srpClient) getABytes() []byte {
return padToN(c.A)
}
// processChallenge computes the session key and proof values from the server challenge.
// username is the Apple ID, derivedKey is the output of derivePassword, salt and B come
// from the server's init response (raw bytes, already base64-decoded).
func (c *srpClient) processChallenge(username, derivedKey, salt, serverB []byte) {
B := new(big.Int).SetBytes(serverB)
// Validate B
if B.Cmp(big.NewInt(0)) <= 0 || B.Cmp(srpN) >= 0 {
panic("srp: invalid server-supplied B, must be 1..N-1")
}
x := calculateX(salt, derivedKey)
u := calculateU(c.A, B)
S := calculateS(c.k, x, c.a, B, u)
c.K = calculateK(S)
aBytes := padToN(c.A)
bBytes := padToN(B)
c.M1 = calculateM1(username, salt, aBytes, bBytes, c.K)
c.M2 = calculateM2(aBytes, c.M1, c.K)
}
// derivePassword performs Apple's password key derivation.
// For "s2k": PBKDF2(SHA256(password), salt, iterations, 32, SHA256)
// For "s2k_fo": PBKDF2(hex(SHA256(password)), salt, iterations, 32, SHA256)
func derivePassword(password string, salt []byte, iterations int, protocol string) ([]byte, error) {
passHash := sha256.Sum256([]byte(password))
var passInput string
switch protocol {
case "s2k_fo":
passInput = hex.EncodeToString(passHash[:])
default: // "s2k"
passInput = string(passHash[:])
}
return pbkdf2.Key(sha256.New, passInput, salt, iterations, 32)
}
// padToN pads a big.Int to the SRP group size (256 bytes for 2048-bit).
func padToN(n *big.Int) []byte {
b := n.Bytes()
if len(b) >= srpNLenBytes {
return b
}
padded := make([]byte, srpNLenBytes)
copy(padded[srpNLenBytes-len(b):], b)
return padded
}
func srpHash(data []byte) []byte {
h := srpHashFunc()
h.Write(data)
return h.Sum(nil)
}
func hashToInt(h hash.Hash) *big.Int {
return new(big.Int).SetBytes(h.Sum(nil))
}
// getMultiplier computes k = H(N | pad(g))
func getMultiplier() *big.Int {
h := srpHashFunc()
nBytes := srpN.Bytes()
gBytes := srpG.Bytes()
// pad g to same length as N
for len(gBytes) < len(nBytes) {
gBytes = append([]byte{0}, gBytes...)
}
h.Write(nBytes)
h.Write(gBytes)
return hashToInt(h)
}
// calculateX computes x = H(salt | H(":" | password))
// Apple's variant: NoUserNameInX — username is omitted from the inner hash.
// The "password" here is actually the derived key from derivePassword.
func calculateX(salt, derivedKey []byte) *big.Int {
h := srpHashFunc()
// Apple omits username (NoUserNameInX), only writes ":" + derivedKey
h.Write([]byte(":"))
h.Write(derivedKey)
digest := h.Sum(nil)
h2 := srpHashFunc()
h2.Write(salt)
h2.Write(digest)
return new(big.Int).SetBytes(h2.Sum(nil))
}
// calculateU computes u = H(pad(A) | pad(B))
func calculateU(A, B *big.Int) *big.Int {
h := srpHashFunc()
h.Write(padToN(A))
h.Write(padToN(B))
return hashToInt(h)
}
// calculateS computes the client-side shared secret:
// S = (B - k * g^x) ^ (a + u*x) mod N
func calculateS(k, x, a, B, u *big.Int) []byte {
// g^x mod N
gx := new(big.Int).Exp(srpG, x, srpN)
// k * g^x
kgx := new(big.Int).Mul(k, gx)
// B - k*g^x
diff := new(big.Int).Sub(B, kgx)
// u*x
ux := new(big.Int).Mul(u, x)
// a + u*x
exp := new(big.Int).Add(a, ux)
// (B - k*g^x) ^ (a + u*x) mod N
S := new(big.Int).Exp(diff, exp, srpN)
// Ensure positive
S.Mod(S, srpN)
return padToN(S)
}
// calculateK computes K = H(S)
func calculateK(S []byte) []byte {
return srpHash(S)
}
// calculateM1 computes the client proof (Apple/iCloud variant):
// M1 = H(H(g) XOR H(N) | H(username) | salt | A | B | K)
func calculateM1(username, salt, A, B, K []byte) []byte {
hg := srpHash(padToN(srpG))
hn := srpHash(srpN.Bytes())
hi := srpHash(username)
hxor := make([]byte, len(hg))
for i := range hg {
hxor[i] = hg[i] ^ hn[i]
}
h := srpHashFunc()
h.Write(hxor)
h.Write(hi)
h.Write(salt)
h.Write(A)
h.Write(B)
h.Write(K)
return h.Sum(nil)
}
// calculateM2 computes the server proof: M2 = H(A | M1 | K)
func calculateM2(A, M1, K []byte) []byte {
h := srpHashFunc()
h.Write(A)
h.Write(M1)
h.Write(K)
return h.Sum(nil)
}
-379
View File
@@ -1,379 +0,0 @@
package api
import (
"crypto/sha256"
"encoding/hex"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPadToN(t *testing.T) {
t.Run("pads small value to 256 bytes", func(t *testing.T) {
result := padToN(big.NewInt(1))
assert.Equal(t, srpNLenBytes, len(result))
assert.Equal(t, byte(0), result[0])
assert.Equal(t, byte(1), result[srpNLenBytes-1])
})
t.Run("pads zero to 256 bytes", func(t *testing.T) {
result := padToN(big.NewInt(0))
assert.Equal(t, srpNLenBytes, len(result))
for _, b := range result {
assert.Equal(t, byte(0), b)
}
})
t.Run("preserves value that fills N", func(t *testing.T) {
// Use N itself — already 256 bytes
result := padToN(srpN)
assert.Equal(t, srpNLenBytes, len(result))
assert.Equal(t, srpN.Bytes(), result)
})
t.Run("round-trips through big.Int", func(t *testing.T) {
original := big.NewInt(123456789)
padded := padToN(original)
recovered := new(big.Int).SetBytes(padded)
assert.Equal(t, 0, original.Cmp(recovered))
})
}
func TestGetMultiplier(t *testing.T) {
k := getMultiplier()
// k must be non-zero and less than N
assert.True(t, k.Sign() > 0, "multiplier must be positive")
assert.True(t, k.Cmp(srpN) < 0, "multiplier must be less than N")
// k is deterministic
k2 := getMultiplier()
assert.Equal(t, 0, k.Cmp(k2), "multiplier must be deterministic")
// k = H(N | pad(g)) — verify by manual computation
h := srpHashFunc()
nBytes := srpN.Bytes()
gBytes := srpG.Bytes()
for len(gBytes) < len(nBytes) {
gBytes = append([]byte{0}, gBytes...)
}
h.Write(nBytes)
h.Write(gBytes)
expected := new(big.Int).SetBytes(h.Sum(nil))
assert.Equal(t, 0, expected.Cmp(k), "multiplier must equal H(N|pad(g))")
}
func TestDerivePassword(t *testing.T) {
salt := []byte("test_salt_value!")
password := "test_password"
t.Run("s2k produces 32-byte key", func(t *testing.T) {
key, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
t.Run("s2k_fo produces 32-byte key", func(t *testing.T) {
key, err := derivePassword(password, salt, 1000, "s2k_fo")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
t.Run("s2k and s2k_fo produce different keys", func(t *testing.T) {
key1, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword(password, salt, 1000, "s2k_fo")
require.NoError(t, err)
assert.NotEqual(t, key1, key2, "s2k and s2k_fo must produce different keys")
})
t.Run("deterministic output", func(t *testing.T) {
key1, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
assert.Equal(t, key1, key2)
})
t.Run("different passwords produce different keys", func(t *testing.T) {
key1, err := derivePassword("password1", salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword("password2", salt, 1000, "s2k")
require.NoError(t, err)
assert.NotEqual(t, key1, key2)
})
t.Run("s2k uses raw SHA256 bytes", func(t *testing.T) {
// Verify that s2k uses SHA256(password) as the PBKDF2 input.
// Two passwords with the same SHA256 hash would produce the same key,
// while two passwords with different SHA256 hashes must produce different keys.
key1, err := derivePassword("hello", salt, 10, "s2k")
require.NoError(t, err)
key2, err := derivePassword("world", salt, 10, "s2k")
require.NoError(t, err)
assert.NotEqual(t, key1, key2)
})
t.Run("s2k_fo uses hex-encoded SHA256", func(t *testing.T) {
// For s2k_fo, the PBKDF2 input is hex(SHA256(password)), which is
// a 64-character ASCII string, not raw 32-byte hash.
key, err := derivePassword("hello", salt, 10, "s2k_fo")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
}
func TestCalculateX(t *testing.T) {
salt := []byte("some_salt")
derivedKey := []byte("some_derived_key_value_32_bytes!")
x := calculateX(salt, derivedKey)
// x must be positive and less than the hash output space
assert.True(t, x.Sign() > 0, "x must be positive")
// x is deterministic
x2 := calculateX(salt, derivedKey)
assert.Equal(t, 0, x.Cmp(x2), "x must be deterministic")
// Verify manually: x = H(salt | H(":" | derivedKey))
h1 := srpHashFunc()
h1.Write([]byte(":"))
h1.Write(derivedKey)
inner := h1.Sum(nil)
h2 := srpHashFunc()
h2.Write(salt)
h2.Write(inner)
expected := new(big.Int).SetBytes(h2.Sum(nil))
assert.Equal(t, 0, expected.Cmp(x), "x must equal H(salt | H(\":\" | derivedKey))")
}
func TestCalculateU(t *testing.T) {
A := big.NewInt(12345)
B := big.NewInt(67890)
u := calculateU(A, B)
assert.True(t, u.Sign() > 0, "u must be positive")
// u is deterministic
u2 := calculateU(A, B)
assert.Equal(t, 0, u.Cmp(u2))
// u changes when inputs change
u3 := calculateU(A, big.NewInt(99999))
assert.NotEqual(t, 0, u.Cmp(u3), "u must change when B changes")
// Verify: u = H(pad(A) | pad(B))
h := srpHashFunc()
h.Write(padToN(A))
h.Write(padToN(B))
expected := new(big.Int).SetBytes(h.Sum(nil))
assert.Equal(t, 0, expected.Cmp(u))
}
func TestCalculateK(t *testing.T) {
S := []byte("some_shared_secret_value_32bytes")
K := calculateK(S)
// K is a SHA-256 hash, so 32 bytes
assert.Equal(t, sha256.Size, len(K))
// K is deterministic
K2 := calculateK(S)
assert.Equal(t, K, K2)
// Verify: K = H(S)
expected := srpHash(S)
assert.Equal(t, expected, K)
}
func TestCalculateM1(t *testing.T) {
username := []byte("test@example.com")
salt := []byte("test_salt")
A := make([]byte, srpNLenBytes)
B := make([]byte, srpNLenBytes)
K := make([]byte, 32)
// Fill with non-zero values
A[srpNLenBytes-1] = 0x42
B[srpNLenBytes-1] = 0x43
K[0] = 0x44
m1 := calculateM1(username, salt, A, B, K)
// M1 is a SHA-256 hash
assert.Equal(t, sha256.Size, len(m1))
// M1 is deterministic
m1b := calculateM1(username, salt, A, B, K)
assert.Equal(t, m1, m1b)
// M1 changes when username changes
m1c := calculateM1([]byte("other@example.com"), salt, A, B, K)
assert.NotEqual(t, m1, m1c)
// Verify: M1 = H(H(g) XOR H(N) | H(username) | salt | A | B | K)
hg := srpHash(padToN(srpG))
hn := srpHash(srpN.Bytes())
hi := srpHash(username)
hxor := make([]byte, len(hg))
for i := range hg {
hxor[i] = hg[i] ^ hn[i]
}
h := srpHashFunc()
h.Write(hxor)
h.Write(hi)
h.Write(salt)
h.Write(A)
h.Write(B)
h.Write(K)
expected := h.Sum(nil)
assert.Equal(t, expected, m1)
}
func TestCalculateM2(t *testing.T) {
A := make([]byte, srpNLenBytes)
M1 := make([]byte, 32)
K := make([]byte, 32)
A[srpNLenBytes-1] = 0x01
M1[0] = 0x02
K[0] = 0x03
m2 := calculateM2(A, M1, K)
assert.Equal(t, sha256.Size, len(m2))
// Verify: M2 = H(A | M1 | K)
h := srpHashFunc()
h.Write(A)
h.Write(M1)
h.Write(K)
assert.Equal(t, h.Sum(nil), m2)
}
func TestNewSRPClient(t *testing.T) {
client := newSRPClient()
// A must be non-zero and in range [1, N-1]
assert.True(t, client.A.Sign() > 0, "A must be positive")
assert.True(t, client.A.Cmp(srpN) < 0, "A must be less than N")
// A = g^a mod N
expectedA := new(big.Int).Exp(srpG, client.a, srpN)
assert.Equal(t, 0, expectedA.Cmp(client.A), "A must equal g^a mod N")
// getABytes returns padded A
aBytes := client.getABytes()
assert.Equal(t, srpNLenBytes, len(aBytes))
recoveredA := new(big.Int).SetBytes(aBytes)
assert.Equal(t, 0, client.A.Cmp(recoveredA))
// Two clients should have different secrets (probabilistic, but 2^256 collision chance)
client2 := newSRPClient()
assert.NotEqual(t, 0, client.a.Cmp(client2.a), "two clients must have different secrets")
}
func TestProcessChallenge(t *testing.T) {
// Use a fixed secret for deterministic testing
fixedSecret := make([]byte, 32)
fixedSecret[31] = 0x42 // small non-zero value
a := new(big.Int).SetBytes(fixedSecret)
A := new(big.Int).Exp(srpG, a, srpN)
k := getMultiplier()
client := &srpClient{
a: a,
A: A,
k: k,
}
username := []byte("testuser@apple.com")
derivedKey := make([]byte, 32)
for i := range derivedKey {
derivedKey[i] = byte(i)
}
salt := []byte("fixed_salt_for_test!")
// Compute a valid B: B = (k*v + g^b) mod N where v = g^x mod N
x := calculateX(salt, derivedKey)
v := new(big.Int).Exp(srpG, x, srpN)
bSecret := make([]byte, 32)
bSecret[31] = 0x99
b := new(big.Int).SetBytes(bSecret)
// B = (k*v + g^b) mod N
kv := new(big.Int).Mul(k, v)
gb := new(big.Int).Exp(srpG, b, srpN)
B := new(big.Int).Add(kv, gb)
B.Mod(B, srpN)
serverB := padToN(B)
client.processChallenge(username, derivedKey, salt, serverB)
// M1, M2, K must be populated
assert.NotNil(t, client.M1)
assert.NotNil(t, client.M2)
assert.NotNil(t, client.K)
assert.Equal(t, sha256.Size, len(client.M1))
assert.Equal(t, sha256.Size, len(client.M2))
assert.Equal(t, sha256.Size, len(client.K))
// M1 and M2 must be different
assert.NotEqual(t, client.M1, client.M2)
// Results must be deterministic — run again with same inputs
client2 := &srpClient{
a: new(big.Int).Set(a),
A: new(big.Int).Set(A),
k: new(big.Int).Set(k),
}
client2.processChallenge(username, derivedKey, salt, serverB)
assert.Equal(t, client.M1, client2.M1, "M1 must be deterministic")
assert.Equal(t, client.M2, client2.M2, "M2 must be deterministic")
assert.Equal(t, client.K, client2.K, "K must be deterministic")
// Verify the server could also compute S and get the same K.
// Server computes: S_server = (A * v^u)^b mod N
u := calculateU(A, B)
vu := new(big.Int).Exp(v, u, srpN)
avu := new(big.Int).Mul(A, vu)
avu.Mod(avu, srpN)
sServer := new(big.Int).Exp(avu, b, srpN)
sServer.Mod(sServer, srpN)
kServer := calculateK(padToN(sServer))
assert.Equal(t, client.K, kServer, "client and server must derive the same session key")
}
func TestSRPGroupParameters(t *testing.T) {
// Verify the 2048-bit prime starts with known hex prefix
nHex := hex.EncodeToString(srpN.Bytes())
assert.True(t, len(nHex) > 0)
assert.Equal(t, "ac6bdb41", nHex[:8], "N must start with known prefix")
// g must be 2
assert.Equal(t, int64(2), srpG.Int64())
// N byte length must match expected
assert.Equal(t, 256, srpNLenBytes)
assert.Equal(t, 256, len(srpN.Bytes()))
}
func TestSRPHash(t *testing.T) {
data := []byte("hello world")
hash := srpHash(data)
// Must be SHA-256 output
assert.Equal(t, sha256.Size, len(hash))
// Must equal standard sha256
expected := sha256.Sum256(data)
assert.Equal(t, expected[:], hash)
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !linux
package local
import (
"io"
"os"
)
func newFadviseReadCloser(o *Object, f *os.File, offset, limit int64) io.ReadCloser {
return f
}
+165
View File
@@ -0,0 +1,165 @@
//go:build linux
package local
import (
"io"
"os"
"github.com/rclone/rclone/fs"
"golang.org/x/sys/unix"
)
// fadvise provides means to automate freeing pages in kernel page cache for
// a given file descriptor as the file is sequentially processed (read or
// written).
//
// When copying a file to a remote backend all the file content is read by
// kernel and put to page cache to make future reads faster.
// This causes memory pressure visible in both memory usage and CPU consumption
// and can even cause OOM errors in applications consuming large amounts memory.
//
// In case of an upload to a remote backend, there is no benefits from caching.
//
// fadvise would orchestrate calling POSIX_FADV_DONTNEED
//
// POSIX_FADV_DONTNEED attempts to free cached pages associated
// with the specified region. This is useful, for example, while
// streaming large files. A program may periodically request the
// kernel to free cached data that has already been used, so that
// more useful cached pages are not discarded instead.
//
// Requests to discard partial pages are ignored. It is
// preferable to preserve needed data than discard unneeded data.
// If the application requires that data be considered for
// discarding, then offset and len must be page-aligned.
//
// The implementation may attempt to write back dirty pages in
// the specified region, but this is not guaranteed. Any
// unwritten dirty pages will not be freed. If the application
// wishes to ensure that dirty pages will be released, it should
// call fsync(2) or fdatasync(2) first.
type fadvise struct {
o *Object
fd int
lastPos int64
curPos int64
windowSize int64
freePagesCh chan offsetLength
doneCh chan struct{}
}
type offsetLength struct {
offset int64
length int64
}
const (
defaultAllowPages = 32
defaultWorkerQueueSize = 64
)
func newFadvise(o *Object, fd int, offset int64) *fadvise {
f := &fadvise{
o: o,
fd: fd,
lastPos: offset,
curPos: offset,
windowSize: int64(os.Getpagesize()) * defaultAllowPages,
freePagesCh: make(chan offsetLength, defaultWorkerQueueSize),
doneCh: make(chan struct{}),
}
go f.worker()
return f
}
// sequential configures readahead strategy in Linux kernel.
//
// Under Linux, POSIX_FADV_NORMAL sets the readahead window to the
// default size for the backing device; POSIX_FADV_SEQUENTIAL doubles
// this size, and POSIX_FADV_RANDOM disables file readahead entirely.
func (f *fadvise) sequential(limit int64) bool {
l := int64(0)
if limit > 0 {
l = limit
}
if err := unix.Fadvise(f.fd, f.curPos, l, unix.FADV_SEQUENTIAL); err != nil {
fs.Debugf(f.o, "fadvise sequential failed on file descriptor %d: %s", f.fd, err)
return false
}
return true
}
func (f *fadvise) next(n int) {
f.curPos += int64(n)
f.freePagesIfNeeded()
}
func (f *fadvise) freePagesIfNeeded() {
if f.curPos >= f.lastPos+f.windowSize {
f.freePages()
}
}
func (f *fadvise) freePages() {
f.freePagesCh <- offsetLength{f.lastPos, f.curPos - f.lastPos}
f.lastPos = f.curPos
}
func (f *fadvise) worker() {
for p := range f.freePagesCh {
if err := unix.Fadvise(f.fd, p.offset, p.length, unix.FADV_DONTNEED); err != nil {
fs.Debugf(f.o, "fadvise dontneed failed on file descriptor %d: %s", f.fd, err)
}
}
close(f.doneCh)
}
func (f *fadvise) wait() {
close(f.freePagesCh)
<-f.doneCh
}
type fadviseReadCloser struct {
*fadvise
inner io.ReadCloser
}
// newFadviseReadCloser wraps os.File so that reading from that file would
// remove already consumed pages from kernel page cache.
// In addition to that it instructs kernel to double the readahead window to
// make sequential reads faster.
// See also fadvise.
func newFadviseReadCloser(o *Object, f *os.File, offset, limit int64) io.ReadCloser {
r := fadviseReadCloser{
fadvise: newFadvise(o, int(f.Fd()), offset),
inner: f,
}
// If syscall failed it's likely that the subsequent syscalls to that
// file descriptor would also fail. In that case return the provided os.File
// pointer.
if !r.sequential(limit) {
r.wait()
return f
}
return r
}
func (f fadviseReadCloser) Read(p []byte) (n int, err error) {
n, err = f.inner.Read(p)
f.next(n)
return
}
func (f fadviseReadCloser) Close() error {
f.freePages()
f.wait()
return f.inner.Close()
}
+2 -2
View File
@@ -1168,7 +1168,7 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
var fd *os.File
fd, err = file.Open(o.path)
if fd != nil {
in = fd
in = newFadviseReadCloser(o, fd, 0, 0)
}
} else {
in, err = o.openTranslatedLink(0, -1)
@@ -1374,7 +1374,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
if err != nil {
return
}
wrappedFd := readers.NewLimitedReadCloser(fd, limit)
wrappedFd := readers.NewLimitedReadCloser(newFadviseReadCloser(o, fd, offset, limit), limit)
if offset != 0 {
// seek the object
_, err = fd.Seek(offset, io.SeekStart)
+4 -2
View File
@@ -33,10 +33,12 @@ func TestRemove(t *testing.T) {
assert.True(t, exists())
// close the file in the background
var wg sync.WaitGroup
wg.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
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 := range maxTries {
for i := 0; i < maxTries; i++ {
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"`
} `json:"count,omitempty"`
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"`
} `json:"body,omitempty"`
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"`
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.
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.
}
// 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"` // 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.
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.
}
// 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"` // 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.
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.
}
// 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"` // TODO: undiscovered yet
Locale string `json:"locale,omitempty"` // e.g. "en"
Metadata struct{} `json:"metadata,omitempty"` // 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"`
DeleteTime Time `json:"delete_time"`
CreatedTime Time `json:"created_time,omitempty"`
DeleteTime Time `json:"delete_time,omitempty"`
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"` // updated when renamed or moved
ModifiedTime Time `json:"modified_time,omitempty"` // 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"`
UserModifiedTime Time `json:"user_modified_time,omitempty"`
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"`
} `json:"video,omitempty"`
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"` // TODO
Params struct{} `json:"params,omitempty"` // TODO
CategoryIDs []any `json:"category_ids,omitempty"`
AdSceneType int `json:"ad_scene_type,omitempty"`
Space string `json:"space,omitempty"`
Links struct{} `json:"links"` // TODO
Links struct{} `json:"links,omitempty"` // 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"`
UpdatedTime Time `json:"updated_time"`
CreatedTime Time `json:"created_time,omitempty"`
UpdatedTime Time `json:"updated_time,omitempty"`
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"`
Expiration Time `json:"expiration,omitempty"`
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"` // maybe []*Quota?
Quotas struct{} `json:"quotas,omitempty"` // 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"`
PasswordUpdatedAt Time `json:"password_updated_at"`
CreatedAt Time `json:"created_at,omitempty"`
PasswordUpdatedAt Time `json:"password_updated_at,omitempty"`
}
// 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"`
Expire Time `json:"expire,omitempty"`
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"`
} `json:"data,omitempty"`
}
// 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"`
Expiry time.Time `json:"expiry,omitempty"`
URL string `json:"url,omitempty"` // a link for users to solve captcha
}
+3 -14
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, name, path string) (*api.Task, error) {
func (f *Fs) addURL(ctx context.Context, url, path string) (*api.Task, error) {
req := api.RequestNewTask{
Kind: api.KindOfFile,
UploadType: "UPLOAD_TYPE_URL",
@@ -1617,9 +1617,6 @@ func (f *Fs) addURL(ctx context.Context, url, name, path string) (*api.Task, err
},
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 = ""
@@ -1684,18 +1681,14 @@ var commandHelp = []fs.CommandHelp{{
Short: "Add offline download task for url.",
Long: `This command adds offline download task for url.
Usage examples:
Usage example:
` + "```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.",
@@ -1739,11 +1732,7 @@ 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")
}
filename := ""
if name, ok := opt["name"]; ok {
filename = name
}
return f.addURL(ctx, arg[0], filename, "")
return f.addURL(ctx, arg[0], "")
case "decompress":
filename := ""
if len(arg) > 0 {
-1
View File
@@ -170,7 +170,6 @@ 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"`
+5 -6
View File
@@ -16,12 +16,11 @@ type Authenticator interface {
}
// IbmIamSigner is a structure for signing requests using IBM IAM.
// Requires APIKey and Resource InstanceID
// Requeres APIKey and Resource InstanceID
type IbmIamSigner struct {
APIKey string
InstanceID string
IAMEndpoint string
Auth Authenticator
APIKey string
InstanceID string
Auth Authenticator
}
// SignHTTP signs requests using IBM IAM token.
@@ -30,7 +29,7 @@ func (signer *IbmIamSigner) SignHTTP(ctx context.Context, credentials aws.Creden
if signer.Auth != nil {
authenticator = signer.Auth
} else {
authenticator = &core.IamAuthenticator{ApiKey: signer.APIKey, URL: signer.IAMEndpoint}
authenticator = &core.IamAuthenticator{ApiKey: signer.APIKey}
}
token, err := authenticator.GetToken()
if err != nil {
+3 -5
View File
@@ -23,16 +23,14 @@ func TestSignHTTP(t *testing.T) {
apiKey := "mock-api-key"
instanceID := "mock-instance-id"
token := "mock-iam-token"
iamEndpoint := "https://iamendpoint.com"
mockAuth := &MockAuthenticator{
Token: token,
Error: nil,
}
signer := &IbmIamSigner{
APIKey: apiKey,
InstanceID: instanceID,
IAMEndpoint: iamEndpoint,
Auth: mockAuth,
APIKey: apiKey,
InstanceID: instanceID,
Auth: mockAuth,
}
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
-1
View File
@@ -4,7 +4,6 @@ region:
eu-west-1: Europe West
endpoint:
s3.cubbit.eu: Cubbit DS3 Object Storage endpoint
s3.{tenant_name}.cubbit.eu: Multi-tenant endpoint - replace {tenant_name} with your actual tenant name. Do not select this directly
acl: {}
bucket_acl: true
quirks:
-26
View File
@@ -1,26 +0,0 @@
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
-4
View File
@@ -18,7 +18,3 @@ quirks:
# See: https://issuetracker.google.com/issues/323465186
# So make cutoff very large which it does seem to support
copy_cutoff: 9223372036854775807
# GCS S3 API doesn't fully support Object Lock:
# - Uses x-goog-bypass-governance-retention instead of x-amz-bypass-governance-retention
# - PutObjectLegalHold / GetObjectLegalHold not implemented
object_lock_supported: false
-1
View File
@@ -117,7 +117,6 @@ acl:
This acl is available on IBM Cloud (Infra) and On-Premise IBM COS.
ibm_api_key: true
ibm_resource_instance_id: true
ibm_iam_endpoint: true
bucket_acl: true
quirks:
list_version: 1
+3 -9
View File
@@ -3,17 +3,11 @@ 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-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
s3-eu-central-1.ionoscloud.com: Frankfurt, Germany
s3-eu-central-2.ionoscloud.com: Berlin, Germany
s3-eu-south-2.ionoscloud.com: Logrono, Spain
acl: {}
bucket_acl: true
quirks:
-10
View File
@@ -32,15 +32,5 @@ endpoint:
s3.us-east-va.io.cloud.ovh.us: OVHcloud Vint Hill, Virginia, USA
s3.us-west-or.io.cloud.ovh.us: OVHcloud Hillsboro, Oregon, USA
s3.rbx-archive.io.cloud.ovh.net: OVHcloud Roubaix, France (Cold Archive)
storage_class:
'': Default
EXPRESS_ONEZONE: High Performance storage class
STANDARD: Standard storage class
STANDARD_IA: Standard Infrequent Access storage class
ONEZONE_IA: Standard Infrequent Access storage class
GLACIER: Active Archive storage class
GLACIER_IR: Active Archive storage class
DEEP_ARCHIVE: Cold Archive storage class
INTELLIGENT_TIERING: Standard storage class
acl: {}
bucket_acl: true
+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 the FR-PAR region only.
Available in FR-PAR and NL-AMS regions.
ONEZONE_IA: |-
One Zone - Infrequent Access.
A good choice for storing secondary backup copies or easily re-creatable data.
Available in all regions.
Available in the FR-PAR region only.
bucket_acl: true
quirks:
max_upload_parts: 1000
+14
View File
@@ -0,0 +1,14 @@
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
@@ -1,9 +0,0 @@
name: Zadara
description: Zadara Object Storage
region:
us-east-1: |-
The default region.
Leave location constraint empty.
endpoint: {}
quirks:
force_path_style: true
-44
View File
@@ -1,44 +0,0 @@
name: US3
description: US3 Object Storage
endpoint:
s3-cn-bj.ufileos.com: North China (Beijing 2)
s3-cn-wlcb.ufileos.com: North China (Ulanqab)
s3-cn-sh2.ufileos.com: Shanghai
s3-cn-gd.ufileos.com: South China (Guangzhou)
s3-hk.ufileos.com: Hongkong
s3-us-ca.ufileos.com: United States (Los Angeles)
s3-sg.ufileos.com: Singapore
s3-idn-jakarta.ufileos.com: Indonesia (Jakarta)
s3-tw-tp.ufileos.com: Taiwan (Taipei)
s3-afr-nigeria.ufileos.com: Nigeria (Lagos)
s3-bra-saopaulo.ufileos.com: Brazil (São Paulo)
s3-uae-dubai.ufileos.com: United Arab Emirates (Dubai)
s3-ge-fra.ufileos.com: Germany (Frankfurt)
s3-vn-sng.ufileos.com: Vietnam (Ho Chi Minh City)
s3-us-ws.ufileos.com: United States (Washington)
s3-ind-mumbai.ufileos.com: India (Mumbai)
s3-kr-seoul.ufileos.com: Seoul (South Korea)
s3-jpn-tky.ufileos.com: Japan (Tokyo)
s3-th-bkk.ufileos.com: Bangkok (Thailand)
s3-uk-london.ufileos.com: United Kingdom (London)
s3-rus-mosc.ufileos.com: Russia (Moscow)
s3-cn-guiyang1.ufileos.com: Guiyang 1
s3-pk-khi.ufileos.com: Pakistan
acl:
private: |-
Owner gets FULL_CONTROL.
No one else has access rights (default).
public-read: |-
Owner gets FULL_CONTROL.
The AllUsers group gets READ access.
storage_class:
'': Default
STANDARD: Standard storage class
ARCHIVE: Archive storage mode
STANDARD_IA: Infrequent access storage mode
bucket_acl: true
quirks:
list_version: 1
use_multipart_etag: false
use_already_exists: false
list_url_encode: true
-5
View File
@@ -32,8 +32,6 @@ 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"`
ObjectLockSupported *bool `yaml:"object_lock_supported,omitempty"`
CopyCutoff *int64 `yaml:"copy_cutoff,omitempty"`
MaxUploadParts *int `yaml:"max_upload_parts,omitempty"`
MinChunkSize *int64 `yaml:"min_chunk_size,omitempty"`
@@ -53,7 +51,6 @@ type Provider struct {
// other
IBMApiKey bool `yaml:"ibm_api_key,omitempty"`
IBMResourceInstanceID bool `yaml:"ibm_resource_instance_id,omitempty"`
IBMIAMEndpoint bool `yaml:"ibm_iam_endpoint,omitempty"`
// advanced
BucketACL bool `yaml:"bucket_acl,omitempty"`
@@ -226,8 +223,6 @@ func constructProviders(options fs.Options, providerMap map[string]*Provider) st
addBool(opt, p, p.IBMApiKey)
case "ibm_resource_instance_id":
addBool(opt, p, p.IBMResourceInstanceID)
case "ibm_iam_endpoint":
addBool(opt, p, p.IBMIAMEndpoint)
case "leave_parts_on_error":
addBool(opt, p, p.LeavePartsOnError)
case "sts_endpoint":
+6 -438
View File
@@ -4,7 +4,6 @@ package s3
//go:generate go run gen_setfrom.go -o setfrom.go
import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
@@ -64,7 +63,6 @@ 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"
)
@@ -830,123 +828,6 @@ use |-vv| to see the debug level logs.
}, {
Name: "ibm_resource_instance_id",
Help: "IBM service instance id",
}, {
Name: "ibm_iam_endpoint",
Help: "IBM IAM Endpoint to use for authentication.\n\nLeave blank to use the default public endpoint.",
Advanced: true,
}, {
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,
}, {
Name: "object_lock_supported",
Help: `Whether the provider supports S3 Object Lock.
This should be true, false or left unset to use the default for the provider.
Set to false for providers that don't fully support the S3 Object Lock API
(e.g. GCS which uses non-standard headers for bypass governance retention
and doesn't implement Legal Hold via the S3 API).
`,
Default: fs.Tristate{},
Advanced: true,
},
}}))
}
@@ -1041,21 +922,6 @@ 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
@@ -1124,16 +990,8 @@ type Options struct {
DirectoryBucket bool `config:"directory_bucket"`
IBMAPIKey string `config:"ibm_api_key"`
IBMInstanceID string `config:"ibm_resource_instance_id"`
IBMIAMEndpoint string `config:"ibm_iam_endpoint"`
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"`
ObjectLockSupported fs.Tristate `config:"object_lock_supported"`
}
// Fs represents a remote s3 server
@@ -1178,11 +1036,6 @@ 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
@@ -1203,21 +1056,6 @@ 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)
@@ -1560,7 +1398,7 @@ func s3Connection(ctx context.Context, opt *Options, client *http.Client) (s3Cli
fs.Debugf(nil, "Using v2 auth")
if opt.Provider == "IBMCOS" && opt.IBMAPIKey != "" && opt.IBMInstanceID != "" {
options = append(options, func(s3Opt *s3.Options) {
s3Opt.HTTPSignerV4 = &IbmIamSigner{APIKey: opt.IBMAPIKey, InstanceID: opt.IBMInstanceID, IAMEndpoint: opt.IBMIAMEndpoint}
s3Opt.HTTPSignerV4 = &IbmIamSigner{APIKey: opt.IBMAPIKey, InstanceID: opt.IBMInstanceID}
})
} else {
options = append(options, func(s3Opt *s3.Options) {
@@ -1740,7 +1578,6 @@ func setQuirks(opt *Options, provider *Provider) {
set(&opt.UseUnsignedPayload, true, provider.Quirks.UseUnsignedPayload)
set(&opt.UseXID, true, provider.Quirks.UseXID)
set(&opt.SignAcceptEncoding, true, provider.Quirks.SignAcceptEncoding)
set(&opt.ObjectLockSupported, true, provider.Quirks.ObjectLockSupported)
}
// setRoot changes the root of the Fs
@@ -1827,10 +1664,6 @@ 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
//
@@ -1855,9 +1688,6 @@ 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
}
@@ -2812,9 +2642,8 @@ 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),
ObjectLockEnabledForBucket: &f.opt.BucketObjectLockEnabled,
Bucket: &bucket,
ACL: types.BucketCannedACL(f.opt.BucketACL),
}
if f.opt.LocationConstraint != "" {
req.CreateBucketConfiguration = &types.CreateBucketConfiguration{
@@ -2933,24 +2762,6 @@ 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)
}
@@ -3027,8 +2838,6 @@ 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)
@@ -3063,11 +2872,6 @@ 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
})
}
@@ -3140,15 +2944,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
setFrom_s3CopyObjectInput_s3PutObjectInput(&req, ui.req)
// 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 {
if ci.Metadata {
req.MetadataDirective = types.MetadataDirectiveReplace
}
@@ -3156,21 +2952,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
if err != nil {
return nil, err
}
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
return f.NewObject(ctx, remote)
}
// Hashes returns the supported hash sets.
@@ -4049,19 +3831,6 @@ 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
@@ -4623,31 +4392,8 @@ func (o *Object) uploadMultipart(ctx context.Context, src fs.ObjectInfo, in io.R
return wantETag, gotETag, versionID, s3cw.ui, nil
}
// bufferForObjectLockMD5 buffers the body and computes Content-MD5 when
// Object Lock parameters are set on the request. AWS S3 requires Content-MD5
// for PutObject with Object Lock params and cannot compute it automatically
// from a non-seekable io.Reader.
// See: https://github.com/aws/aws-sdk-go-v2/discussions/2960
func bufferForObjectLockMD5(req *s3.PutObjectInput, in io.Reader) (io.Reader, error) {
if req.ObjectLockMode == "" && req.ObjectLockRetainUntilDate == nil && req.ObjectLockLegalHoldStatus == "" {
return in, nil
}
buf, err := io.ReadAll(in)
if err != nil {
return nil, fmt.Errorf("failed to read body for Content-MD5: %w", err)
}
md5sum := md5.Sum(buf)
md5base64 := base64.StdEncoding.EncodeToString(md5sum[:])
req.ContentMD5 = &md5base64
return bytes.NewReader(buf), nil
}
// Upload a single part using PutObject
func (o *Object) uploadSinglepartPutObject(ctx context.Context, req *s3.PutObjectInput, size int64, in io.Reader) (etag string, lastModified time.Time, versionID *string, err error) {
in, err = bufferForObjectLockMD5(req, in)
if err != nil {
return etag, lastModified, nil, err
}
req.Body = io.NopCloser(in)
var options = []func(*s3.Options){}
if o.fs.opt.UseUnsignedPayload.Value {
@@ -4678,11 +4424,6 @@ func (o *Object) uploadSinglepartPutObject(ctx context.Context, req *s3.PutObjec
// Upload a single part using a presigned request
func (o *Object) uploadSinglepartPresignedRequest(ctx context.Context, req *s3.PutObjectInput, size int64, in io.Reader) (etag string, lastModified time.Time, versionID *string, err error) {
// Content-MD5 must be set before signing so it's included in the presigned URL.
in, err = bufferForObjectLockMD5(req, in)
if err != nil {
return etag, lastModified, nil, err
}
// Create the presigned request
putReq, err := s3.NewPresignClient(o.fs.c).PresignPutObject(ctx, req, s3.WithPresignExpires(15*time.Minute))
if err != nil {
@@ -4808,26 +4549,6 @@ 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
}
@@ -4893,25 +4614,6 @@ 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()
@@ -5035,14 +4737,6 @@ 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
}
@@ -5060,9 +4754,6 @@ 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)
@@ -5070,120 +4761,6 @@ 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)
@@ -5227,7 +4804,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)+10)
metadata = make(fs.Metadata, len(o.meta)+7)
for k, v := range o.meta {
switch k {
case metaMtime:
@@ -5262,15 +4839,6 @@ 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
-278
View File
@@ -498,288 +498,10 @@ func (f *Fs) InternalTestVersions(t *testing.T) {
// Purge gets tested later
}
func (f *Fs) InternalTestObjectLock(t *testing.T) {
if !f.opt.ObjectLockSupported.Value {
t.Skip("Object Lock not supported by this provider (quirk object_lock_supported = false)")
}
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"])
})
t.Run("Multipart", func(t *testing.T) {
// Force multipart upload by setting a very low cutoff
oldCutoff := f.opt.UploadCutoff
f.opt.UploadCutoff = fs.SizeSuffix(1)
f.opt.ObjectLockMode = "GOVERNANCE"
f.opt.ObjectLockRetainUntilDate = retainUntilDate.Format(time.RFC3339)
defer func() {
f.opt.UploadCutoff = oldCutoff
f.opt.ObjectLockMode = ""
f.opt.ObjectLockRetainUntilDate = ""
}()
contents := random.String(100)
item := fstest.NewItem("test-object-lock-multipart", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
removeLocked(t, obj)
}()
o := obj.(*Object)
gotMetadata, err := o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "GOVERNANCE", gotMetadata["object-lock-mode"])
})
t.Run("Presigned", func(t *testing.T) {
// Use presigned request upload path
f.opt.UsePresignedRequest = true
f.opt.ObjectLockMode = "GOVERNANCE"
f.opt.ObjectLockRetainUntilDate = retainUntilDate.Format(time.RFC3339)
defer func() {
f.opt.UsePresignedRequest = false
f.opt.ObjectLockMode = ""
f.opt.ObjectLockRetainUntilDate = ""
}()
contents := random.String(100)
item := fstest.NewItem("test-object-lock-presigned", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
removeLocked(t, obj)
}()
o := obj.(*Object)
gotMetadata, err := o.Metadata(ctx)
require.NoError(t, err)
assert.Equal(t, "GOVERNANCE", gotMetadata["object-lock-mode"])
})
}
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,7 +5,6 @@ import (
"context"
"net/http"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/rclone/rclone/fs"
@@ -93,87 +92,3 @@ 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]any
var claims map[string]interface{}
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 any) (*http.Response, error) {
func (f *Fs) callAPI(ctx context.Context, method, path string, response interface{}) (*http.Response, error) {
token, err := f.refreshJWTToken(ctx)
if err != nil {
return nil, err
+3 -2
View File
@@ -7,7 +7,6 @@ import (
"context"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"path"
@@ -204,7 +203,9 @@ 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)
maps.Copy(opts.ExtraHeaders, partURL.Headers)
for k, v := range partURL.Headers {
opts.ExtraHeaders[k] = v
}
}
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"`
ModifiedAt time.Time `json:"ClientModifiedDate"`
CreatedAt time.Time `json:"CreationDate,omitempty"`
ModifiedAt time.Time `json:"ClientModifiedDate,omitempty"`
IsHidden bool `json:"IsHidden,omitempty"`
Size int64 `json:"FileSizeBytes,omitempty"`
Type string `json:"odata.type,omitempty"`
+3 -21
View File
@@ -225,7 +225,6 @@ type Fs struct {
hasOCMD5 bool // set if can use owncloud style checksums for MD5
hasOCSHA1 bool // set if can use owncloud style checksums for SHA1
hasMESHA1 bool // set if can use fastmail style checksums for SHA1
useStandardProps bool // set if should use standard props for PROPFIND
ntlmAuthMu sync.Mutex // mutex to serialize NTLM auth roundtrips
chunksUploadURL string // upload URL for nextcloud chunked
canChunk bool // set if nextcloud and nextcloud_chunk_size is set
@@ -349,14 +348,11 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string, depth string)
ExtraHeaders: map[string]string{
"Depth": depth,
},
CheckRedirect: rest.PreserveMethodRedirectFn,
NoRedirect: true,
}
if f.hasOCMD5 || f.hasOCSHA1 {
opts.Body = bytes.NewBuffer(owncloudProps)
} else if f.useStandardProps {
opts.Body = bytes.NewBuffer(standardProps)
}
// Note: According to WebDAV RFC 4918, empty PROPFIND body defaults to allprop
var result api.Multistatus
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
@@ -614,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() (any, error) {
_, err, _ := f.authSingleflight.Do("bearerToken", func() (interface{}, error) {
if len(f.opt.BearerTokenCommand) == 0 {
return nil, nil
}
@@ -715,7 +711,6 @@ func (f *Fs) setQuirks(ctx context.Context, vendor string) error {
f.precision = time.Second
f.useOCMtime = true
case "other":
f.useStandardProps = true
default:
fs.Debugf(f, "Unknown vendor %q", vendor)
}
@@ -764,23 +759,13 @@ var owncloudProps = []byte(`<?xml version="1.0"?>
<d:getlastmodified />
<d:getcontentlength />
<d:resourcetype />
<d:getcontenttype />
<oc:checksums />
<oc:permissions />
</d:prop>
</d:propfind>
`)
var standardProps = []byte(`<?xml version="1.0"?>
<d:propfind xmlns:d="DAV:">
<d:prop>
<d:displayname/>
<d:getlastmodified/>
<d:getcontentlength/>
<d:resourcetype/>
</d:prop>
</d:propfind>
`)
// list the objects into the function supplied
//
// If directories is set it only sends directories
@@ -802,10 +787,7 @@ func (f *Fs) listAll(ctx context.Context, dir string, directoriesOnly bool, file
}
if f.hasOCMD5 || f.hasOCSHA1 {
opts.Body = bytes.NewBuffer(owncloudProps)
} else if f.useStandardProps {
opts.Body = bytes.NewBuffer(standardProps)
}
// Note: According to WebDAV RFC 4918, empty PROPFIND body defaults to `allprop`
var result api.Multistatus
var resp *http.Response
err = f.pacer.Call(func() (bool, error) {
+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"`
Attributes WriteAttributes `json:"attributes,omitempty"`
ID string `json:"id,omitempty"`
Type string `json:"type"`
}
+2 -2
View File
@@ -92,10 +92,10 @@ func TestCountWriterConcurrent(t *testing.T) {
var wg sync.WaitGroup
wg.Add(goroutines)
for range goroutines {
for g := 0; g < goroutines; g++ {
go func() {
defer wg.Done()
for range loops {
for i := 0; i < loops; i++ {
n, err := cw.Write(data)
assert.NoError(t, err)
assert.Equal(t, chunkSize, n)
+3 -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,7 +153,6 @@ 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
+53 -65
View File
@@ -1,77 +1,65 @@
//go:build none
// Create the help text for the rc
//
// Run with go generate ./cmd/bisync (defined in rc.go)
package main
package bisync
import (
"fmt"
"os"
"strconv"
"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"
)
// 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())
func makeHelp(help string) string {
replacer := strings.NewReplacer(
"|", "`",
"{MAXDELETE}", strconv.Itoa(DefaultMaxDelete),
"{CHECKFILE}", DefaultCheckFilename,
// "{WORKDIR}", DefaultWorkdir,
)
return replacer.Replace(help)
}
// RcHelp returns the rc help
func RcHelp() string {
return wordwrap.String(bisync.MakeHelp(`This takes the following parameters:
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
- 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.
`), 76)
}
for more information.`)
// 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()
}
var longHelp = shortHelp + makeHelp(`
// 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()
}
[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.`)
+5 -14
View File
@@ -98,26 +98,15 @@ func (b *bisyncRun) lockFileIsExpired() bool {
rdf, err := os.Open(b.lockFile)
b.handleErr(b.lockFile, "error reading lock file", err, true, true)
dec := json.NewDecoder(rdf)
var decodeErr error
for {
if err := dec.Decode(&b.lockFileOpt.data); err != nil {
if err != io.EOF {
decodeErr = err
fs.Errorf(b.lockFile, "err: %v", err)
}
break
}
}
b.handleErr(b.lockFile, "error closing file", rdf.Close(), true, true)
if decodeErr != nil {
if b.opt.MaxLock < basicallyforever {
fs.Infof(b.lockFile, Color(terminal.YellowFg, "Lock file is unreadable (decode error: %v) and --max-lock is set. Treating as expired."), decodeErr)
markFailed(b.listing1)
markFailed(b.listing2)
return true
}
fs.Errorf(b.lockFile, Color(terminal.RedFg, "Lock file exists, but contents are unreadable. (decode error: %v)"), decodeErr)
return false
}
if !b.lockFileOpt.data.TimeExpires.IsZero() && b.lockFileOpt.data.TimeExpires.Before(time.Now()) {
fs.Infof(b.lockFile, Color(terminal.GreenFg, "Lock file found, but it expired at %v. Will delete it and proceed."), b.lockFileOpt.data.TimeExpires)
markFailed(b.listing1) // listing is untrusted so force revert to prior (if --recover) or create new ones (if --resync)
@@ -139,7 +128,9 @@ func (b *bisyncRun) startLockRenewal() func() {
}
stopLockRenewal := make(chan struct{})
var wg sync.WaitGroup
wg.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(time.Duration(b.opt.MaxLock) - time.Minute)
for {
select {
@@ -150,7 +141,7 @@ func (b *bisyncRun) startLockRenewal() func() {
return
}
}
})
}()
return func() {
close(stopLockRenewal)
wg.Wait()
-80
View File
@@ -1,80 +0,0 @@
package bisync
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newTestLockfileBisyncRun(t *testing.T, lockContent string, maxLock fs.Duration) *bisyncRun {
t.Helper()
dir := t.TempDir()
lockPath := filepath.Join(dir, "test.lck")
require.NoError(t, os.WriteFile(lockPath, []byte(lockContent), 0600))
listing1 := filepath.Join(dir, "listing1")
listing2 := filepath.Join(dir, "listing2")
require.NoError(t, os.WriteFile(listing1, []byte(""), 0600))
require.NoError(t, os.WriteFile(listing2, []byte(""), 0600))
return &bisyncRun{
lockFile: lockPath,
opt: &Options{MaxLock: maxLock},
listing1: listing1,
listing2: listing2,
}
}
func TestLockfileIsExpired_UnreadableWithMaxLock(t *testing.T) {
b := newTestLockfileBisyncRun(t, "not json!!!", fs.Duration(5*time.Minute))
assert.True(t, b.lockFileIsExpired(), "unreadable lockfile with --max-lock set should be treated as expired")
}
func TestLockfileIsExpired_UnreadableWithoutMaxLock(t *testing.T) {
b := newTestLockfileBisyncRun(t, "not json!!!", basicallyforever)
assert.False(t, b.lockFileIsExpired(), "unreadable lockfile without --max-lock should not be treated as expired")
}
func TestLockfileIsExpired_ValidExpired(t *testing.T) {
data := struct {
Session string
PID string
TimeRenewed time.Time
TimeExpires time.Time
}{
Session: "test",
PID: "12345",
TimeRenewed: time.Now().Add(-10 * time.Minute),
TimeExpires: time.Now().Add(-5 * time.Minute),
}
content, err := json.Marshal(data)
require.NoError(t, err)
b := newTestLockfileBisyncRun(t, string(content), fs.Duration(5*time.Minute))
assert.True(t, b.lockFileIsExpired(), "valid lockfile with past expiry should be expired")
}
func TestLockfileIsExpired_ValidNotExpired(t *testing.T) {
data := struct {
Session string
PID string
TimeRenewed time.Time
TimeExpires time.Time
}{
Session: "test",
PID: "12345",
TimeRenewed: time.Now(),
TimeExpires: time.Now().Add(10 * time.Minute),
}
content, err := json.Marshal(data)
require.NoError(t, err)
b := newTestLockfileBisyncRun(t, string(content), fs.Duration(5*time.Minute))
assert.False(t, b.lockFileIsExpired(), "valid lockfile with future expiry should not be expired")
}
+25 -124
View File
@@ -1,22 +1,16 @@
//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 addRC() {
func init() {
rc.Add(rc.Call{
Path: "sync/bisync",
AuthRequired: true,
@@ -26,42 +20,6 @@ func addRC() {
})
}
//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)
@@ -83,86 +41,56 @@ func rcBisync(ctx context.Context, in rc.Params) (out rc.Params, err error) {
}
if opt.Resync, err = in.GetBool("resync"); rc.NotErrParamNotFound(err) {
fs.Debugf("resync", "optional parameter is missing. using default value: %v", opt.Resync)
return
}
if opt.CheckAccess, err = in.GetBool("checkAccess"); rc.NotErrParamNotFound(err) {
fs.Debugf("checkAccess", "optional parameter is missing. using default value: %v", opt.CheckAccess)
return
}
if opt.Force, err = in.GetBool("force"); rc.NotErrParamNotFound(err) {
fs.Debugf("force", "optional parameter is missing. using default value: %v", opt.Force)
return
}
if opt.CreateEmptySrcDirs, err = in.GetBool("createEmptySrcDirs"); rc.NotErrParamNotFound(err) {
fs.Debugf("createEmptySrcDirs", "optional parameter is missing. using default value: %v", opt.CreateEmptySrcDirs)
return
}
if opt.RemoveEmptyDirs, err = in.GetBool("removeEmptyDirs"); rc.NotErrParamNotFound(err) {
fs.Debugf("removeEmptyDirs", "optional parameter is missing. using default value: %v", opt.RemoveEmptyDirs)
return
}
if opt.NoCleanup, err = in.GetBool("noCleanup"); rc.NotErrParamNotFound(err) {
fs.Debugf("noCleanup", "optional parameter is missing. using default value: %v", opt.NoCleanup)
return
}
if opt.IgnoreListingChecksum, err = in.GetBool("ignoreListingChecksum"); rc.NotErrParamNotFound(err) {
fs.Debugf("ignoreListingChecksum", "optional parameter is missing. using default value: %v", opt.IgnoreListingChecksum)
return
}
if opt.Resilient, err = in.GetBool("resilient"); rc.NotErrParamNotFound(err) {
fs.Debugf("resilient", "optional parameter is missing. using default value: %v", opt.Resilient)
return
}
if opt.CheckFilename, err = in.GetString("checkFilename"); rc.NotErrParamNotFound(err) {
opt.CheckFilename = DefaultCheckFilename
fs.Debugf("checkFilename", "optional parameter is missing. using default value: %v", opt.CheckFilename)
return
}
if opt.FiltersFile, err = in.GetString("filtersFile"); rc.NotErrParamNotFound(err) {
fs.Debugf("filtersFile", "optional parameter is missing. using default value: %v", opt.FiltersFile)
return
}
if opt.Workdir, err = in.GetString("workdir"); rc.NotErrParamNotFound(err) {
// "" sets correct default later
fs.Debugf("workdir", "optional parameter is missing. using default value: %v", opt.Workdir)
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.BackupDir1, err = in.GetString("backupdir1"); 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)
}
if opt.BackupDir2, err = in.GetString("backupdir2"); rc.NotErrParamNotFound(err) {
return
}
if err = setEnum(in, "checkSync", "true", opt.CheckSync.Set); err != nil {
checkSync, err := in.GetString("checkSync")
if rc.NotErrParamNotFound(err) {
return nil, err
}
if err = setEnum(in, "resyncMode", opt.ResyncMode.String(), opt.ResyncMode.Set); err != nil {
if checkSync == "" {
checkSync = "true"
}
if err := opt.CheckSync.Set(checkSync); 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 {
@@ -177,33 +105,6 @@ 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),
"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
return rc.Params{"output": string(output)}, err
}
-61
View File
@@ -1,61 +0,0 @@
<!--- 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.
+4 -2
View File
@@ -361,7 +361,9 @@ func StartStats() func() {
}
stopStats := make(chan struct{})
var wg sync.WaitGroup
wg.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(*statsInterval)
for {
select {
@@ -372,7 +374,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 range int(totalWait / individualWait) {
for i := 0; i < int(totalWait/individualWait); i++ {
ok = fn()
if ok {
return ok
+14 -16
View File
@@ -1,8 +1,7 @@
Rclone @ allows Linux, FreeBSD, macOS and Windows to
mount any of Rclone's cloud storage systems as a file system with FUSE.
First set up your remote using `rclone config`. Check it works with `rclone ls`
etc.
First set up your remote using `rclone config`. Check it works with `rclone ls` etc.
On Linux and macOS, you can run mount in either foreground or background (aka
daemon) mode. Mount runs in foreground mode by default. Use the `--daemon` flag
@@ -30,8 +29,8 @@ The following examples will mount to an automatically assigned drive,
to specific drive letter `X:`, to path `C:\path\parent\mount`
(where parent directory or drive must exist, and mount must **not** exist,
and is not supported when [mounting as a network drive](#mounting-modes-on-windows)),
and the last example will mount as network share `\\cloud\remote` and map it to
an automatically assigned drive:
and the last example will mount as network share `\\cloud\remote` and map it to an
automatically assigned drive:
```console
rclone @ remote:path/to/files *
@@ -137,8 +136,8 @@ rclone @ remote:path/to/files X: --volname \\server\share
You may also specify the network share UNC path as the mountpoint itself. Then rclone
will automatically assign a drive letter, same as with `*` and use that as
mountpoint, and instead use the UNC path specified as the volume name, as if it
were specified with the `--volname` option. This will also implicitly set
mountpoint, and instead use the UNC path specified as the volume name, as if it were
specified with the `--volname` option. This will also implicitly set
the `--network-mode` option. This means the following two examples have same result:
```console
@@ -269,7 +268,7 @@ does not suffer from the same limitations.
Mounting on macOS can be done either via [built-in NFS server](/commands/rclone_serve_nfs/),
[macFUSE](https://osxfuse.github.io/) (also known as osxfuse) or
[FUSE-T](https://www.fuse-t.org/). macFUSE is a traditional FUSE driver utilizing
[FUSE-T](https://www.fuse-t.org/).macFUSE is a traditional FUSE driver utilizing
a macOS kernel extension (kext). FUSE-T is an alternative FUSE system which
"mounts" via an NFSv4 local server.
@@ -312,13 +311,13 @@ current as of FUSE-T version 1.0.14.
As per the [FUSE-T wiki](https://github.com/macos-fuse-t/fuse-t/wiki#caveats):
> File access and modification times cannot be set separately as it seems to be
> an issue with the NFS client which always modifies both. Can be reproduced
> with `touch -m` and `touch -a` commands
> File access and modification times cannot be set separately as it seems to be an
> issue with the NFS client which always modifies both. Can be reproduced with
> 'touch -m' and 'touch -a' commands
This means that viewing files with various tools, notably macOS Finder, will
cause rlcone to update the modification time of the file. This may make rclone
upload a full new copy of the file.
This means that viewing files with various tools, notably macOS Finder, will cause
rlcone to update the modification time of the file. This may make rclone upload a
full new copy of the file.
##### Read Only mounts
@@ -332,10 +331,9 @@ On newer versions of Ubuntu, you may encounter the following error when running
> NOTICE: mount helper error: fusermount3: mount failed: Permission denied
> CRITICAL: Fatal error: failed to mount FUSE fs: fusermount: exit status 1
This may be due to newer [Apparmor](https://wiki.ubuntu.com/AppArmor) restrictions,
which can be disabled with `sudo aa-disable /usr/bin/fusermount3` (you may need
to `sudo apt install apparmor-utils` beforehand).
which can be disabled with `sudo aa-disable /usr/bin/fusermount3` (you may need to
`sudo apt install apparmor-utils` beforehand).
### Limitations
+4 -2
View File
@@ -41,7 +41,9 @@ func startProgress() func() {
}
var wg sync.WaitGroup
wg.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
progressInterval := defaultProgressInterval
if ShowStats() && *statsInterval > 0 {
progressInterval = *statsInterval
@@ -63,7 +65,7 @@ func startProgress() func() {
return
}
}
})
}()
return func() {
close(stopStats)
wg.Wait()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 704 B

-27
View File
@@ -3,7 +3,6 @@ package http
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
@@ -58,9 +57,6 @@ 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})
}
@@ -202,11 +198,9 @@ 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)
@@ -231,27 +225,6 @@ 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,7 +1,6 @@
package http
import (
"compress/gzip"
"context"
"flag"
"io"
@@ -298,116 +297,6 @@ 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",
+8 -4
View File
@@ -66,9 +66,11 @@ 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.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
testCacheCRUD(t, h, c, fmt.Sprintf("file-%d", i))
})
}()
}
wg.Wait()
}
@@ -77,7 +79,9 @@ 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.Go(func() {
wg.Add(1)
go func() {
defer wg.Done()
// Write a handle
splitPath := []string{"file"}
@@ -104,7 +108,7 @@ func testCacheThrashSame(t *testing.T, h *Handler, c Cache) {
require.Error(t, err)
assert.Equal(t, errStaleHandle, err)
}
})
}()
}
wg.Wait()
}
+4 -9
View File
@@ -61,11 +61,7 @@ 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.
Metadata can be added when creating a new file with ` + "`--metadata-set`" + `.
For example:
rclone touch remote:path -M --metadata-set key=value`,
then add the ` + "`--localtime`" + ` flag.`,
Annotations: map[string]string{
"versionIntroduced": "v1.39",
"groups": "Filter,Listing,Important",
@@ -127,10 +123,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, options []fs.OpenOption) error {
func createEmptyObject(ctx context.Context, remote string, modTime time.Time, f fs.Fs) error {
var buffer []byte
src := object.NewStaticObjectInfo(remote, modTime, int64(len(buffer)), true, nil, f)
_, err := f.Put(ctx, bytes.NewBuffer(buffer), src, options...)
_, err := f.Put(ctx, bytes.NewBuffer(buffer), src)
return err
}
@@ -167,8 +163,7 @@ func Touch(ctx context.Context, f fs.Fs, remote string) error {
return nil
}
fs.Debugf(f, "Touching (creating) %q", remote)
options := fs.MetadataAsOpenOptions(ctx)
if err = createEmptyObject(ctx, remote, t, f, options); err != nil {
if err = createEmptyObject(ctx, remote, t, f); err != nil {
return fmt.Errorf("failed to touch (create): %w", err)
}
}
-29
View File
@@ -150,32 +150,3 @@ 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)
}
+1 -1
View File
@@ -34,7 +34,7 @@
}
},
"highlight": {
"noClasses": false
"style": "monokailight"
}
}
}
+6 -8
View File
@@ -8,7 +8,7 @@ notoc: true
# Rclone syncs your files to cloud storage
<!-- markdownlint-disable-next-line line-length -->
{{< img width="50%" src="/img/logo_on_light__horizontal_color.svg" dark-src="/img/logo_on_dark__horizontal_color.svg" alt="rclone logo" style="float:right; padding: 5px;" class="hide-mobile" >}}
{{< img width="50%" src="/img/logo_on_light__horizontal_color.svg" alt="rclone logo" style="float:right; padding: 5px;" >}}
- [About rclone](#about)
- [What can rclone do for you?](#what)
@@ -133,7 +133,6 @@ 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" >}}
@@ -211,16 +210,15 @@ 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/" >}}
{{< provider name="Tencent Cloud Object Storage (COS)" home="https://intl.cloud.tencent.com/product/cos" config="/s3/#tencent-cos" >}}
{{< provider name="Uloz.to" home="https://uloz.to" config="/ulozto/" >}}
{{< provider name="US3" home="https://www.ucloud.cn/site/product/ufile.html" config="/s3/#us3" >}}
{{< 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">}}
@@ -249,7 +247,7 @@ These backends adapt or modify other storage providers:
## Links
- [Home page](https://rclone.org/)
- [GitHub project page for source and bug tracker](https://github.com/rclone/rclone)
- [Rclone Forum](https://forum.rclone.org)
- [Downloads](/downloads/)
- {{< icon "fa fa-home fa-fw" >}} [Home page](https://rclone.org/)
- {{< icon "fab fa-github fa-fw" >}} [GitHub project page for source and bug tracker](https://github.com/rclone/rclone)
- {{< icon "fa fa-comments fa-fw" >}} [Rclone Forum](https://forum.rclone.org)
- {{< icon "fas fa-cloud-download-alt fa-fw" >}}[Downloads](/downloads/)
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Remote Aliases"
versionIntroduced: "v1.40"
---
# Alias
# {{< icon "fa fa-link" >}} Alias
The `alias` remote provides a new name for another remote.
+1 -1
View File
@@ -5,7 +5,7 @@ versionIntroduced: "v1.20"
status: Removed
---
# Amazon Drive
# {{< icon "fab fa-amazon" >}} Amazon Drive
Amazon Drive, formerly known as Amazon Cloud Drive, was a cloud storage
service run by Amazon for consumers.
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Archive Remote"
versionIntroduced: "v1.72"
---
# Archive
# {{< icon "fas fa-archive" >}} Archive
The Archive backend allows read only access to the content of archive
files on cloud storage without downloading the complete archive. This
+1 -37
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@github.com>
- kingston125 <support@filelu.com>
- Ser-Bul <30335009+Ser-Bul@users.noreply.github.com>
- jinjingroad <jinjingroad@sina.com>
- necaran <55765083+necaran@users.noreply.github.com>
@@ -1073,39 +1073,3 @@ 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>
- Bhagyashreek8 <57988406+Bhagyashreek8@users.noreply.github.com>
- Andriy Senyshyn <135705861+sam-mt@users.noreply.github.com>
- Andrew Furman <7343697+furmandev@users.noreply.github.com>
- ZRHan <56144550+ZRHann@users.noreply.github.com>
- Jason <jasonbabo@gmail.com>
- Patrick Farrell <pfarrell@whamcloud.com>
- BizaNator <17164422+BizaNator@users.noreply.github.com>
- lif <1835304752@qq.com>
- jinkeyuu <44105232+jinkeyuu@users.noreply.github.com>
- jinyu.han <jinyu.han@ucloud.cn>
- Claude Opus 4.6 <noreply@anthropic.com>
- Andriy Senyshyn <andriy.senyshyn@kiteworks.com>
- Mike GIllan <mike.gillan@gmail.com>
- Xiangzhe <xiangzhedev@gmail.com>
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Rclone docs for Microsoft Azure Blob Storage"
versionIntroduced: "v1.38"
---
# Microsoft Azure Blob Storage
# {{< icon "fab fa-windows" >}} Microsoft Azure Blob Storage
Paths are specified as `remote:container` (or `remote:` for the `lsd`
command.) You may put subdirectories in too, e.g.
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Rclone docs for Microsoft Azure Files Storage"
versionIntroduced: "v1.65"
---
# Microsoft Azure Files Storage
# {{< icon "fab fa-windows" >}} Microsoft Azure Files Storage
Paths are specified as `remote:` You may put subdirectories in too,
e.g. `remote:path/to/dir`.
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Backblaze B2"
versionIntroduced: "v1.26"
---
# Backblaze B2
# {{< icon "fa fa-fire" >}} Backblaze B2
B2 is [Backblaze's cloud storage system](https://www.backblaze.com/cloud-storage).
+1 -17
View File
@@ -820,12 +820,6 @@ running -- and you can therefore be reasonably sure that any *expired* lock
file you may find was left there by an interrupted run, not one that is still
running and just taking awhile.
If a lock file exists but its contents are unreadable (for example, due to an
incomplete write or disk error), it is treated as expired when `--max-lock` is
set to a value greater than `0`. If `--max-lock` is `0` or not set, an
unreadable lock file will produce an error and block future runs until removed
manually.
If `--max-lock` is `0` or not set, the default is that lock files will never
expire, and will block future runs (of these same two bisync paths)
indefinitely.
@@ -1055,11 +1049,7 @@ The following backends have known issues that need more investigation:
<!--- start list_failures - DO NOT EDIT THIS SECTION - use make commanddocs --->
- `TestDropbox` (`dropbox`)
- [`TestBisyncRemoteRemote/normalization`](https://pub.rclone.org/integration-tests/current/dropbox-cmd.bisync-TestDropbox-1.txt)
- `TestSeafile` (`seafile`)
- [`TestBisyncLocalRemote/volatile`](https://pub.rclone.org/integration-tests/current/seafile-cmd.bisync-TestSeafile-1.txt)
- `TestSeafileV6` (`seafile`)
- [`TestBisyncLocalRemote/volatile`](https://pub.rclone.org/integration-tests/current/seafile-cmd.bisync-TestSeafileV6-1.txt)
- Updated: 2026-01-30-010015
- Updated: 2026-03-06-010015
<!--- end list_failures - DO NOT EDIT THIS SECTION - use make commanddocs --->
The following backends either have not been tested recently or have known issues
@@ -1903,12 +1893,6 @@ 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.
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Rclone docs for Box"
versionIntroduced: "v1.38"
---
# Box
# {{< icon "fa fa-archive" >}} Box
Paths are specified as `remote:path`
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Rclone docs for cache remote"
versionIntroduced: "v1.39"
---
# Cache
# {{< icon "fa fa-archive" >}} Cache
The `cache` remote wraps another existing remote and stores file structure
and its data for long running tasks like `rclone mount`.
-16
View File
@@ -6,22 +6,6 @@ description: "Rclone Changelog"
# Changelog
## v1.73.3 - 2026-03-23
[See commits](https://github.com/rclone/rclone/compare/v1.73.2...v1.73.3)
- Bug Fixes
- build
- Update to google.golang.org/grpc 1.79.3 to fix CVE-2026-33186 (dependabot[bot])
- Update to github.com/buger/jsonparser 1.1.2 to fix GHSA-6g7g-w4f8-9c9x (dependabot[bot])
- doc fixes
- Added text to the label showing version-introduced info (Jan-Philipp Reßler)
- Clarify Filen password change requires updating both password and API key in rclone config (Jason)
- s3: clarify multi tenant support for Cubbit (Marco Ferretti)
- jottacloud: Fix broken link (albertony)
- lib/rest: Fix URLPathEscapeAll breaking WebDAV servers (eg nzbdav) with strict path matching (Andrew Furman)
- list: Fix nil pointer panic in Sorter when temp file creation fails (Nick Craig-Wood)
## v1.73.2 - 2026-03-06
[See commits](https://github.com/rclone/rclone/compare/v1.73.1...v1.73.2)
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Split-chunking overlay remote"
versionIntroduced: "v1.50"
---
# Chunker
# {{< icon "fa fa-cut" >}} Chunker
The `chunker` overlay transparently splits large files into smaller chunks
during upload to wrapped remote and transparently assembles them back
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Rclone docs for Cloudinary backend"
versionIntroduced: "v1.69"
---
# Cloudinary
# {{< icon "fa fa-cloud" >}} Cloudinary
This is a backend for the [Cloudinary](https://cloudinary.com/) platform
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Combine several remotes into one"
versionIntroduced: "v1.59"
---
# Combine
# {{< icon "fa fa-folder-plus" >}} Combine
The `combine` backend joins remotes together into a single directory
tree.
+3 -1
View File
@@ -329,9 +329,11 @@ rclone [flags]
--filefabric-token-expiry string Token expiry time
--filefabric-url string URL of the Enterprise File Fabric to connect to
--filefabric-version string Version read from the file fabric
--filelu-chunk-size SizeSuffix Chunk size to use for uploading. Used for multipart uploads (default 64Mi)
--filelu-description string Description of the remote
--filelu-encoding Encoding The encoding for the backend (default Slash,LtGt,DoubleQuote,SingleQuote,BackQuote,Dollar,Colon,Question,Asterisk,Pipe,Hash,Percent,BackSlash,CrLf,Del,Ctl,LeftSpace,LeftPeriod,LeftTilde,LeftCrLfHtVt,RightSpace,RightPeriod,RightCrLfHtVt,InvalidUtf8,Dot,SquareBracket,Semicolon,Exclamation)
--filelu-key string Your FileLu Rclone key from My Account
--filelu-upload-cutoff SizeSuffix Cutoff for switching to chunked upload. Any files larger than this will be uploaded in chunks of chunk_size (default 500Mi)
--filen-api-key string API Key for your Filen account (obscured)
--filen-auth-version string Authentication Version (internal use only)
--filen-base-folder-uuid string UUID of Account Root Directory (internal use only)
@@ -1063,7 +1065,7 @@ rclone [flags]
--use-json-log Use json log format
--use-mmap Use mmap allocator (see docs)
--use-server-modtime Use server modified time instead of object metadata
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.0")
--user-agent string Set the user-agent to a specified string (default "rclone/v1.73.2")
-v, --verbose count Print lots more stuff (repeat for more)
-V, --version Print the version number
--webdav-auth-redirect Preserve authentication on redirect
+20
View File
@@ -107,6 +107,26 @@ Flags for anything which can copy a file
-u, --update Skip files that are newer on the destination
```
### Sync Options
Flags used for sync commands
```text
--backup-dir string Make backups into hierarchy based in DIR
--delete-after When synchronizing, delete files on destination after transferring (default)
--delete-before When synchronizing, delete files on destination before transferring
--delete-during When synchronizing, delete files during transfer
--fix-case Force rename of case insensitive dest to match source
--ignore-errors Delete even if there are I/O errors
--list-cutoff int To save memory, sort directory listings on disk above this threshold (default 1000000)
--max-delete int When synchronizing, limit the number of deletes (default -1)
--max-delete-size SizeSuffix When synchronizing, limit the total size of deletes (default off)
--suffix string Suffix to add to changed files
--suffix-keep-extension Preserve the extension when using --suffix
--track-renames When synchronizing, track file renames and do a server-side move if possible
--track-renames-strategy string Strategies to use when synchronizing using track-renames hash|modtime|leaf (default "hash")
```
### Important Options
Important flags useful for most commands
+2 -2
View File
@@ -231,12 +231,12 @@ rclone convmv "stories/The Quick Brown Fox!.txt" --name-transform "all,command=e
```console
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{YYYYMMDD}"
// Output: stories/The Quick Brown Fox!-20260130
// Output: stories/The Quick Brown Fox!-20260306
```
```console
rclone convmv "stories/The Quick Brown Fox!" --name-transform "date=-{macfriendlytime}"
// Output: stories/The Quick Brown Fox!-2026-01-30 0825PM
// Output: stories/The Quick Brown Fox!-2026-03-06 0556PM
```
```console
+9
View File
@@ -39,6 +39,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
@@ -336,7 +336,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`:
+1 -1
View File
@@ -337,7 +337,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`:
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Compression Remote"
versionIntroduced: "v1.54"
---
# Compress
# {{< icon "fas fa-compress" >}} Compress
## Warning
+1 -1
View File
@@ -4,7 +4,7 @@ description: "Encryption overlay remote"
versionIntroduced: "v1.33"
---
# Crypt
# {{< icon "fa fa-lock" >}} Crypt
Rclone `crypt` remotes encrypt and decrypt other remotes.
+17 -18
View File
@@ -753,21 +753,21 @@ object also.
Here is a table of standard system metadata which, if appropriate, a
backend may implement.
| key | description | example |
| --- | ----------- | ------- |
| mode | File type and mode: octal, unix style | 0100664 |
| uid | User ID of owner: decimal number | 500 |
| gid | Group ID of owner: decimal number | 500 |
| rdev | Device ID (if special file) => hexadecimal | 0 |
| atime | Time of last access: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| mtime | Time of last modification: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| btime | Time of file creation (birth): RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| utime | Time of file upload: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| cache-control | Cache-Control header | no-cache |
| key | description | example |
|---------------------|-------------|---------|
| mode | File type and mode: octal, unix style | 0100664 |
| uid | User ID of owner: decimal number | 500 |
| gid | Group ID of owner: decimal number | 500 |
| rdev | Device ID (if special file) => hexadecimal | 0 |
| atime | Time of last access: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| mtime | Time of last modification: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| btime | Time of file creation (birth): RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| utime | Time of file upload: RFC 3339 | 2006-01-02T15:04:05.999999999Z07:00 |
| cache-control | Cache-Control header | no-cache |
| content-disposition | Content-Disposition header | inline |
| content-encoding | Content-Encoding header | gzip |
| content-language | Content-Language header | en-US |
| content-type | Content-Type header | text/plain |
| content-encoding | Content-Encoding header | gzip |
| content-language | Content-Language header | en-US |
| content-type | Content-Type header | text/plain |
The metadata keys `mtime` and `content-type` will take precedence if
supplied in the metadata over reading the `Content-Type` or
@@ -1193,8 +1193,7 @@ on any OS, and the value is defined as following:
- On Windows: `%HOME%` if defined, else `%USERPROFILE%`, or else `%HOMEDRIVE%\%HOMEPATH%`.
- On Unix: `$HOME` if defined, else by looking up current user in OS-specific user
database (e.g. passwd file), or else use the result from shell command
`cd && pwd`.
database (e.g. passwd file), or else use the result from shell command `cd && pwd`.
If you run `rclone config file` you will see where the default location is for
you. Running `rclone config touch` will ensure a configuration file exists,
@@ -2060,7 +2059,7 @@ This is the default.
`CAUTIOUS` will try to prevent rclone from reaching the limit. Only applicable
for `--max-transfer`.
### -M, --metadata
## -M, --metadata
Setting this flag enables rclone to copy the metadata from the source
to the destination. For local backends this is ownership, permissions,
@@ -3445,7 +3444,7 @@ many items, the input is treated as a [CSV encoded](https://godoc.org/encoding/c
string. For example
| Environment variable | Equivalent options |
| -------------------- | ------------------ |
|----------------------|--------------------|
| `RCLONE_EXCLUDE="*.jpg"` | `--exclude "*.jpg"` |
| `RCLONE_EXCLUDE="*.jpg,*.png"` | `--exclude "*.jpg"` `--exclude "*.png"` |
| `RCLONE_EXCLUDE='"*.jpg","*.png"'` | `--exclude "*.jpg"` `--exclude "*.png"` |
Loaded 100 of 299 files, more files were not shown because too many files have changed in this diff. Show more