Compare commits

..
Author SHA1 Message Date
albertony 25bf29db20 build: bump DavidAnson/markdownlint-cli2-action from 22 to 23 2026-04-04 21:45:47 +02:00
albertony 1680e76ff5 docs: fix markdownlint issue MD013/line-length Line length 2026-04-04 21:44:48 +02:00
albertony 962cf6d53b docs: fix markdownlint issue MD060/table-column-style 2026-04-04 21:44:45 +02:00
dependabot[bot] fde3a4e2ee build: bump DavidAnson/markdownlint-cli2-action from 20 to 22
Bumps [DavidAnson/markdownlint-cli2-action](https://github.com/davidanson/markdownlint-cli2-action) from 20 to 22.
- [Release notes](https://github.com/davidanson/markdownlint-cli2-action/releases)
- [Commits](https://github.com/davidanson/markdownlint-cli2-action/compare/v20...v22)

---
updated-dependencies:
- dependency-name: DavidAnson/markdownlint-cli2-action
  dependency-version: '22'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-04 21:43:15 +02:00
290 changed files with 5420 additions and 37485 deletions

No files matched your search

+11 -125
View File
@@ -19,9 +19,6 @@ on:
type: boolean
default: true
permissions:
contents: read
jobs:
build:
if: inputs.manual || (github.repository == 'rclone/rclone' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name))
@@ -37,7 +34,7 @@ jobs:
include:
- job_name: linux
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.0'
gotags: cmount
build_flags: '-include "^linux/"'
check: true
@@ -48,14 +45,14 @@ jobs:
- job_name: linux_386
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.0'
goarch: 386
gotags: cmount
quicktest: true
- job_name: mac_amd64
os: macos-latest
go: '~1.26.5'
go: '~1.26.0'
gotags: 'cmount'
build_flags: '-include "^darwin/amd64" -cgo'
quicktest: true
@@ -64,14 +61,14 @@ jobs:
- job_name: mac_arm64
os: macos-latest
go: '~1.26.5'
go: '~1.26.0'
gotags: 'cmount'
build_flags: '-include "^darwin/arm64" -cgo -macos-arch arm64 -cgo-cflags=-I/usr/local/include -cgo-ldflags=-L/usr/local/lib'
deploy: true
- job_name: windows
os: windows-latest
go: '~1.26.5'
go: '~1.26.0'
gotags: cmount
cgo: '0'
build_flags: '-include "^windows/"'
@@ -81,14 +78,14 @@ jobs:
- job_name: other_os
os: ubuntu-latest
go: '~1.26.5'
go: '~1.26.0'
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
compile_all: true
deploy: true
- job_name: go1.25
os: ubuntu-latest
go: '~1.25.12'
go: '~1.25.7'
quicktest: true
racequicktest: true
@@ -97,58 +94,16 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- name: Get runner parameters
id: get-runner-parameters
run: |
echo "year-week=$(date -u "+%Y%V")" >> $GITHUB_OUTPUT
echo "runner-os-version=$ImageOS" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Install Go
id: setup-go
uses: actions/setup-go@v6
with:
go-version: ${{ matrix.go }}
check-latest: true
# Caching is handled explicitly below. setup-go's built-in cache
# keys only on go.sum, so all matrix jobs collide on one key and
# only the first to finish saves - which loses the cross-compile
# build cache.
cache: false
- name: Get Go paths
id: go-paths
run: |
echo "build-cache=$(go env GOCACHE)" >> $GITHUB_OUTPUT
echo "mod-cache=$(go env GOMODCACHE)" >> $GITHUB_OUTPUT
# The module cache holds downloaded source and is identical across
# jobs (it depends only on go.sum, not on OS, arch or Go version), so
# it is shared via a single key to avoid storing the same ~600 MiB in
# every job's cache and overflowing the repo cache limit.
- name: Module cache
uses: actions/cache@v5
with:
path: ${{ steps.go-paths.outputs.mod-cache }}
key: go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-
go-mod-
# The build cache holds compiled artifacts which are specific to the
# OS, arch and Go version, so it is kept per job.
- name: Build cache
uses: actions/cache@v5
with:
path: ${{ steps.go-paths.outputs.build-cache }}
key: go-build-${{ matrix.job_name }}-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-build-${{ matrix.job_name }}-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-
go-build-${{ matrix.job_name }}-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-
- name: Set environment variables
run: |
@@ -247,15 +202,6 @@ jobs:
# Deploy binaries if enabled in config && not a PR && not a fork
if: env.RCLONE_CONFIG_PASS != '' && matrix.deploy && github.head_ref == '' && github.repository == 'rclone/rclone'
- name: Trim module cache before saving
if: always()
run: |
# The downloaded module .zip archives are not needed to build from
# the already-extracted module cache, so drop them before the cache
# is saved - this roughly halves the module cache size.
modcache=$(go env GOMODCACHE | tr '\\' '/')
find "$modcache/cache/download" -name '*.zip' -type f -delete 2>/dev/null || true
lint:
if: inputs.manual || (github.repository == 'rclone/rclone' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name))
timeout-minutes: 30
@@ -278,23 +224,15 @@ jobs:
id: setup-go
uses: actions/setup-go@v6
with:
go-version: '~1.26.5'
go-version: '~1.26.0'
check-latest: true
cache: false
- name: Module cache
uses: actions/cache@v5
with:
path: ~/go/pkg/mod
key: go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-
go-mod-
- name: Cache
uses: actions/cache@v5
with:
path: |
~/go/pkg/mod
~/.cache/go-build
~/.cache/golangci-lint
key: golangci-lint-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
@@ -345,7 +283,7 @@ jobs:
run: govulncheck ./...
- name: Check Markdown format
uses: DavidAnson/markdownlint-cli2-action@v20
uses: DavidAnson/markdownlint-cli2-action@v23
with:
globs: |
CONTRIBUTING.md
@@ -361,15 +299,6 @@ jobs:
run: bin/check_autogenerated_edits.py 'origin/${{ github.base_ref }}'
if: github.event_name == 'pull_request'
- name: Trim module cache before saving
if: always()
run: |
# The downloaded module .zip archives are not needed to build from
# the already-extracted module cache, so drop them before the cache
# is saved - this roughly halves the module cache size.
modcache=$(go env GOMODCACHE | tr '\\' '/')
find "$modcache/cache/download" -name '*.zip' -type f -delete 2>/dev/null || true
android:
if: inputs.manual || (github.repository == 'rclone/rclone' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name))
timeout-minutes: 30
@@ -377,12 +306,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Get runner parameters
id: get-runner-parameters
run: |
echo "year-week=$(date -u "+%Y%V")" >> $GITHUB_OUTPUT
echo "runner-os-version=$ImageOS" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@v6
with:
@@ -390,37 +313,9 @@ jobs:
# Upgrade together with NDK version
- name: Set up Go
id: setup-go
uses: actions/setup-go@v6
with:
go-version: '~1.26.5'
# Caching is handled explicitly below to share the module cache
# with the other jobs - see the build job for the rationale.
cache: false
- name: Get Go paths
id: go-paths
run: |
echo "build-cache=$(go env GOCACHE)" >> $GITHUB_OUTPUT
echo "mod-cache=$(go env GOMODCACHE)" >> $GITHUB_OUTPUT
- name: Module cache
uses: actions/cache@v5
with:
path: ${{ steps.go-paths.outputs.mod-cache }}
key: go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-mod-${{ steps.get-runner-parameters.outputs.year-week }}-
go-mod-
- name: Build cache
uses: actions/cache@v5
with:
path: ${{ steps.go-paths.outputs.build-cache }}
key: go-build-android-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-build-android-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-${{ steps.get-runner-parameters.outputs.year-week }}-
go-build-android-${{ steps.get-runner-parameters.outputs.runner-os-version }}-go${{ steps.setup-go.outputs.go-version }}-
go-version: '~1.26.0'
- name: Set global environment variables
run: |
@@ -496,12 +391,3 @@ jobs:
RCLONE_CONFIG_PASS: ${{ secrets.RCLONE_CONFIG_PASS }}
# Upload artifacts if not a PR && not a fork
if: env.RCLONE_CONFIG_PASS != '' && github.head_ref == '' && github.repository == 'rclone/rclone'
- name: Trim module cache before saving
if: always()
run: |
# The downloaded module .zip archives are not needed to build from
# the already-extracted module cache, so drop them before the cache
# is saved - this roughly halves the module cache size.
modcache=$(go env GOMODCACHE | tr '\\' '/')
find "$modcache/cache/download" -name '*.zip' -type f -delete 2>/dev/null || true
@@ -18,10 +18,6 @@ on:
type: boolean
default: true
permissions:
contents: read
packages: write
jobs:
build-image:
if: inputs.manual || (github.repository == 'rclone/rclone' && github.event_name != 'pull_request')
@@ -96,7 +92,7 @@ jobs:
# There's no way around this, because "ImageOS" is only available to
# processes, but the setup-go action uses it in its key.
id: imageos
uses: actions/github-script@v9
uses: actions/github-script@v8
with:
result-encoding: string
script: |
@@ -14,9 +14,6 @@ on:
type: boolean
default: true
permissions:
contents: read
jobs:
build_docker_volume_plugin:
if: inputs.manual || github.repository == 'rclone/rclone'
-3
View File
@@ -4,9 +4,6 @@ on:
issues:
types: [labeled]
permissions:
contents: read
jobs:
notify:
runs-on: ubuntu-latest
-3
View File
@@ -3,9 +3,6 @@ on:
release:
types: [released]
permissions:
contents: read
jobs:
publish:
runs-on: ubuntu-latest
+3 -3
View File
@@ -1,6 +1,6 @@
default: true
# Use specific styles, to be consistent across all documents.
# Use specific styles, to be consistent accross all documents.
# Default is to accept any as long as it is consistent within the same document.
heading-style: # MD003
style: atx
@@ -48,12 +48,12 @@ link-fragments: false # MD051
# https://gohugo.io/content-management/syntax-highlighting/#languages
# https://docs.github.com//get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks#syntax-highlighting
# In addition, we only want to allow identifiers (aliases) that correspond to
# the same language in Hugo and GitHub, and preferably also VSCode and other
# the same language in Hugo and GitHub, and preferrably also VSCode and other
# commonly used tools, to avoid confusion. An example of this is that "shell"
# by some are considered an identifier for shell scripts, i.e. an alias for
# "sh", while others consider it an identifier for shell sessions, i.e. an
# alias for "console". Although Hugo and GitHub in this case are consistent and
# have chosen the former, using "sh" instead, and not allowing use of "shell",
# have choosen the former, using "sh" instead, and not allowing use of "shell",
# avoids the confusion entirely.
fenced-code-language: # MD040
allowed_languages:
+4 -3
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,7 +580,8 @@ 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
+20 -21
View File
@@ -2,28 +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 |
| Enduriel | @Enduriel | filen backend |
| 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
+2089 -5642
View File
File diff suppressed because it is too large. Load diff
Generated
+466 -3364
View File
File diff suppressed because it is too large. Load diff
Generated
+411 -3532
View File
File diff suppressed because it is too large. Load diff
+1 -26
View File
@@ -45,7 +45,7 @@ LINTTAGS=--build-tags "$(GOTAGS)"
endif
LDFLAGS=--ldflags "-s -X github.com/rclone/rclone/fs.Version=$(TAG)"
.PHONY: rclone test_all vars version fetch-gui fetch-gui-and-commit
.PHONY: rclone test_all vars version
rclone:
ifeq ($(GO_OS),windows)
@@ -59,12 +59,6 @@ endif
cp -av rclone`go env GOEXE` `go env GOPATH`/bin/rclone`go env GOEXE`.new
mv -v `go env GOPATH`/bin/rclone`go env GOEXE`.new `go env GOPATH`/bin/rclone`go env GOEXE`
fetch-gui:
$(SHELL) ./bin/fetch-gui-dist.sh
fetch-gui-and-commit:
$(SHELL) ./bin/fetch-gui-dist.sh --commit
test_all:
go install $(LDFLAGS) $(BUILDTAGS) $(BUILD_ARGS) github.com/rclone/rclone/fstest/test_all
@@ -127,25 +121,6 @@ updatedirect:
go get $$(go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all)
go mod tidy
# Update direct dependencies only but won't update the `go` line in go.mod
updatedirectnoupgrade:
@GO_VERSION=$$(awk '/^go /{print $$2}' go.mod) && \
for mod in $$(go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all); do \
cp go.mod go.mod.bak && \
cp go.sum go.sum.bak && \
go get $$mod && \
NEW_VERSION=$$(awk '/^go /{print $$2}' go.mod) && \
if [ "$$NEW_VERSION" != "$$GO_VERSION" ]; then \
echo "SKIPPING $$mod (requires go $$NEW_VERSION)"; \
cp go.mod.bak go.mod; \
cp go.sum.bak go.sum; \
else \
echo "updated $$mod"; \
fi; \
done && \
rm -f go.mod.bak go.sum.bak && \
go mod tidy
# Update direct and indirect dependencies and test dependencies
update:
go get -u -t ./...
-3
View File
@@ -59,17 +59,14 @@ directories to and from different cloud storage providers.
- Hetzner Object Storage [:page_facing_up:](https://rclone.org/s3/#hetzner)
- Hetzner Storage Box [:page_facing_up:](https://rclone.org/sftp/#hetzner-storage-box)
- HiDrive [:page_facing_up:](https://rclone.org/hidrive/)
- Hitachi Content Platform (HCP) [:page_facing_up:](https://rclone.org/s3/#hcp)
- HTTP [:page_facing_up:](https://rclone.org/http/)
- Huawei Cloud Object Storage Service(OBS) [:page_facing_up:](https://rclone.org/s3/#huawei-obs)
- Huawei Drive [:page_facing_up:](https://rclone.org/huaweidrive/)
- iCloud Drive [:page_facing_up:](https://rclone.org/iclouddrive/)
- ImageKit [:page_facing_up:](https://rclone.org/imagekit/)
- Internet Archive [:page_facing_up:](https://rclone.org/internetarchive/)
- Internxt [:page_facing_up:](https://rclone.org/internxt/)
- Jottacloud [:page_facing_up:](https://rclone.org/jottacloud/)
- IBM COS S3 [:page_facing_up:](https://rclone.org/s3/#ibm-cos-s3)
- Impossible Cloud [:page_facing_up:](https://rclone.org/s3/#impossible-cloud)
- Intercolo Object Storage [:page_facing_up:](https://rclone.org/s3/#intercolo)
- IONOS Cloud [:page_facing_up:](https://rclone.org/s3/#ionos)
- Koofr [:page_facing_up:](https://rclone.org/koofr/)
+25 -28
View File
@@ -11,7 +11,6 @@ This file describes how to make the various kinds of releases
- git checkout master # see below for stable branch
- git pull # IMPORTANT
- make fetch-gui-and-commit # bump the embedded GUI if rclone-web has a newer release
- git status - make sure everything is checked in
- Check GitHub actions build for master is Green
- make test # see integration test server or run locally
@@ -43,10 +42,7 @@ This file describes how to make the various kinds of releases
Early in the next release cycle update the dependencies.
- Active Pins
- `github.com/gdamore/tcell/v2` v2.9.0 - awaiting fix for [tcell/issues/1124](https://github.com/gdamore/tcell/issues/1124)
- See: [#9539](https://github.com/rclone/rclone/issues/9539)
- Review Active Pins in go.mod and remove if possible
- Review any pinned packages in go.mod and remove if possible
- `make updatedirect`
- `make GOTAGS=cmount`
- `make compiletest`
@@ -59,18 +55,32 @@ If the `make updatedirect` upgrades the version of go in the `go.mod`
go 1.22.0
```
then so this instead `make updatedirectnoupgrade`. This will try each
upgrade individually. Consider making an upstream bug report for any
`SKIPPING` lines as these only support the latest Go version not the
previous version too.
then go to manual mode. `go1.22` here is the lowest supported version
in the `go.mod`.
If `make updatedirect` or `make updatedirectnoupgrade` added a
`toolchain` directive then remove it. We don't want to force a
toolchain on our users. Linux packagers are often using a version of
Go that is a few versions out of date.
If `make updatedirect` added a `toolchain` directive then remove it.
We don't want to force a toolchain on our users. Linux packagers are
often using a version of Go that is a few versions out of date.
```console
go list -m -f '{{if not (or .Main .Indirect)}}{{.Path}}{{end}}' all > /tmp/potential-upgrades
go get -d $(cat /tmp/potential-upgrades)
go mod tidy -go=1.22 -compat=1.22
```
If the `go mod tidy` fails use the output from it to remove the
package which can't be upgraded from `/tmp/potential-upgrades` when
done
```console
git co go.mod go.sum
```
And try again.
Optionally upgrade the direct and indirect dependencies. This is very
likely to fail if `make updatedirectnoupgrade` was used.
likely to fail if the manual method was used abve - in that case
ignore it as it is too time consuming to fix.
- `make update`
- `make GOTAGS=cmount`
@@ -88,19 +98,6 @@ build.
Once it compiles locally, push it on a test branch and commit fixes
until the tests pass.
### Pseudo versions
Go makes pseudo versions for untagged repos and repos not at a tag.
The pseudo versions on repos that have been tagged before do not get
updated automatically so need manually checking. These can be found with
```console
grep -E '[0-9]{14}-[0-9a-f]{12}' go.mod | grep -v indirect | grep -v 'v0\.0\.0'
```
These will need to be updated manually using the `go get ...@branch`
syntax.
### Major versions
The above procedure will not upgrade major versions, so v2 to v3.
@@ -195,7 +192,7 @@ this will be done already.
Now
- git co ${BASE_TAG}-stable
- `git cherry-pick -x` any fixes
- git cherry-pick any fixes
- make startstable
- Do the steps as above
- git co master
+1 -1
View File
@@ -1 +1 @@
v1.74.4
v1.74.0
-1
View File
@@ -32,7 +32,6 @@ import (
_ "github.com/rclone/rclone/backend/hdfs"
_ "github.com/rclone/rclone/backend/hidrive"
_ "github.com/rclone/rclone/backend/http"
_ "github.com/rclone/rclone/backend/huaweidrive"
_ "github.com/rclone/rclone/backend/iclouddrive"
_ "github.com/rclone/rclone/backend/imagekit"
_ "github.com/rclone/rclone/backend/internetarchive"
+1 -1
View File
@@ -36,7 +36,7 @@ func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (*Fs
// FIXME vfs cache?
// FIXME could factor out ReadFileHandle and just use that rather than the full VFS
fs.Debugf(nil, "New: remote=%q, prefix=%q, root=%q", remote, prefix, root)
VFS := vfs.New(ctx, wrappedFs, nil)
VFS := vfs.New(wrappedFs, nil)
node, err := VFS.Stat(remote)
if err != nil {
return nil, fmt.Errorf("failed to find %q archive: %w", remote, err)
+1 -1
View File
@@ -50,7 +50,7 @@ func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (fs.
fs.Debugf(nil, "Squashfs: New: remote=%q, prefix=%q, root=%q", remote, prefix, root)
vfsOpt := vfscommon.Opt
vfsOpt.ReadWait = 0
VFS := vfs.New(ctx, wrappedFs, &vfsOpt)
VFS := vfs.New(wrappedFs, &vfsOpt)
node, err := VFS.Stat(remote)
if err != nil {
return nil, fmt.Errorf("failed to find %q archive: %w", remote, err)
+1 -1
View File
@@ -52,7 +52,7 @@ func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (fs.
fs.Debugf(nil, "Zip: New: remote=%q, prefix=%q, root=%q", remote, prefix, root)
vfsOpt := vfscommon.Opt
vfsOpt.ReadWait = 0
VFS := vfs.New(ctx, wrappedFs, &vfsOpt)
VFS := vfs.New(wrappedFs, &vfsOpt)
node, err := VFS.Stat(remote)
if err != nil {
return nil, fmt.Errorf("failed to find %q archive: %w", remote, err)
-4
View File
@@ -9,7 +9,6 @@ import (
"net/http"
"net/url"
"os"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
@@ -284,9 +283,6 @@ type transporter struct {
// Make a new transporter
func newTransporter(ctx context.Context) transporter {
// Set the User-Agent to include the Microsoft Partner Network prefix
ctx, ci := fs.AddConfig(ctx)
ci.UserAgent = "APN/1.0 rclone/1.0 rclone/" + strings.TrimPrefix(fs.Version, "v")
return transporter{
RoundTripper: fshttp.NewTransport(ctx),
}
+9 -76
View File
@@ -47,7 +47,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/readers"
"github.com/rclone/rclone/lib/transferaccounter"
"golang.org/x/sync/errgroup"
)
@@ -68,16 +67,6 @@ const (
sasCopyValidity = time.Hour // how long SAS should last when doing server side copy
)
// setAcceptEncodingGzip is a per-call policy that sets Accept-Encoding: gzip
// on every request. This prevents the Go HTTP transport from automatically
// decompressing gzip-encoded blobs on download.
type setAcceptEncodingGzip struct{}
func (p setAcceptEncodingGzip) Do(req *policy.Request) (*http.Response, error) {
req.Raw().Header.Set("Accept-Encoding", "gzip")
return req.Next()
}
var (
errCantUpdateArchiveTierBlobs = fserrors.NoRetryError(errors.New("can't update archive tier blob without --azureblob-archive-tier-delete"))
@@ -361,19 +350,6 @@ rclone does if you know the container exists already.
Default: "",
Exclusive: true,
Advanced: true,
}, {
Name: "decompress",
Help: `If set this will decompress gzip encoded objects.
It is possible to upload objects to Azure Blob Storage with "Content-Encoding: gzip"
set. Normally rclone will download these files as compressed objects.
If this flag is set then rclone will decompress these files with
"Content-Encoding: gzip" as they are received. This means that rclone
can't check the size and hash but the file contents will be decompressed.
`,
Advanced: true,
Default: false,
}}),
})
}
@@ -397,7 +373,6 @@ type Options struct {
NoCheckContainer bool `config:"no_check_container"`
NoHeadObject bool `config:"no_head_object"`
DeleteSnapshots string `config:"delete_snapshots"`
Decompress bool `config:"decompress"`
}
// Fs represents a remote azure server
@@ -422,8 +397,6 @@ type Fs struct {
copyToken *pacer.TokenDispenser // global multipart copy concurrency limiter
publicAccess container.PublicAccessType // Container Public Access Level
warnCompressed sync.Once // warn once about compressed files
// user delegation cache
userDelegationMu sync.Mutex
userDelegation *service.UserDelegationCredential
@@ -432,16 +405,15 @@ type Fs struct {
// Object describes an azure object
type Object struct {
fs *Fs // what this object is part of
remote string // The remote path
modTime time.Time // The modified time of the object if known
md5 string // MD5 hash if known
size int64 // Size of the object
mimeType string // Content-Type of the object
accessTier blob.AccessTier // Blob Access Tier
meta map[string]string // blob metadata - take metadataMu when accessing
tags map[string]string // blob tags
contentEncoding *string // Content-Encoding of the object
fs *Fs // what this object is part of
remote string // The remote path
modTime time.Time // The modified time of the object if known
md5 string // MD5 hash if known
size int64 // Size of the object
mimeType string // Content-Type of the object
accessTier blob.AccessTier // Blob Access Tier
meta map[string]string // blob metadata - take metadataMu when accessing
tags map[string]string // blob tags
}
// ------------------------------------------------------------
@@ -662,9 +634,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
NewClientWithSharedKeyCredential: service.NewClientWithSharedKeyCredential,
NewSharedKeyCredential: service.NewSharedKeyCredential,
SetClientOptions: func(options *service.ClientOptions, policyClientOptions policy.ClientOptions) {
// Override the automatic decompression in the transport
// to download compressed files as-is
policyClientOptions.PerCallPolicies = append(policyClientOptions.PerCallPolicies, setAcceptEncodingGzip{})
options.ClientOptions = policyClientOptions
},
}
@@ -2032,10 +2001,6 @@ func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
if t != hash.MD5 {
return "", hash.ErrUnsupported
}
// If decompressing, erase the hash
if o.size < 0 {
return "", nil
}
// Convert base64 encoded md5 into lower case hex
if o.md5 == "" {
return "", nil
@@ -2161,13 +2126,6 @@ func (o *Object) decodeMetaDataFromPropertiesResponse(info *blob.GetPropertiesRe
o.accessTier = blob.AccessTier(*info.AccessTier)
}
o.setMetadata(metadata)
o.contentEncoding = info.ContentEncoding
// If decompressing then size and md5sum are unknown
if o.fs.opt.Decompress && o.contentEncoding != nil && *o.contentEncoding == "gzip" {
o.size = -1
o.md5 = ""
}
return nil
}
@@ -2220,13 +2178,6 @@ func (o *Object) decodeMetaDataFromDownloadResponse(info *blob.DownloadStreamRes
fs.Debugf(o, "Failed to find length in %q", contentRange)
}
}
o.contentEncoding = info.ContentEncoding
// If decompressing then size and md5sum are unknown
if o.fs.opt.Decompress && o.contentEncoding != nil && *o.contentEncoding == "gzip" {
o.size = -1
o.md5 = ""
}
return nil
}
@@ -2265,13 +2216,6 @@ func (o *Object) decodeMetaDataFromBlob(info *container.BlobItem) (err error) {
o.accessTier = *info.Properties.AccessTier
}
o.setMetadata(metadata)
o.contentEncoding = info.Properties.ContentEncoding
// If decompressing then size and md5sum are unknown
if o.fs.opt.Decompress && o.contentEncoding != nil && *o.contentEncoding == "gzip" {
o.size = -1
o.md5 = ""
}
return nil
}
@@ -2447,17 +2391,6 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
if err != nil {
return nil, fmt.Errorf("failed to decode metadata for download: %w", err)
}
// Decompress body if necessary
if downloadResponse.ContentEncoding != nil && *downloadResponse.ContentEncoding == "gzip" {
if o.fs.opt.Decompress {
return readers.NewGzipReader(downloadResponse.Body)
}
o.fs.warnCompressed.Do(func() {
fs.Logf(o, "Not decompressing 'Content-Encoding: gzip' compressed file. Use --azureblob-decompress to override")
})
}
return downloadResponse.Body, nil
}
@@ -3,10 +3,7 @@
package azureblob
import (
"bytes"
"compress/gzip"
"context"
"crypto/md5"
"encoding/base64"
"fmt"
"net/http"
@@ -17,7 +14,6 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
@@ -154,65 +150,10 @@ func (f *Fs) testWriteUncommittedBlocks(t *testing.T) {
require.NoError(t, dst.Remove(ctx))
}
func gz(t *testing.T, s string) string {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write([]byte(s))
require.NoError(t, err)
err = zw.Close()
require.NoError(t, err)
return buf.String()
}
func md5sum(t *testing.T, s string) string {
hash := md5.Sum([]byte(s))
return fmt.Sprintf("%x", hash)
}
func (f *Fs) testGzipEncoding(t *testing.T) {
ctx := context.Background()
original := random.String(1000)
contents := gz(t, original)
item := fstest.NewItem("test-gzip", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
metadata := fs.Metadata{
"content-encoding": "gzip",
"content-type": "text/plain",
}
obj := fstests.PutTestContentsMetadata(ctx, t, f, &item, true, contents, true, "text/html", metadata)
defer func() {
assert.NoError(t, obj.Remove(ctx))
}()
o := obj.(*Object)
// Test that the gzipped file we uploaded can be
// downloaded with and without decompression
checkDownload := func(wantContents string, wantSize int64, wantHash string) {
gotContents := fstests.ReadObject(ctx, t, o, -1)
assert.Equal(t, wantContents, gotContents)
assert.Equal(t, wantSize, o.Size())
gotHash, err := o.Hash(ctx, hash.MD5)
require.NoError(t, err)
assert.Equal(t, wantHash, gotHash)
}
t.Run("NoDecompress", func(t *testing.T) {
checkDownload(contents, int64(len(contents)), md5sum(t, contents))
})
t.Run("Decompress", func(t *testing.T) {
f.opt.Decompress = true
defer func() {
f.opt.Decompress = false
}()
checkDownload(original, -1, "")
})
}
func (f *Fs) InternalTest(t *testing.T) {
t.Run("Features", f.testFeatures)
t.Run("WriteUncommittedBlocks", f.testWriteUncommittedBlocks)
t.Run("Metadata", f.testMetadataPaths)
t.Run("GzipEncoding", f.testGzipEncoding)
}
// helper to read blob properties for an object
-4
View File
@@ -173,10 +173,6 @@ func newFsFromOptions(ctx context.Context, name, root string, opt *Options) (fs.
NewSharedKeyCredential: service.NewSharedKeyCredential,
SetClientOptions: func(options *service.ClientOptions, policyClientOptions policy.ClientOptions) {
options.ClientOptions = policyClientOptions
// FileRequestIntent is required for TokenCredential (OAuth)
// auth; the SDK omits it for shared-key / SAS.
backup := service.ShareTokenIntentBackup
options.FileRequestIntent = &backup
},
}
res, err := auth.NewClient(ctx, conf, &opt.Options)
+3 -4
View File
@@ -563,10 +563,9 @@ Eg
})
rc.Add(rc.Call{
Path: "cache/stats",
NoAuth: true,
Fn: f.httpStats,
Title: "Get cache stats",
Path: "cache/stats",
Fn: f.httpStats,
Title: "Get cache stats",
Help: `
Show statistics for the cache remote.
`,
+7 -11
View File
@@ -34,13 +34,6 @@ import (
"github.com/zeebo/blake3"
)
// Pacer settings - tuned to match other rclone backends
const (
minSleep = 10 * time.Millisecond
maxSleep = 2 * time.Second
decayConstant = 2 // bigger for slower decay, exponential
)
// Cloudinary shouldn't have a trailing dot if there is no path
func cldPathDir(somePath string) string {
if somePath == "" || somePath == "." {
@@ -196,7 +189,7 @@ func NewFs(ctx context.Context, name string, root string, m configmap.Mapper) (f
root: root,
opt: *opt,
cld: cld,
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(1000), pacer.MaxSleep(10000), pacer.DecayConstant(2))),
srv: rest.NewClient(client),
}
@@ -593,18 +586,21 @@ func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, err
if fserrors.ContextError(ctx, &err) {
return false, err
}
// Cloudinary returns rate-limit windows as "Try again on YYYY-MM-DD HH:MM:SS UTC"
// embedded in the error message - honour it as a retry-after.
if err != nil {
tryAgain := "Try again on "
if idx := strings.Index(err.Error(), tryAgain); idx != -1 {
layout := "2006-01-02 15:04:05 UTC"
dateStr := err.Error()[idx+len(tryAgain) : idx+len(tryAgain)+len(layout)]
if timestamp, err2 := time.Parse(layout, dateStr); err2 == nil {
timestamp, err2 := time.Parse(layout, dateStr)
if err2 == nil {
return true, fserrors.NewErrorRetryAfter(time.Until(timestamp))
}
}
fs.Debugf(nil, "Retrying API error %v", err)
return true, err
}
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
}
+5 -5
View File
@@ -21,7 +21,7 @@ type User struct {
Avatar string `json:"avatar"`
ModelType string `json:"model_type"`
OwnsEntry bool `json:"owns_entry"`
EntryPermissions any `json:"entry_permissions"`
EntryPermissions []any `json:"entry_permissions"`
DisplayName string `json:"display_name"`
}
@@ -77,9 +77,9 @@ type Listing struct {
Data []Item `json:"data"`
From int `json:"from"`
LastPage int `json:"last_page"`
NextPageURL string `json:"next_page_url"`
NextPage int `json:"next_page"`
PerPage int `json:"per_page"`
PrevPageURL string `json:"prev_page_url"`
PrevPage int `json:"prev_page"`
To int `json:"to"`
Total int `json:"total"`
}
@@ -171,7 +171,7 @@ type MultiPartCreateRequest struct {
Mime string `json:"mime"`
Size int64 `json:"size"`
Extension string `json:"extension"`
ParentID json.Number `json:"parentId"`
ParentID json.Number `json:"parent_id"`
RelativePath string `json:"relativePath"`
WorkspaceID string `json:"workspaceId,omitempty"`
}
@@ -222,7 +222,7 @@ type MultiPartEntriesRequest struct {
Filename string `json:"filename"`
Size int64 `json:"size"`
ClientExtension string `json:"clientExtension"`
ParentID json.Number `json:"parentId"`
ParentID json.Number `json:"parent_id"`
RelativePath string `json:"relativePath"`
WorkspaceID string `json:"workspaceId,omitempty"`
}
+19 -90
View File
@@ -54,7 +54,7 @@ const (
rootURL = baseURL + "api/v1"
maxUploadParts = 10000 // maximum allowed number of parts in a multi-part upload
minChunkSize = fs.SizeSuffix(1024 * 1024 * 5)
defaultUploadCutoff = fs.SizeSuffix(5 * 1024 * 1024) // as per https://docs.drime.cloud/uploads-guide
defaultUploadCutoff = fs.SizeSuffix(200 * 1024 * 1024)
)
// Register with Fs
@@ -146,6 +146,14 @@ and these uploads do not fully utilize your bandwidth, then increasing
this may help to speed up the transfers.`,
Default: 4,
Advanced: true,
}, {
Name: "upload_cutoff",
Help: `Cutoff for switching to chunked upload.
Any files larger than this will be uploaded in chunks of chunk_size.
The minimum is 0 and the maximum is 5 GiB.`,
Default: defaultUploadCutoff,
Advanced: true,
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
@@ -270,11 +278,6 @@ var retryErrorCodes = []int{
503, // Service Unavailable
504, // Gateway Timeout
509, // Bandwidth Limit Exceeded
520, // Cloudflare: Web server returns an unknown error
521, // Cloudflare: Web server is down
522, // Cloudflare: Connection timed out
523, // Cloudflare: Origin is unreachable
524, // Cloudflare: A timeout occurred
}
// shouldRetry returns a boolean as to whether this resp and err
@@ -524,7 +527,7 @@ func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, fi
Parameters: url.Values{},
}
if dirID != "" {
opts.Parameters.Add("folderId", dirID)
opts.Parameters.Add("parentIds", dirID)
}
if directoriesOnly {
opts.Parameters.Add("type", api.ItemTypeFolder)
@@ -562,10 +565,10 @@ OUTER:
break OUTER
}
}
if result.CurrentPage == result.LastPage {
if result.NextPage == 0 {
break
}
page = result.CurrentPage + 1
page = result.NextPage
}
return found, err
}
@@ -706,11 +709,6 @@ func (f *Fs) deleteObject(ctx context.Context, id string) error {
return shouldRetry(ctx, resp, err)
})
if err != nil {
// If Drime returns 422 with invalid entry ID, the object is already gone.
// Map this to a standard not-found error
if strings.Contains(err.Error(), "entry ids is invalid") {
return fs.ErrorObjectNotFound
}
return fmt.Errorf("failed to delete item: %w", err)
}
// Check the individual result codes also
@@ -784,16 +782,10 @@ func (f *Fs) patch(ctx context.Context, id, attribute string, value string) (ite
Name: value,
}
var result api.UpdateItemResponse
// The drime origin returns a malformed response (seen by Cloudflare as
// a 520) for a literal PUT to this endpoint, so use a POST with Laravel
// method spoofing instead - the API routes it to the same handler.
opts := rest.Opts{
Method: "POST",
Method: "PUT",
Path: "/file-entries/" + id,
Parameters: url.Values{},
ExtraHeaders: map[string]string{
"X-HTTP-Method-Override": "PUT",
},
}
if f.opt.WorkspaceID != "" {
opts.Parameters.Set("workspaceId", f.opt.WorkspaceID)
@@ -927,48 +919,6 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
return dstObj, nil
}
// countDirChildren returns the number of direct children of dirID.
func (f *Fs) countDirChildren(ctx context.Context, dirID string) (int, error) {
n := 0
_, err := f.listAll(ctx, dirID, false, false, "", func(*api.Item) bool {
n++
return false
})
return n, err
}
// waitForDirChildren polls dirID until it lists at least want direct
// children, or the timeout elapses. Drime's folder rename has visible
// eventual-consistency on the children listing - the rename returns
// success immediately but the renamed folder lists as empty for a
// short window - so callers that rename a folder use this to wait for
// the listing to settle before returning (see issue #9450).
func (f *Fs) waitForDirChildren(ctx context.Context, dirID string, want int) error {
const timeout = 30 * time.Second
deadline := time.Now().Add(timeout)
backoff := 100 * time.Millisecond
for {
got, err := f.countDirChildren(ctx, dirID)
if err != nil {
return err
}
if got >= want {
return nil
}
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for directory listing to settle: got %d, want %d", got, want)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff):
}
if backoff < 2*time.Second {
backoff *= 2
}
}
}
// DirMove moves src, srcRemote to this remote at dstRemote
// using server-side move operations.
//
@@ -989,25 +939,11 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
return err
}
// Count children before the move so we can wait for the server's
// children listing to reflect the rename - see waitForDirChildren.
preCount, err := f.countDirChildren(ctx, srcID)
if err != nil {
return fmt.Errorf("DirMove: count source children: %w", err)
}
// Do the move
info, err := f.moveTo(ctx, srcID, srcLeaf, dstLeaf, srcDirectoryID, dstDirectoryID)
_, err = f.moveTo(ctx, srcID, srcLeaf, dstLeaf, srcDirectoryID, dstDirectoryID)
if err != nil {
return err
}
if preCount > 0 {
if err := f.waitForDirChildren(ctx, info.ID.String(), preCount); err != nil {
fs.Logf(f, "DirMove: %v (continuing)", err)
}
}
srcFs.dirCache.FlushDir(srcRemote)
return nil
}
@@ -1160,11 +1096,6 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
return info, nil, err
}
// Send just the leaf as relativePath, matching the single-part /uploads
// convention. The file is placed by parentId; sending an absolute path
// here makes the server build folders from it and drop "0" path segments.
relPath := f.opt.Enc.FromStandardName(leaf)
// Temporary Object under construction
o := &Object{
fs: f,
@@ -1198,7 +1129,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
Size: createSize,
Extension: strings.TrimPrefix(path.Ext(leaf), `.`),
ParentID: json.Number(directoryID),
RelativePath: relPath,
RelativePath: f.opt.Enc.FromStandardPath(path.Join(f.root, remote)),
WorkspaceID: f.opt.WorkspaceID,
}
@@ -1225,6 +1156,8 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
if ext == "" {
ext = "bin"
}
rel := f.opt.Enc.FromStandardPath(path.Join(f.root, remote))
chunkWriter := &drimeChunkWriter{
uploadID: resp.UploadID,
key: resp.Key,
@@ -1237,7 +1170,7 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
mime: mime,
extension: ext,
parentID: json.Number(directoryID),
relativePath: relPath,
relativePath: rel,
}
info = fs.ChunkWriterInfo{
ChunkSize: int64(chunkSize),
@@ -1597,11 +1530,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
fs.Debugf(o, "Removing old object on successful upload")
deleteErr := o.fs.deleteObject(ctx, id)
if deleteErr != nil {
if errors.Is(deleteErr, fs.ErrorObjectNotFound) {
fs.Debugf(o, "Old object already deleted, safely ignoring")
} else {
err = fmt.Errorf("failed to delete existing object: %w", deleteErr)
}
err = fmt.Errorf("failed to delete existing object: %w", deleteErr)
}
}()
}
+4 -16
View File
@@ -144,7 +144,6 @@ var (
_importFormats map[string][]string // allowed import MIME type conversions
templatesOnce sync.Once // parse link templates only once
_linkTemplates map[string]*template.Template // available link types
gdocsWarnOnce sync.Once // warn once about skipped non-exportable Google documents
)
// rwChoices type for fs.Bits
@@ -1303,7 +1302,6 @@ func createOAuthClient(ctx context.Context, opt *Options, name string, m configm
return nil, fmt.Errorf("failed to create client from environment: %w", err)
}
} else {
oauthutil.SharedClientIDWarning(name, "Google Drive", "https://rclone.org/drive/#making-your-own-client-id", m)
oAuthClient, _, err = oauthutil.NewClientWithBaseClient(ctx, name, m, driveConfig, getClient(ctx, opt))
if err != nil {
return nil, fmt.Errorf("failed to create oauth client: %w", err)
@@ -1688,9 +1686,6 @@ func (f *Fs) newObjectWithExportInfo(
// If item MimeType is in the ExportFormats then it is a google doc
if !isDocument {
fs.Debugf(remote, "Ignoring unknown document type %q", info.MimeType)
gdocsWarnOnce.Do(func() {
fs.Logf(remote, "Skipping unexportable google document %q. Use --drive-show-all-gdocs to include them in server side copy and move", info.MimeType)
})
return nil, fs.ErrorObjectNotFound
}
if extension == "" {
@@ -3039,18 +3034,11 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
remote = remote[:len(remote)-len(ext)]
}
// Find the ID of the parent to remove the file from.
var srcParentID string
if len(srcObj.parents) == 1 {
srcParentID = srcObj.parents[0]
} else {
var err error
_, srcParentID, err = srcObj.fs.dirCache.FindPath(ctx, src.Remote(), false)
if err != nil {
return nil, err
}
srcParentID = actualID(srcParentID)
_, srcParentID, err := srcObj.fs.dirCache.FindPath(ctx, src.Remote(), false)
if err != nil {
return nil, err
}
srcParentID = actualID(srcParentID)
// Temporary Object under construction
dstInfo, err := f.createFileInfo(ctx, remote, src.ModTime(ctx))
-78
View File
@@ -681,83 +681,6 @@ func (f *Fs) InternalTestSingleQuoteFolder(t *testing.T) {
assert.NoError(t, err)
}
// TestIntegration/FsMkdir/FsPutFiles/Internal/MoveDuplicateParent
//
// Check that moving a file removes it from its real parent even when there
// are two directories with the same name and the directory cache resolves the
// path to the wrong duplicate. Otherwise the file ends up with two parents
// which fails on shared drives with a teamDrivesParentLimit error (#9472).
func (f *Fs) InternalTestMoveDuplicateParent(t *testing.T) {
ctx := context.Background()
if f.Features().Move == nil {
t.Skip("Move not supported")
}
rootID, err := f.dirCache.RootID(ctx, false)
require.NoError(t, err)
const dupName = "dup9472"
const dstName = "dst9472"
const fileName = "michael.txt"
// Create the first "dup9472" directory - this is the one the directory
// cache will resolve the path to.
dirA, err := f.createDir(ctx, rootID, dupName, nil)
require.NoError(t, err)
f.dirCache.Put(dupName, dirA.Id)
// Create a second directory with the SAME name and parent: a duplicate
// the directory cache does not know about.
dirB, err := f.createDir(ctx, rootID, dupName, nil)
require.NoError(t, err)
// Destination directory
dirDst, err := f.createDir(ctx, rootID, dstName, nil)
require.NoError(t, err)
defer func() {
_ = f.delete(ctx, dirA.Id, false)
_ = f.delete(ctx, dirB.Id, false)
_ = f.delete(ctx, dirDst.Id, false)
f.dirCache.Flush()
}()
// Upload a file directly into dirB (the duplicate the cache doesn't know).
createInfo := &drive.File{
Name: fileName,
Parents: []string{dirB.Id},
}
var fileInfo *drive.File
err = f.pacer.Call(func() (bool, error) {
fileInfo, err = f.svc.Files.Create(createInfo).
Media(strings.NewReader("9472 duplicate parent test")).
Fields(f.getFileFields(ctx)).
SupportsAllDrives(true).
Context(ctx).Do()
return f.shouldRetry(ctx, err)
})
require.NoError(t, err)
require.Equal(t, []string{dirB.Id}, fileInfo.Parents)
// Sanity check: the directory cache resolves the path to dirA, not the
// dirB the file actually lives in.
gotDirID, err := f.dirCache.FindDir(ctx, dupName, false)
require.NoError(t, err)
require.Equal(t, dirA.Id, gotDirID, "directory cache should resolve to the wrong duplicate")
// Build the source object pointing at the file in dirB and move it.
srcObj, err := f.newObjectWithInfo(ctx, dupName+"/"+fileName, fileInfo)
require.NoError(t, err)
dstObj, err := f.Move(ctx, srcObj, dstName+"/"+fileName)
require.NoError(t, err)
// The moved file must have exactly one parent: the destination.
movedInfo, err := f.getFile(ctx, dstObj.(fs.IDer).ID(), "id,parents")
require.NoError(t, err)
assert.Equal(t, []string{dirDst.Id}, movedInfo.Parents)
}
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) {
@@ -778,7 +701,6 @@ func (f *Fs) InternalTest(t *testing.T) {
t.Run("Query", f.InternalTestQuery)
t.Run("AgeQuery", f.InternalTestAgeQuery)
t.Run("SingleQuoteFolder", f.InternalTestSingleQuoteFolder)
t.Run("MoveDuplicateParent", f.InternalTestMoveDuplicateParent)
t.Run("ShouldRetry", f.InternalTestShouldRetry)
}
+17 -15
View File
@@ -222,36 +222,38 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
return nil, err
}
fldMap := map[string]bool{}
for _, folder := range result.Result.Folders {
fldMap[folder.FldID.String()] = true
if f.root == "" && dir == "" && strings.Contains(folder.Path, "/") {
continue
}
folderPath := strings.Trim(folder.Path, "/")
root := strings.Trim(f.root, "/")
remotePathWithoutRoot := folderPath
if root != "" {
if remotePathWithoutRoot == root {
continue
}
remotePathWithoutRoot = strings.TrimPrefix(remotePathWithoutRoot, root+"/")
paths := strings.Split(folder.Path, fullPath+"/")
remote := paths[0]
if len(paths) > 1 {
remote = paths[1]
}
remotePathWithoutRoot = strings.TrimPrefix(remotePathWithoutRoot, "/")
if remotePathWithoutRoot == "" {
if strings.Contains(remote, "/") {
continue
}
pathsWithoutRoot := strings.Split(folder.Path, "/"+f.root+"/")
remotePathWithoutRoot := pathsWithoutRoot[0]
if len(pathsWithoutRoot) > 1 {
remotePathWithoutRoot = pathsWithoutRoot[1]
}
remotePathWithoutRoot = strings.TrimPrefix(remotePathWithoutRoot, "/")
entries = append(entries, fs.NewDir(remotePathWithoutRoot, time.Now()))
}
for _, file := range result.Result.Files {
if _, ok := fldMap[file.FldID.String()]; ok {
continue
}
remote := path.Join(dir, file.Name)
// trim leading slashes
remote = strings.TrimPrefix(remote, "/")
obj := &Object{
fs: f,
remote: remote,
+2 -30
View File
@@ -21,11 +21,9 @@ import (
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/list"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"golang.org/x/sync/errgroup"
)
@@ -49,7 +47,7 @@ func init() {
},
{
Name: "api_key",
Help: `API Key for your Filen account
Help: `API Key for your Filen account
Get this using the Filen CLI export-api-key command
You can download the Filen CLI from https://github.com/FilenCloudDienste/filen-cli`,
@@ -163,7 +161,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
filen: filen,
Enc: opt.Encoder,
concurrency: opt.UploadConcurrency,
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
}
fileSystem.features = (&fs.Features{
@@ -197,13 +194,6 @@ type Options struct {
UploadConcurrency int `config:"upload_concurrency"`
}
// defaults copied from box
const (
minSleep = 10 * time.Millisecond
maxSleep = 2 * time.Second
decayConstant = 2 // bigger for slower decay, exponential
)
// Fs represents a virtual filesystem mounted on a specific root folder
type Fs struct {
name string
@@ -212,7 +202,6 @@ type Fs struct {
Enc encoder.MultiEncoder
features *fs.Features
concurrency int
pacer *fs.Pacer
}
// Name of the remote (as passed into NewFs)
@@ -362,7 +351,6 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
type chunkWriter struct {
sdk.FileUpload
filen *sdk.Filen
pacer *fs.Pacer
bucketAndRegion chan client.V3UploadResponse
chunkSize int64
@@ -374,13 +362,6 @@ type chunkWriter struct {
size int64
}
func shouldRetry(ctx context.Context, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
return fserrors.ShouldRetry(err), err
}
func (cw *chunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader io.ReadSeeker) (bytesWritten int64, err error) {
realChunkNumber := int64(chunkNumber) * (cw.chunkSize) / sdk.ChunkSize
chunk := make([]byte, sdk.ChunkSize, sdk.ChunkSize+cw.EncryptionKey.Cipher.Overhead())
@@ -433,15 +414,7 @@ func (cw *chunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader i
if err != nil {
return totalWritten, err
}
var resp *client.V3UploadResponse
err = cw.pacer.Call(func() (bool, error) {
var err error
resp, err = cw.filen.UploadChunk(ctx, &cw.FileUpload, realChunkNumber, chunkReadSlice)
if err != nil {
return shouldRetry(ctx, err)
}
return false, nil
})
resp, err := cw.filen.UploadChunk(ctx, &cw.FileUpload, realChunkNumber, chunkReadSlice)
if err != nil {
return totalWritten, err
}
@@ -521,7 +494,6 @@ func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectIn
return info, &chunkWriter{
FileUpload: *fu,
filen: f.filen,
pacer: f.pacer,
chunkSize: chunkSize,
bucketAndRegion: make(chan client.V3UploadResponse, 1),
knownChunks: make(map[int64][]byte),
-2
View File
@@ -349,8 +349,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return nil, err
}
oauthutil.SharedClientIDWarning(name, "Google Photos", "https://rclone.org/googlephotos/#making-your-own-client-id", m)
baseClient := fshttp.NewClient(ctx)
oAuthClient, ts, err := oauthutil.NewClientWithBaseClient(ctx, name, m, oauthConfig, baseClient)
if err != nil {
-44
View File
@@ -1,44 +0,0 @@
api文档
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-public-info-0000001050159641
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-aboutget-0000001050151684
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filescopy-0000001050151696
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filescreate-0000001050151686
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filescreatecontent-0000001050151688
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filescreatemultipart-0000001050151694
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filescreateresume-0000001050151690
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesdelete-0000001050153647
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesemptyrecycle-0000001050151698
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesgetmetadata-0000001050153645
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesgetcontent-0000001050153651
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-fileslist-0000001050153649
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesresume-0000001050153643
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filessubscribe-0000001050153637
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdate-0000001050153639
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdatepatchcontent-0000001050151700
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdatepatchmultipart-0000001050153653
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdatepatchresume-0000001050153641
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdateputcontent-0000001050151702
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdateputmultipart-0000001050151704
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-filesupdateputresume-0000001050151692
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-thumbnailget-0000001050151706
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-changesgetstartcursor-0000001050153659
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-changeslist-0000001050151710
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-changessubscribe-0000001050151708
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-channelsstop-0000001050151712
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentscreate-0000001050151716
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsdelete-0000001050151718
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsget-0000001050153665
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentslist-0000001050151714
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsupdate-0000001050153667
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-repliescreate-0000001050151722
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-repliesdelete-0000001050151724
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-repliesget-0000001050153671
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-replieslist-0000001050151720
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-repliesupdate-0000001050153673
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-smallthumbnailget-0000001050151726
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsdelete-0000001050188702
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsget-0000001050430911
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-historyversionsgetcontent-0000001050747405
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentslist-0000001050188698
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-commentsupdate-0000001050190853
https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-api-batchcallback-0000001050727110
-255
View File
@@ -1,255 +0,0 @@
// Package api provides types used by the Huawei Drive API.
package api
import (
"time"
)
// About represents response to About.get endpoint
type About struct {
StorageQuota struct {
UsedSpace string `json:"usedSpace"`
UserCapacity string `json:"userCapacity"`
} `json:"storageQuota"`
MaxThumbnailSize int64 `json:"maxThumbnailSize"`
NeedUpdate bool `json:"needUpdate"`
MaxFileUploadSize string `json:"maxFileUploadSize"`
Domain string `json:"domain"`
Category string `json:"category"`
User User `json:"user"`
FolderLevel int `json:"folderLevel"`
}
// User represents a user
type User struct {
PermissionID string `json:"permissionId"`
DisplayName string `json:"displayName"`
Me bool `json:"me"`
Category string `json:"category"`
}
// FileList represents response to Files.list endpoint
type FileList struct {
Files []File `json:"files"`
NextPageToken string `json:"nextPageToken,omitempty"`
Category string `json:"category"`
}
// File represents a file or folder in Huawei Drive
type File struct {
ID string `json:"id"`
FileName string `json:"fileName"`
OriginalFilename string `json:"originalFilename,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
Category string `json:"category"`
Size int64 `json:"size,omitempty"`
SHA256 string `json:"sha256,omitempty"`
CreatedTime time.Time `json:"createdTime"`
EditedTime time.Time `json:"editedTime"`
EditedByMeTime time.Time `json:"editedByMeTime,omitempty"`
ParentFolder []string `json:"parentFolder,omitempty"`
Owners []User `json:"owners"`
LastEditor User `json:"lastEditor"`
Permissions []Permission `json:"permissions"`
PermissionIDs []string `json:"permissionIds"`
Capabilities FileCapabilities `json:"capabilities"`
OwnedByMe bool `json:"ownedByMe"`
EditedByMe bool `json:"editedByMe"`
ViewedByMe bool `json:"viewedByMe"`
HasShared bool `json:"hasShared"`
Recycled bool `json:"recycled"`
DirectlyRecycled bool `json:"directlyRecycled"`
Favorite bool `json:"favorite"`
ExistThumbnail bool `json:"existThumbnail"`
ThumbnailVersion int64 `json:"thumbnailVersion"`
IconDownloadLink string `json:"iconDownloadLink,omitempty"`
ContentDownloadLink string `json:"contentDownloadLink,omitempty"`
ContentVersion string `json:"contentVersion,omitempty"`
LastHistoryVersionID string `json:"lastHistoryVersionId,omitempty"`
OccupiedSpace int64 `json:"occupiedSpace,omitempty"`
Version int64 `json:"version"`
WritersHasSharePermission bool `json:"writersHasSharePermission"`
WriterHasCopyPermission bool `json:"writerHasCopyPermission"`
Containers []string `json:"containers"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
ContentExtras *ContentExtras `json:"contentExtras,omitempty"`
}
// IsDir returns true if the file is a directory
func (f *File) IsDir() bool {
return f.MimeType == FolderMimeType
}
// Permission represents file permission
type Permission struct {
ID string `json:"id"`
Type string `json:"type"`
Role string `json:"role"`
DisplayName string `json:"displayName,omitempty"`
Deleted bool `json:"deleted"`
AllowFileDiscovery bool `json:"allowFileDiscovery,omitempty"`
Category string `json:"category"`
}
// FileCapabilities represents capabilities for a file
type FileCapabilities struct {
DownloadPermission bool `json:"downloadPermission"`
RenameFilePermission bool `json:"renameFilePermission"`
CommentPermission bool `json:"commentPermission"`
DeletePermission bool `json:"deletePermission"`
ReadHistoryVersionPermission bool `json:"readHistoryVersionPermission"`
RecyclePermission bool `json:"recyclePermission"`
AddChildNodePermission bool `json:"addChildNodePermission"`
UnrecyclePermission bool `json:"unrecyclePermission"`
WriterHasChangeCopyPermission bool `json:"writerHasChangeCopyPermission"`
CopyPermission bool `json:"copyPermission"`
EditContentPermission bool `json:"editContentPermission"`
RemoveChildNodePermission bool `json:"removeChildNodePermission"`
EditPermission bool `json:"editPermission"`
ListChildNodePermission bool `json:"listChildNodePermission"`
ShareFilePermission bool `json:"shareFilePermission"`
}
// ContentExtras represents additional content information
type ContentExtras struct {
Thumbnail *Thumbnail `json:"thumbnail,omitempty"`
}
// Thumbnail represents thumbnail information
type Thumbnail struct {
Content string `json:"content"` // base64 encoded
MimeType string `json:"mimeType"`
}
// CreateFolderRequest represents request to create a folder
type CreateFolderRequest struct {
FileName string `json:"fileName"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType"`
ParentFolder []string `json:"parentFolder,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
AutoRename int `json:"autoRename,omitempty"`
}
// UpdateFileRequest represents request to update a file
type UpdateFileRequest struct {
FileName string `json:"fileName,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
Favorite *bool `json:"favorite,omitempty"`
Recycled *bool `json:"recycled,omitempty"`
OriginalFilename string `json:"originalFilename,omitempty"`
WriterHasCopyPermission *bool `json:"writerHasCopyPermission,omitempty"`
WritersHasSharePermission *bool `json:"writersHasSharePermission,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
AddParentFolder []string `json:"addParentFolder,omitempty"`
RemoveParentFolder []string `json:"removeParentFolder,omitempty"`
CreatedTime *time.Time `json:"createdTime,omitempty"`
EditedTime *time.Time `json:"editedTime,omitempty"`
}
// CopyFileRequest represents request to copy a file
type CopyFileRequest struct {
FileName string `json:"fileName,omitempty"`
MimeType string `json:"mimeType,omitempty"`
ParentFolder []string `json:"parentFolder,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
AppSettings map[string]interface{} `json:"appSettings,omitempty"`
}
// ResumeUploadInitResponse represents response to resume upload init
type ResumeUploadInitResponse struct {
SliceSize int64 `json:"sliceSize"`
}
// ErrorResponse represents an error response from the API
type ErrorResponse struct {
Error struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
// Constants
const (
// MIME types
FolderMimeType = "application/vnd.huawei-apps.folder"
// Special folder names
ApplicationDataFolder = "applicationData"
// Upload types
UploadTypeMultipart = "multipart"
UploadTypeContent = "content"
UploadTypeResume = "resume"
// Form types
FormContent = "content"
FormJSON = "json"
// Categories
CategoryDriveFile = "drive#file"
CategoryDriveFileList = "drive#fileList"
CategoryDriveAbout = "drive#about"
CategoryDriveUser = "drive#user"
// Global API domain (always available)
GlobalDriveAPI = "https://driveapis.cloud.huawei.com.cn"
GlobalUploadAPI = "https://driveapis.cloud.huawei.com.cn"
)
// DomainToRootURL maps the domain field from About:get to the regional API root URL.
// The API returns the full domain name (e.g., "driveapis.cloud.huawei.com.cn").
// If the domain matches the global API, no switch is needed.
// See: https://developer.huawei.com/consumer/cn/doc/HMSCore-References/server-public-info-0000001050159641
var DomainToRootURL = map[string]string{
"china": "https://drive-drcn.cloud.dbankcloud.cn",
"europe": "https://drive-dre.cloud.dbankcloud.cn",
"aala": "https://drive-dra.cloud.dbankcloud.cn",
"russia": "https://drive-drru.cloud.dbankcloud.cn",
"drive-drcn.cloud.dbankcloud.cn": "https://drive-drcn.cloud.dbankcloud.cn",
"drive-dre.cloud.dbankcloud.cn": "https://drive-dre.cloud.dbankcloud.cn",
"drive-dra.cloud.dbankcloud.cn": "https://drive-dra.cloud.dbankcloud.cn",
"drive-drru.cloud.dbankcloud.cn": "https://drive-drru.cloud.dbankcloud.cn",
}
// GlobalDomains lists domain values that indicate the global API endpoint (no switch needed)
var GlobalDomains = map[string]bool{
"driveapis.cloud.huawei.com.cn": true,
"drive.cloud.hicloud.com": true,
}
// BoolPtr returns a pointer to a bool value (helper for UpdateFileRequest)
func BoolPtr(b bool) *bool {
return &b
}
// StartCursor represents response to Changes.getStartCursor endpoint
type StartCursor struct {
Category string `json:"category"` // "drive#startCursor"
StartCursor string `json:"startCursor"`
}
// ChangeList represents response to Changes.list endpoint
type ChangeList struct {
Category string `json:"category"` // "drive#changeList"
NextCursor string `json:"nextCursor,omitempty"`
NewStartCursor string `json:"newStartCursor,omitempty"`
Changes []ChangeItem `json:"changes"`
}
// ChangeItem represents a single change entry
type ChangeItem struct {
Category string `json:"category"` // "drive#change"
Type string `json:"type"` // resource type, e.g. "File"
ChangeType string `json:"changeType"` // change type, e.g. "File"
Time string `json:"time"`
Deleted bool `json:"deleted"`
FileID string `json:"fileId"`
File *File `json:"file,omitempty"`
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+50 -113
View File
@@ -1,4 +1,4 @@
// Package api provides functionality for interacting with the iCloud API
// Package api provides functionality for interacting with the iCloud API.
package api
import (
@@ -8,55 +8,46 @@ import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/lib/rest"
)
const (
baseEndpoint = "https://www.icloud.com"
homeEndpoint = "https://www.icloud.com"
setupEndpoint = "https://setup.icloud.com/setup/ws/1"
authEndpoint = "https://idmsa.apple.com/appleauth/auth"
)
// Webservice keys in AccountInfo.Webservices map
const (
WsDrive = "drivews"
WsDocs = "docws"
WsPhotos = "ckdatabasews"
)
type sessionSave func(*Session)
// Client defines the client configuration
type Client struct {
appleID string
password string
remoteName string // rclone remote name, used for cache namespacing
pcsWSKey string // webservice key for PCS cookie scoping (e.g. WsDrive, WsPhotos)
srv *rest.Client
Session *Session
sessionSaveCallback sessionSave
drive *DriveService
mu sync.Mutex // protects drive and Authenticate
}
// New creates a new iCloud API client and initializes its HTTP session
// pcsWSKey scopes PCS cookie acquisition to the caller's webservice (WsDrive, WsPhotos);
// empty string skips PCS entirely
func New(appleID, password, trustToken string, clientID string, cookies []*http.Cookie, sessionSaveCallback sessionSave, remoteName string, pcsWSKey string) (*Client, error) {
// New creates a new Client instance with the provided Apple ID, password, trust token, cookies, and session save callback.
//
// Parameters:
// - appleID: the Apple ID of the user.
// - password: the password of the user.
// - trustToken: the trust token for the session.
// - clientID: the client id for the session.
// - cookies: the cookies for the session.
// - sessionSaveCallback: the callback function to save the session.
func New(appleID, password, trustToken string, clientID string, cookies []*http.Cookie, sessionSaveCallback sessionSave) (*Client, error) {
icloud := &Client{
appleID: strings.ToLower(appleID), // Apple SRP requires lowercase in client-side proof
appleID: appleID,
password: password,
remoteName: filepath.Base(remoteName),
pcsWSKey: pcsWSKey,
srv: rest.NewClient(fshttp.NewClient(context.Background())),
Session: NewSession(),
sessionSaveCallback: sessionSaveCallback,
@@ -68,12 +59,10 @@ func New(appleID, password, trustToken string, clientID string, cookies []*http.
return icloud, nil
}
// DriveService returns the DriveService instance, creating it on first call
// DriveService returns the DriveService instance associated with the Client.
func (c *Client) DriveService() (*DriveService, error) {
c.mu.Lock()
defer c.mu.Unlock()
var err error
if c.drive == nil {
var err error
c.drive, err = NewDriveService(c)
if err != nil {
return nil, err
@@ -82,12 +71,16 @@ func (c *Client) DriveService() (*DriveService, error) {
return c.drive, nil
}
// Request makes a request to the iCloud API, re-authenticating on 401/421
// Request makes a request and retries it if the session is invalid.
//
// This function is the main entry point for making requests to the iCloud
// API. If the initial request returns a 401 (Unauthorized), it will try to
// reauthenticate and retry the request.
func (c *Client) Request(ctx context.Context, opts rest.Opts, request any, response any) (resp *http.Response, err error) {
resp, err = c.Session.Request(ctx, opts, request, response)
if err != nil && resp != nil {
// 401/421 = session expired, 423 = missing PCS cookies (ADP)
if resp.StatusCode == 401 || resp.StatusCode == 421 || resp.StatusCode == 423 {
// try to reauth
if resp.StatusCode == 401 || resp.StatusCode == 421 {
err = c.Authenticate(ctx)
if err != nil {
return nil, err
@@ -96,111 +89,55 @@ func (c *Client) Request(ctx context.Context, opts rest.Opts, request any, respo
if c.Session.Requires2FA() {
return nil, errors.New("trust token expired, please reauth")
}
return c.Session.Request(ctx, opts, request, response)
return c.RequestNoReAuth(ctx, opts, request, response)
}
}
return resp, err
}
// Authenticate authenticates the client, reusing existing session if valid
func (c *Client) Authenticate(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.authenticateSession(ctx); err != nil {
return err
}
// Ensure PCS cookies after any successful auth path (ADP accounts)
acquired, err := c.Session.ensurePCSCookies(ctx, c.pcsWSKey)
if err != nil {
return err
}
if acquired && c.sessionSaveCallback != nil {
c.sessionSaveCallback(c.Session)
}
return nil
// RequestNoReAuth makes a request without re-authenticating.
//
// This function is useful when you have a session that is already
// authenticated, but you need to make a request without triggering
// a re-authentication.
func (c *Client) RequestNoReAuth(ctx context.Context, opts rest.Opts, request any, response any) (resp *http.Response, err error) {
// Make the request without re-authenticating
resp, err = c.Session.Request(ctx, opts, request, response)
return resp, err
}
// authenticateSession establishes a valid session via the cheapest available path
func (c *Client) authenticateSession(ctx context.Context) error {
// Skip /validate round-trip when saved session has cookies + service endpoints
// Native client behavior: use cached session, reauth lazily on 401/421
if c.Session.Cookies != nil && len(c.Session.AccountInfo.Webservices) > 0 {
fs.Debugf(nil, "iclouddrive: reusing saved session")
return nil
}
// Try loading cached service endpoints to avoid /validate round-trip (~5s)
if c.Session.Cookies != nil && c.loadCachedWebservices() {
fs.Debugf(nil, "iclouddrive: reusing session with cached endpoints")
return nil
}
// Authenticate authenticates the client with the iCloud API.
func (c *Client) Authenticate(ctx context.Context) error {
if c.Session.Cookies != nil {
if err := c.Session.ValidateSession(ctx); err == nil {
fs.Debugf(nil, "iclouddrive: valid session, no need to reauth")
c.saveCachedWebservices()
fs.Debugf("icloud", "Valid session, no need to reauth")
return nil
}
c.Session.Cookies = nil
}
fs.Debugf(nil, "iclouddrive: authenticating")
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, skip AuthWithToken - caller must complete 2FA first
// 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.saveCachedWebservices()
if c.sessionSaveCallback != nil {
c.sessionSaveCallback(c.Session)
}
if err == nil && c.sessionSaveCallback != nil {
c.sessionSaveCallback(c.Session)
}
return err
}
// loadCachedWebservices loads service endpoints from disk cache
func (c *Client) loadCachedWebservices() bool {
data, err := os.ReadFile(filepath.Join(config.GetCacheDir(), cacheSubdir, c.remoteName, "webservices.json"))
if err != nil {
return false
}
var ws map[string]*webService
if err := json.Unmarshal(data, &ws); err != nil {
return false
}
if len(ws) == 0 {
return false
}
c.Session.AccountInfo.Webservices = ws
return true
}
// saveCachedWebservices persists service endpoints to disk
func (c *Client) saveCachedWebservices() {
if len(c.Session.AccountInfo.Webservices) == 0 {
return
}
saveJSONCache(filepath.Join(config.GetCacheDir(), cacheSubdir, c.remoteName), "webservices.json", c.Session.AccountInfo.Webservices)
}
// CacheDir returns the disk cache directory for this remote
func (c *Client) CacheDir() string {
return filepath.Join(config.GetCacheDir(), cacheSubdir, c.remoteName)
}
// ClearCacheDir removes all disk cache files for a remote
func ClearCacheDir(remoteName string) {
dir := filepath.Join(config.GetCacheDir(), cacheSubdir, filepath.Base(remoteName))
if err := os.RemoveAll(dir); err != nil {
fs.Debugf(nil, "iclouddrive: failed to clear cache: %v", err)
}
// SignIn signs in the client using the provided context and credentials.
func (c *Client) SignIn(ctx context.Context) error {
return c.Session.SignIn(ctx, c.appleID, c.password)
}
// IntoReader marshals the provided values into a JSON encoded reader
@@ -218,19 +155,19 @@ type RequestError struct {
Text string
}
// Error satisfies the error interface
// Error satisfy the error interface.
func (e *RequestError) Error() string {
return fmt.Sprintf("%s: %s", e.Text, e.Status)
}
func newRequestError(status string, text string) *RequestError {
func newRequestError(Status string, Text string) *RequestError {
return &RequestError{
Status: strings.ToLower(status),
Text: text,
Status: strings.ToLower(Status),
Text: Text,
}
}
// newRequestErrorf makes a new error from sprintf parameters
func newRequestErrorf(status string, text string, params ...any) *RequestError {
return newRequestError(status, fmt.Sprintf(text, params...))
// newErr orf makes a new error from sprintf parameters.
func newRequestErrorf(Status string, Text string, Parameters ...any) *RequestError {
return newRequestError(strings.ToLower(Status), fmt.Sprintf(Text, Parameters...))
}
+1 -1
View File
@@ -33,7 +33,7 @@ type DriveService struct {
// NewDriveService creates a new DriveService instance.
func NewDriveService(icloud *Client) (*DriveService, error) {
return &DriveService{icloud: icloud, RootID: "FOLDER::com.apple.CloudDocs::root", endpoint: icloud.Session.AccountInfo.Webservices[WsDrive].URL, docsEndpoint: icloud.Session.AccountInfo.Webservices[WsDocs].URL}, nil
return &DriveService{icloud: icloud, RootID: "FOLDER::com.apple.CloudDocs::root", endpoint: icloud.Session.AccountInfo.Webservices["drivews"].URL, docsEndpoint: icloud.Session.AccountInfo.Webservices["docws"].URL}, nil
}
// GetItemByDriveID retrieves a DriveItem by its Drive ID.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+239 -477
View File
@@ -2,21 +2,16 @@ package api
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"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"
@@ -37,7 +32,6 @@ type Session struct {
Cookies []*http.Cookie `json:"cookies"`
AccountInfo AccountInfo `json:"account_info"`
mu sync.Mutex `json:"-"` // protects session fields during concurrent Request calls
srv *rest.Client `json:"-"`
needs2FA bool `json:"-"` // set when SRP signin returns 409
}
@@ -51,117 +45,20 @@ type srpInitResponse struct {
C string `json:"c"`
}
func cookieValueFingerprint(value string) string {
if value == "" {
return ""
}
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:6])
}
// String returns the session as a string
// func (s *Session) String() string {
// jsession, _ := json.Marshal(s)
// return string(jsession)
// }
func authStateBodySummary(body []byte) string {
summary := []string{fmt.Sprintf("bytes=%d", len(body)), "hash=" + cookieValueFingerprint(string(body))}
var top map[string]json.RawMessage
if err := json.Unmarshal(body, &top); err != nil {
return strings.Join(summary, " ")
}
keys := make([]string, 0, len(top))
for key := range top {
keys = append(keys, key)
}
slices.Sort(keys)
summary = append(summary, fmt.Sprintf("keys=%v", keys))
if _, ok := top["phoneNumberVerification"]; ok {
summary = append(summary, "wrapped=true")
}
return strings.Join(summary, " ")
}
// Request makes a request
func (s *Session) Request(ctx context.Context, opts rest.Opts, request any, response any) (*http.Response, error) {
resp, err := s.srv.CallJSON(ctx, &opts, &request, &response)
func cookieDebugSummary(c *http.Cookie) string {
parts := []string{c.Name}
if c.Value == "" {
parts = append(parts, "empty", "len=0")
} else {
parts = append(parts, "set", fmt.Sprintf("len=%d", len(c.Value)), "hash="+cookieValueFingerprint(c.Value))
if err != nil {
return resp, err
}
if c.Path != "" {
parts = append(parts, "path="+c.Path)
}
if c.Domain != "" {
parts = append(parts, "domain="+c.Domain)
}
if c.MaxAge != 0 {
parts = append(parts, fmt.Sprintf("maxAge=%d", c.MaxAge))
}
if !c.Expires.IsZero() {
parts = append(parts, "expires")
}
return strings.Join(parts, ",")
}
func cookieDebugSummaries(cookies []*http.Cookie) []string {
if len(cookies) == 0 {
return nil
}
out := make([]string, 0, len(cookies))
for _, c := range cookies {
out = append(out, cookieDebugSummary(c))
}
return out
}
func cookieJarDebugSummaries(cookies []*http.Cookie) []string {
if len(cookies) == 0 {
return nil
}
out := make([]string, 0, len(cookies))
for _, c := range cookies {
summary := c.Name
if c.Value == "" {
summary += ",empty,len=0"
} else {
summary += fmt.Sprintf(",len=%d,hash=%s", len(c.Value), cookieValueFingerprint(c.Value))
}
out = append(out, summary)
}
return out
}
func (s *Session) mergeCookies(cookies []*http.Cookie) {
if len(cookies) == 0 {
return
}
existing := make(map[string]int, len(s.Cookies))
for i, c := range s.Cookies {
existing[c.Name] = i
}
for _, c := range cookies {
if c.Value == "" {
if idx, ok := existing[c.Name]; ok {
fs.Debugf(nil, "iclouddrive: deleting empty auth cookie: %s", cookieDebugSummary(c))
s.Cookies = append(s.Cookies[:idx], s.Cookies[idx+1:]...)
delete(existing, c.Name)
for j := idx; j < len(s.Cookies); j++ {
existing[s.Cookies[j].Name] = j
}
} else {
fs.Debugf(nil, "iclouddrive: ignoring empty auth cookie tombstone for missing cookie: %s", cookieDebugSummary(c))
}
continue
}
if idx, ok := existing[c.Name]; ok {
s.Cookies[idx] = c
} else {
s.Cookies = append(s.Cookies, c)
existing[c.Name] = len(s.Cookies) - 1
}
}
}
// extractHeaders reads Apple session headers from an HTTP response into the session
// Does NOT acquire s.mu - caller is responsible for locking if needed
func (s *Session) extractHeaders(resp *http.Response) {
s.mergeCookies(resp.Cookies())
if val := resp.Header.Get("X-Apple-ID-Account-Country"); val != "" {
s.AccountCountry = val
}
@@ -180,17 +77,7 @@ func (s *Session) extractHeaders(resp *http.Response) {
if val := resp.Header.Get("X-Apple-Auth-Attributes"); val != "" {
s.AuthAttributes = val
}
}
// Request makes a JSON API request and extracts session headers
func (s *Session) Request(ctx context.Context, opts rest.Opts, request any, response any) (*http.Response, error) {
resp, err := s.srv.CallJSON(ctx, &opts, &request, &response)
if err != nil {
return resp, err
}
s.mu.Lock()
s.extractHeaders(resp)
s.mu.Unlock()
return resp, nil
}
@@ -202,8 +89,13 @@ func (s *Session) Requires2FA() bool {
return s.AccountInfo.DsInfo != nil && s.AccountInfo.DsInfo.HsaVersion == 2 && s.AccountInfo.HsaChallengeRequired
}
// SignIn performs SRP-based authentication against Apple's idmsa endpoint
// SignIn performs SRP-based authentication against Apple's idmsa endpoint.
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)
@@ -214,11 +106,8 @@ func (s *Session) SignIn(ctx context.Context, appleID, password string) error {
return fmt.Errorf("authFederate: %w", err)
}
// Step 3: SRP init - send client public value A, get salt + B
client, err := newSRPClient()
if err != nil {
return fmt.Errorf("newSRPClient: %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)
@@ -241,11 +130,9 @@ func (s *Session) SignIn(ctx context.Context, appleID, password string) error {
if err != nil {
return fmt.Errorf("derivePassword: %w", err)
}
if err := client.processChallenge([]byte(appleID), derivedKey, salt, serverB); err != nil {
return fmt.Errorf("processChallenge: %w", err)
}
client.processChallenge([]byte(appleID), derivedKey, salt, serverB)
// Step 5: Complete - send M1, M2 proofs
// Step 5: Complete — send M1, M2 proofs
m1Base64 := base64.StdEncoding.EncodeToString(client.M1)
m2Base64 := base64.StdEncoding.EncodeToString(client.M2)
@@ -256,7 +143,7 @@ func (s *Session) SignIn(ctx context.Context, appleID, password string) error {
return nil
}
// authStart initializes the SRP auth session by hitting the authorize/signin endpoint
// 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())
@@ -297,11 +184,20 @@ func (s *Session) authStart(ctx context.Context) error {
return fmt.Errorf("authStart: unexpected status %s", resp.Status)
}
s.extractHeaders(resp)
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
// 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,
@@ -328,7 +224,16 @@ func (s *Session) authFederate(ctx context.Context, accountName string) error {
}
_ = resp.Body.Close()
s.extractHeaders(resp)
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)
}
@@ -336,7 +241,7 @@ func (s *Session) authFederate(ctx context.Context, accountName string) error {
}
// authSRPInit sends the client's public value A to the server and retrieves
// the salt, server public value B, iteration count, protocol, and challenge
// 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,
@@ -362,12 +267,18 @@ func (s *Session) authSRPInit(ctx context.Context, aBase64, accountName string)
return nil, err
}
s.extractHeaders(resp)
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)
// 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 != "" {
@@ -394,72 +305,59 @@ func (s *Session) authSRPComplete(ctx context.Context, accountName, m1Base64, m2
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: authEndpoint,
IgnoreStatus: true,
Body: body,
}
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return err
}
respBody, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
s.extractHeaders(resp)
switch resp.StatusCode {
case http.StatusOK:
fs.Debugf(nil, "iclouddrive: SRP sign in successful")
return nil
case http.StatusConflict:
// 409 = 2FA required
fs.Debugf(nil, "iclouddrive: SRP sign in requires 2FA, response: %s", respBody)
s.needs2FA = true
return nil
case http.StatusPreconditionFailed:
// 412 = non-2FA account needs repair/complete step
fs.Debugf(nil, "iclouddrive: SRP sign in returned 412, attempting repair/complete")
return s.authRepairComplete(ctx)
case http.StatusForbidden:
return fmt.Errorf("sign in failed: incorrect username or password")
default:
return fmt.Errorf("sign in failed: %s: %s", resp.Status, respBody)
}
}
// authRepairComplete handles the repair flow for non-2FA accounts that return 412
func (s *Session) authRepairComplete(ctx context.Context) error {
body, err := IntoReader(map[string]any{})
if err != nil {
return err
}
opts := rest.Opts{
Method: "POST",
Path: "/repair/complete",
ExtraHeaders: s.getSRPAuthHeaders(),
RootURL: authEndpoint,
IgnoreStatus: true,
NoResponse: true,
Body: body,
}
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return fmt.Errorf("repair/complete failed: %w", err)
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("repair/complete returned %s", resp.Status)
_ = resp.Body.Close()
// 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)
}
s.extractHeaders(resp)
fs.Debugf(nil, "iclouddrive: repair/complete successful")
return nil
}
// getAuthOrigin returns the origin URL for auth requests
// Supports both global (idmsa.apple.com) and China (idmsa.apple.com.cn) endpoints
// 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
// getSRPAuthHeaders returns headers needed for SRP auth requests.
func (s *Session) getSRPAuthHeaders() map[string]string {
frameTag := "auth-" + s.FrameID
authOrigin := getAuthOrigin()
@@ -495,7 +393,7 @@ func (s *Session) getSRPAuthHeaders() map[string]string {
return headers
}
// AuthWithToken authenticates the session with the account login endpoint
// AuthWithToken authenticates the session
func (s *Session) AuthWithToken(ctx context.Context) error {
values := map[string]any{
"accountCountryCode": s.AccountCountry,
@@ -516,134 +414,14 @@ func (s *Session) AuthWithToken(ctx context.Context) error {
}
resp, err := s.Request(ctx, opts, nil, &s.AccountInfo)
if err != nil {
return err
}
fs.Debugf(nil, "iclouddrive: accountLogin response cookies: %v", cookieDebugSummaries(resp.Cookies()))
fs.Debugf(nil, "iclouddrive: session cookie jar after accountLogin: %v", cookieJarDebugSummaries(s.Cookies))
return nil
}
type pcsService struct {
wsKey string
appName string
cookies []string
}
// pcsServices lists all services that need PCS cookies
// appName values from icloud.com JS (Build 2616/19)
var pcsServices = []pcsService{
{WsPhotos, "photos", []string{"X-APPLE-WEBAUTH-PCS-Photos", "X-APPLE-WEBAUTH-PCS-Sharing"}},
{WsDrive, "iclouddrive", []string{"X-APPLE-WEBAUTH-PCS-Documents"}},
}
func (s *Session) hasPCSCookiesFor(names []string) bool {
for _, name := range names {
if !slices.ContainsFunc(s.Cookies, func(c *http.Cookie) bool { return c.Name == name }) {
return false
}
}
return true
}
// ensurePCSCookies checks whether the session needs PCS cookies for the given
// webservice and acquires them if missing, returning true if new cookies were acquired
func (s *Session) ensurePCSCookies(ctx context.Context, pcsWSKey string) (bool, error) {
if pcsWSKey == "" {
return false, nil
}
for _, pcs := range pcsServices {
if pcs.wsKey != pcsWSKey {
continue
}
ws := s.AccountInfo.Webservices[pcs.wsKey]
if ws == nil || !ws.PcsRequired {
return false, nil
}
if s.hasPCSCookiesFor(pcs.cookies) {
return false, nil
}
fs.Debugf(nil, "iclouddrive: ADP detected, acquiring PCS cookies for %s", pcs.appName)
if err := s.acquirePCSCookiesFor(ctx, pcs.appName, pcs.cookies); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// acquirePCSCookiesFor requests PCS cookies for a specific service on ADP-enabled accounts
// May require user approval on a trusted device (polls every 10s, max 5 min)
func (s *Session) acquirePCSCookiesFor(ctx context.Context, appName string, cookies []string) error {
fs.Logf(nil, "iclouddrive: Advanced Data Protection enabled, requesting PCS cookies for %s", appName)
const maxAttempts = 30
for range maxAttempts {
fs.Debugf(nil, "iclouddrive: requestPCS(%s) outgoing cookies: %v", appName, cookieJarDebugSummaries(s.Cookies))
values := map[string]any{
"appName": appName,
"derivedFromUserAction": true,
}
body, err := IntoReader(values)
if err != nil {
return fmt.Errorf("requestPCS(%s): %w", appName, err)
}
opts := rest.Opts{
Method: "POST",
Path: "/requestPCS",
ExtraHeaders: s.GetHeaders(map[string]string{}),
RootURL: setupEndpoint,
Body: body,
}
var pcsResp struct {
Status string `json:"status"`
Message string `json:"message"`
}
resp, err := s.Request(ctx, opts, nil, &pcsResp)
if err != nil {
return fmt.Errorf("requestPCS(%s): %w", appName, err)
}
fs.Debugf(nil, "iclouddrive: requestPCS(%s) response: status=%q message=%q cookies=%d %v",
appName, pcsResp.Status, pcsResp.Message, len(resp.Cookies()), cookieDebugSummaries(resp.Cookies()))
if pcsResp.Status == "success" {
if !s.hasPCSCookiesFor(cookies) {
var missing []string
for _, name := range cookies {
if !slices.ContainsFunc(s.Cookies, func(c *http.Cookie) bool { return c.Name == name }) {
missing = append(missing, name)
}
}
return fmt.Errorf("requestPCS(%s): server returned success but cookies still missing: %v", appName, missing)
}
fs.Logf(nil, "iclouddrive: PCS cookies acquired for %s", appName)
return nil
}
fs.Logf(nil, "iclouddrive: waiting for device approval for PCS/%s (%s)", appName, pcsResp.Message)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(10 * time.Second):
}
}
return fmt.Errorf("requestPCS(%s): timed out waiting for device approval after 5 minutes", appName)
}
// RequestPushNotification explicitly requests a push notification to trusted devices
// Required for iOS 26.4+ where the SRP 409 response no longer auto-pushes
func (s *Session) RequestPushNotification(ctx context.Context) error {
opts := rest.Opts{
Method: "PUT",
Path: "/verify/trusteddevice/securitycode",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
NoResponse: true,
if err == nil {
s.Cookies = resp.Cookies()
}
_, err := s.Request(ctx, opts, nil, nil)
return err
}
// Validate2FACode validates the 2FA code from a trusted device push notification
// Validate2FACode validates the 2FA code
func (s *Session) Validate2FACode(ctx context.Context, code string) error {
values := map[string]any{"securityCode": map[string]string{"code": code}}
body, err := IntoReader(values)
@@ -672,132 +450,6 @@ func (s *Session) Validate2FACode(ctx context.Context, code string) error {
return fmt.Errorf("validate2FACode failed: %w", err)
}
// TrustedPhoneNumber represents a phone number that can receive SMS verification codes
type TrustedPhoneNumber struct {
ID int `json:"id"`
NumberWithDialCode string `json:"numberWithDialCode"`
ObfuscatedNumber string `json:"obfuscatedNumber"`
PushMode string `json:"pushMode"`
NonFTEU bool `json:"nonFTEU"`
}
// AuthStateResponse is the response from GET /appleauth/auth after sign-in
// Some accounts return fields at top level, others nest them under phoneNumberVerification
type AuthStateResponse struct {
TrustedPhoneNumbers []TrustedPhoneNumber `json:"trustedPhoneNumbers"`
TrustedPhoneNumber *TrustedPhoneNumber `json:"trustedPhoneNumber"`
NoTrustedDevices bool `json:"noTrustedDevices"`
AuthenticationType string `json:"authenticationType"`
Hsa2Account bool `json:"hsa2Account"`
PhoneNumberVerification *AuthStateResponse `json:"phoneNumberVerification"`
}
// GetAuthState retrieves the current auth state including trusted phone numbers for SMS 2FA
func (s *Session) GetAuthState(ctx context.Context) (*AuthStateResponse, error) {
opts := rest.Opts{
Method: "GET",
Path: "",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
ContentLength: int64Ptr(0),
}
// Use srv.Call directly to capture the raw response body for debugging
resp, err := s.srv.Call(ctx, &opts)
if err != nil {
return nil, fmt.Errorf("getAuthState: %w", err)
}
s.mu.Lock()
s.extractHeaders(resp)
s.mu.Unlock()
body, readErr := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if readErr != nil {
return nil, fmt.Errorf("getAuthState read: %w", readErr)
}
fs.Debugf(nil, "iclouddrive: auth state response summary: %s", authStateBodySummary(body))
var state AuthStateResponse
if err := json.Unmarshal(body, &state); err != nil {
fs.Debugf(nil, "iclouddrive: auth state parse failed: %s", authStateBodySummary(body))
return nil, fmt.Errorf("getAuthState unmarshal: %w", err)
}
// Some accounts nest auth data under phoneNumberVerification
if state.PhoneNumberVerification != nil && state.AuthenticationType == "" {
fs.Debugf(nil, "iclouddrive: unwrapping phoneNumberVerification envelope")
n := state.PhoneNumberVerification
state.TrustedPhoneNumbers = n.TrustedPhoneNumbers
state.TrustedPhoneNumber = n.TrustedPhoneNumber
state.NoTrustedDevices = n.NoTrustedDevices
state.AuthenticationType = n.AuthenticationType
state.Hsa2Account = n.Hsa2Account
state.PhoneNumberVerification = nil
}
fs.Debugf(nil, "iclouddrive: auth state: type=%s hsa2=%v noTrustedDevices=%v phones=%d phoneSingular=%v",
state.AuthenticationType, state.Hsa2Account, state.NoTrustedDevices,
len(state.TrustedPhoneNumbers), state.TrustedPhoneNumber != nil)
// Fall back to singular trustedPhoneNumber when plural array is empty
// Some accounts return only the singular form (SMS-only, no trusted devices)
if len(state.TrustedPhoneNumbers) == 0 && state.TrustedPhoneNumber != nil {
fs.Debugf(nil, "iclouddrive: using singular trustedPhoneNumber (id=%d) as fallback",
state.TrustedPhoneNumber.ID)
state.TrustedPhoneNumbers = []TrustedPhoneNumber{*state.TrustedPhoneNumber}
}
return &state, nil
}
// RequestSMSCode triggers SMS code delivery to a trusted phone number
func (s *Session) RequestSMSCode(ctx context.Context, phoneID int, mode string) error {
values := map[string]any{
"phoneNumber": map[string]any{"id": phoneID},
"mode": mode,
}
body, err := IntoReader(values)
if err != nil {
return err
}
opts := rest.Opts{
Method: "PUT",
Path: "/verify/phone",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
_, err = s.Request(ctx, opts, nil, nil)
if err != nil {
return fmt.Errorf("requestSMSCode: %w", err)
}
return nil
}
// ValidateSMSCode validates a 2FA code received via SMS
func (s *Session) ValidateSMSCode(ctx context.Context, code string, phoneID int, mode string) error {
values := map[string]any{
"securityCode": map[string]string{"code": code},
"phoneNumber": map[string]any{"id": phoneID},
"mode": mode,
}
body, err := IntoReader(values)
if err != nil {
return err
}
opts := rest.Opts{
Method: "POST",
Path: "/verify/phone/securitycode",
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
Body: body,
NoResponse: true,
}
_, err = s.Request(ctx, opts, nil, nil)
if err == nil {
if err := s.TrustSession(ctx); err != nil {
return err
}
return nil
}
return fmt.Errorf("validateSMSCode: %w", err)
}
// TrustSession trusts the session
func (s *Session) TrustSession(ctx context.Context) error {
opts := rest.Opts{
@@ -806,7 +458,7 @@ func (s *Session) TrustSession(ctx context.Context) error {
ExtraHeaders: s.GetAuthHeaders(map[string]string{}),
RootURL: authEndpoint,
NoResponse: true,
ContentLength: int64Ptr(0),
ContentLength: common.Int64(0),
}
_, err := s.Request(ctx, opts, nil, nil)
@@ -824,26 +476,25 @@ func (s *Session) ValidateSession(ctx context.Context) error {
Path: "/validate",
ExtraHeaders: s.GetHeaders(map[string]string{}),
RootURL: setupEndpoint,
ContentLength: int64Ptr(0),
ContentLength: common.Int64(0),
}
_, err := s.Request(ctx, opts, nil, &s.AccountInfo)
if err != nil {
return fmt.Errorf("validateSession failed: %w", err)
}
s.needs2FA = false
return nil
}
// GetAuthHeaders returns the authentication headers for the session
// Used for 2FA validation and trust requests to idmsa.apple.com
// GetAuthHeaders returns the authentication headers for the session.
// Used for 2FA validation and trust requests to idmsa.apple.com.
func (s *Session) GetAuthHeaders(overwrite map[string]string) map[string]string {
headers := s.getSRPAuthHeaders()
maps.Copy(headers, overwrite)
return headers
}
// GetHeaders returns the authentication headers required for a request
// GetHeaders Gets the authentication headers required for a request
func (s *Session) GetHeaders(overwrite map[string]string) map[string]string {
headers := GetCommonHeaders(map[string]string{})
headers["Cookie"] = s.GetCookieString()
@@ -851,26 +502,17 @@ func (s *Session) GetHeaders(overwrite map[string]string) map[string]string {
return headers
}
// GetCookieString returns the cookie header string for the session
// GetCookieString returns the cookie header string for the session.
func (s *Session) GetCookieString() string {
var b strings.Builder
first := true
cookieHeader := ""
// we only care about name and value.
for _, cookie := range s.Cookies {
if cookie.Value == "" {
continue
}
if !first {
b.WriteString("; ")
}
first = false
b.WriteString(cookie.Name)
b.WriteByte('=')
b.WriteString(cookie.Value)
cookieHeader = cookieHeader + cookie.Name + "=" + cookie.Value + ";"
}
return b.String()
return cookieHeader
}
// GetCommonHeaders generates common HTTP headers with optional overwrite
// GetCommonHeaders generates common HTTP headers with optional overwrite.
func GetCommonHeaders(overwrite map[string]string) map[string]string {
headers := map[string]string{
"Content-Type": "application/json",
@@ -882,9 +524,32 @@ func GetCommonHeaders(overwrite map[string]string) map[string]string {
return headers
}
func int64Ptr(v int64) *int64 { return &v }
// MergeCookies merges two slices of http.Cookies, ensuring no duplicates are added.
func MergeCookies(left []*http.Cookie, right []*http.Cookie) ([]*http.Cookie, error) {
var hashes []string
for _, cookie := range right {
hashes = append(hashes, cookie.Raw)
}
for _, cookie := range left {
if !slices.Contains(hashes, cookie.Raw) {
right = append(right, cookie)
}
}
return right, nil
}
// NewSession creates a new Session instance with default values
// GetCookiesForDomain filters the provided cookies based on the domain of the given URL.
func GetCookiesForDomain(url *url.URL, cookies []*http.Cookie) ([]*http.Cookie, error) {
var domainCookies []*http.Cookie
for _, cookie := range cookies {
if strings.HasSuffix(url.Host, cookie.Domain) {
domainCookies = append(domainCookies, cookie)
}
}
return domainCookies, nil
}
// NewSession creates a new Session instance with default values.
func NewSession() *Session {
session := &Session{
FrameID: strings.ToLower(uuid.New().String()),
@@ -899,20 +564,117 @@ func NewSession() *Session {
return session
}
// AccountInfo represents the subset of Apple's account response we actually use
// json.Unmarshal silently ignores extra fields in the response
// AccountInfo represents an account info
type AccountInfo struct {
DsInfo *dsInfo `json:"dsInfo"`
Webservices map[string]*webService `json:"webservices"`
HsaChallengeRequired bool `json:"hsaChallengeRequired"`
DsInfo *ValidateDataDsInfo `json:"dsInfo"`
HasMinimumDeviceForPhotosWeb bool `json:"hasMinimumDeviceForPhotosWeb"`
ICDPEnabled bool `json:"iCDPEnabled"`
Webservices map[string]*webService `json:"webservices"`
PcsEnabled bool `json:"pcsEnabled"`
TermsUpdateNeeded bool `json:"termsUpdateNeeded"`
ConfigBag struct {
Urls struct {
AccountCreateUI string `json:"accountCreateUI"`
AccountLoginUI string `json:"accountLoginUI"`
AccountLogin string `json:"accountLogin"`
AccountRepairUI string `json:"accountRepairUI"`
DownloadICloudTerms string `json:"downloadICloudTerms"`
RepairDone string `json:"repairDone"`
AccountAuthorizeUI string `json:"accountAuthorizeUI"`
VettingURLForEmail string `json:"vettingUrlForEmail"`
AccountCreate string `json:"accountCreate"`
GetICloudTerms string `json:"getICloudTerms"`
VettingURLForPhone string `json:"vettingUrlForPhone"`
} `json:"urls"`
AccountCreateEnabled bool `json:"accountCreateEnabled"`
} `json:"configBag"`
HsaTrustedBrowser bool `json:"hsaTrustedBrowser"`
AppsOrder []string `json:"appsOrder"`
Version int `json:"version"`
IsExtendedLogin bool `json:"isExtendedLogin"`
PcsServiceIdentitiesIncluded bool `json:"pcsServiceIdentitiesIncluded"`
IsRepairNeeded bool `json:"isRepairNeeded"`
HsaChallengeRequired bool `json:"hsaChallengeRequired"`
RequestInfo struct {
Country string `json:"country"`
TimeZone string `json:"timeZone"`
Region string `json:"region"`
} `json:"requestInfo"`
PcsDeleted bool `json:"pcsDeleted"`
ICloudInfo struct {
SafariBookmarksHasMigratedToCloudKit bool `json:"SafariBookmarksHasMigratedToCloudKit"`
} `json:"iCloudInfo"`
Apps map[string]*ValidateDataApp `json:"apps"`
}
// dsInfo holds the account metadata fields we read
type dsInfo struct {
HsaVersion int `json:"hsaVersion"`
// ValidateDataDsInfo represents an validation info
type ValidateDataDsInfo struct {
HsaVersion int `json:"hsaVersion"`
LastName string `json:"lastName"`
ICDPEnabled bool `json:"iCDPEnabled"`
TantorMigrated bool `json:"tantorMigrated"`
Dsid string `json:"dsid"`
HsaEnabled bool `json:"hsaEnabled"`
IsHideMyEmailSubscriptionActive bool `json:"isHideMyEmailSubscriptionActive"`
IroncadeMigrated bool `json:"ironcadeMigrated"`
Locale string `json:"locale"`
BrZoneConsolidated bool `json:"brZoneConsolidated"`
ICDRSCapableDeviceList string `json:"ICDRSCapableDeviceList"`
IsManagedAppleID bool `json:"isManagedAppleID"`
IsCustomDomainsFeatureAvailable bool `json:"isCustomDomainsFeatureAvailable"`
IsHideMyEmailFeatureAvailable bool `json:"isHideMyEmailFeatureAvailable"`
ContinueOnDeviceEligibleDeviceInfo []string `json:"ContinueOnDeviceEligibleDeviceInfo"`
Gilligvited bool `json:"gilligvited"`
AppleIDAliases []any `json:"appleIdAliases"`
UbiquityEOLEnabled bool `json:"ubiquityEOLEnabled"`
IsPaidDeveloper bool `json:"isPaidDeveloper"`
CountryCode string `json:"countryCode"`
NotificationID string `json:"notificationId"`
PrimaryEmailVerified bool `json:"primaryEmailVerified"`
ADsID string `json:"aDsID"`
Locked bool `json:"locked"`
ICDRSCapableDeviceCount int `json:"ICDRSCapableDeviceCount"`
HasICloudQualifyingDevice bool `json:"hasICloudQualifyingDevice"`
PrimaryEmail string `json:"primaryEmail"`
AppleIDEntries []struct {
IsPrimary bool `json:"isPrimary"`
Type string `json:"type"`
Value string `json:"value"`
} `json:"appleIdEntries"`
GilliganEnabled bool `json:"gilligan-enabled"`
IsWebAccessAllowed bool `json:"isWebAccessAllowed"`
FullName string `json:"fullName"`
MailFlags struct {
IsThreadingAvailable bool `json:"isThreadingAvailable"`
IsSearchV2Provisioned bool `json:"isSearchV2Provisioned"`
SCKMail bool `json:"sCKMail"`
IsMppSupportedInCurrentCountry bool `json:"isMppSupportedInCurrentCountry"`
} `json:"mailFlags"`
LanguageCode string `json:"languageCode"`
AppleID string `json:"appleId"`
HasUnreleasedOS bool `json:"hasUnreleasedOS"`
AnalyticsOptInStatus bool `json:"analyticsOptInStatus"`
FirstName string `json:"firstName"`
ICloudAppleIDAlias string `json:"iCloudAppleIdAlias"`
NotesMigrated bool `json:"notesMigrated"`
BeneficiaryInfo struct {
IsBeneficiary bool `json:"isBeneficiary"`
} `json:"beneficiaryInfo"`
HasPaymentInfo bool `json:"hasPaymentInfo"`
PcsDelet bool `json:"pcsDelet"`
AppleIDAlias string `json:"appleIdAlias"`
BrMigrated bool `json:"brMigrated"`
StatusCode int `json:"statusCode"`
FamilyEligible bool `json:"familyEligible"`
}
// webService represents a web service
// ValidateDataApp represents an app
type ValidateDataApp struct {
CanLaunchWithOneFactor bool `json:"canLaunchWithOneFactor"`
IsQualifiedForBeta bool `json:"isQualifiedForBeta"`
}
// WebService represents a web service
type webService struct {
PcsRequired bool `json:"pcsRequired"`
URL string `json:"url"`
-40
View File
@@ -1,40 +0,0 @@
package api
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestExtractHeadersMergesCookies(t *testing.T) {
s := NewSession()
s.Cookies = []*http.Cookie{{Name: "existing", Value: "old"}}
resp := &http.Response{Header: make(http.Header)}
resp.Header.Add("Set-Cookie", (&http.Cookie{Name: "existing", Value: "new"}).String())
resp.Header.Add("Set-Cookie", (&http.Cookie{Name: "fresh", Value: "value"}).String())
resp.Header.Set("X-Apple-Session-Token", "session-token")
s.extractHeaders(resp)
require.Len(t, s.Cookies, 2)
assert.Equal(t, "new", s.Cookies[0].Value)
assert.Equal(t, "fresh", s.Cookies[1].Name)
assert.Equal(t, "session-token", s.SessionToken)
}
func TestExtractHeadersDeletesEmptyCookies(t *testing.T) {
s := NewSession()
s.Cookies = []*http.Cookie{{Name: "X-APPLE-WEBAUTH-HSA-LOGIN", Value: "stale"}, {Name: "keep", Value: "value"}}
resp := &http.Response{Header: make(http.Header)}
resp.Header.Add("Set-Cookie", (&http.Cookie{Name: "X-APPLE-WEBAUTH-HSA-LOGIN", Value: ""}).String())
s.extractHeaders(resp)
require.Len(t, s.Cookies, 1)
assert.Equal(t, "keep", s.Cookies[0].Name)
assert.Equal(t, "keep=value", s.GetCookieString())
}
+9 -17
View File
@@ -46,10 +46,10 @@ type srpClient struct {
}
// newSRPClient generates a random 32-byte secret and computes the public value A.
func newSRPClient() (*srpClient, error) {
func newSRPClient() *srpClient {
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, fmt.Errorf("srp: rand.Read failed: %w", err)
panic(fmt.Sprintf("srp: rand.Read failed: %v", err))
}
a := new(big.Int).SetBytes(secret)
@@ -60,7 +60,7 @@ func newSRPClient() (*srpClient, error) {
a: a,
A: A,
k: k,
}, nil
}
}
// getABytes returns the padded public value A.
@@ -71,21 +71,16 @@ func (c *srpClient) getABytes() []byte {
// 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) error {
func (c *srpClient) processChallenge(username, derivedKey, salt, serverB []byte) {
B := new(big.Int).SetBytes(serverB)
// Validate B (RFC 5054)
// Validate B
if B.Cmp(big.NewInt(0)) <= 0 || B.Cmp(srpN) >= 0 {
return fmt.Errorf("srp: invalid server-supplied B, must be 1..N-1")
panic("srp: invalid server-supplied B, must be 1..N-1")
}
x := calculateX(salt, derivedKey)
u := calculateU(c.A, B)
// Validate u (RFC 5054)
if u.Sign() == 0 {
return fmt.Errorf("srp: calculated u is zero, aborting")
}
S := calculateS(c.k, x, c.a, B, u)
c.K = calculateK(S)
@@ -93,7 +88,6 @@ func (c *srpClient) processChallenge(username, derivedKey, salt, serverB []byte)
bBytes := padToN(B)
c.M1 = calculateM1(username, salt, aBytes, bBytes, c.K)
c.M2 = calculateM2(aBytes, c.M1, c.K)
return nil
}
// derivePassword performs Apple's password key derivation.
@@ -104,12 +98,10 @@ func derivePassword(password string, salt []byte, iterations int, protocol strin
var passInput string
switch protocol {
case "s2k":
passInput = string(passHash[:])
case "s2k_fo":
passInput = hex.EncodeToString(passHash[:])
default:
return nil, fmt.Errorf("unsupported SRP protocol: %q", protocol)
default: // "s2k"
passInput = string(passHash[:])
}
return pbkdf2.Key(sha256.New, passInput, salt, iterations, 32)
}
@@ -150,7 +142,7 @@ func getMultiplier() *big.Int {
}
// calculateX computes x = H(salt | H(":" | password))
// Apple's variant: NoUserNameInX - username is omitted from the inner hash.
// 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()
+7 -39
View File
@@ -27,7 +27,7 @@ func TestPadToN(t *testing.T) {
})
t.Run("preserves value that fills N", func(t *testing.T) {
// Use N itself - already 256 bytes
// Use N itself — already 256 bytes
result := padToN(srpN)
assert.Equal(t, srpNLenBytes, len(result))
assert.Equal(t, srpN.Bytes(), result)
@@ -52,7 +52,7 @@ func TestGetMultiplier(t *testing.T) {
k2 := getMultiplier()
assert.Equal(t, 0, k.Cmp(k2), "multiplier must be deterministic")
// k = H(N | pad(g)) - verify by manual computation
// k = H(N | pad(g)) — verify by manual computation
h := srpHashFunc()
nBytes := srpN.Bytes()
gBytes := srpG.Bytes()
@@ -123,12 +123,6 @@ func TestDerivePassword(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
t.Run("unknown protocol returns error", func(t *testing.T) {
_, err := derivePassword(password, salt, 1000, "unknown")
assert.Error(t, err)
assert.Contains(t, err.Error(), "unsupported SRP protocol")
})
}
func TestCalculateX(t *testing.T) {
@@ -262,8 +256,7 @@ func TestCalculateM2(t *testing.T) {
}
func TestNewSRPClient(t *testing.T) {
client, err := newSRPClient()
require.NoError(t, err)
client := newSRPClient()
// A must be non-zero and in range [1, N-1]
assert.True(t, client.A.Sign() > 0, "A must be positive")
@@ -280,8 +273,7 @@ func TestNewSRPClient(t *testing.T) {
assert.Equal(t, 0, client.A.Cmp(recoveredA))
// Two clients should have different secrets (probabilistic, but 2^256 collision chance)
client2, err := newSRPClient()
require.NoError(t, err)
client2 := newSRPClient()
assert.NotEqual(t, 0, client.a.Cmp(client2.a), "two clients must have different secrets")
}
@@ -323,8 +315,7 @@ func TestProcessChallenge(t *testing.T) {
serverB := padToN(B)
err := client.processChallenge(username, derivedKey, salt, serverB)
require.NoError(t, err)
client.processChallenge(username, derivedKey, salt, serverB)
// M1, M2, K must be populated
assert.NotNil(t, client.M1)
@@ -337,14 +328,13 @@ func TestProcessChallenge(t *testing.T) {
// M1 and M2 must be different
assert.NotEqual(t, client.M1, client.M2)
// Results must be deterministic - run again with same inputs
// 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),
}
err = client2.processChallenge(username, derivedKey, salt, serverB)
require.NoError(t, err)
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")
@@ -362,28 +352,6 @@ func TestProcessChallenge(t *testing.T) {
assert.Equal(t, client.K, kServer, "client and server must derive the same session key")
}
func TestProcessChallenge_InvalidB(t *testing.T) {
k := getMultiplier()
client := &srpClient{
a: big.NewInt(42),
A: new(big.Int).Exp(srpG, big.NewInt(42), srpN),
k: k,
}
username := []byte("test@apple.com")
derivedKey := make([]byte, 32)
salt := []byte("salt")
t.Run("B=0 rejected", func(t *testing.T) {
err := client.processChallenge(username, derivedKey, salt, padToN(big.NewInt(0)))
assert.Error(t, err)
})
t.Run("B=N rejected", func(t *testing.T) {
err := client.processChallenge(username, derivedKey, salt, padToN(srpN))
assert.Error(t, err)
})
}
func TestSRPGroupParameters(t *testing.T) {
// Verify the 2048-bit prime starts with known hex prefix
nHex := hex.EncodeToString(srpN.Bytes())
-497
View File
@@ -1,497 +0,0 @@
//go:build !plan9 && !solaris
// Package iclouddrive provides access to iCloud Drive and Photos
package iclouddrive
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"github.com/rclone/rclone/backend/iclouddrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/lib/encoder"
)
const configAuthSession = "_auth_session"
// configAuthState holds session fields that must be preserved across
// Config() state machine steps (push 2FA and SMS both need it)
type configAuthState struct {
Scnt string `json:"s"`
SessionID string `json:"i"`
AuthAttributes string `json:"a"`
FrameID string `json:"f"`
SessionToken string `json:"t"`
ClientID string `json:"c"`
AccountCountry string `json:"ac"`
Phones []smsPhone `json:"p,omitempty"`
}
type smsPhone struct {
ID int `json:"id"`
Num string `json:"n"`
Mode string `json:"m"`
}
func saveAuthSession(m configmap.Mapper, s *api.Session, phones []smsPhone) {
st := configAuthState{
Scnt: s.Scnt,
SessionID: s.SessionID,
AuthAttributes: s.AuthAttributes,
FrameID: s.FrameID,
SessionToken: s.SessionToken,
ClientID: s.ClientID,
AccountCountry: s.AccountCountry,
Phones: phones,
}
data, err := json.Marshal(st)
if err != nil {
fs.Debugf(nil, "iclouddrive: failed to marshal auth session: %v", err)
return
}
m.Set(configAuthSession, base64.StdEncoding.EncodeToString(data))
}
func loadAuthSession(m configmap.Mapper) (*configAuthState, error) {
raw, _ := m.Get(configAuthSession)
if raw == "" {
return nil, errors.New("auth session state lost, please reconfigure")
}
data, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
return nil, fmt.Errorf("corrupt auth session state: %w", err)
}
var st configAuthState
if err := json.Unmarshal(data, &st); err != nil {
return nil, fmt.Errorf("invalid auth session state: %w", err)
}
return &st, nil
}
func restoreAuthSession(icloud *api.Client, st *configAuthState) {
icloud.Session.Scnt = st.Scnt
icloud.Session.SessionID = st.SessionID
icloud.Session.AuthAttributes = st.AuthAttributes
icloud.Session.FrameID = st.FrameID
icloud.Session.SessionToken = st.SessionToken
icloud.Session.ClientID = st.ClientID
icloud.Session.AccountCountry = st.AccountCountry
}
// resumeConfigClient recreates an API client and restores session state saved
// from a previous Config() step. Used across 2FA states to avoid re-authenticating
func resumeConfigClient(m configmap.Mapper, appleid, password, trustToken, clientID string, cookies []*http.Cookie) (*api.Client, *configAuthState, error) {
st, err := loadAuthSession(m)
if err != nil {
return nil, nil, err
}
icloud, err := api.New(appleid, password, trustToken, clientID, cookies, nil, "_config", "")
if err != nil {
return nil, nil, err
}
restoreAuthSession(icloud, st)
return icloud, st, nil
}
// saveAuthCredentials persists trust token, cookies, and clears session state
// after successful 2FA validation
func saveAuthCredentials(m configmap.Mapper, icloud *api.Client, name string) {
m.Set(configTrustToken, icloud.Session.TrustToken)
m.Set(configCookies, icloud.Session.GetCookieString())
m.Set(configAuthSession, "")
api.ClearCacheDir(name)
}
// triggerSMSFlow handles phone selection and SMS triggering
// Single phone: triggers SMS immediately, returns code prompt
// Multiple phones: saves session + phone list, returns phone picker
func triggerSMSFlow(ctx context.Context, icloud *api.Client, phones []api.TrustedPhoneNumber, m configmap.Mapper) (*fs.ConfigOut, error) {
smsPhones := make([]smsPhone, len(phones))
for i, p := range phones {
mode := p.PushMode
if mode == "" {
mode = "sms"
}
smsPhones[i] = smsPhone{ID: p.ID, Num: p.NumberWithDialCode, Mode: mode}
}
if len(phones) == 1 {
p := smsPhones[0]
if err := icloud.Session.RequestSMSCode(ctx, p.ID, p.Mode); err != nil {
return nil, fmt.Errorf("failed to send SMS code: %w", err)
}
saveAuthSession(m, icloud.Session, nil)
nextState := fmt.Sprintf("2fa_sms_%d_%s", p.ID, p.Mode)
return fs.ConfigInput(nextState, "config_2fa_sms", fmt.Sprintf("Enter the verification code sent to %s", p.Num))
}
// Multiple phones - save session and present picker
saveAuthSession(m, icloud.Session, smsPhones)
items := make([]fs.OptionExample, len(smsPhones))
for i, p := range smsPhones {
items[i] = fs.OptionExample{
Value: fmt.Sprintf("%d_%s", p.ID, p.Mode),
Help: p.Num,
}
}
return fs.ConfigChooseExclusiveFixed("2fa_sms_select", "config_2fa_phone", "Select phone number for SMS verification", items)
}
const (
configService = "service"
// Service types
serviceDrive = "drive"
servicePhotos = "photos"
)
// ServiceOptions defines the configuration for service selection
type ServiceOptions struct {
Service string `config:"service"`
}
// Register with rclone
func init() {
fs.Register(&fs.RegInfo{
Name: "iclouddrive",
Description: "iCloud Drive and Photos",
Config: Config,
NewFs: NewServiceFs,
MetadataInfo: &fs.MetadataInfo{
System: map[string]fs.MetadataHelp{
"width": {
Help: "Image width in pixels",
Type: "int",
ReadOnly: true,
},
"height": {
Help: "Image height in pixels",
Type: "int",
ReadOnly: true,
},
"added-time": {
Help: "Time the item was added to the iCloud library",
Type: "RFC 3339",
Example: "2006-01-02T15:04:05Z",
ReadOnly: true,
},
"favorite": {
Help: "Whether the item is marked as favorite",
Type: "bool",
ReadOnly: true,
},
"hidden": {
Help: "Whether the item is hidden",
Type: "bool",
ReadOnly: true,
},
},
Help: "Metadata is read-only and available for the Photos service only.",
},
Options: []fs.Option{{
Name: configService,
Help: "iCloud service to use.",
Required: true,
Default: serviceDrive,
Examples: []fs.OptionExample{{
Value: serviceDrive,
Help: "iCloud Drive",
}, {
Value: servicePhotos,
Help: "iCloud Photos",
}},
}, {
Name: configAppleID,
Help: "Apple ID.",
Required: true,
Sensitive: true,
}, {
Name: configPassword,
Help: "Password.",
Required: true,
IsPassword: true,
Sensitive: true,
}, {
Name: configTrustToken,
Help: "Trust token for session authentication.",
IsPassword: false,
Required: false,
Sensitive: true,
Hide: fs.OptionHideBoth,
}, {
Name: configCookies,
Help: "Session cookies.",
Required: false,
Advanced: false,
Sensitive: true,
Hide: fs.OptionHideBoth,
}, {
Name: configClientID,
Help: "Client ID for iCloud API access.",
Required: false,
Advanced: true,
Default: "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde8d9d1a815d",
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
Advanced: true,
Default: (encoder.Display |
encoder.EncodeBackSlash |
encoder.EncodeSlash |
encoder.EncodeInvalidUtf8),
}},
})
}
// Config handles the authentication and configuration flow
func Config(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
var err error
appleid, _ := m.Get(configAppleID)
if appleid == "" {
return nil, errors.New("an Apple ID is required")
}
password, _ := m.Get(configPassword)
if password != "" {
password, err = obscure.Reveal(password)
if err != nil {
return nil, err
}
}
trustToken, _ := m.Get(configTrustToken)
cookieRaw, _ := m.Get(configCookies)
clientID, _ := m.Get(configClientID)
cookies := ReadCookies(cookieRaw)
switch {
case config.State == "":
// Force fresh SRP authentication - ignore stale trust token and cookies
// so that reconnect always prompts for 2FA
m.Set(configAuthSession, "")
icloud, err := api.New(appleid, password, "", clientID, nil, nil, "_config", "")
if err != nil {
return nil, err
}
if err := icloud.Authenticate(ctx); err != nil {
return nil, err
}
m.Set(configCookies, icloud.Session.GetCookieString())
if icloud.Session.Requires2FA() {
// Check if user has no trusted devices - auto-trigger SMS if so
authState, err := icloud.Session.GetAuthState(ctx)
if err == nil && authState.NoTrustedDevices && len(authState.TrustedPhoneNumbers) > 0 {
return triggerSMSFlow(ctx, icloud, authState.TrustedPhoneNumbers, m)
}
// Explicitly request push to trusted devices - required for iOS 26.4+
// where the SRP 409 no longer auto-pushes. GET /appleauth/auth above
// may also trigger a push (cosmetic double on pre-26.4, harmless)
if err := icloud.Session.RequestPushNotification(ctx); err != nil {
fs.Debugf(nil, "iclouddrive: push notification request failed (SMS fallback available): %v", err)
} else {
fs.Debugf(nil, "iclouddrive: push notification requested to trusted devices")
}
// Save session state so 2fa_do can validate without re-authenticating
// Push codes are account-scoped so session reuse is not strictly required,
// but it avoids a redundant SRP roundtrip and a second push on pre-26.4
saveAuthSession(m, icloud.Session, nil)
return fs.ConfigInput("2fa_do", "config_2fa", "Two-factor authentication: enter your 2FA code or type 'sms' for a text message")
}
// Auth succeeded without 2FA - save updated credentials and clear stale cache
m.Set(configTrustToken, icloud.Session.TrustToken)
api.ClearCacheDir(name)
return nil, nil
case config.State == "2fa_do":
code := config.Result
if code == "" {
return fs.ConfigError("authenticate", "2FA codes can't be blank")
}
// Restore session from initial sign-in instead of re-authenticating
// This avoids a redundant SRP roundtrip and extra push on pre-26.4
icloud, _, err := resumeConfigClient(m, appleid, password, trustToken, clientID, cookies)
if err != nil {
return nil, err
}
if strings.EqualFold(code, "sms") {
authState, err := icloud.Session.GetAuthState(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get trusted phone numbers: %w", err)
}
if len(authState.TrustedPhoneNumbers) == 0 {
return nil, errors.New("no trusted phone numbers on this account")
}
return triggerSMSFlow(ctx, icloud, authState.TrustedPhoneNumbers, m)
}
if err := icloud.Session.Validate2FACode(ctx, code); err != nil {
return nil, err
}
saveAuthCredentials(m, icloud, name)
return nil, nil
case config.State == "2fa_sms_select":
// User selected a phone from ConfigChooseExclusiveFixed (value: "ID_mode")
idStr, mode, _ := strings.Cut(config.Result, "_")
phoneID, err := strconv.Atoi(idStr)
if err != nil {
m.Set(configAuthSession, "")
return nil, fmt.Errorf("invalid phone selection %q", config.Result)
}
if mode == "" {
mode = "sms"
}
icloud, smsState, err := resumeConfigClient(m, appleid, password, trustToken, clientID, cookies)
if err != nil {
return nil, err
}
// Find the selected phone's display number
var phoneNum string
for _, p := range smsState.Phones {
if p.ID == phoneID {
phoneNum = p.Num
break
}
}
if err := icloud.Session.RequestSMSCode(ctx, phoneID, mode); err != nil {
m.Set(configAuthSession, "")
return nil, fmt.Errorf("failed to send SMS code: %w", err)
}
saveAuthSession(m, icloud.Session, nil)
nextState := fmt.Sprintf("2fa_sms_%d_%s", phoneID, mode)
return fs.ConfigInput(nextState, "config_2fa_sms", fmt.Sprintf("Enter the verification code sent to %s", phoneNum))
case strings.HasPrefix(config.State, "2fa_sms_"):
code := config.Result
if code == "" {
return fs.ConfigError("authenticate", "SMS code can't be blank")
}
// State encodes phone ID and mode: "2fa_sms_<ID>_<mode>"
suffix := strings.TrimPrefix(config.State, "2fa_sms_")
idStr, mode, _ := strings.Cut(suffix, "_")
phoneID, err := strconv.Atoi(idStr)
if err != nil {
return nil, fmt.Errorf("invalid phone ID in state %q: %w", config.State, err)
}
if mode == "" {
mode = "sms"
}
icloud, _, err := resumeConfigClient(m, appleid, password, trustToken, clientID, cookies)
if err != nil {
return nil, err
}
if err := icloud.Session.ValidateSMSCode(ctx, code, phoneID, mode); err != nil {
m.Set(configAuthSession, "")
return nil, err
}
saveAuthCredentials(m, icloud, name)
return nil, nil
default:
return nil, fmt.Errorf("unknown state %q", config.State)
}
}
// newICloudClient parses options, authenticates, and returns a ready client
// Shared between NewFs (Drive) and NewFsPhotos (Photos) to avoid duplication
// pcsWSKey scopes PCS cookie acquisition to the caller's service
func newICloudClient(ctx context.Context, name string, m configmap.Mapper, pcsWSKey string) (*api.Client, *Options, error) {
opt := new(Options)
err := configstruct.Set(m, opt)
if err != nil {
return nil, nil, err
}
if opt.Password != "" {
opt.Password, err = obscure.Reveal(opt.Password)
if err != nil {
return nil, nil, fmt.Errorf("couldn't decrypt user password: %w", err)
}
}
if opt.TrustToken == "" {
return nil, nil, fmt.Errorf("missing icloud trust token: try refreshing it with \"rclone config reconnect %s:\"", name)
}
cookies := ReadCookies(opt.Cookies)
callback := func(session *api.Session) {
m.Set(configCookies, session.GetCookieString())
}
icloud, err := api.New(
opt.AppleID,
opt.Password,
opt.TrustToken,
opt.ClientID,
cookies,
callback,
name,
pcsWSKey,
)
if err != nil {
return nil, nil, err
}
if err := icloud.Authenticate(ctx); err != nil {
return nil, nil, err
}
if icloud.Session.Requires2FA() {
return nil, nil, errors.New("trust token expired, please reauth")
}
return icloud, opt, nil
}
// disconnectClient clears authentication state and removes disk caches
// Shared between Drive Fs and Photos Fs Disconnect() implementations
func disconnectClient(m configmap.Mapper, icloud *api.Client) error {
m.Set(configTrustToken, "")
m.Set(configCookies, "")
m.Set(configAuthSession, "")
return os.RemoveAll(icloud.CacheDir())
}
// NewServiceFs creates a filesystem instance for the selected service
func NewServiceFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
// Parse the service selection
opt := new(ServiceOptions)
err := configstruct.Set(m, opt)
if err != nil {
return nil, err
}
// Set default service if not specified
if opt.Service == "" {
opt.Service = serviceDrive
}
// Route to the appropriate backend
switch opt.Service {
case serviceDrive:
// Create Drive filesystem
return NewFs(ctx, name, root, m)
case servicePhotos:
// Create Photos filesystem
return NewFsPhotos(ctx, name, root, m)
default:
return nil, fmt.Errorf("invalid service selection: %s (must be 'drive' or 'photos')", opt.Service)
}
}
+163 -13
View File
@@ -9,13 +9,17 @@ import (
"path"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/backend/iclouddrive/api"
@@ -23,8 +27,6 @@ import (
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/pacer"
"golang.org/x/text/unicode/norm"
)
/*
@@ -47,10 +49,61 @@ const (
decayConstant = 2
)
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
Name: "iclouddrive",
Description: "iCloud Drive",
Config: Config,
NewFs: NewFs,
Options: []fs.Option{{
Name: configAppleID,
Help: "Apple ID.",
Required: true,
Sensitive: true,
}, {
Name: configPassword,
Help: "Password.",
Required: true,
IsPassword: true,
Sensitive: true,
}, {
Name: configTrustToken,
Help: "Trust token (internal use)",
IsPassword: false,
Required: false,
Sensitive: true,
Hide: fs.OptionHideBoth,
}, {
Name: configCookies,
Help: "cookies (internal use only)",
Required: false,
Advanced: false,
Sensitive: true,
Hide: fs.OptionHideBoth,
}, {
Name: configClientID,
Help: "Client id",
Required: false,
Advanced: true,
Default: "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde8d9d1a815d",
}, {
Name: config.ConfigEncoding,
Help: config.ConfigEncodingHelp,
Advanced: true,
Default: (encoder.Display |
//encoder.EncodeDot |
encoder.EncodeBackSlash |
encoder.EncodeInvalidUtf8),
}},
})
}
// Options defines the configuration for this backend
type Options struct {
AppleID string `config:"apple_id"`
Password string `config:"password"`
Photos bool `config:"photos"`
TrustToken string `config:"trust_token"`
Cookies string `config:"cookies"`
ClientID string `config:"client_id"`
@@ -63,7 +116,6 @@ type Fs struct {
root string // the path we are working on.
rootID string
opt Options // parsed config options
m configmap.Mapper // config map for persisting auth state
features *fs.Features // optional features
dirCache *dircache.DirCache // Map of directory path to directory id
icloud *api.Client
@@ -85,6 +137,72 @@ type Object struct {
downloadURL string
}
// Config configures the iCloud remote.
func Config(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
var err error
appleid, _ := m.Get(configAppleID)
if appleid == "" {
return nil, errors.New("a apple ID is required")
}
password, _ := m.Get(configPassword)
if password != "" {
password, err = obscure.Reveal(password)
if err != nil {
return nil, err
}
}
trustToken, _ := m.Get(configTrustToken)
cookieRaw, _ := m.Get(configCookies)
clientID, _ := m.Get(configClientID)
cookies := ReadCookies(cookieRaw)
switch config.State {
case "":
icloud, err := api.New(appleid, password, trustToken, clientID, cookies, nil)
if err != nil {
return nil, err
}
if err := icloud.Authenticate(ctx); err != nil {
return nil, err
}
m.Set(configCookies, icloud.Session.GetCookieString())
if icloud.Session.Requires2FA() {
return fs.ConfigInput("2fa_do", "config_2fa", "Two-factor authentication: please enter your 2FA code")
}
return nil, nil
case "2fa_do":
code := config.Result
if code == "" {
return fs.ConfigError("authenticate", "2FA codes can't be blank")
}
icloud, err := api.New(appleid, password, trustToken, clientID, cookies, nil)
if err != nil {
return nil, err
}
if err := icloud.SignIn(ctx); err != nil {
return nil, err
}
if err := icloud.Session.Validate2FACode(ctx, code); err != nil {
return nil, err
}
m.Set(configTrustToken, icloud.Session.TrustToken)
m.Set(configCookies, icloud.Session.GetCookieString())
return nil, nil
case "2fa_error":
if config.Result == "true" {
return fs.ConfigGoto("2fa")
}
return nil, errors.New("2fa authentication failed")
}
return nil, fmt.Errorf("unknown state %q", config.State)
}
// find item by path. Will not return any children for the item
func (f *Fs) findItem(ctx context.Context, dir string) (item *api.DriveItem, found bool, err error) {
var resp *http.Response
@@ -107,8 +225,7 @@ func (f *Fs) findLeafItem(ctx context.Context, pathID string, leaf string) (item
return nil, false, err
}
for _, item := range items {
// iCloud returns file names in NFD Unicode normalization, so normalized to NFC for consistent comparison
if strings.EqualFold(norm.NFC.String(item.FullName()), leaf) {
if strings.EqualFold(item.FullName(), leaf) {
return item, true, nil
}
}
@@ -677,11 +794,51 @@ func retryResultUnknown(ctx context.Context, resp *http.Response, err error) (bo
// NewFs constructs an Fs from the path, container:path
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
icloud, opt, err := newICloudClient(ctx, name, m, api.WsDrive)
// Parse config into Options struct
opt := new(Options)
err := configstruct.Set(m, opt)
if err != nil {
return nil, err
}
if opt.Password != "" {
var err error
opt.Password, err = obscure.Reveal(opt.Password)
if err != nil {
return nil, fmt.Errorf("couldn't decrypt user password: %w", err)
}
}
if opt.TrustToken == "" {
return nil, fmt.Errorf("missing icloud trust token: try refreshing it with \"rclone config reconnect %s:\"", name)
}
cookies := ReadCookies(opt.Cookies)
callback := func(session *api.Session) {
m.Set(configCookies, session.GetCookieString())
}
icloud, err := api.New(
opt.AppleID,
opt.Password,
opt.TrustToken,
opt.ClientID,
cookies,
callback,
)
if err != nil {
return nil, err
}
if err := icloud.Authenticate(ctx); err != nil {
return nil, err
}
if icloud.Session.Requires2FA() {
return nil, errors.New("trust token expired, please reauth")
}
root = strings.Trim(root, "/")
f := &Fs{
@@ -690,7 +847,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
icloud: icloud,
rootID: "FOLDER::com.apple.CloudDocs::root",
opt: *opt,
m: m,
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
}
f.features = (&fs.Features{
@@ -1005,15 +1161,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return nil
}
// Disconnect clears authentication state and removes disk caches
func (f *Fs) Disconnect(ctx context.Context) error {
return disconnectClient(f.m, f.icloud)
}
// Check interfaces are satisfied
var (
_ fs.Fs = &Fs{}
_ fs.Disconnecter = (*Fs)(nil)
_ fs.Mover = (*Fs)(nil)
_ fs.Purger = (*Fs)(nil)
_ fs.DirMover = (*Fs)(nil)
@@ -4,4 +4,4 @@
//go:build plan9 || solaris
// Package iclouddrive implements the iCloud Drive backend
package iclouddrive
package iclouddrive
-892
View File
@@ -1,892 +0,0 @@
//go:build !plan9 && !solaris
package iclouddrive
import (
"context"
"fmt"
"io"
"net/http"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/rclone/rclone/backend/iclouddrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/list"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/pacer"
)
const rootID = "photos-root"
// PhotosFs represents a remote iCloud Photos server
type PhotosFs struct {
name string
root string
opt Options
features *fs.Features
icloud *api.Client
m configmap.Mapper
pacer *fs.Pacer
dirCache *dircache.DirCache
httpClient *http.Client
startTime time.Time
mu sync.Mutex
photos *api.PhotosService
}
// PhotosObject describes an iCloud Photos object
type PhotosObject struct {
fs *PhotosFs
remote string
size int64
modTime time.Time
masterID string // CloudKit recordName for fresh URL lookup (master or asset depending on resource)
zone string // CloudKit zone (e.g. "PrimarySync")
resourceKey string // CloudKit resource field (resOriginalRes or resOriginalVidComplRes)
width int
height int
addedDate int64
isFavorite bool
isHidden bool
}
// NewFsPhotos constructs an Fs for Photos from the path, container:path
func NewFsPhotos(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
icloud, opt, err := newICloudClient(ctx, name, m, api.WsPhotos)
if err != nil {
return nil, err
}
root = strings.Trim(root, "/")
f := &PhotosFs{
name: name,
root: root,
opt: *opt,
icloud: icloud,
m: m,
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
httpClient: fshttp.NewClient(ctx),
startTime: time.Now(),
}
f.features = (&fs.Features{
CanHaveEmptyDirectories: true,
PartialUploads: false,
ReadMimeType: false,
ReadMetadata: true,
}).Fill(ctx, f)
f.dirCache = dircache.New(root, rootID, f)
err = f.dirCache.FindRoot(ctx, false)
if err != nil {
// Check if root points to a file (e.g. PrimarySync/Videos/file.mp4)
newRoot, remote := dircache.SplitPath(root)
tempF := &PhotosFs{
name: f.name,
root: newRoot,
opt: f.opt,
features: f.features,
icloud: f.icloud,
pacer: f.pacer,
httpClient: f.httpClient,
startTime: f.startTime,
photos: f.photos, // nil here; photosService() creates lazily on first use
}
tempF.dirCache = dircache.New(newRoot, rootID, tempF)
if err2 := tempF.dirCache.FindRoot(ctx, false); err2 != nil {
return f, nil
}
_, err2 := tempF.NewObject(ctx, remote)
if err2 != nil {
return f, nil
}
// Root is a file - adjust f to parent dir, signal ErrorIsFile
f.root = newRoot
f.dirCache = tempF.dirCache
return f, fs.ErrorIsFile
}
return f, nil
}
// photosService returns the PhotosService, creating it on first call
func (f *PhotosFs) photosService(ctx context.Context) (*api.PhotosService, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.photos == nil {
var err error
f.photos, err = api.NewPhotosService(ctx, f.icloud, f.pacer, shouldRetry)
if err != nil {
return nil, err
}
}
return f.photos, nil
}
// Name of the remote (as passed into NewFs)
func (f *PhotosFs) Name() string {
return f.name
}
// Root of the remote (as passed into NewFs)
func (f *PhotosFs) Root() string {
return f.opt.Enc.ToStandardPath(f.root)
}
// String converts this Fs to a string
func (f *PhotosFs) String() string {
return fmt.Sprintf("iCloud Photos root '%s'", f.root)
}
// Precision of the object storage system
func (f *PhotosFs) Precision() time.Duration {
return time.Second
}
// Hashes returns the supported hash sets
func (f *PhotosFs) Hashes() hash.Set {
return hash.Set(hash.None)
}
// Features returns the optional features of this Fs
func (f *PhotosFs) Features() *fs.Features {
return f.features
}
// List the objects and directories in dir into entries
func (f *PhotosFs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
photosService, err := f.photosService(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get photos service: %w", err)
}
dirID, err := f.dirCache.FindDir(ctx, dir, false)
if err != nil {
return nil, err
}
switch {
case dirID == rootID:
// List libraries
libraries, err := photosService.GetLibraries(ctx)
if err != nil {
return nil, err
}
albumCounts, err := photosService.GetLibraryAlbumCounts(ctx)
if err != nil {
fs.Debugf(f, "Failed to get library album counts: %v", err)
}
for libraryName := range libraries {
count := int64(-1)
if albumCounts != nil {
if c, ok := albumCounts[libraryName]; ok {
count = c
}
}
d := fs.NewDir(path.Join(dir, f.opt.Enc.ToStandardName(libraryName)), f.startTime).SetItems(count)
entries = append(entries, d)
}
case strings.HasPrefix(dirID, "lib:"):
// List albums in a library
libraryName := strings.TrimPrefix(dirID, "lib:")
libraries, err := photosService.GetLibraries(ctx)
if err != nil {
return nil, err
}
library, exists := libraries[libraryName]
if !exists {
return nil, fs.ErrorDirNotFound
}
albums, err := library.GetAlbums(ctx)
if err != nil {
return nil, err
}
counts, err := library.GetAlbumCounts(ctx)
if err != nil {
fs.Debugf(f, "Failed to get album counts for library %q: %v", libraryName, err)
}
for albumName := range albums {
count := int64(-1)
if counts != nil {
if c, ok := counts[albumName]; ok {
count = c
}
}
d := fs.NewDir(path.Join(dir, f.opt.Enc.ToStandardName(albumName)), f.startTime).SetItems(count)
entries = append(entries, d)
}
case strings.HasPrefix(dirID, "album:"):
// List contents of an album or folder
libraryName, albumPath, ok := parseAlbumDirID(dirID)
if !ok {
return nil, fs.ErrorDirNotFound
}
album, err := f.resolveAlbum(ctx, photosService, libraryName, albumPath)
if err != nil {
return nil, err
}
// Folders list their child albums as subdirectories
if album.IsFolder {
for childName, child := range album.Children {
d := fs.NewDir(path.Join(dir, f.opt.Enc.ToStandardName(childName)), f.startTime)
if child.IsFolder {
d.SetItems(int64(len(child.Children)))
}
entries = append(entries, d)
}
return entries, nil
}
photos, err := album.GetPhotos(ctx)
if err != nil {
return nil, err
}
for _, photo := range photos {
if photo.Filename == "" {
continue
}
encodedName := f.opt.Enc.ToStandardName(photo.Filename)
remotePath := encodedName
if dir != "" {
remotePath = path.Join(dir, encodedName)
}
o := f.newPhotosObject(remotePath, photo, libraryName)
entries = append(entries, o)
}
default:
return nil, fs.ErrorDirNotFound
}
return entries, nil
}
// NewObject finds the Object at remote. If it can't be found
// it returns the error fs.ErrorObjectNotFound
func (f *PhotosFs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
dir, leaf := dircache.SplitPath(remote)
filename := f.opt.Enc.FromStandardName(leaf)
dirID, err := f.dirCache.FindDir(ctx, dir, false)
if err != nil {
fs.Debugf(f, "NewObject(%s): FindDir: %v", remote, err)
return nil, fs.ErrorObjectNotFound
}
if !strings.HasPrefix(dirID, "album:") {
return nil, fs.ErrorObjectNotFound
}
libraryName, albumPath, ok := parseAlbumDirID(dirID)
if !ok {
return nil, fs.ErrorObjectNotFound
}
photosService, err := f.photosService(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get photos service: %w", err)
}
album, err := f.resolveAlbum(ctx, photosService, libraryName, albumPath)
if err != nil || album.IsFolder {
fs.Debugf(f, "NewObject(%s): album resolve failed or is folder", remote)
return nil, fs.ErrorObjectNotFound
}
photo, err := album.GetPhotoByName(ctx, filename)
if err != nil {
fs.Debugf(f, "NewObject(%s): %v", remote, err)
return nil, fs.ErrorObjectNotFound
}
return f.newPhotosObject(remote, photo, libraryName), nil
}
// newPhotosObject creates a PhotosObject from a Photo and zone
func (f *PhotosFs) newPhotosObject(remote string, photo *api.Photo, zone string) *PhotosObject {
return &PhotosObject{
fs: f,
remote: remote,
size: photo.Size,
modTime: time.UnixMilli(photo.AssetDate),
masterID: photo.ID,
zone: zone,
resourceKey: photo.ResourceKey,
width: photo.Width,
height: photo.Height,
addedDate: photo.AddedDate,
isFavorite: photo.IsFavorite,
isHidden: photo.IsHidden,
}
}
// Put is not supported for this read-only backend
func (f *PhotosFs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
return nil, fs.ErrorNotImplemented
}
// Mkdir is not supported for this read-only backend
func (f *PhotosFs) Mkdir(ctx context.Context, dir string) error {
return fs.ErrorNotImplemented
}
// Rmdir is not supported for this read-only backend
func (f *PhotosFs) Rmdir(ctx context.Context, dir string) error {
return fs.ErrorNotImplemented
}
// FindLeaf finds a directory of name leaf in the folder with ID pathID
func (f *PhotosFs) FindLeaf(ctx context.Context, pathID, leaf string) (pathIDOut string, found bool, err error) {
decodedLeaf := f.opt.Enc.FromStandardName(leaf)
photosService, err := f.photosService(ctx)
if err != nil {
return "", false, fmt.Errorf("failed to get photos service: %w", err)
}
if pathID == rootID {
libraries, err := photosService.GetLibraries(ctx)
if err != nil {
return "", false, err
}
if _, exists := libraries[decodedLeaf]; exists {
return "lib:" + decodedLeaf, true, nil
}
return "", false, nil
}
if strings.HasPrefix(pathID, "lib:") {
libraryName := strings.TrimPrefix(pathID, "lib:")
libraries, err := photosService.GetLibraries(ctx)
if err != nil {
return "", false, err
}
library, exists := libraries[libraryName]
if !exists {
return "", false, fs.ErrorDirNotFound
}
albums, err := library.GetAlbums(ctx)
if err != nil {
return "", false, err
}
if _, exists := albums[decodedLeaf]; exists {
albumID := "album:" + libraryName + ":" + decodedLeaf
return albumID, true, nil
}
return "", false, nil
}
if strings.HasPrefix(pathID, "album:") {
// Check if this is a folder containing child albums
libraryName, albumPath, ok := parseAlbumDirID(pathID)
if !ok {
return "", false, nil
}
album, err := f.resolveAlbum(ctx, photosService, libraryName, albumPath)
if err != nil {
return "", false, nil
}
if album.IsFolder {
if _, exists := album.Children[decodedLeaf]; exists {
childID := "album:" + libraryName + ":" + albumPath + "/" + decodedLeaf
return childID, true, nil
}
}
return "", false, nil
}
return "", false, nil
}
// CreateDir makes a directory with pathID as parent and name leaf
func (f *PhotosFs) CreateDir(ctx context.Context, pathID, leaf string) (newID string, err error) {
return "", fs.ErrorNotImplemented
}
// Fs returns the parent Fs
func (o *PhotosObject) Fs() fs.Info {
return o.fs
}
// Return a string version
func (o *PhotosObject) String() string {
if o == nil {
return "<nil>"
}
return o.remote
}
// Remote returns the remote path
func (o *PhotosObject) Remote() string {
return o.remote
}
// ModTime returns the modification time of the object
func (o *PhotosObject) ModTime(ctx context.Context) time.Time {
return o.modTime
}
// Size returns the size of an object in bytes
func (o *PhotosObject) Size() int64 {
return o.size
}
// Storable returns a boolean as to whether this object is storable
func (o *PhotosObject) Storable() bool {
return true
}
// Hash returns the hash of an object returning a lowercase hex string
func (o *PhotosObject) Hash(ctx context.Context, ty hash.Type) (string, error) {
return "", hash.ErrUnsupported
}
// SetModTime sets the modification time of the object
func (o *PhotosObject) SetModTime(ctx context.Context, modTime time.Time) error {
return fs.ErrorCantSetModTime
}
// Metadata returns metadata for the photo object
func (o *PhotosObject) Metadata(ctx context.Context) (fs.Metadata, error) {
metadata := make(fs.Metadata, 5)
if o.width > 0 {
metadata["width"] = strconv.Itoa(o.width)
}
if o.height > 0 {
metadata["height"] = strconv.Itoa(o.height)
}
if o.addedDate > 0 {
metadata["added-time"] = time.UnixMilli(o.addedDate).UTC().Format(time.RFC3339)
}
metadata["favorite"] = strconv.FormatBool(o.isFavorite)
metadata["hidden"] = strconv.FormatBool(o.isHidden)
return metadata, nil
}
// Open an object for read, fetching a fresh download URL via records/lookup
func (o *PhotosObject) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
photosService, err := o.fs.photosService(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get photos service: %w", err)
}
downloadURL, err := photosService.LookupDownloadURL(ctx, o.masterID, o.zone, o.resourceKey)
if err != nil {
return nil, fmt.Errorf("failed to get download URL for %q: %w", o.remote, err)
}
fs.FixRangeOption(options, o.size)
var resp *http.Response
err = o.fs.pacer.Call(func() (bool, error) {
if resp != nil {
_ = resp.Body.Close()
resp = nil
}
req, err := http.NewRequestWithContext(ctx, "GET", downloadURL, nil)
if err != nil {
return false, fmt.Errorf("failed to create request: %w", err)
}
fs.OpenOptionAddHTTPHeaders(req.Header, options)
resp, err = o.fs.httpClient.Do(req)
return shouldRetry(ctx, resp, err)
})
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
_ = resp.Body.Close()
return nil, fmt.Errorf("download %q failed: %s", o.remote, resp.Status)
}
return resp.Body, nil
}
// Update is not supported for this read-only backend
func (o *PhotosObject) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
return fs.ErrorNotImplemented
}
// Remove is not supported for this read-only backend
func (o *PhotosObject) Remove(ctx context.Context) error {
return fs.ErrorNotImplemented
}
// resolveAlbum finds an album by path, traversing folder hierarchy
// albumPath can be "AlbumName" or "FolderName/AlbumName" for nested albums
func (f *PhotosFs) resolveAlbum(ctx context.Context, ps *api.PhotosService, libraryName, albumPath string) (*api.Album, error) {
libraries, err := ps.GetLibraries(ctx)
if err != nil {
return nil, err
}
library, exists := libraries[libraryName]
if !exists {
return nil, fs.ErrorDirNotFound
}
albums, err := library.GetAlbums(ctx)
if err != nil {
return nil, err
}
return resolveAlbumPath(albums, albumPath)
}
// resolveAlbumPath finds an album inside an album tree by slash-separated path
func resolveAlbumPath(albums map[string]*api.Album, albumPath string) (*api.Album, error) {
parts := strings.Split(albumPath, "/")
current := albums
for i, part := range parts {
album, exists := current[part]
if !exists {
return nil, fs.ErrorDirNotFound
}
if i == len(parts)-1 {
return album, nil
}
if !album.IsFolder || album.Children == nil {
return nil, fs.ErrorDirNotFound
}
current = album.Children
}
return nil, fs.ErrorDirNotFound
}
// parseAlbumDirID extracts library and album names from "album:lib:album" dirID
func parseAlbumDirID(dirID string) (libraryName, albumName string, ok bool) {
parts := strings.SplitN(strings.TrimPrefix(dirID, "album:"), ":", 2)
if len(parts) != 2 {
return "", "", false
}
return parts[0], parts[1], true
}
// DirCacheFlush resets the directory cache - used in testing as an
// optional interface
func (f *PhotosFs) DirCacheFlush() {
f.dirCache.ResetRoot()
// Also flush API-layer caches so albums/photos are re-fetched
// DirCacheFlusher interface has no ctx param; use a bounded timeout
// to avoid hanging indefinitely if photosService triggers first init
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if ps, err := f.photosService(ctx); err == nil {
ps.FlushCaches()
}
}
// listRAlbumJob represents an album to be listed by a ListR worker
type listRAlbumJob struct {
album *api.Album
zone string
dirPath string // path relative to Fs root (e.g. "Videos" when f.root="PrimarySync")
}
// ListR lists the objects and directories of the Fs starting from dir
// recursively into out, calling callback for each batch of entries
// Albums are listed in parallel using a goroutine pool
func (f *PhotosFs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) error {
ps, err := f.photosService(ctx)
if err != nil {
return err
}
helper := list.NewHelper(callback)
var mu sync.Mutex // protects helper (not thread-safe)
addEntry := func(entry fs.DirEntry) error {
mu.Lock()
defer mu.Unlock()
return helper.Add(entry)
}
// Resolve dir through dirCache - this respects f.root
dirID, err := f.dirCache.FindDir(ctx, dir, false)
if err != nil {
return err
}
// Collect album jobs, scoped to the resolved directory
var jobs []listRAlbumJob
// collectAlbumJobs emits directory entries for albums/folders under basePath
// and collects leaf albums as jobs for parallel photo listing
// Recurses into folders to handle arbitrary nesting depth
var collectAlbumJobs func(albums map[string]*api.Album, zone, basePath string) error
collectAlbumJobs = func(albums map[string]*api.Album, zone, basePath string) error {
for albumName, album := range albums {
albumPath := path.Join(basePath, f.opt.Enc.ToStandardName(albumName))
if err := addEntry(fs.NewDir(albumPath, f.startTime)); err != nil {
return err
}
if album.IsFolder {
if err := collectAlbumJobs(album.Children, zone, albumPath); err != nil {
return err
}
} else {
jobs = append(jobs, listRAlbumJob{album: album, zone: zone, dirPath: albumPath})
}
}
return nil
}
switch {
case dirID == rootID:
// Root level - emit libraries, then all albums
libraries, err := ps.GetLibraries(ctx)
if err != nil {
return err
}
for libName, lib := range libraries {
libPath := path.Join(dir, f.opt.Enc.ToStandardName(libName))
if err := addEntry(fs.NewDir(libPath, f.startTime)); err != nil {
return err
}
albums, err := lib.GetAlbums(ctx)
if err != nil {
return err
}
if err := collectAlbumJobs(albums, libName, libPath); err != nil {
return err
}
}
case strings.HasPrefix(dirID, "lib:"):
// Library level - emit and collect all albums
libraryName := strings.TrimPrefix(dirID, "lib:")
libraries, err := ps.GetLibraries(ctx)
if err != nil {
return err
}
library, exists := libraries[libraryName]
if !exists {
return fs.ErrorDirNotFound
}
albums, err := library.GetAlbums(ctx)
if err != nil {
return err
}
if err := collectAlbumJobs(albums, libraryName, dir); err != nil {
return err
}
case strings.HasPrefix(dirID, "album:"):
// Album or folder level
libraryName, albumPath, ok := parseAlbumDirID(dirID)
if !ok {
return fs.ErrorDirNotFound
}
album, err := f.resolveAlbum(ctx, ps, libraryName, albumPath)
if err != nil {
return err
}
if album.IsFolder {
if err := collectAlbumJobs(album.Children, libraryName, dir); err != nil {
return err
}
} else {
// Single album - just list its photos
jobs = append(jobs, listRAlbumJob{album: album, zone: libraryName, dirPath: dir})
}
default:
return fs.ErrorDirNotFound
}
if len(jobs) == 0 {
return helper.Flush()
}
// Fan out album photo listing across goroutines
ctx, cancel := context.WithCancel(ctx)
defer cancel()
jobCh := make(chan listRAlbumJob, len(jobs))
for _, job := range jobs {
jobCh <- job
}
close(jobCh)
workers := fs.GetConfig(ctx).Checkers
if len(jobs) < workers {
workers = len(jobs)
}
errs := make(chan error, workers)
for range workers {
go func() {
for job := range jobCh {
photos, err := job.album.GetPhotos(ctx)
if err != nil {
errs <- err
cancel()
return
}
for _, photo := range photos {
if photo.Filename == "" {
continue
}
remotePath := path.Join(job.dirPath, f.opt.Enc.ToStandardName(photo.Filename))
o := f.newPhotosObject(remotePath, photo, job.zone)
if err := addEntry(o); err != nil {
errs <- err
cancel()
return
}
}
}
errs <- nil
}()
}
for range workers {
if e := <-errs; e != nil && err == nil {
err = e
}
}
if err != nil {
return err
}
return helper.Flush()
}
func notifyAlbumTree(albums map[string]*api.Album, base string, notifyFunc func(string, fs.EntryType)) {
for name, album := range albums {
albumPath := name
if base != "" {
albumPath = path.Join(base, name)
}
notifyFunc(albumPath, fs.EntryDirectory)
if album.IsFolder {
notifyAlbumTree(album.Children, albumPath, notifyFunc)
}
}
}
func (f *PhotosFs) notifyZoneChange(ctx context.Context, ps *api.PhotosService, zone string, notifyFunc func(string, fs.EntryType)) {
if f.root == "" {
notifyFunc(zone, fs.EntryDirectory)
return
}
libraryName, albumPath, _ := strings.Cut(f.root, "/")
if libraryName != zone {
return
}
// Always invalidate the mounted root when its backing zone changes
notifyFunc("", fs.EntryDirectory)
libraries, err := ps.GetLibraries(ctx)
if err != nil {
return
}
library, ok := libraries[zone]
if !ok {
return
}
albums, err := library.GetAlbums(ctx)
if err != nil {
return
}
if albumPath == "" {
notifyAlbumTree(albums, "", notifyFunc)
return
}
album, err := resolveAlbumPath(albums, albumPath)
if err != nil {
return
}
if album.IsFolder {
notifyAlbumTree(album.Children, "", notifyFunc)
}
}
// ChangeNotify polls for changes and notifies the VFS when directories are modified
func (f *PhotosFs) ChangeNotify(ctx context.Context, notifyFunc func(string, fs.EntryType), pollIntervalChan <-chan time.Duration) {
go func() {
var ticker *time.Ticker
var tickerC <-chan time.Time
for {
select {
case pollInterval, ok := <-pollIntervalChan:
if !ok {
if ticker != nil {
ticker.Stop()
}
return
}
if ticker != nil {
ticker.Stop()
tickerC = nil
}
if pollInterval > 0 {
ticker = time.NewTicker(pollInterval)
tickerC = ticker.C
}
case <-tickerC:
ps, err := f.photosService(ctx)
if err != nil {
fs.Debugf(f, "ChangeNotify: failed to get photos service: %v", err)
continue
}
changedZones := ps.PollForChanges(ctx)
for _, zone := range changedZones {
f.notifyZoneChange(ctx, ps, zone, notifyFunc)
}
case <-ctx.Done():
if ticker != nil {
ticker.Stop()
}
return
}
}
}()
}
// Disconnect clears authentication state and removes disk caches
func (f *PhotosFs) Disconnect(ctx context.Context) error {
return disconnectClient(f.m, f.icloud)
}
// Check interfaces are satisfied
var (
_ fs.Fs = (*PhotosFs)(nil)
_ fs.Disconnecter = (*PhotosFs)(nil)
_ fs.ListRer = (*PhotosFs)(nil)
_ fs.ChangeNotifier = (*PhotosFs)(nil)
_ fs.DirCacheFlusher = (*PhotosFs)(nil)
_ fs.Object = (*PhotosObject)(nil)
_ fs.Metadataer = (*PhotosObject)(nil)
)
-516
View File
@@ -1,516 +0,0 @@
//go:build !plan9 && !solaris
package iclouddrive
import (
"context"
"sort"
"testing"
"time"
"github.com/rclone/rclone/backend/iclouddrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/dircache"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newTestPhotosFs() *PhotosFs {
return &PhotosFs{
name: "test-icp",
root: "",
opt: Options{},
}
}
func TestSmartAlbumDefinitions(t *testing.T) {
expected := map[string]struct {
ObjectType string
ListType string
}{
"All Photos": {"CPLAssetByAssetDateWithoutHiddenOrDeleted", "CPLAssetAndMasterByAssetDateWithoutHiddenOrDeleted"},
"Time-lapse": {"CPLAssetInSmartAlbumByAssetDate:Timelapse", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Videos": {"CPLAssetInSmartAlbumByAssetDate:Video", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Slo-mo": {"CPLAssetInSmartAlbumByAssetDate:Slomo", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Bursts": {"CPLAssetBurstStackAssetByAssetDate", "CPLBurstStackAssetAndMasterByAssetDate"},
"Favorites": {"CPLAssetInSmartAlbumByAssetDate:Favorite", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Panoramas": {"CPLAssetInSmartAlbumByAssetDate:Panorama", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Screenshots": {"CPLAssetInSmartAlbumByAssetDate:Screenshot", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Live": {"CPLAssetInSmartAlbumByAssetDate:Live", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Recently Deleted": {"CPLAssetDeletedByExpungedDate", "CPLAssetAndMasterDeletedByExpungedDate"},
"Hidden": {"CPLAssetHiddenByAssetDate", "CPLAssetAndMasterHiddenByAssetDate"},
"Portrait": {"CPLAssetInSmartAlbumByAssetDate:Depth", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Long Exposure": {"CPLAssetInSmartAlbumByAssetDate:Exposure", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
"Animated": {"CPLAssetInSmartAlbumByAssetDate:Animated", "CPLAssetAndMasterInSmartAlbumByAssetDate"},
}
for name, exp := range expected {
t.Run(name, func(t *testing.T) {
album, exists := api.SmartAlbums[name]
require.True(t, exists, "smart album %q must be defined", name)
assert.Equal(t, exp.ObjectType, album.ObjectType)
assert.Equal(t, exp.ListType, album.ListType)
})
}
assert.Equal(t, len(expected), len(api.SmartAlbums))
}
func TestSmartAlbumFilters(t *testing.T) {
filtered := map[string]string{
"Time-lapse": "TIMELAPSE",
"Videos": "VIDEO",
"Slo-mo": "SLOMO",
"Favorites": "FAVORITE",
"Panoramas": "PANORAMA",
"Screenshots": "SCREENSHOT",
"Live": "LIVE",
"Portrait": "DEPTH",
"Long Exposure": "EXPOSURE",
"Animated": "ANIMATED",
}
for name, filterVal := range filtered {
t.Run(name, func(t *testing.T) {
album := api.SmartAlbums[name]
require.NotEmpty(t, album.Filters, "album %q must have filters", name)
assert.Equal(t, "smartAlbum", album.Filters[0].FieldName)
assert.Equal(t, "EQUALS", album.Filters[0].Comparator)
fv, ok := album.Filters[0].FieldValue.(map[string]string)
require.True(t, ok, "filter value must be map[string]string")
assert.Equal(t, filterVal, fv["value"])
})
}
unfiltered := []string{"All Photos", "Bursts", "Recently Deleted", "Hidden"}
for _, name := range unfiltered {
t.Run(name+"_no_filter", func(t *testing.T) {
album := api.SmartAlbums[name]
assert.Empty(t, album.Filters, "album %q must not have filters", name)
})
}
}
func TestParseAlbumDirID(t *testing.T) {
lib, album, ok := parseAlbumDirID("album:PrimarySync:Favorites")
assert.True(t, ok)
assert.Equal(t, "PrimarySync", lib)
assert.Equal(t, "Favorites", album)
// Colon in album name
lib, album, ok = parseAlbumDirID("album:PrimarySync:My:Album")
assert.True(t, ok)
assert.Equal(t, "PrimarySync", lib)
assert.Equal(t, "My:Album", album)
// Missing album
_, _, ok = parseAlbumDirID("album:PrimarySync")
assert.False(t, ok)
// Empty
_, _, ok = parseAlbumDirID("album:")
assert.False(t, ok)
}
func TestPhotosObject_Metadata(t *testing.T) {
o := &PhotosObject{
fs: &PhotosFs{name: "test"},
remote: "PrimarySync/All Photos/IMG_0001.HEIC",
size: 4200000,
modTime: time.Date(2025, 6, 15, 14, 30, 0, 0, time.UTC),
masterID: "master-001",
zone: "PrimarySync",
width: 4032,
height: 3024,
addedDate: 1718459400000, // 2024-06-15T13:50:00Z in millis
isFavorite: true,
isHidden: false,
}
metadata, err := o.Metadata(context.Background())
require.NoError(t, err)
assert.Equal(t, "4032", metadata["width"])
assert.Equal(t, "3024", metadata["height"])
assert.Equal(t, "2024-06-15T13:50:00Z", metadata["added-time"])
assert.Equal(t, "true", metadata["favorite"])
assert.Equal(t, "false", metadata["hidden"])
}
func TestPhotosObject_MetadataZeroDimensions(t *testing.T) {
// Live Photo .MOV companion - no width/height, not favorite
o := &PhotosObject{
fs: &PhotosFs{name: "test"},
remote: "PrimarySync/Live/IMG_3031.MOV",
}
metadata, err := o.Metadata(context.Background())
require.NoError(t, err)
_, hasWidth := metadata["width"]
_, hasHeight := metadata["height"]
assert.False(t, hasWidth, "zero width should be omitted")
assert.False(t, hasHeight, "zero height should be omitted")
assert.Equal(t, "false", metadata["favorite"])
assert.Equal(t, "false", metadata["hidden"])
}
// newTestPhotosService builds a PhotosService with pre-populated libraries and albums
// for testing resolveAlbum and FindLeaf without HTTP calls
func newTestPhotosService() *api.PhotosService {
return api.NewTestPhotosService(map[string]map[string]*api.Album{
"PrimarySync": {
"All Photos": {Name: "All Photos", ObjectType: "CPLAssetByAssetDateWithoutHiddenOrDeleted"},
"Videos": {Name: "Videos", ObjectType: "CPLAssetInSmartAlbumByAssetDate:Video"},
"UserAlbum": {Name: "UserAlbum", ObjectType: "CPLContainerRelationNotDeletedByAssetDate:rec1", RecordName: "rec1"},
"Folder": {
Name: "Folder", RecordName: "folder1", IsFolder: true,
Children: map[string]*api.Album{
"ChildAlbum": {Name: "ChildAlbum", ObjectType: "CPLContainerRelationNotDeletedByAssetDate:rec2", RecordName: "rec2"},
"NestedFolder": {
Name: "NestedFolder", RecordName: "folder2", IsFolder: true,
Children: map[string]*api.Album{
"LeafAlbum": {Name: "LeafAlbum", ObjectType: "CPLContainerRelationNotDeletedByAssetDate:rec3", RecordName: "rec3"},
},
},
},
},
},
})
}
func TestResolveAlbum(t *testing.T) {
f := newTestPhotosFs()
f.photos = newTestPhotosService()
ctx := context.Background()
t.Run("simple album", func(t *testing.T) {
album, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Videos")
require.NoError(t, err)
assert.Equal(t, "Videos", album.Name)
})
t.Run("nested folder child", func(t *testing.T) {
album, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Folder/ChildAlbum")
require.NoError(t, err)
assert.Equal(t, "ChildAlbum", album.Name)
})
t.Run("two-level nesting", func(t *testing.T) {
album, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Folder/NestedFolder/LeafAlbum")
require.NoError(t, err)
assert.Equal(t, "LeafAlbum", album.Name)
})
t.Run("folder itself", func(t *testing.T) {
album, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Folder")
require.NoError(t, err)
assert.True(t, album.IsFolder)
})
t.Run("missing album", func(t *testing.T) {
_, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "NoSuchAlbum")
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
})
t.Run("missing library", func(t *testing.T) {
_, err := f.resolveAlbum(ctx, f.photos, "NoSuchLib", "Videos")
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
})
t.Run("traverse into non-folder", func(t *testing.T) {
_, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Videos/SubAlbum")
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
})
}
func TestFindLeaf(t *testing.T) {
f := newTestPhotosFs()
f.photos = newTestPhotosService()
ctx := context.Background()
t.Run("root to library", func(t *testing.T) {
id, found, err := f.FindLeaf(ctx, rootID, "PrimarySync")
require.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "lib:PrimarySync", id)
})
t.Run("root to missing library", func(t *testing.T) {
_, found, err := f.FindLeaf(ctx, rootID, "NoSuchLib")
require.NoError(t, err)
assert.False(t, found)
})
t.Run("library to album", func(t *testing.T) {
id, found, err := f.FindLeaf(ctx, "lib:PrimarySync", "Videos")
require.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "album:PrimarySync:Videos", id)
})
t.Run("library to missing album", func(t *testing.T) {
_, found, err := f.FindLeaf(ctx, "lib:PrimarySync", "NoSuchAlbum")
require.NoError(t, err)
assert.False(t, found)
})
t.Run("missing library returns ErrorDirNotFound", func(t *testing.T) {
_, _, err := f.FindLeaf(ctx, "lib:NoSuchLib", "Videos")
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
})
t.Run("folder to child album", func(t *testing.T) {
id, found, err := f.FindLeaf(ctx, "album:PrimarySync:Folder", "ChildAlbum")
require.NoError(t, err)
assert.True(t, found)
assert.Equal(t, "album:PrimarySync:Folder/ChildAlbum", id)
})
t.Run("non-folder album returns not found", func(t *testing.T) {
_, found, err := f.FindLeaf(ctx, "album:PrimarySync:Videos", "SubAlbum")
require.NoError(t, err)
assert.False(t, found)
})
t.Run("unknown prefix returns not found", func(t *testing.T) {
_, found, err := f.FindLeaf(ctx, "unknown:prefix", "leaf")
require.NoError(t, err)
assert.False(t, found)
})
}
func TestResolveAlbum_EmptyPath(t *testing.T) {
f := newTestPhotosFs()
f.photos = newTestPhotosService()
ctx := context.Background()
// parseAlbumDirID("album:PrimarySync:") returns ("PrimarySync", "", true)
// This empty album path feeds into resolveAlbum
_, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "")
assert.ErrorIs(t, err, fs.ErrorDirNotFound, "empty album path should return ErrorDirNotFound")
}
func TestNewObject_ErrorPaths(t *testing.T) {
f := newTestPhotosFs()
f.photos = newTestPhotosService()
ctx := context.Background()
// Pre-populate photoCache on the "Videos" album so GetPhotoByName works
// without HTTP. Access via the test PhotosService's internal structure
libs, _ := f.photos.GetLibraries(ctx)
albums, _ := libs["PrimarySync"].GetAlbums(ctx)
videos := albums["Videos"]
videos.SetTestPhotoCache(map[string]*api.Photo{
"existing.mp4": {ID: "m1", Filename: "existing.mp4", Size: 1024, ResourceKey: "resOriginalRes"},
})
// NewObject depends on dircache.FindDir which requires FindRoot + HTTP
// Test the reachable paths through resolveAlbum and GetPhotoByName
// Test resolveAlbum → folder → GetPhotoByName on folder (should fail)
album, err := f.resolveAlbum(ctx, f.photos, "PrimarySync", "Folder")
require.NoError(t, err)
assert.True(t, album.IsFolder, "Folder should be a folder")
// NewObject would return ErrorObjectNotFound for a folder path
// Test GetPhotoByName on album with populated cache
photo, err := videos.GetPhotoByName(ctx, "existing.mp4")
require.NoError(t, err)
assert.Equal(t, "m1", photo.ID)
// Test GetPhotoByName cache miss
_, err = videos.GetPhotoByName(ctx, "nonexistent.mp4")
assert.Error(t, err)
assert.Contains(t, err.Error(), "nonexistent.mp4")
}
func TestParseAlbumDirID_Exhaustive(t *testing.T) {
tests := []struct {
input string
lib, album string
ok bool
}{
{"album:PrimarySync:Videos", "PrimarySync", "Videos", true},
{"album:PrimarySync:Folder/Child", "PrimarySync", "Folder/Child", true},
{"album:PrimarySync:Name:With:Colons", "PrimarySync", "Name:With:Colons", true},
{"album:PrimarySync:", "PrimarySync", "", true},
{"album:", "", "", false},
{"notalbum:foo:bar", "notalbum", "foo:bar", true}, // strips "album:" prefix literally, "notalbum:" stays
{"", "", "", false},
}
for _, tt := range tests {
lib, album, ok := parseAlbumDirID(tt.input)
if tt.ok {
assert.True(t, ok, "input=%q", tt.input)
assert.Equal(t, tt.lib, lib, "input=%q", tt.input)
assert.Equal(t, tt.album, album, "input=%q", tt.input)
} else {
assert.False(t, ok, "input=%q", tt.input)
}
}
}
// setEmptyPhotoCaches recursively sets empty photo caches on all leaf albums
// so GetPhotos returns without HTTP (service=nil test fast path)
func setEmptyPhotoCaches(albums map[string]*api.Album) {
for _, album := range albums {
if album.IsFolder {
setEmptyPhotoCaches(album.Children)
} else {
album.SetTestPhotoCache(map[string]*api.Photo{})
}
}
}
func TestListR_NestedFolderRecursion(t *testing.T) {
f := newTestPhotosFs()
f.photos = newTestPhotosService()
f.dirCache = dircache.New("", rootID, f)
f.features = (&fs.Features{}).Fill(context.Background(), f)
f.startTime = time.Now()
ctx := context.Background()
err := f.dirCache.FindRoot(ctx, false)
require.NoError(t, err)
// Pre-populate empty photo caches on all leaf albums
libs, err := f.photos.GetLibraries(ctx)
require.NoError(t, err)
for _, lib := range libs {
albums, err := lib.GetAlbums(ctx)
require.NoError(t, err)
setEmptyPhotoCaches(albums)
}
var dirs []string
err = f.ListR(ctx, "", func(entries fs.DirEntries) error {
for _, entry := range entries {
if _, ok := entry.(fs.Directory); ok {
dirs = append(dirs, entry.Remote())
}
}
return nil
})
require.NoError(t, err)
sort.Strings(dirs)
// All directories must be present, including deeply nested ones
assert.Contains(t, dirs, "PrimarySync")
assert.Contains(t, dirs, "PrimarySync/All Photos")
assert.Contains(t, dirs, "PrimarySync/Videos")
assert.Contains(t, dirs, "PrimarySync/Folder")
assert.Contains(t, dirs, "PrimarySync/Folder/ChildAlbum")
assert.Contains(t, dirs, "PrimarySync/Folder/NestedFolder")
assert.Contains(t, dirs, "PrimarySync/Folder/NestedFolder/LeafAlbum")
}
func TestListR_FolderLevel(t *testing.T) {
f := &PhotosFs{
name: "test",
root: "PrimarySync/Folder",
opt: Options{},
startTime: time.Now(),
}
f.features = (&fs.Features{}).Fill(context.Background(), f)
f.photos = newTestPhotosService()
f.dirCache = dircache.New("PrimarySync/Folder", rootID, f)
ctx := context.Background()
err := f.dirCache.FindRoot(ctx, false)
require.NoError(t, err)
libs, _ := f.photos.GetLibraries(ctx)
for _, lib := range libs {
albums, _ := lib.GetAlbums(ctx)
setEmptyPhotoCaches(albums)
}
var dirs []string
err = f.ListR(ctx, "", func(entries fs.DirEntries) error {
for _, entry := range entries {
if _, ok := entry.(fs.Directory); ok {
dirs = append(dirs, entry.Remote())
}
}
return nil
})
require.NoError(t, err)
// When rooted at a folder, should see children recursively
assert.Contains(t, dirs, "ChildAlbum")
assert.Contains(t, dirs, "NestedFolder")
assert.Contains(t, dirs, "NestedFolder/LeafAlbum")
}
func TestNotifyZoneChange(t *testing.T) {
ctx := context.Background()
ps := newTestPhotosService()
tests := []struct {
name string
root string
zone string
want []string
}{
{
name: "top level root",
root: "",
zone: "PrimarySync",
want: []string{"PrimarySync"},
},
{
name: "library root",
root: "PrimarySync",
zone: "PrimarySync",
want: []string{"", "All Photos", "Folder", "Folder/ChildAlbum", "Folder/NestedFolder", "Folder/NestedFolder/LeafAlbum", "UserAlbum", "Videos"},
},
{
name: "folder root",
root: "PrimarySync/Folder",
zone: "PrimarySync",
want: []string{"", "ChildAlbum", "NestedFolder", "NestedFolder/LeafAlbum"},
},
{
name: "nested folder root",
root: "PrimarySync/Folder/NestedFolder",
zone: "PrimarySync",
want: []string{"", "LeafAlbum"},
},
{
name: "leaf album root",
root: "PrimarySync/Folder/NestedFolder/LeafAlbum",
zone: "PrimarySync",
want: []string{""},
},
{
name: "missing nested album still invalidates root",
root: "PrimarySync/Folder/NoSuchAlbum",
zone: "PrimarySync",
want: []string{""},
},
{
name: "different zone ignored",
root: "PrimarySync/Folder/NestedFolder",
zone: "SharedSync",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newTestPhotosFs()
f.root = tt.root
var got []string
f.notifyZoneChange(ctx, ps, tt.zone, func(remote string, entryType fs.EntryType) {
assert.Equal(t, fs.EntryDirectory, entryType)
got = append(got, remote)
})
sort.Strings(got)
want := append([]string(nil), tt.want...)
sort.Strings(want)
assert.Equal(t, want, got)
})
}
}
+25 -82
View File
@@ -30,21 +30,15 @@ import (
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/oauthutil"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/random"
)
const (
minSleep = 10 * time.Millisecond
maxSleep = 2 * time.Second
decayConstant = 2
maxUploadParts = 10000
minChunkSize = fs.SizeSuffix(5 * 1024 * 1024)
minUploadCutoff = fs.SizeSuffix(100 * 1024 * 1024)
defaultUploadCutoff = fs.SizeSuffix(100 * 1024 * 1024)
maxUploadCutoff = fs.SizeSuffix(5 * 1024 * 1024 * 1024)
minSleep = 10 * time.Millisecond
maxSleep = 2 * time.Second
decayConstant = 2 // bigger for slower decay, exponential
)
// shouldRetry determines if an error should be retried.
@@ -107,21 +101,6 @@ func init() {
Default: true,
Advanced: true,
Help: "Skip hash validation when downloading files.\n\nBy default, hash validation is disabled. Set this to false to enable validation.",
}, {
Name: "upload_concurrency",
Help: "Concurrency for multipart uploads.\n\nThis is the number of chunks of the same file that are uploaded concurrently.\n\nNote that each chunk is buffered in memory.",
Default: 4,
Advanced: true,
}, {
Name: "upload_cutoff",
Help: "Cutoff for switching to multipart upload.\n\nAny files larger than this will be uploaded in chunks of chunk_size.\nThe minimum is 100 MiB and the maximum is 5 GiB.",
Default: defaultUploadCutoff,
Advanced: true,
}, {
Name: "chunk_size",
Help: "Chunk size for multipart uploads.\n\nFiles larger than upload_cutoff will be uploaded in chunks of this size.\n\nMemory usage is approximately chunk_size * upload_concurrency.",
Default: fs.SizeSuffix(30 * 1024 * 1024),
Advanced: true,
}, {
Name: rclone_config.ConfigEncoding,
Help: rclone_config.ConfigEncodingHelp,
@@ -215,9 +194,6 @@ type Options struct {
TwoFA string `config:"2fa"`
Mnemonic string `config:"mnemonic"`
SkipHashValidation bool `config:"skip_hash_validation"`
UploadCutoff fs.SizeSuffix `config:"upload_cutoff"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
UploadConcurrency int `config:"upload_concurrency"`
Encoding encoder.MultiEncoder `config:"encoding"`
}
@@ -262,11 +238,6 @@ func (f *Fs) Features() *fs.Features {
return f.features
}
// DirCacheFlush resets the directory cache
func (f *Fs) DirCacheFlush() {
f.dirCache.ResetRoot()
}
// Hashes returns type of hashes supported by Internxt
func (f *Fs) Hashes() hash.Set {
return hash.NewHashSet()
@@ -284,13 +255,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return nil, err
}
if err := checkUploadChunkSize(opt.ChunkSize); err != nil {
return nil, fmt.Errorf("internxt: chunk size: %w", err)
}
if err := checkUploadCutoff(opt.UploadCutoff); err != nil {
return nil, fmt.Errorf("internxt: upload cutoff: %w", err)
}
if opt.Mnemonic == "" {
return nil, errors.New("mnemonic is required - please run: rclone config reconnect " + name + ":")
}
@@ -920,53 +884,32 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
fs.Debugf(o.f, "Renamed existing file %s to backup %s.%s (UUID: %s)", remote, backupName, backupType, backupUUID)
}
size := src.Size()
var meta *buckets.CreateMetaResponse
if size < 0 || size >= int64(o.f.opt.UploadCutoff) {
chunkWriter, uploadErr := multipart.UploadMultipart(ctx, src, in, multipart.UploadMultipartOptions{
Open: o.f,
OpenOptions: options,
})
err = o.f.pacer.CallNoRetry(func() (bool, error) {
var err error
meta, err = buckets.UploadFileStreamAuto(ctx,
o.f.cfg,
dirID,
o.f.opt.Encoding.FromStandardName(path.Base(remote)),
in,
src.Size(),
src.ModTime(ctx),
)
return o.f.shouldRetry(ctx, err)
})
if uploadErr != nil {
if isEmptyFileLimitError(uploadErr) {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return fs.ErrorCantUploadEmptyFiles
}
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return uploadErr
}
w := chunkWriter.(*internxtChunkWriter)
meta = w.meta
} else {
// Use single-part upload for small files
err = o.f.pacer.CallNoRetry(func() (bool, error) {
var err error
meta, err = buckets.UploadFileStreamAuto(ctx,
o.f.cfg,
dirID,
o.f.opt.Encoding.FromStandardName(path.Base(remote)),
in,
size,
src.ModTime(ctx),
)
return o.f.shouldRetry(ctx, err)
})
if err != nil && isEmptyFileLimitError(err) {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return fs.ErrorCantUploadEmptyFiles
}
if err != nil && isEmptyFileLimitError(err) {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return fs.ErrorCantUploadEmptyFiles
}
if err != nil {
meta, err = o.recoverFromTimeoutConflict(ctx, err, remote, dirID)
}
if err != nil {
meta, err = o.recoverFromTimeoutConflict(ctx, err, remote, dirID)
}
if err != nil {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return err
}
if err != nil {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return err
}
// Update object metadata
-5
View File
@@ -3,7 +3,6 @@ package internxt_test
import (
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest/fstests"
)
@@ -11,9 +10,5 @@ import (
func TestIntegration(t *testing.T) {
fstests.Run(t, &fstests.Opt{
RemoteName: "TestInternxt:",
ChunkedUpload: fstests.ChunkedUploadConfig{
MinChunkSize: 100 * fs.Mebi,
NeedMultipleChunks: true,
},
})
}
-293
View File
@@ -1,293 +0,0 @@
package internxt
import (
"context"
"crypto/cipher"
"fmt"
"io"
"path"
"sort"
"strings"
"sync"
"github.com/internxt/rclone-adapter/buckets"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/chunksize"
"github.com/rclone/rclone/lib/multipart"
"github.com/rclone/rclone/lib/pool"
)
var warnStreamUpload sync.Once
func checkUploadChunkSize(cs fs.SizeSuffix) error {
if cs < minChunkSize {
return fmt.Errorf("%s is less than %s", cs, minChunkSize)
}
return nil
}
// SetUploadChunkSize sets the chunk size used for multipart uploads
func (f *Fs) SetUploadChunkSize(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
err := checkUploadChunkSize(cs)
if err == nil {
old := f.opt.ChunkSize
f.opt.ChunkSize = cs
return old, nil
}
return f.opt.ChunkSize, err
}
func checkUploadCutoff(cs fs.SizeSuffix) error {
if cs < minUploadCutoff {
return fmt.Errorf("%s is less than %s (Internxt requires minimum %s for multipart uploads)", cs, minUploadCutoff, minUploadCutoff)
}
if cs > maxUploadCutoff {
return fmt.Errorf("%s is greater than %s", cs, maxUploadCutoff)
}
return nil
}
// SetUploadCutoff sets the cutoff for switching to multipart upload
func (f *Fs) SetUploadCutoff(cs fs.SizeSuffix) (fs.SizeSuffix, error) {
err := checkUploadCutoff(cs)
if err == nil {
old := f.opt.UploadCutoff
f.opt.UploadCutoff = cs
return old, nil
}
return f.opt.UploadCutoff, err
}
// internxtChunkWriter implements fs.ChunkWriter for Internxt multipart uploads.
type internxtChunkWriter struct {
f *Fs
remote string
src fs.ObjectInfo
session *buckets.ChunkUploadSession
completedParts []buckets.CompletedPart
partsMu sync.Mutex
size int64
dirID string
meta *buckets.CreateMetaResponse
chunkSize int64
hashMu sync.Mutex
nextHashChunk int
pendingChunks map[int]*pool.RW
}
// OpenChunkWriter returns the chunk size and a ChunkWriter for multipart uploads.
func (f *Fs) OpenChunkWriter(ctx context.Context, remote string, src fs.ObjectInfo, options ...fs.OpenOption) (info fs.ChunkWriterInfo, writer fs.ChunkWriter, err error) {
size := src.Size()
info = fs.ChunkWriterInfo{
ChunkSize: int64(f.opt.ChunkSize),
Concurrency: f.opt.UploadConcurrency,
LeavePartsOnError: false,
}
// Reject files below the upload cutoff
if size >= 0 && size < int64(f.opt.UploadCutoff) {
return info, nil, &fs.FileTooSmallError{MinSize: int64(f.opt.UploadCutoff)}
}
chunkSize := f.opt.ChunkSize
if size < 0 {
warnStreamUpload.Do(func() {
fs.Logf(f, "Streaming uploads using chunk size %v will have maximum file size of %v",
chunkSize, fs.SizeSuffix(int64(chunkSize)*int64(maxUploadParts)))
})
} else {
chunkSize = chunksize.Calculator(src, size, maxUploadParts, chunkSize)
info.ChunkSize = int64(chunkSize)
}
// Ensure parent directory exists
_, dirID, err := f.dirCache.FindPath(ctx, remote, true)
if err != nil {
return info, nil, fmt.Errorf("failed to find parent directory: %w", err)
}
var session *buckets.ChunkUploadSession
err = f.pacer.Call(func() (bool, error) {
var err error
session, err = buckets.NewChunkUploadSession(ctx, f.cfg, size, int64(chunkSize))
return f.shouldRetry(ctx, err)
})
if err != nil {
return info, nil, fmt.Errorf("failed to create upload session: %w", err)
}
w := &internxtChunkWriter{
f: f,
remote: remote,
src: src,
session: session,
size: size,
dirID: dirID,
chunkSize: int64(chunkSize),
pendingChunks: make(map[int]*pool.RW),
}
return info, w, nil
}
// WriteChunk encrypts plaintext per-chunk using AES-256-CTR at the correct
// byte offset, uploads the encrypted data, then feeds it into the ordered
// hash accumulator
func (w *internxtChunkWriter) WriteChunk(ctx context.Context, chunkNumber int, reader io.ReadSeeker) (int64, error) {
byteOffset := int64(chunkNumber) * w.chunkSize
cipherStream, err := w.session.NewCipherAtOffset(byteOffset)
if err != nil {
return 0, err
}
encRW := multipart.NewRW().Reserve(w.chunkSize)
cipherReader := &cipher.StreamReader{S: cipherStream, R: reader}
size, err := io.Copy(encRW, cipherReader)
if err != nil {
_ = encRW.Close()
return 0, err
}
if size == 0 {
_ = encRW.Close()
return 0, nil
}
var etag string
err = w.f.pacer.Call(func() (bool, error) {
if _, err := encRW.Seek(0, io.SeekStart); err != nil {
return false, err
}
var uploadErr error
etag, uploadErr = w.session.UploadChunk(ctx, chunkNumber, encRW, size)
return w.f.shouldRetry(ctx, uploadErr)
})
if err != nil {
_ = encRW.Close()
return 0, err
}
w.recordCompletedPart(chunkNumber, etag)
if _, err := encRW.Seek(0, io.SeekStart); err != nil {
_ = encRW.Close()
return 0, err
}
w.submitForHashing(chunkNumber, encRW)
return size, nil
}
// recordCompletedPart appends a completed part to the list (thread-safe).
func (w *internxtChunkWriter) recordCompletedPart(chunkNumber int, etag string) {
w.partsMu.Lock()
w.completedParts = append(w.completedParts, buckets.CompletedPart{
PartNumber: chunkNumber + 1,
ETag: etag,
})
w.partsMu.Unlock()
}
// hashWriter is an io.Writer that feeds data into the session's SHA-256 hash.
type hashWriter struct {
session *buckets.ChunkUploadSession
}
func (hw hashWriter) Write(p []byte) (int, error) {
hw.session.HashEncryptedData(p)
return len(p), nil
}
// submitForHashing feeds encrypted chunk data into the session's hash in order.
func (w *internxtChunkWriter) submitForHashing(chunkNumber int, encRW *pool.RW) {
w.hashMu.Lock()
defer w.hashMu.Unlock()
hw := hashWriter{w.session}
if chunkNumber == w.nextHashChunk {
_, _ = encRW.WriteTo(hw)
_ = encRW.Close()
w.nextHashChunk++
for {
next, ok := w.pendingChunks[w.nextHashChunk]
if !ok {
break
}
_, _ = next.WriteTo(hw)
_ = next.Close()
delete(w.pendingChunks, w.nextHashChunk)
w.nextHashChunk++
}
} else {
w.pendingChunks[chunkNumber] = encRW
}
}
// Close completes the multipart upload and registers the file in Internxt Drive.
func (w *internxtChunkWriter) Close(ctx context.Context) error {
w.hashMu.Lock()
pending := len(w.pendingChunks)
if pending != 0 {
for _, rw := range w.pendingChunks {
_ = rw.Close()
}
w.pendingChunks = nil
}
w.hashMu.Unlock()
if pending != 0 {
return fmt.Errorf("internal error: %d chunks still pending hash", pending)
}
// Sort parts by part number
w.partsMu.Lock()
sort.Slice(w.completedParts, func(i, j int) bool {
return w.completedParts[i].PartNumber < w.completedParts[j].PartNumber
})
parts := make([]buckets.CompletedPart, len(w.completedParts))
copy(parts, w.completedParts)
w.partsMu.Unlock()
// Finish multipart upload (SDK computes hash + calls FinishMultipartUpload)
var finishResp *buckets.FinishUploadResp
err := w.f.pacer.Call(func() (bool, error) {
var err error
finishResp, err = w.session.Finish(ctx, parts)
return w.f.shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("failed to finish multipart upload: %w", err)
}
// Create file metadata in Internxt Drive
baseName := w.f.opt.Encoding.FromStandardName(path.Base(w.remote))
name := strings.TrimSuffix(baseName, path.Ext(baseName))
ext := strings.TrimPrefix(path.Ext(baseName), ".")
var meta *buckets.CreateMetaResponse
err = w.f.pacer.Call(func() (bool, error) {
var err error
meta, err = buckets.CreateMetaFile(ctx, w.f.cfg,
name, w.f.cfg.Bucket, &finishResp.ID, "03-aes",
w.dirID, name, ext, w.size, w.src.ModTime(ctx))
return w.f.shouldRetry(ctx, err)
})
if err != nil {
return fmt.Errorf("failed to create file metadata: %w", err)
}
w.meta = meta
return nil
}
// Abort cleans up after a failed upload.
func (w *internxtChunkWriter) Abort(ctx context.Context) error {
w.hashMu.Lock()
for _, rw := range w.pendingChunks {
_ = rw.Close()
}
w.pendingChunks = nil
w.hashMu.Unlock()
fs.Logf(w.f, "Multipart upload aborted for %s", w.remote)
return nil
}
+1 -3
View File
@@ -91,7 +91,6 @@ func getServices() []service {
{"letsgo", "Let's Go Cloud (Germany)", "letsgo.jotta.cloud", "letsgo", "desktop-win", []string{"openid", "offline_access"}},
{"mediamarkt", "MediaMarkt Cloud (Multiregional)", "mediamarkt.jottacloud.com", "mediamarkt", "desktop", []string{"openid", "jotta-default", "offline_access"}},
{"onlime", "Onlime (Denmark)", "cloud-auth.onlime.dk", "onlime_wl", "desktop", []string{"openid", "jotta-default", "offline_access"}},
{"phonero", "Phonero Sky", "sky.phonero.no", "phonero", "desktop-win", []string{"openid", "offline_access"}},
{"tele2", "Tele2 Cloud (Sweden)", "mittcloud-auth.tele2.se", "comhem", "desktop", []string{"openid", "jotta-default", "offline_access"}},
{"telia_no", "Telia Sky (Norway)", "sky-auth.telia.no", "get", "desktop", []string{"openid", "jotta-default", "offline_access"}},
{"telia_se", "Telia Cloud (Sweden)", "cloud-auth.telia.se", "telia_se", "desktop", []string{"openid", "jotta-default", "offline_access"}},
@@ -167,8 +166,7 @@ func init() {
// Also: '*', '/', ':', '<', '>', '?', '\"', '\x00', '|'
Default: (encoder.Display |
encoder.EncodeWin | // :?"*<>|
encoder.EncodeInvalidUtf8 |
encoder.EncodePercent),
encoder.EncodeInvalidUtf8),
}}...),
})
}
+43 -162
View File
@@ -14,21 +14,19 @@ import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"fmt"
"io"
"net/http"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
@@ -43,7 +41,6 @@ const (
maxSleep = 2 * time.Second
pacerBurst = 1
linkboxAPIURL = "https://www.linkbox.to/api/open/"
linkboxWebAPIURL = "https://www.linkbox.to/api/"
rootID = "0" // ID of root directory
)
@@ -57,20 +54,6 @@ func init() {
Help: "Token from https://www.linkbox.to/admin/account",
Sensitive: true,
Required: true,
}, {
Name: "email",
Help: "Email for login",
Sensitive: true,
Required: true,
}, {
Name: "password",
Help: "Password for login",
IsPassword: true,
Required: true,
}, {
Name: "web_token",
Help: "Web API login token - set automatically.",
Hide: fs.OptionHideBoth,
}},
}
fs.Register(fsi)
@@ -78,26 +61,19 @@ func init() {
// Options defines the configuration for this backend
type Options struct {
Token string `config:"token"`
Email string `config:"email"`
Password string `config:"password"`
WebToken string `config:"web_token"`
Token string `config:"token"`
}
// Fs stores the interface to the remote Linkbox files
type Fs struct {
name string
root string
opt Options // options for this backend
features *fs.Features // optional features
ci *fs.ConfigInfo // global config
srv *rest.Client // the connection to the server
cdnSrv *rest.Client // HTTP client for CDN downloads (HTTP/2 disabled)
dirCache *dircache.DirCache // Map of directory path to directory id
pacer *fs.Pacer
m configmap.Mapper // config mapper for saving tokens
webToken string // token from web API login
webTokenMu sync.Mutex // protects webToken
name string
root string
opt Options // options for this backend
features *fs.Features // optional features
ci *fs.ConfigInfo // global config
srv *rest.Client // the connection to the server
dirCache *dircache.DirCache // Map of directory path to directory id
pacer *fs.Pacer
}
// Object is a remote object that has been stat'd (so it exists, but is not necessarily open for reading)
@@ -128,27 +104,14 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
ci := fs.GetConfig(ctx)
// Create a separate HTTP client for CDN downloads with HTTP/2 disabled.
// The Linkbox CDN intermittently blocks Go's HTTP/2 fingerprint and
// non-browser User-Agents.
cdnClient := fshttp.NewClientCustom(ctx, func(t *http.Transport) {
t.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
})
if tr, ok := cdnClient.Transport.(*fshttp.Transport); ok {
tr.SetRequestFilter(func(req *http.Request) {
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
})
}
f := &Fs{
name: name,
opt: *opt,
root: root,
ci: ci,
srv: rest.NewClient(fshttp.NewClient(ctx)),
cdnSrv: rest.NewClient(cdnClient),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep))),
m: m,
name: name,
opt: *opt,
root: root,
ci: ci,
srv: rest.NewClient(fshttp.NewClient(ctx)),
pacer: fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep))),
}
f.dirCache = dircache.New(root, rootID, f)
@@ -157,27 +120,12 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
CaseInsensitive: true,
}).Fill(ctx, f)
if f.opt.Email == "" || f.opt.Password == "" {
return nil, fmt.Errorf("email and password are required - run `rclone config`")
}
// Load cached web token or login to get a new one
if opt.WebToken != "" {
f.webToken = opt.WebToken
fs.Debugf(f, "Using cached web token")
} else {
err = f.login(ctx)
if err != nil {
return nil, err
}
}
// Find the current root
err = f.dirCache.FindRoot(ctx, false)
if err != nil {
// Assume it is a file
newRoot, remote := dircache.SplitPath(root)
tempF := *f //nolint:govet // copying mutex is OK here as it is a new Fs
tempF := *f
tempF.dirCache = dircache.New(newRoot, rootID, &tempF)
tempF.root = newRoot
// Make new Fs which is the parent
@@ -206,78 +154,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return f, nil
}
// loginResponse is the response from the web API login
type loginResponse struct {
response
Data struct {
Token string `json:"token"`
} `json:"data"`
}
// login authenticates with the web API using email and password
// and saves the token in the config for reuse.
func (f *Fs) login(ctx context.Context) error {
password, err := obscure.Reveal(f.opt.Password)
if err != nil {
return fmt.Errorf("failed to decrypt password: %w", err)
}
opts := &rest.Opts{
Method: "GET",
RootURL: linkboxWebAPIURL,
Path: "user/login_email",
Parameters: url.Values{
"email": {f.opt.Email},
"pwd": {password},
"platform": {"web"},
"pf": {"web"},
"lan": {"en"},
},
}
var result loginResponse
err = getUnmarshaledResponse(ctx, f, opts, &result)
if err != nil {
return fmt.Errorf("login failed: %w", err)
}
if result.Data.Token == "" {
return fmt.Errorf("login returned empty token")
}
f.webTokenMu.Lock()
f.webToken = result.Data.Token
f.webTokenMu.Unlock()
// Save token to config for reuse across invocations
f.m.Set("web_token", f.webToken)
fs.Debugf(f, "Login successful")
return nil
}
// shouldRetryWeb determines whether a web API error should be retried.
//
// If the API returns an error it may be because the token has expired,
// so this refreshes the token and updates the request parameters for
// the retry.
func (f *Fs) shouldRetryWeb(ctx context.Context, resp *http.Response, err error, result responser, opts *rest.Opts) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
if fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes) {
return true, err
}
// If the web API returned an error, it may be due to an expired token.
// Refresh the token and retry.
if result.IsError() {
fs.Debugf(f, "Web API returned error %q - refreshing token", result.Error())
loginErr := f.login(ctx)
if loginErr != nil {
return false, loginErr
}
f.webTokenMu.Lock()
opts.Parameters.Set("token", f.webToken)
f.webTokenMu.Unlock()
return true, nil
}
return false, nil
}
type entity struct {
Type string `json:"type"`
Name string `json:"name"`
@@ -340,28 +216,40 @@ func getUnmarshaledResponse(ctx context.Context, f *Fs, opts *rest.Opts, result
// Should return true to finish processing
type listAllFn func(*entity) bool
// Search is a bit fussy about which characters match
//
// If the name doesn't match this then do an dir list instead
// N.B.: Linkbox doesn't support search by name that is longer than 50 chars
var searchOK = regexp.MustCompile(`^[a-zA-Z0-9_ -.]{1,50}$`)
// Lists the directory required calling the user function on each item found
//
// If the user fn ever returns true then it early exits with found = true
//
// If you set name then search ignores dirID. name is a substring
// search also so name="dir" matches "sub dir" also. This filters it
// down so it only returns items in dirID
func (f *Fs) listAll(ctx context.Context, dirID string, name string, fn listAllFn) (found bool, err error) {
_ = name // name parameter kept for call-site compatibility but unused with web API
var (
pageNumber = 0
numberOfEntities = maxEntitiesPerPage
)
name = strings.TrimSpace(name) // search doesn't like spaces
if !searchOK.MatchString(name) {
// If name isn't good then do an unbounded search
name = ""
}
OUTER:
for numberOfEntities == maxEntitiesPerPage {
pageNumber++
f.webTokenMu.Lock()
webToken := f.webToken
f.webTokenMu.Unlock()
opts := &rest.Opts{
Method: "GET",
RootURL: linkboxWebAPIURL,
Path: "file/my_file_list/web",
RootURL: linkboxAPIURL,
Path: "file_search",
Parameters: url.Values{
"token": {webToken},
"token": {f.opt.Token},
"name": {name},
"pid": {dirID},
"pageNo": {itoa(pageNumber)},
"pageSize": {itoa64(maxEntitiesPerPage)},
@@ -369,10 +257,7 @@ OUTER:
}
var responseResult fileSearchRes
err = f.pacer.Call(func() (bool, error) {
resp, err := f.srv.CallJSON(ctx, opts, nil, &responseResult)
return f.shouldRetryWeb(ctx, resp, err, &responseResult, opts)
})
err = getUnmarshaledResponse(ctx, f, opts, &responseResult)
if err != nil {
return false, fmt.Errorf("getting files failed: %w", err)
}
@@ -518,7 +403,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
}
// get an entity with leaf from dirID
func getEntity(ctx context.Context, f *Fs, leaf string, directoryID string) (*entity, error) {
func getEntity(ctx context.Context, f *Fs, leaf string, directoryID string, token string) (*entity, error) {
var result *entity
var resultErr = fs.ErrorObjectNotFound
_, err := f.listAll(ctx, directoryID, leaf, func(entity *entity) bool {
@@ -556,7 +441,7 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
return nil, err
}
entity, err := getEntity(ctx, f, leaf, dirID)
entity, err := getEntity(ctx, f, leaf, dirID, f.opt.Token)
if err != nil {
return nil, err
}
@@ -633,7 +518,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
downloadURL := o.fullURL
if downloadURL == "" {
_, name := splitDirAndName(o.Remote())
newObject, err := getEntity(ctx, o.fs, name, itoa64(o.dirID))
newObject, err := getEntity(ctx, o.fs, name, itoa64(o.dirID), o.fs.opt.Token)
if err != nil {
return nil, err
}
@@ -645,10 +530,6 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
downloadURL = newObject.URL
}
if downloadURL == "" {
return nil, fmt.Errorf("no download URL for %q - try re-running `rclone config reconnect`", o.Remote())
}
opts := &rest.Opts{
Method: "GET",
RootURL: downloadURL,
@@ -657,7 +538,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
err := o.fs.pacer.Call(func() (bool, error) {
var err error
res, err = o.fs.cdnSrv.Call(ctx, opts)
res, err = o.fs.srv.Call(ctx, opts)
return o.fs.shouldRetry(ctx, res, err)
})
@@ -816,7 +697,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
var sleepTime = 100 * time.Millisecond
var entity *entity
for try := 1; try <= maxTries; try++ {
entity, err = getEntity(ctx, o.fs, leaf, dirID)
entity, err = getEntity(ctx, o.fs, leaf, dirID, o.fs.opt.Token)
if err == nil {
break
}
+32 -140
View File
@@ -78,13 +78,6 @@ User metadata is stored as extended attributes (which may not be
supported by all file systems) under the "user.*" prefix.
Metadata is supported on files and directories.
When restoring metadata with ` + "`--metadata`" + ` rclone applies the
"mode", "uid" and "gid" from the source. These come from the source
remote which may not be trusted, so restoring metadata as root from an
untrusted source can change file ownership and is not recommended. The
setuid, setgid and sticky bits are not restored by default - see the
` + "`--local-metadata-restore-special-bits`" + ` flag.
`,
},
Options: []fs.Option{
@@ -287,37 +280,6 @@ enabled, rclone will no longer update the modtime after copying a file.`,
Default: false,
Advanced: true,
},
{
Name: "metadata_restore_special_bits",
Help: `Restore the setuid, setgid and sticky bits from metadata.
When restoring metadata with --metadata rclone applies the "mode" from
the source. By default rclone applies only the permission bits and
strips the setuid, setgid and sticky bits.
The "mode" comes from the source remote which may not be trusted.
Restoring a setuid or setgid bit onto freshly written,
source-controlled content can plant a setuid binary, which is dangerous
in particular when restoring from an untrusted source while running as
root. For this reason these bits are not restored by default.
If you trust the source and want the setuid, setgid and sticky bits
restored - for example when restoring a system backup made by rclone -
set this flag.`,
Default: false,
Advanced: true,
},
{
Name: "fatal_if_no_space",
Help: `Make out-of-space errors fatal during transfers.
When enabled, an ENOSPC error during a write returns a fatal error so
that rclone aborts rather than retrying the operation. Useful for
backup scripts that should halt loudly on a full disk rather than spin
retrying.`,
Default: false,
Advanced: true,
},
{
Name: "time_type",
Help: `Set what kind of time is returned.
@@ -374,24 +336,23 @@ only useful for reading.
// Options defines the configuration for this backend
type Options struct {
FollowSymlinks bool `config:"copy_links"`
TranslateSymlinks bool `config:"links"`
SkipSymlinks bool `config:"skip_links"`
SkipSpecials bool `config:"skip_specials"`
UTFNorm bool `config:"unicode_normalization"`
NoCheckUpdated bool `config:"no_check_updated"`
NoUNC bool `config:"nounc"`
OneFileSystem bool `config:"one_file_system"`
CaseSensitive bool `config:"case_sensitive"`
CaseInsensitive bool `config:"case_insensitive"`
NoPreAllocate bool `config:"no_preallocate"`
NoSparse bool `config:"no_sparse"`
NoSetModTime bool `config:"no_set_modtime"`
TimeType timeType `config:"time_type"`
Hashes fs.CommaSepList `config:"hashes"`
Enc encoder.MultiEncoder `config:"encoding"`
NoClone bool `config:"no_clone"`
MetadataRestoreSpecial bool `config:"metadata_restore_special_bits"`
FollowSymlinks bool `config:"copy_links"`
TranslateSymlinks bool `config:"links"`
SkipSymlinks bool `config:"skip_links"`
SkipSpecials bool `config:"skip_specials"`
UTFNorm bool `config:"unicode_normalization"`
NoCheckUpdated bool `config:"no_check_updated"`
NoUNC bool `config:"nounc"`
OneFileSystem bool `config:"one_file_system"`
CaseSensitive bool `config:"case_sensitive"`
CaseInsensitive bool `config:"case_insensitive"`
NoPreAllocate bool `config:"no_preallocate"`
NoSparse bool `config:"no_sparse"`
NoSetModTime bool `config:"no_set_modtime"`
TimeType timeType `config:"time_type"`
Hashes fs.CommaSepList `config:"hashes"`
Enc encoder.MultiEncoder `config:"encoding"`
NoClone bool `config:"no_clone"`
}
// Fs represents a local filesystem rooted at root
@@ -817,7 +778,7 @@ func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, opt
// Mkdir creates the directory if it doesn't exist
func (f *Fs) Mkdir(ctx context.Context, dir string) error {
localPath := f.localPath(dir)
err := f.mkdirAll(localPath)
err := file.MkdirAll(localPath, 0777)
if err != nil {
return err
}
@@ -1434,84 +1395,10 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
return in, nil
}
// osRoot opens an *os.Root anchored at f.root, together with localPath
// expressed relative to it. The caller must Close the returned root.
//
// When translating symlinks (-l/--links) all writes go through an os.Root so a
// symlink planted by a malicious source can never be traversed to escape the
// destination (CWE-59, GHSA-cf44-9pgv-m4xc).
//
// f.root is the trusted destination the user chose, so it is created (and
// followed if it is itself a symlink) before being opened.
func (f *Fs) osRoot(localPath string) (root *os.Root, rel string, err error) {
rel, err = filepath.Rel(f.root, localPath)
if err != nil {
return nil, "", err
}
if err = file.MkdirAll(f.root, 0777); err != nil {
return nil, "", err
}
root, err = os.OpenRoot(f.root)
if err != nil {
return nil, "", err
}
return root, rel, nil
}
// mkdirAll makes localPath and any missing parents. When translating
// symlinks it does so through os.Root so directory creation can't be
// redirected through a planted symlink out of the destination.
func (f *Fs) mkdirAll(localPath string) (err error) {
if !f.opt.TranslateSymlinks {
return file.MkdirAll(localPath, 0777)
}
root, rel, err := f.osRoot(localPath)
if err != nil {
return err
}
defer fs.CheckClose(root, &err)
if rel == "." {
return nil // the root itself, already created by linkRoot
}
return root.MkdirAll(rel, 0777)
}
// openFile opens localPath for writing. When translating symlinks it goes
// through os.Root so a symlink planted at the path, or at any parent, is never
// followed out of the destination. The returned file is independent of the
// root, which is closed before returning.
func (f *Fs) openFile(localPath string, flags int, perm os.FileMode) (fi *os.File, err error) {
if !f.opt.TranslateSymlinks {
return file.OpenFile(localPath, flags, perm)
}
root, rel, err := f.osRoot(localPath)
if err != nil {
return nil, err
}
defer fs.CheckClose(root, &err)
return root.OpenFile(rel, flags, perm)
}
// symlink creates a symlink with the given target at localPath, removing
// any existing file or symlink there first. It goes through os.Root, which
// creates the link verbatim (the target may point anywhere, preserving a
// faithful backup) but refuses to create it through a planted symlink, and
// won't remove a directory in the way.
func (f *Fs) symlink(target, localPath string) (err error) {
root, rel, err := f.osRoot(localPath)
if err != nil {
return err
}
defer fs.CheckClose(root, &err)
if err := root.Remove(rel); err != nil && !os.IsNotExist(err) {
return err
}
return root.Symlink(target, rel)
}
// mkdirAll makes all the directories needed to store the object
func (o *Object) mkdirAll() error {
return o.fs.mkdirAll(filepath.Dir(o.path))
dir := filepath.Dir(o.path)
return file.MkdirAll(dir, 0777)
}
type nopWriterCloser struct {
@@ -1553,13 +1440,13 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// If it is a translated link, just read in the contents, and
// then create a symlink
if !o.translatedLink {
f, err := o.fs.openFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
f, err := file.OpenFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
if runtime.GOOS == "windows" && os.IsPermission(err) {
// If permission denied on Windows might be trying to update a
// hidden file, in which case try opening without CREATE
// See: https://stackoverflow.com/questions/13215716/ioerror-errno-13-permission-denied-when-trying-to-open-hidden-file-in-w-mod
f, err = o.fs.openFile(o.path, os.O_WRONLY|os.O_TRUNC, 0666)
f, err = file.OpenFile(o.path, os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return err
}
@@ -1596,10 +1483,15 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
if o.translatedLink {
if err == nil {
// Use the contents of the copied object to create a symlink,
// without following or creating it through a planted symlink
// (CWE-59). Any existing file or symlink at the path is replaced.
err = o.fs.symlink(symlinkData.String(), o.path)
// Remove any current symlink or file, if one exists
if _, err := os.Lstat(o.path); err == nil {
if removeErr := os.Remove(o.path); removeErr != nil {
fs.Errorf(o, "Failed to remove previous file: %v", removeErr)
return removeErr
}
}
// Use the contents for the copied object to create a symlink
err = os.Symlink(symlinkData.String(), o.path)
}
// only continue if symlink creation succeeded
@@ -1663,7 +1555,7 @@ func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.Wr
return nil, errors.New("can't open a symlink for random writing")
}
out, err := f.openFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
out, err := file.OpenFile(o.path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return nil, err
}
-188
View File
@@ -10,7 +10,6 @@ import (
"path/filepath"
"runtime"
"sort"
"sync"
"testing"
"time"
@@ -205,140 +204,6 @@ func TestSymlinkError(t *testing.T) {
assert.Equal(t, errLinksAndCopyLinks, err)
}
// putLink writes target as a translated link object (name + ".rclonelink") on f.
func putLink(ctx context.Context, f fs.Fs, name, target string) error {
in := bytes.NewBufferString(target)
src := object.NewStaticObjectInfo(name+fs.LinkSuffix, fstest.Time("2001-02-03T04:05:10Z"), int64(len(target)), true, nil, nil)
_, err := f.Put(ctx, in, src)
return err
}
// putFile writes content as a regular object on f.
func putFile(ctx context.Context, f fs.Fs, remote, content string) error {
in := bytes.NewBufferString(content)
src := object.NewStaticObjectInfo(remote, fstest.Time("2001-02-03T04:05:10Z"), int64(len(content)), true, nil, nil)
_, err := f.Put(ctx, in, src)
return err
}
// linksMode puts f into "-l/--links" mode, as if --links or the backend
// links=true option were set.
func linksMode(f *Fs) {
f.opt.FollowSymlinks = false
f.opt.TranslateSymlinks = true
f.lstat = os.Lstat
}
// TestSymlinkEscapeWriteThroughBlocked mirrors the GHSA-cf44-9pgv-m4xc PoC: a
// malicious --links source serves "pwn.rclonelink" whose body is a path outside
// the destination, plus a sibling "pwn/authkeys" that sorts after it and would
// be written through the planted symlink. rclone reproduces the symlink (a
// faithful backup of the source) but must refuse to write through it, so
// nothing lands outside the destination (CWE-59).
func TestSymlinkEscapeWriteThroughBlocked(t *testing.T) {
ctx := context.Background()
// A directory outside the destination the attacker wants to write into
evil := t.TempDir()
evilFile := filepath.Join(evil, "authkeys")
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
linksMode(f)
// The symlink is reproduced faithfully, pointing outside the destination.
require.NoError(t, putLink(ctx, f, "pwn", evil))
link := filepath.Join(f.root, "pwn")
fi, err := os.Lstat(link)
require.NoError(t, err)
require.True(t, fi.Mode()&os.ModeSymlink != 0, "symlink should be reproduced faithfully")
target, err := os.Readlink(link)
require.NoError(t, err)
require.Equal(t, evil, target)
// But writing the sibling object through it must be refused.
err = putFile(ctx, f, "pwn/authkeys", "PWNED")
require.Error(t, err, "writing through a planted symlink should be refused")
// Nothing escaped the destination.
_, err = os.Stat(evilFile)
require.True(t, os.IsNotExist(err), "a file escaped the destination into %q", evilFile)
}
// TestSymlinkEscapeNestedBlocked covers the chained variant: an in-tree symlink
// "evil" -> "." (the destination root) is created, then "evil/pwn" -> outside
// is planted through it, then a write nested under that. Every component is
// re-validated against the root, so the write-through is refused and nothing
// escapes.
func TestSymlinkEscapeNestedBlocked(t *testing.T) {
ctx := context.Background()
evil := t.TempDir()
evilFile := filepath.Join(evil, "authkeys")
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
linksMode(f)
require.NoError(t, putLink(ctx, f, "evil", "."))
require.NoError(t, putLink(ctx, f, "evil/pwn", evil))
err := putFile(ctx, f, "evil/pwn/authkeys", "PWNED")
require.Error(t, err, "writing through a nested planted symlink should be refused")
_, err = os.Stat(evilFile)
require.True(t, os.IsNotExist(err), "a file escaped the destination into %q", evilFile)
}
// TestSymlinkEscapeConcurrent races symlink creation against the sibling write
// for many pairs at once, exercising the time-of-check/time-of-use window.
// os.Root resolves relative to a directory file descriptor, so whatever the
// interleaving nothing may escape the destination.
func TestSymlinkEscapeConcurrent(t *testing.T) {
ctx := context.Background()
evil := t.TempDir()
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
linksMode(f)
const pairs = 50
var wg sync.WaitGroup
for i := range pairs {
name := fmt.Sprintf("pwn%d", i)
wg.Add(2)
go func() { defer wg.Done(); _ = putLink(ctx, f, name, evil) }()
go func() { defer wg.Done(); _ = putFile(ctx, f, name+"/authkeys", "PWNED") }()
}
wg.Wait()
entries, err := os.ReadDir(evil)
require.NoError(t, err)
require.Empty(t, entries, "files escaped the destination into %q", evil)
}
// TestSymlinkInTreeWriteThroughWorks checks the fix doesn't break legitimate
// use: an in-tree symlink to a sibling directory can still be created and
// written through, since that write stays inside the destination.
func TestSymlinkInTreeWriteThroughWorks(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
linksMode(f)
require.NoError(t, putFile(ctx, f, "sub/keep.txt", "hello"))
require.NoError(t, putLink(ctx, f, "link", "sub"))
require.NoError(t, putFile(ctx, f, "link/file.txt", "world"))
// The write landed in the real sibling directory, inside the destination.
got, err := os.ReadFile(filepath.Join(f.root, "sub", "file.txt"))
require.NoError(t, err)
require.Equal(t, "world", string(got))
}
func TestHashWithTypeNone(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
@@ -606,59 +471,6 @@ func testMetadata(t *testing.T, r *fstest.Run, o *Object, when time.Time) {
})
}
// Check that the setuid, setgid and sticky bits from "mode" metadata are
// stripped by default and only restored with --local-metadata-restore-special-bits.
//
// See: https://github.com/rclone/rclone/security/advisories/GHSA-945v-v9p3-v5xw
func TestMetadataSpecialBits(t *testing.T) {
switch runtime.GOOS {
case "windows", "plan9", "js":
t.Skip("mode metadata is not applied on this OS")
}
ctx := context.Background()
r := fstest.NewRun(t)
const filePath = "setuid.bin"
r.WriteFile(filePath, "payload", time.Now())
f := r.Flocal.(*Fs)
obj, err := f.NewObject(ctx, filePath)
require.NoError(t, err)
o := obj.(*Object)
osPath := filepath.Join(f.root, filePath)
statMode := func() os.FileMode {
t.Helper()
fi, err := os.Stat(osPath)
require.NoError(t, err)
return fi.Mode()
}
// "40000755" is Go's os.FileMode layout for setuid|0755 - a value a real
// unix st_mode can never produce, so it can only come from an
// attacker-controlled source remote.
const setuidMode = "40000755"
t.Run("StrippedByDefault", func(t *testing.T) {
require.NoError(t, os.Chmod(osPath, 0644))
require.NoError(t, o.writeMetadataToFile(fs.Metadata{"mode": setuidMode}))
mode := statMode()
assert.Equal(t, os.FileMode(0755), mode.Perm())
assert.Zero(t, mode&(os.ModeSetuid|os.ModeSetgid|os.ModeSticky),
fmt.Sprintf("special bits should be stripped by default, got %v", mode))
})
t.Run("RestoredWithFlag", func(t *testing.T) {
f.opt.MetadataRestoreSpecial = true
defer func() { f.opt.MetadataRestoreSpecial = false }()
require.NoError(t, os.Chmod(osPath, 0644))
require.NoError(t, o.writeMetadataToFile(fs.Metadata{"mode": setuidMode}))
mode := statMode()
assert.Equal(t, os.FileMode(0755), mode.Perm())
assert.NotZero(t, mode&os.ModeSetuid,
fmt.Sprintf("setuid bit should be restored with the flag, got %v", mode))
})
}
func TestFilter(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
+3 -10
View File
@@ -140,22 +140,15 @@ func (o *Object) writeMetadataToFile(m fs.Metadata) (outErr error) {
if mode >= 0 {
umode := uint(mode)
if umode <= math.MaxUint32 {
fileMode := os.FileMode(umode)
// fileMode comes from the source, which may be untrusted, so
// by default apply only the permission bits and strip the
// setuid, setgid and sticky bits.
if !o.fs.opt.MetadataRestoreSpecial {
fileMode = fileMode.Perm()
}
if o.translatedLink {
if haveLChmod {
err = lChmod(o.path, fileMode)
err = lChmod(o.path, os.FileMode(umode))
} else {
fs.Debugf(o, "Unable to set mode %v on a symlink on this OS", fileMode)
fs.Debugf(o, "Unable to set mode %v on a symlink on this OS", os.FileMode(umode))
err = nil
}
} else {
err = os.Chmod(o.path, fileMode)
err = os.Chmod(o.path, os.FileMode(umode))
}
if err != nil {
outErr = fmt.Errorf("failed to change permissions: %w", err)
-4
View File
@@ -81,10 +81,6 @@ func (o *Object) getXattr() (metadata fs.Metadata, err error) {
}
metadata[k] = string(v)
}
// Return nil if all xattrs were filtered out (e.g. com.apple.provenance on macOS)
if len(metadata) == 0 {
return nil, nil
}
return metadata, nil
}
+3 -13
View File
@@ -284,7 +284,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
}
err = srv.LoginWithKeys(opt.SessionID, decodedMasterKey)
if err != nil {
return nil, fmt.Errorf("login with previous auth keys failed: %w", err)
fs.Debugf(f, "login with previous auth keys failed: %v", err)
}
}
}
@@ -770,8 +770,6 @@ func (f *Fs) move(ctx context.Context, dstRemote string, srcFs *Fs, srcRemote st
return fmt.Errorf("server-side move failed to lookup src parent dir: %w", err)
}
waitEvent := f.srv.WaitEventsStart()
// move the object into its new directory if required
if srcDirNode != dstDirNode && srcDirNode.GetHash() != dstDirNode.GetHash() {
//log.Printf("move src %p %q dst %p %q", srcDirNode, srcDirNode.GetName(), dstDirNode, dstDirNode.GetName())
@@ -784,6 +782,8 @@ func (f *Fs) move(ctx context.Context, dstRemote string, srcFs *Fs, srcRemote st
}
}
waitEvent := f.srv.WaitEventsStart()
// rename the object if required
if srcLeaf != dstLeaf {
//log.Printf("rename %q to %q", srcLeaf, dstLeaf)
@@ -1216,8 +1216,6 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
}
}
waitEvent := o.fs.srv.WaitEventsStart()
// Finish the upload
var info *mega.Node
err = o.fs.pacer.Call(func() (bool, error) {
@@ -1237,23 +1235,15 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
o.info = nil
}
// Wait for the server to confirm the new file
o.fs.srv.WaitEvents(waitEvent, eventWaitTime)
return o.setMetaData(info)
}
// Remove an object
func (o *Object) Remove(ctx context.Context) error {
waitEvent := o.fs.srv.WaitEventsStart()
err := o.fs.deleteNode(ctx, o.info)
if err != nil {
return fmt.Errorf("Remove object failed: %w", err)
}
// Wait for the server to confirm the deletion
o.fs.srv.WaitEvents(waitEvent, eventWaitTime)
return nil
}
-54
View File
@@ -1,54 +0,0 @@
package mega
import (
"bytes"
"context"
"testing"
"time"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest/fstests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// InternalTestGhostAfterRemove checks that a file removed in a long-running
// process disappears from listings straight away rather than lingering as a
// ghost until go-mega's next event poll reconciles the in-memory tree.
//
// It puts, removes and lists in a tight loop to make any lingering entry
// show up reliably, exercising whichever delete mode the remote is
// configured with (hard_delete or the default trash).
func (f *Fs) InternalTestGhostAfterRemove(t *testing.T) {
ctx := context.Background()
dir := "ghost-test"
require.NoError(t, f.Mkdir(ctx, dir))
defer func() { _ = f.Rmdir(ctx, dir) }()
contents := []byte("ghost test contents")
for i := range 10 {
remote := dir + "/test.txt"
src := object.NewStaticObjectInfo(remote, time.Now(), int64(len(contents)), true, nil, nil)
obj, err := f.Put(ctx, bytes.NewReader(contents), src)
require.NoError(t, err)
require.NoError(t, obj.Remove(ctx))
// The file must be gone from the listing straight away - if the
// in-memory tree isn't settled it lingers as a ghost.
entries, err := f.List(ctx, dir)
require.NoError(t, err)
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Remote())
}
assert.NotContains(t, names, remote, "file should be gone immediately after remove (iteration %d)", i)
}
}
// InternalTest dispatches the backend specific internal tests
func (f *Fs) InternalTest(t *testing.T) {
t.Run("GhostAfterRemove", f.InternalTestGhostAfterRemove)
}
var _ fstests.InternalTester = (*Fs)(nil)
-57
View File
@@ -238,10 +238,6 @@ func shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, err
// Check if it is an api.Error
if apiErr, ok := err.(*api.Error); ok {
// Handle error 1101 specifically - don't retry as it's a permanent API restriction
if apiErr.Result == 1101 {
return false, err
}
// See https://docs.pcloud.com/errors/ for error treatment
// Errors are classified as 1xxx, 2xxx, etc.
switch apiErr.Result / 1000 {
@@ -535,63 +531,10 @@ func fileIDtoNumber(fileID string) string {
// Should return true to finish processing
type listAllFn func(*api.Item) bool
// listAllRootRecursive handles recursive listing for root directory (folderid=0)
// using a two-step approach to work around pCloud API limitation
func (f *Fs) listAllRootRecursive(ctx context.Context, dirID string, directoriesOnly bool, filesOnly bool, fn listAllFn) (found bool, err error) {
// List root directory non-recursively to get immediate contents
var rootSubdirs []*api.Item
found, err = f.listAll(ctx, dirID, false, false, false, func(item *api.Item) bool {
if item.IsFolder {
// Store subdirectories for recursive list later
rootSubdirs = append(rootSubdirs, item)
// Handle directories immediately if not filesOnly
if !filesOnly {
if fn(item) {
return true // stop iteration
}
}
} else if !directoriesOnly {
// Handle files immediately if not directoriesOnly
if fn(item) {
return true // stop iteration
}
}
return false // continue iteration
})
if err != nil || found {
return found, err
}
// Recursively list each subdirectory
for _, subdir := range rootSubdirs {
subdirName := f.opt.Enc.ToStandardName(subdir.Name)
found, err = f.listAll(ctx, subdir.ID, directoriesOnly, filesOnly, true, func(item *api.Item) bool {
// Prepend the subdirectory name to create correct relative path
origItemName := item.Name
item.Name = subdirName + "/" + item.Name
result := fn(item)
item.Name = origItemName
return result
})
if err != nil || found {
return found, err
}
}
return found, nil
}
// Lists the directory required calling the user function on each item found
//
// If the user fn ever returns true then it early exits with found = true
func (f *Fs) listAll(ctx context.Context, dirID string, directoriesOnly bool, filesOnly bool, recursive bool, fn listAllFn) (found bool, err error) {
// Special case: root directory with recursive listing
// pCloud API rejects folderid=0 with recursive=1 (error 1101)
// See: https://github.com/rclone/rclone/issues/9315
if recursive && dirIDtoNumber(dirID) == "0" {
return f.listAllRootRecursive(ctx, dirID, directoriesOnly, filesOnly, fn)
}
opts := rest.Opts{
Method: "GET",
Path: "/listfolder",
+6 -121
View File
@@ -7,11 +7,9 @@ import (
"fmt"
"io"
"path"
"regexp"
"strings"
"time"
"github.com/coreos/go-semver/semver"
protonDriveAPI "github.com/rclone/Proton-API-Bridge"
"github.com/rclone/go-proton-api"
@@ -22,7 +20,6 @@ import (
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/rclone/rclone/fs/fshttp"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/encoder"
@@ -52,7 +49,6 @@ const (
var (
errCanNotUploadFileWithUnknownSize = errors.New("proton Drive can't upload files with unknown size")
errCanNotPurgeRootDirectory = errors.New("can't purge root directory")
protonDriveInvalidVersionChars = regexp.MustCompile(`[^0-9A-Za-z.+-]+`)
// for the auth/deauth handler
_mapper configmap.Mapper
@@ -155,12 +151,11 @@ size, will fail to operate properly`,
Name: "app_version",
Help: `The app version string
The app version string identifies the client that is currently performing
the API request. Third-party Proton Drive integrations should use the form
external-drive-<project>@<version>. If this option is left empty, rclone
derives a compliant value from its own version. This value is sent with
every API request; the option itself is optional.`,
The app version string indicates the client that is currently performing
the API request. This information is required and will be sent with every
API request.`,
Advanced: true,
Default: "macos-drive@1.0.0-alpha.1+rclone",
}, {
Name: "replace_existing_draft",
Help: `Create a new revision when filename conflict is detected
@@ -333,121 +328,11 @@ func deAuthHandler() {
clearConfigMap(_mapper)
}
func protonDriveAppVersionFromRcloneVersion(version string) string {
const fallback = "external-drive-rclone@1.0.0-stable"
version = strings.TrimSpace(strings.TrimPrefix(version, "v"))
version = protonDriveInvalidVersionChars.ReplaceAllString(version, "-")
if version == "" {
return fallback
}
parsedVersion, err := semver.NewVersion(version)
if err != nil {
return fallback
}
appVersion := fmt.Sprintf(
"external-drive-rclone@%d.%d.%d",
parsedVersion.Major,
parsedVersion.Minor,
parsedVersion.Patch,
)
metadataParts := protonDriveMetadataParts(parsedVersion.Metadata)
preRelease := strings.ToLower(string(parsedVersion.PreRelease))
switch {
case preRelease == "":
return protonDriveJoinAppVersion(appVersion, "-stable", metadataParts)
case preRelease == "dev":
return protonDriveJoinAppVersion(appVersion, "-dev", metadataParts)
case preRelease == "beta" || strings.HasPrefix(preRelease, "beta."):
betaSuffix, betaMetadataParts := protonDriveBetaSuffixAndMetadata(preRelease)
return protonDriveJoinAppVersion(appVersion, betaSuffix, append(betaMetadataParts, metadataParts...))
default:
return fallback
}
}
func protonDriveMetadataParts(metadata string) []string {
if metadata == "" {
return nil
}
parts := strings.Split(metadata, ".")
out := make([]string, 0, len(parts))
for _, part := range parts {
if part != "" {
out = append(out, part)
}
}
return out
}
func protonDriveBetaSuffixAndMetadata(preRelease string) (suffix string, metadata []string) {
suffix = "-beta"
remainder := strings.TrimPrefix(strings.TrimPrefix(preRelease, "beta"), ".")
if remainder == "" {
return suffix, nil
}
parts := protonDriveMetadataParts(remainder)
i := 0
for i < len(parts) && isDecimalString(parts[i]) {
suffix += "." + parts[i]
i++
}
return suffix, parts[i:]
}
func protonDriveJoinAppVersion(appVersion, suffix string, metadata []string) string {
version := appVersion + suffix
if len(metadata) != 0 {
version += "+" + strings.Join(metadata, ".")
}
return version
}
func isDecimalString(value string) bool {
if value == "" {
return false
}
for _, r := range value {
if r < '0' || r > '9' {
return false
}
}
return true
}
// protonLogger adapts rclone's fs.Debugf/Logf/Errorf into the
// resty.Logger / common.Logger shape expected by Proton-API-Bridge and
// go-proton-api so that library output participates in -v / -vv levels
// and is captured by --log-file.
type protonLogger struct{ f *Fs }
func (l protonLogger) Errorf(format string, v ...interface{}) { fs.Errorf(l.f, format, v...) }
func (l protonLogger) Warnf(format string, v ...interface{}) { fs.Logf(l.f, format, v...) }
func (l protonLogger) Debugf(format string, v ...interface{}) { fs.Debugf(l.f, format, v...) }
func newProtonDrive(ctx context.Context, f *Fs, opt *Options, m configmap.Mapper) (*protonDriveAPI.ProtonDrive, error) {
config := protonDriveAPI.NewDefaultConfig()
config.AppVersion = opt.AppVersion
if config.AppVersion == "" {
config.AppVersion = protonDriveAppVersionFromRcloneVersion(fs.Version)
}
config.UserAgent = f.ci.UserAgent // opt.UserAgent
// Route HTTP through rclone's transport so global flags such as
// --dump headers, --no-check-certificate, --user-agent, --bind,
// --ca-cert and --header all take effect against Proton Drive.
config.Transport = fshttp.NewTransport(ctx)
// Route bridge and go-proton-api log output through rclone's
// logging system so it honours -v / -vv and --log-file.
config.Logger = protonLogger{f: f}
config.ReplaceExistingDraft = opt.ReplaceExistingDraft
config.EnableCaching = opt.EnableCaching
@@ -969,7 +854,7 @@ func (o *Object) Hash(ctx context.Context, t hash.Type) (string, error) {
}
if o.digests != nil {
return strings.ToLower(*o.digests), nil
return *o.digests, nil
}
// sha1 not cached: we fetch and try to obtain the sha1 of the link
@@ -1019,7 +904,7 @@ func (o *Object) Storable() bool {
// Open opens the file for read. Call Close() on the returned io.ReadCloser
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadCloser, error) {
fs.FixRangeOption(options, o.Size())
fs.FixRangeOption(options, *o.originalSize)
var offset, limit int64 = 0, -1
for _, option := range options { // if the caller passes in nil for options, it will become array of nil
switch x := option.(type) {
@@ -1,55 +0,0 @@
package protondrive
import (
"regexp"
"testing"
)
var protonDriveAppVersionPattern = regexp.MustCompile(`(?i)^external-drive(-[a-z_]+)+@[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?-((stable|beta|RC|alpha)(([.-]?\d+)*)?)?([.-]?dev)?(\+.*)?$`)
func TestProtonDriveAppVersionFromRcloneVersion(t *testing.T) {
testCases := []struct {
name string
rcloneVersion string
want string
}{
{
name: "release",
rcloneVersion: "v1.73.5",
want: "external-drive-rclone@1.73.5-stable",
},
{
name: "dev build",
rcloneVersion: "v1.74.0-DEV",
want: "external-drive-rclone@1.74.0-dev",
},
{
name: "beta build with extra metadata",
rcloneVersion: "v1.74.0-beta.9519.990f33f2a.fix-protondrive-sdk-2026",
want: "external-drive-rclone@1.74.0-beta.9519+990f33f2a.fix-protondrive-sdk-2026",
},
{
name: "beta build with unsanitized branch name",
rcloneVersion: "v1.74.0-beta.9519.990f33f2a.fix/protondrive-sdk-2026",
want: "external-drive-rclone@1.74.0-beta.9519+990f33f2a.fix-protondrive-sdk-2026",
},
{
name: "invalid version falls back to stable",
rcloneVersion: "not-a-version",
want: "external-drive-rclone@1.0.0-stable",
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
got := protonDriveAppVersionFromRcloneVersion(testCase.rcloneVersion)
if got != testCase.want {
t.Fatalf("unexpected app version: got %q, want %q", got, testCase.want)
}
if !protonDriveAppVersionPattern.MatchString(got) {
t.Fatalf("app version %q does not match Proton pattern", got)
}
})
}
}
-1
View File
@@ -18,4 +18,3 @@ quirks:
list_version: 1
force_path_style: true
list_url_encode: false
use_already_exists: false
-6
View File
@@ -4,26 +4,20 @@ region:
au-east-1: AU East 1
eu-central: EU Central
eu-south-1: EU South 1
eu-west-1: EU West 1
jp-central-1: JP Central 1
uk-east-1: UK East 1
us-central-1: US Central 1
us-east: US East
us-east-1: US East 1
us-west: US West
us-west-1: US West 1
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
eu-west-1.object.fastlystorage.app: EU West 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-east-1.object.fastlystorage.app: US East 1
us-west.object.fastlystorage.app: US West
us-west-1.object.fastlystorage.app: US West 1
quirks:
force_path_style: true
use_already_exists: false
-18
View File
@@ -1,18 +0,0 @@
name: HCP
description: Hitachi Content Platform (HCP)
region: {}
endpoint: {}
location_constraint: {}
acl: {}
bucket_acl: true
quirks:
force_path_style: true
list_url_encode: true
# HCP returns a SHA256-based ETag for multipart uploads instead of the
# standard MD5-based ETag, so ETag verification after multipart upload
# must be disabled:
use_multipart_etag: false
# HCP returns object versions oldest first (ascending chronological order)
# instead of the S3 standard newest first:
# https://docs.hitachivantara.com/r/en-us/content-platform/9.6.x/mk-95hcph002/using-the-hitachi-api-for-amazon-s3/working-with-buckets/listing-bucket-contents-version-2
list_versions_oldest_first: true
-21
View File
@@ -1,21 +0,0 @@
name: ImpossibleCloud
description: Impossible Cloud Object Storage
region:
eu-central-2: Frankfurt, Germany
eu-west-1: Amsterdam, Netherlands
eu-west-2: London, UK
eu-west-3: Paris, France
eu-east-1: Poznań, Poland
eu-north-1: Copenhagen, Denmark
us-east-1: New York, USA
endpoint:
eu-central-2.storage.impossibleapi.net: Frankfurt, Germany
eu-west-1.storage.impossibleapi.net: Amsterdam, Netherlands
eu-west-2.storage.impossibleapi.net: London, UK
eu-west-3.storage.impossibleapi.net: Paris, France
eu-east-1.storage.impossibleapi.net: Poznań, Poland
eu-north-1.storage.impossibleapi.net: Copenhagen, Denmark
us-east-1.storage.impossibleapi.net: New York, USA
location_constraint: {}
acl: {}
bucket_acl: true
+4 -11
View File
@@ -1,17 +1,10 @@
name: Mega
description: MEGA S4 Object Storage
endpoint:
s3.eu-amsterdam.megas4.com: Mega S4 Amsterdam
s3.eu-luxembourg.megas4.com: Mega S4 Luxembourg
s3.eu-paris.megas4.com: Mega S4 Paris
s3.eu-barcelona.megas4.com: Mega S4 Barcelona
s3.ca-montreal.megas4.com: Mega S4 Montreal
s3.ca-vancouver.megas4.com: Mega S4 Vancouver
s3.ap-tokyo.megas4.com: Mega S4 Tokyo
s3.eu-central-1.s4.mega.io: Mega S4 eu-central-1 (Amsterdam, legacy)
s3.eu-central-2.s4.mega.io: Mega S4 eu-central-2 (Bettembourg, legacy)
s3.ca-central-1.s4.mega.io: Mega S4 ca-central-1 (Montreal, legacy)
s3.ca-west-1.s4.mega.io: Mega S4 ca-west-1 (Vancouver, legacy)
s3.eu-central-1.s4.mega.io: Mega S4 eu-central-1 (Amsterdam)
s3.eu-central-2.s4.mega.io: Mega S4 eu-central-2 (Bettembourg)
s3.ca-central-1.s4.mega.io: Mega S4 ca-central-1 (Montreal)
s3.ca-west-1.s4.mega.io: Mega S4 ca-west-1 (Vancouver)
bucket_acl: true
quirks:
list_version: 2
-1
View File
@@ -30,7 +30,6 @@ type Quirks struct {
MightGzip *bool `yaml:"might_gzip,omitempty"`
UseMultipartUploads *bool `yaml:"use_multipart_uploads,omitempty"`
UseUnsignedPayload *bool `yaml:"use_unsigned_payload,omitempty"`
ListVersionsOldestFirst *bool `yaml:"list_versions_oldest_first,omitempty"`
UseXID *bool `yaml:"use_x_id,omitempty"`
SignAcceptEncoding *bool `yaml:"sign_accept_encoding,omitempty"`
EtagIsNotMD5 *bool `yaml:"etag_is_not_md5,omitempty"`
+15 -108
View File
@@ -286,7 +286,7 @@ large file of a known size to stay below this number of chunks limit.
Any files larger than this that need to be server-side copied will be
copied in chunks of this size.
The minimum is 1 byte and the maximum is 5 GiB.`,
The minimum is 0 and the maximum is 5 GiB.`,
Default: fs.SizeSuffix(maxSizeForCopy),
Advanced: true,
}, {
@@ -371,7 +371,7 @@ this may help to speed up the transfers.`,
If this is true (the default) then rclone will use path style access,
if false then rclone will use virtual path style. See [the AWS S3
docs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html)
docs](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro)
for more info.
Some providers (e.g. AWS, Aliyun OSS, Netease COS, or Tencent COS) require this set to
@@ -742,21 +742,6 @@ knows about - please make a bug report if not.
You can change this if you want to disable the use of multipart uploads.
This shouldn't be necessary in normal operation.
This should be automatically set correctly for all providers rclone
knows about - please make a bug report if not.
`,
Default: fs.Tristate{},
Advanced: true,
}, {
Name: "list_versions_oldest_first",
Help: `Set if the backend returns object versions oldest first.
The S3 standard returns object versions newest first. Some backends
(e.g. Hitachi HCP) return them oldest first instead.
Set this quirk if --s3-version-at or --s3-versions produce incorrect
results with your backend.
This should be automatically set correctly for all providers rclone
knows about - please make a bug report if not.
`,
@@ -1140,7 +1125,6 @@ type Options struct {
IBMAPIKey string `config:"ibm_api_key"`
IBMInstanceID string `config:"ibm_resource_instance_id"`
IBMIAMEndpoint string `config:"ibm_iam_endpoint"`
ListVersionsOldestFirst fs.Tristate `config:"list_versions_oldest_first"`
UseXID fs.Tristate `config:"use_x_id"`
SignAcceptEncoding fs.Tristate `config:"sign_accept_encoding"`
ObjectLockMode string `config:"object_lock_mode"`
@@ -1351,34 +1335,10 @@ func getClient(ctx context.Context, opt *Options) *http.Client {
}
})
return &http.Client{
Transport: t,
CheckRedirect: s3CheckRedirect,
Transport: t,
}
}
func s3CheckRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
if s3RedirectCrossesHost(req, via) {
req.Header.Del("X-Amz-Security-Token")
}
return nil
}
func s3RedirectCrossesHost(req *http.Request, via []*http.Request) bool {
if len(via) == 0 {
return false
}
scheme, host := via[0].URL.Scheme, via[0].URL.Host
for _, redirect := range via[1:] {
if redirect.URL.Host != host || redirect.URL.Scheme != scheme {
return true
}
}
return host != req.URL.Host || scheme != req.URL.Scheme
}
// Fixup the request if needed.
//
// Google Cloud Storage alters the Accept-Encoding header, which
@@ -1546,10 +1506,8 @@ func s3Connection(ctx context.Context, opt *Options, client *http.Client) (s3Cli
}
}
// Create AssumeRole credentials provider, wrapped in a
// CredentialsCache so we don't call AssumeRole on every
// request.
awsConfig.Credentials = aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(stsClient, opt.RoleARN, assumeRoleOptions))
// Create AssumeRole credentials provider
awsConfig.Credentials = stscreds.NewAssumeRoleProvider(stsClient, opt.RoleARN, assumeRoleOptions)
}
provider = loadProvider(opt.Provider)
@@ -1783,7 +1741,6 @@ func setQuirks(opt *Options, provider *Provider) {
set(&opt.UseXID, true, provider.Quirks.UseXID)
set(&opt.SignAcceptEncoding, true, provider.Quirks.SignAcceptEncoding)
set(&opt.ObjectLockSupported, true, provider.Quirks.ObjectLockSupported)
set(&opt.ListVersionsOldestFirst, false, provider.Quirks.ListVersionsOldestFirst)
}
// setRoot changes the root of the Fs
@@ -1904,10 +1861,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if opt.Provider == "Rabata" {
f.features.Copy = nil
}
if opt.Provider == "TencentCOS" && strings.Contains(opt.Endpoint, "cos.accelerate.myqcloud.com") {
// Global Acceleration endpoint does not support bucket creation.
f.opt.NoCheckBucket = true
}
if opt.DirectoryMarkers {
f.features.CanHaveEmptyDirectories = true
}
@@ -1923,52 +1876,20 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
newRoot, leaf := path.Split(oldRoot)
f.setRoot(newRoot)
_, err := f.NewObject(ctx, leaf)
switch {
case err == nil:
// It is a file so return an fs which points to the parent
return f, fs.ErrorIsFile
case errors.Is(err, fs.ErrorObjectNotFound):
if errors.Is(err, fs.ErrorObjectNotFound) {
// File doesn't exist or is a directory so return old f
f.setRoot(oldRoot)
return f, nil
default:
// We couldn't HEAD the object so now attempt to list it
hasChildren, listErr := f.hasChildren(ctx, leaf)
if listErr != nil {
fs.Debugf(f, "Couldn't check %q for children after HEAD failed (%v): %v", oldRoot, err, listErr)
}
// If it listed and has children it must be a directory
if hasChildren {
f.setRoot(oldRoot)
return f, nil
}
// If it has no children it is either a file or an empty directory. We can't
// tell these two cases apart. We choose file which is more likely, and
// return an fs which points to the parent.
return f, fs.ErrorIsFile
}
if err != nil {
return nil, err
}
// return an error with an fs which points to the parent
return f, fs.ErrorIsFile
}
return f, nil
}
// hasChildren reports whether the directory dir contains any objects.
func (f *Fs) hasChildren(ctx context.Context, dir string) (found bool, err error) {
bucket, directory := f.split(dir)
err = f.list(ctx, listOpt{
bucket: bucket,
directory: directory,
prefix: f.rootDirectory,
recurse: true,
}, func(remote string, object *types.Object, versionID *string, isDirectory bool) error {
found = true
return errEndList // stop after the first object
})
if err != nil && err != fs.ErrorDirNotFound {
return false, err
}
return found, nil
}
// getMetaDataListing gets the metadata from the object unconditionally from the listing
//
// This is needed to find versioned objects from their paths.
@@ -2333,13 +2254,6 @@ func (ls *versionsList) List(ctx context.Context) (resp *s3.ListObjectsV2Output,
//structs.SetFrom(resp, respVersions)
setFrom_s3ListObjectsV2Output_s3ListObjectVersionsOutput(resp, respVersions)
// Some backends (e.g. Hitachi HCP) return versions oldest first instead
// of newest first. Reverse both lists so mergeDeleteMarkers works correctly.
if ls.f.opt.ListVersionsOldestFirst.Value {
slices.Reverse(respVersions.Versions)
slices.Reverse(respVersions.DeleteMarkers)
}
// Merge in delete Markers as types.ObjectVersion if we need them
if ls.hidden || ls.usingVersionAt {
respVersions.Versions = mergeDeleteMarkers(respVersions.Versions, respVersions.DeleteMarkers)
@@ -2425,11 +2339,9 @@ func (f *Fs) list(ctx context.Context, opt listOpt, fn listFn) error {
opt.directory += "/"
}
}
// Use nil delimiter for recursive listings to omit the parameter
// entirely. Some S3-compatible servers reject an empty delimiter.
var delimiter *string
delimiter := ""
if !opt.recurse {
delimiter = aws.String("/")
delimiter = "/"
}
// URL encode the listings so we can use control characters in object names
// See: https://github.com/aws/aws-sdk-go/issues/1914
@@ -2449,7 +2361,7 @@ func (f *Fs) list(ctx context.Context, opt listOpt, fn listFn) error {
urlEncodeListings := f.opt.ListURLEncode.Value
req := s3.ListObjectsV2Input{
Bucket: &opt.bucket,
Delimiter: delimiter,
Delimiter: &delimiter,
Prefix: &opt.directory,
MaxKeys: &f.opt.ListChunk,
}
@@ -3871,9 +3783,7 @@ func (f *Fs) purge(ctx context.Context, dir string, oldOnly bool) error {
if bucket == "" {
return errors.New("can't purge from root")
}
// If the user explicitly set --s3-versions, trust that the bucket is
// versioned even if GetBucketVersioning fails (e.g. missing permission).
versioned := f.opt.Versions || f.isVersioned(ctx)
versioned := f.isVersioned(ctx)
if !versioned && oldOnly {
fs.Infof(f, "bucket is not versioned so not removing old versions")
return nil
@@ -4393,9 +4303,6 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
}
}
if err != nil {
if statusCode := getHTTPStatusCode(err); statusCode == http.StatusNotFound || statusCode == http.StatusMethodNotAllowed {
return nil, fs.ErrorObjectNotFound
}
return nil, err
}
-33
View File
@@ -44,13 +44,6 @@ func md5sum(t *testing.T, s string) string {
}
func (f *Fs) InternalTestMetadata(t *testing.T) {
// Impossible Cloud silently drops cache-control,
// content-disposition, content-encoding and content-language
// system metadata on retrieval (and thus also breaks the
// Content-Encoding response header that --s3-decompress relies on).
if f.opt.Provider == "ImpossibleCloud" {
t.Skip("Impossible Cloud does not preserve all S3 system metadata")
}
ctx := context.Background()
original := random.String(1000)
contents := gz(t, original)
@@ -144,31 +137,6 @@ func (f *Fs) InternalTestNoHead(t *testing.T) {
}
func (f *Fs) InternalTestHasChildren(t *testing.T) {
ctx := context.Background()
contents := random.String(100)
item := fstest.NewItem("has-children/file.txt", contents, fstest.Time("2001-05-06T04:05:06.499999999Z"))
obj := fstests.PutTestContents(ctx, t, f, &item, contents, true)
defer func() {
assert.NoError(t, obj.Remove(ctx))
}()
// A prefix with an object under it is a directory
found, err := f.hasChildren(ctx, "has-children")
require.NoError(t, err)
assert.True(t, found, "prefix with an object should report children")
// The object itself is a file so has no children
found, err = f.hasChildren(ctx, "has-children/file.txt")
require.NoError(t, err)
assert.False(t, found, "a file should not report children")
// A path which doesn't exist has no children
found, err = f.hasChildren(ctx, "has-children/does-not-exist")
require.NoError(t, err)
assert.False(t, found, "a missing path should not report children")
}
func TestVersionLess(t *testing.T) {
key1 := "key1"
key2 := "key2"
@@ -810,7 +778,6 @@ func (f *Fs) InternalTestObjectLock(t *testing.T) {
func (f *Fs) InternalTest(t *testing.T) {
t.Run("Metadata", f.InternalTestMetadata)
t.Run("NoHead", f.InternalTestNoHead)
t.Run("HasChildren", f.InternalTestHasChildren)
t.Run("Versions", f.InternalTestVersions)
t.Run("ObjectLock", f.InternalTestObjectLock)
}
-208
View File
@@ -4,7 +4,6 @@ package s3
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
@@ -12,8 +11,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/bucket"
"github.com/rclone/rclone/lib/pacer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -25,211 +22,6 @@ func SetupS3Test(t *testing.T) (context.Context, *Options, *http.Client) {
return ctx, opt, client
}
func TestClientRemovesSecurityTokenOnCrossHostRedirect(t *testing.T) {
ctx, _, client := SetupS3Test(t)
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Empty(t, r.Header.Get("X-Amz-Security-Token"))
assert.Equal(t, "date", r.Header.Get("X-Amz-Date"))
w.WriteHeader(http.StatusOK)
}))
defer redirectServer.Close()
initialServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "token", r.Header.Get("X-Amz-Security-Token"))
http.Redirect(w, r, redirectServer.URL, http.StatusTemporaryRedirect)
}))
defer initialServer.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, initialServer.URL, nil)
require.NoError(t, err)
req.Header.Set("X-Amz-Security-Token", "token")
req.Header.Set("X-Amz-Date", "date")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestClientDoesNotRestoreSecurityTokenAfterCrossHostRedirect(t *testing.T) {
ctx, _, client := SetupS3Test(t)
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/middle":
assert.Empty(t, r.Header.Get("X-Amz-Security-Token"))
assert.Equal(t, "date", r.Header.Get("X-Amz-Date"))
http.Redirect(w, r, "/final", http.StatusTemporaryRedirect)
case "/final":
assert.Empty(t, r.Header.Get("X-Amz-Security-Token"))
assert.Equal(t, "date", r.Header.Get("X-Amz-Date"))
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}))
defer redirectServer.Close()
initialServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "token", r.Header.Get("X-Amz-Security-Token"))
http.Redirect(w, r, redirectServer.URL+"/middle", http.StatusTemporaryRedirect)
}))
defer initialServer.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, initialServer.URL, nil)
require.NoError(t, err)
req.Header.Set("X-Amz-Security-Token", "token")
req.Header.Set("X-Amz-Date", "date")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestClientKeepsSecurityTokenOnSameHostRedirect(t *testing.T) {
ctx, _, client := SetupS3Test(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
assert.Equal(t, "token", r.Header.Get("X-Amz-Security-Token"))
http.Redirect(w, r, "/redirected", http.StatusTemporaryRedirect)
case "/redirected":
assert.Equal(t, "token", r.Header.Get("X-Amz-Security-Token"))
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
require.NoError(t, err)
req.Header.Set("X-Amz-Security-Token", "token")
resp, err := client.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestRedirectCrossesHost(t *testing.T) {
mustReq := func(method, url string) *http.Request {
req, err := http.NewRequest(method, url, nil)
require.NoError(t, err)
return req
}
for _, test := range []struct {
name string
via []string
req string
want bool
}{
{
name: "SameHost",
via: []string{"https://bucket.example.com/"},
req: "https://bucket.example.com/redirected",
want: false,
},
{
name: "DifferentHost",
via: []string{"https://bucket.example.com/"},
req: "https://evil.example.com/redirected",
want: true,
},
{
name: "SchemeDowngradeSameHost",
via: []string{"https://bucket.example.com/"},
req: "http://bucket.example.com/redirected",
want: true,
},
{
name: "SchemeDowngradeMidChain",
via: []string{"https://bucket.example.com/", "http://bucket.example.com/middle"},
req: "http://bucket.example.com/final",
want: true,
},
} {
t.Run(test.name, func(t *testing.T) {
via := make([]*http.Request, len(test.via))
for i, url := range test.via {
via[i] = mustReq(http.MethodGet, url)
}
got := s3RedirectCrossesHost(mustReq(http.MethodGet, test.req), via)
assert.Equal(t, test.want, got)
})
}
}
func TestClientStopsAfterTenRedirects(t *testing.T) {
_, _, client := SetupS3Test(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
}))
defer server.Close()
resp, err := client.Get(server.URL)
if resp != nil {
_ = resp.Body.Close()
}
require.Error(t, err)
assert.Contains(t, err.Error(), "stopped after 10 redirects")
}
func TestObjectNotFoundMapping(t *testing.T) {
ctx, opt, client := SetupS3Test(t)
gotHead, gotGet := false, false
// Return 404 for all requests.
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodHead:
gotHead = true
case http.MethodGet:
gotGet = true
}
w.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
opt.Endpoint = server.URL
opt.ForcePathStyle = true
opt.Region = "us-east-1"
opt.AccessKeyID = "id"
opt.SecretAccessKey = "secret"
c, _, err := s3Connection(ctx, opt, client)
require.NoError(t, err)
f := &Fs{
name: "s3test",
opt: *opt,
ctx: ctx,
c: c,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep))),
cache: bucket.NewCache(),
}
f.setRoot("bucket")
// HEAD path: NewObject reads metadata via HeadObject.
_, headErr := f.NewObject(ctx, "missing.txt")
require.True(t, gotHead, "server should have received a HEAD request")
assert.ErrorIs(t, headErr, fs.ErrorObjectNotFound)
// GET path: Object.Open issues a GetObject.
o := &Object{fs: f, remote: "missing.txt"}
in, getErr := o.Open(ctx)
if in != nil {
_ = in.Close()
}
require.True(t, gotGet, "server should have received a GET request")
assert.ErrorIs(t, getErr, fs.ErrorObjectNotFound)
assert.Equal(t, headErr, getErr, "HeadObject and GetObject should map a 404 to the same error")
}
// TestIntegration runs integration tests against the remote
func TestIntegration(t *testing.T) {
opt := &fstests.Opt{
+5 -12
View File
@@ -928,10 +928,11 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
// Set up sshConfig here from opt
// **NB** everything else should be setup in NewFsWithConnection
sshConfig := &ssh.ClientConfig{
User: opt.User,
Auth: []ssh.AuthMethod{},
Timeout: time.Duration(f.ci.ConnectTimeout),
ClientVersion: "SSH-2.0-" + f.ci.UserAgent,
User: opt.User,
Auth: []ssh.AuthMethod{},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: time.Duration(f.ci.ConnectTimeout),
ClientVersion: "SSH-2.0-" + f.ci.UserAgent,
}
if len(opt.HostKeyAlgorithms) != 0 {
@@ -944,14 +945,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
return nil, fmt.Errorf("couldn't parse known_hosts_file: %w", err)
}
sshConfig.HostKeyCallback = hostcallback
} else {
// Set insecure HostKeyCallback if no known_hosts_file is
// configured. Rclone has no mechanism to manage
// known_hosts files so we can't enable host key
// validation by default. Users can enable it by setting
// known_hosts_file. See: https://rclone.org/sftp/#host-key-validation
sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
fs.Logf(name, "No host key validation is being performed. Set known_hosts_file to enable it. See: https://rclone.org/sftp/#host-key-validation")
}
if opt.UseInsecureCipher && (opt.Ciphers != nil || opt.KeyExchange != nil) {
+11 -9
View File
@@ -98,19 +98,21 @@ func (p *Prop) Code() int {
return code
}
// Parse a status of the form "HTTP/1.1 2xx"
var parseStatus2XX = regexp.MustCompile(`^HTTP/[\d.]+\s+2\d{2}`)
// StatusOK returns true if there is at least one 2XX response.
// StatusOK examines the Status and returns an OK flag
func (p *Prop) StatusOK() bool {
// Fetch status code as int
c := p.Code()
// Assume OK if no statuses received
if len(p.Status) == 0 {
if c == -1 {
return true
}
for _, statusStr := range p.Status {
if parseStatus2XX.MatchString(statusStr) {
return true
}
if c == 0 {
return false
}
if c >= 200 && c < 300 {
return true
}
return false
}
-29
View File
@@ -1,29 +0,0 @@
package api
import (
"testing"
)
func TestPropStatusOK(t *testing.T) {
tests := []struct {
name string
status []string
want bool
}{
{"Empty status", []string{}, true},
{"Single 200 OK", []string{"HTTP/1.1 200 OK"}, true},
{"Single 404 Not Found", []string{"HTTP/1.1 404 Not Found"}, false},
{"Mixed status with 404 first", []string{"HTTP/1.1 404 Not Found", "HTTP/1.1 200 OK"}, true},
{"Mixed status with 200 first", []string{"HTTP/1.1 200 OK", "HTTP/1.1 404 Not Found"}, true},
{"Multiple non-2xx statuses", []string{"HTTP/1.1 404 Not Found", "HTTP/1.1 403 Forbidden"}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := &Prop{Status: tt.status}
if got := p.StatusOK(); got != tt.want {
t.Errorf("Prop.StatusOK() = %v, want %v", got, tt.want)
}
})
}
}
+11 -5
View File
@@ -341,13 +341,13 @@ func itemIsDir(item *api.Response) bool {
}
// readMetaDataForPath reads the metadata from the path
func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Prop, err error) {
func (f *Fs) readMetaDataForPath(ctx context.Context, path string, depth string) (info *api.Prop, err error) {
// FIXME how do we read back additional properties?
opts := rest.Opts{
Method: "PROPFIND",
Path: f.filePath(path),
ExtraHeaders: map[string]string{
"Depth": "0",
"Depth": depth,
},
CheckRedirect: rest.PreserveMethodRedirectFn,
}
@@ -367,6 +367,9 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Pr
// does not exist
switch apiErr.StatusCode {
case http.StatusNotFound:
if f.retryWithZeroDepth && depth != "0" {
return f.readMetaDataForPath(ctx, path, "0")
}
return nil, fs.ErrorObjectNotFound
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther:
// Some sort of redirect - go doesn't deal with these properly (it resets
@@ -796,7 +799,6 @@ func (f *Fs) listAll(ctx context.Context, dir string, directoriesOnly bool, file
ExtraHeaders: map[string]string{
"Depth": depth,
},
AuthRedirect: f.opt.AuthRedirect, // allow redirects to preserve Auth
}
if f.hasOCMD5 || f.hasOCSHA1 {
opts.Body = bytes.NewBuffer(owncloudProps)
@@ -1107,7 +1109,11 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) error {
// does not really exist so we perform an extra check here.
// Only the existence is checked, all other errors must be
// ignored here to make the rclone test suite pass.
_, err := f.readMetaDataForPath(ctx, dir)
depth := defaultDepth
if f.retryWithZeroDepth {
depth = "0"
}
_, err := f.readMetaDataForPath(ctx, dir, depth)
if err == fs.ErrorObjectNotFound {
return fs.ErrorDirNotFound
}
@@ -1416,7 +1422,7 @@ func (o *Object) readMetaData(ctx context.Context) (err error) {
if o.hasMetaData {
return nil
}
info, err := o.fs.readMetaDataForPath(ctx, o.remote)
info, err := o.fs.readMetaDataForPath(ctx, o.remote, defaultDepth)
if err != nil {
return err
}
-39
View File
@@ -12,7 +12,6 @@ import (
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configfile"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/config/obscure"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -82,44 +81,6 @@ func TestHeaders(t *testing.T) {
require.NoError(t, err)
}
// TestListAllAuthRedirect checks auth_redirect is honoured on listAll PROPFIND.
func TestListAllAuthRedirect(t *testing.T) {
var targetAuth string
var targetHits int
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
targetHits++
targetAuth = r.Header.Get("Authorization")
_, err := fmt.Fprint(w, `<d:multistatus xmlns:d="DAV:"></d:multistatus>`)
require.NoError(t, err)
}))
defer target.Close()
// Redirect via a different hostname so net/http strips Authorization on cross-host redirect.
targetURL := strings.Replace(target.URL, "127.0.0.1", "localhost", 1)
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, targetURL+r.URL.Path, http.StatusTemporaryRedirect)
}))
defer source.Close()
configfile.Install()
m := configmap.Simple{
"type": "webdav",
"url": source.URL,
"user": "alice",
"pass": obscure.MustObscure("secret"),
"auth_redirect": "true",
}
f, err := webdav.NewFs(context.Background(), remoteName, "", m)
require.NoError(t, err)
_, _ = f.List(context.Background(), "")
assert.GreaterOrEqual(t, targetHits, 1, "redirect target should receive the request")
assert.NotEmpty(t, targetAuth, "Authorization header should be preserved across redirect")
}
// TestReservedCharactersInPathAreEscaped verifies that reserved characters
// like semicolons and equals signs in file paths are percent-encoded in
// HTTP requests to the WebDAV server (RFC 3986 compliance).
-97
View File
@@ -1,97 +0,0 @@
#!/bin/bash
# Fetch the latest GUI dist.zip from rclone/rclone-web GitHub releases.
#
# Downloads dist.zip from the latest release to cmd/gui/dist.zip and
# records the tag in cmd/gui/dist.tag. Both files are committed to the
# repo so that builds are reproducible and `go build` works on a fresh
# clone without needing to fetch anything.
#
# Skips the download when both dist.zip and dist.tag exist and the tag
# matches the latest release.
#
# Requires: curl
set -euo pipefail
REPO="rclone/rclone-web"
DEST_DIR="cmd/gui"
ZIP_FILE="${DEST_DIR}/dist.zip"
TAG_FILE="${DEST_DIR}/dist.tag"
COMMIT=0
for arg in "$@"; do
case "$arg" in
--commit) COMMIT=1 ;;
*) echo "Unknown argument: $arg" >&2; exit 1 ;;
esac
done
CURL_OPTS=(-fSs --retry 5 --retry-delay 2 --retry-all-errors)
# Use GITHUB_TOKEN (or GH_TOKEN) if present so that GitHub API calls are
# authenticated. Unauthenticated calls are limited to 60/hour per source IP,
# which is regularly exhausted on shared GitHub Actions runners.
AUTH_HEADER=()
TOKEN="${GITHUB_TOKEN:-${GH_TOKEN:-}}"
if [ -n "${TOKEN}" ]; then
AUTH_HEADER=(-H "Authorization: Bearer ${TOKEN}")
fi
# Get the latest release info
echo "Checking latest release of ${REPO}..."
RELEASE_JSON=$(curl "${CURL_OPTS[@]}" "${AUTH_HEADER[@]}" \
-H "Accept: application/vnd.github+json" \
"https://api.github.com/repos/${REPO}/releases/latest") || {
echo "Error: failed to fetch release info from GitHub API" >&2
exit 1
}
TAG=$(echo "${RELEASE_JSON}" | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])")
ASSET_URL=$(echo "${RELEASE_JSON}" | python3 -c "
import sys, json
r = json.load(sys.stdin)
for a in r['assets']:
if a['name'] == 'dist.zip':
print(a['browser_download_url'])
sys.exit(0)
print('', file=sys.stderr)
sys.exit(1)
") || {
echo "Error: dist.zip asset not found in release ${TAG}" >&2
exit 1
}
echo "Latest release: ${TAG}"
# Skip only when both the zip and the tag are present and the tag matches.
# If only the tag exists (e.g. someone deleted the zip), force a re-download.
if [ -f "${ZIP_FILE}" ] && [ -f "${TAG_FILE}" ] && [ "$(cat "${TAG_FILE}")" = "${TAG}" ]; then
echo "Already up to date (${TAG})"
exit 0
fi
# Download dist.zip directly to its final location, via a temp file so a
# failed download doesn't leave a partial file behind.
TMPFILE=$(mktemp "${DEST_DIR}/.dist.zip.XXXXXX")
trap 'rm -f "${TMPFILE}"' EXIT
echo "Downloading dist.zip from ${TAG}..."
curl -L "${CURL_OPTS[@]}" "${AUTH_HEADER[@]}" -o "${TMPFILE}" "${ASSET_URL}" || {
echo "Error: failed to download dist.zip" >&2
exit 1
}
mv "${TMPFILE}" "${ZIP_FILE}"
chmod 644 "${ZIP_FILE}"
echo -n "${TAG}" > "${TAG_FILE}"
echo "Done. ${ZIP_FILE} updated to ${TAG}"
if [ "${COMMIT}" -eq 1 ]; then
git add "${ZIP_FILE}" "${TAG_FILE}"
if git diff --cached --quiet -- "${ZIP_FILE}" "${TAG_FILE}"; then
echo "No changes to commit (zip and tag are identical to HEAD)"
else
git commit -m "gui: update embedded release to ${TAG}" -- "${ZIP_FILE}" "${TAG_FILE}"
fi
fi
-2
View File
@@ -56,7 +56,6 @@ docs = [
"drive.md",
"googlephotos.md",
"hasher.md",
"huaweidrive.md",
"hdfs.md",
"hidrive.md",
"http.md",
@@ -136,7 +135,6 @@ ignore_docs = [
"privacy.md",
"sponsor.md",
"amazonclouddrive.md",
"backends.md", # Makes JSON confusingly
]
def read_doc(doc):
-1
View File
@@ -31,7 +31,6 @@ import (
_ "github.com/rclone/rclone/cmd/genautocomplete"
_ "github.com/rclone/rclone/cmd/gendocs"
_ "github.com/rclone/rclone/cmd/gitannex"
_ "github.com/rclone/rclone/cmd/gui"
_ "github.com/rclone/rclone/cmd/hashsum"
_ "github.com/rclone/rclone/cmd/link"
_ "github.com/rclone/rclone/cmd/listremotes"
-56
View File
@@ -1,8 +1,6 @@
package archive_test
import (
"archive/zip"
"bytes"
"context"
"strings"
"testing"
@@ -172,60 +170,6 @@ func TestIntegration(t *testing.T) {
testArchive(t)
}
// craftZip builds an in-memory zip archive with the given entries, returning
// it as a string. The entry names are written verbatim so they can include
// crafted path traversal sequences that the archive create command would
// never produce from real files.
func craftZip(t *testing.T, entries []struct{ name, content string }) string {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, e := range entries {
w, err := zw.CreateHeader(&zip.FileHeader{Name: e.name, Method: zip.Store})
require.NoError(t, err)
_, err = w.Write([]byte(e.content))
require.NoError(t, err)
}
require.NoError(t, zw.Close())
return buf.String()
}
// TestExtractPathTraversal checks that a crafted archive whose entries try to
// escape the destination directory with ".." components is rejected and does
// not write anything outside the destination (GHSA-4vr5-p2gc-h23p).
func TestExtractPathTraversal(t *testing.T) {
ctx := context.Background()
for _, tc := range []struct {
name string
entry string
}{
{name: "forward slash", entry: "../escaped.txt"},
{name: "backslash", entry: `..\escaped.txt`},
} {
t.Run(tc.name, func(t *testing.T) {
r := fstest.NewRun(t)
zipData := craftZip(t, []struct{ name, content string }{
{"safe.txt", "safe content"},
{tc.entry, "escaped content"},
})
r.WriteObject(ctx, "malicious.zip", zipData, t1)
// Extract into a subdirectory so a successful escape would land
// in "safe/escaped.txt", a sibling of the "safe/prefix" target.
err := extract.ArchiveExtract(ctx, r.Flocal, "safe/prefix", r.Fremote, "malicious.zip")
require.Error(t, err)
assert.Contains(t, err.Error(), "..")
// Nothing should have escaped the destination directory.
for _, escaped := range []string{"safe/escaped.txt", "escaped.txt"} {
_, err := r.Flocal.NewObject(ctx, escaped)
assert.ErrorIs(t, err, fs.ErrorObjectNotFound, escaped)
}
})
}
}
func TestMemory(t *testing.T) {
if *fstest.RemoteName != "" {
t.Skip("skipping as -remote is set")
+13 -46
View File
@@ -131,11 +131,7 @@ func ArchiveExtract(ctx context.Context, dst fs.Fs, dstDir string, src fs.Fs, sr
}
// account and buffer the transfer
// in = tr.Account(ctx, in).WithBuffer()
acc := tr.Account(ctx, in0)
in, err := acc.WithReadAtSeeker()
if err != nil {
return err
}
in := tr.Account(ctx, in0)
// identify format
format, _, err := archives.Identify(ctx, "", in)
if err != nil {
@@ -150,14 +146,20 @@ func ArchiveExtract(ctx context.Context, dst fs.Fs, dstDir string, src fs.Fs, sr
}
// extract files
err = ex.Extract(ctx, in, func(ctx context.Context, f archives.FileInfo) error {
remote, err := destPath(f.NameInArchive, dstDir)
if err != nil {
return err
}
// Skip the archive root entry ("./") which has no name of its own.
if remote == "" {
remote := f.NameInArchive
// Strip leading "./" from archive paths. Tar files created with
// relative paths (e.g. "tar -czf archive.tar.gz .") use "./" prefixed
// entries. Without stripping, rclone encodes the "." as a full-width
// dot character creating a spurious directory. We only strip "./"
// specifically to avoid enabling path traversal attacks via "../".
remote = strings.TrimPrefix(remote, "./")
// If the entry was exactly "./" (the root dir), skip it
if remote == "" && f.IsDir() {
return nil
}
if dstDir != "" {
remote = path.Join(dstDir, remote)
}
// check if file should be extracted
if !fi.Include(remote, f.Size(), f.ModTime(), fs.Metadata{}) {
return nil
@@ -197,38 +199,3 @@ func ArchiveExtract(ctx context.Context, dst fs.Fs, dstDir string, src fs.Fs, sr
return err
}
// destPath maps an archive entry name onto its destination remote within
// dstDir, returning an error if the name is unsafe.
//
// Archive entry names are attacker controlled. A leading "./" is stripped:
// tar archives created with relative paths (e.g. "tar -czf archive.tar.gz .")
// use "./" prefixed entries and, without stripping, rclone would encode the
// "." as a full-width dot character creating a spurious directory.
//
// Any entry with a ".." path component is then rejected to prevent a path
// traversal ("Zip Slip") attack: path.Join collapses "..", so an entry such
// as "../escaped.txt" joined onto "dir" would resolve to "escaped.txt" and be
// written outside the selected destination directory. Both "/" and "\" are
// treated as separators when looking for ".." segments: archive names should
// use "/", but a crafted archive may use "\", which the local backend treats
// as a path separator on Windows.
//
// The returned remote is empty for the archive root entry ("./"), which the
// caller should skip.
func destPath(nameInArchive, dstDir string) (string, error) {
remote := strings.TrimPrefix(nameInArchive, "./")
isSeparator := func(r rune) bool { return r == '/' || r == '\\' }
for _, segment := range strings.FieldsFunc(remote, isSeparator) {
if segment == ".." {
return "", fmt.Errorf("refusing to extract archive entry %q with a %q path component", nameInArchive, "..")
}
}
if remote == "" {
return "", nil
}
if dstDir != "" {
remote = path.Join(dstDir, remote)
}
return remote, nil
}
+8 -48
View File
@@ -3,19 +3,17 @@
package extract
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDestPath(t *testing.T) {
func TestStripDotSlashPrefix(t *testing.T) {
tests := []struct {
name string
input string
dstDir string
expected string
wantErr bool
}{
{
name: "strip leading dot-slash from file",
@@ -38,13 +36,12 @@ func TestDestPath(t *testing.T) {
expected: "dir/file.txt",
},
{
name: "joined onto destination directory",
input: "file.txt",
dstDir: "safe/prefix",
expected: "safe/prefix/file.txt",
name: "dot-dot-slash NOT stripped (path traversal safety)",
input: "../etc/passwd",
expected: "../etc/passwd",
},
{
name: "archive root entry skipped",
name: "dot-slash directory entry becomes empty",
input: "./",
expected: "",
},
@@ -53,49 +50,12 @@ func TestDestPath(t *testing.T) {
input: "././file.txt",
expected: "./file.txt",
},
{
name: "leading dot-dot rejected",
input: "../etc/passwd",
wantErr: true,
},
{
name: "leading dot-dot rejected with destination",
input: "../escaped.txt",
dstDir: "safe/prefix",
wantErr: true,
},
{
name: "interior dot-dot rejected",
input: "dir/../../escaped.txt",
dstDir: "safe/prefix",
wantErr: true,
},
{
name: "trailing dot-dot rejected",
input: "dir/..",
wantErr: true,
},
{
name: "backslash dot-dot rejected",
input: `..\escaped.txt`,
wantErr: true,
},
{
name: "nested backslash dot-dot rejected",
input: `dir\..\..\escaped.txt`,
dstDir: "safe/prefix",
wantErr: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := destPath(tc.input, tc.dstDir)
if tc.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
// This mirrors the stripping logic in ArchiveExtract
got := strings.TrimPrefix(tc.input, "./")
assert.Equal(t, tc.expected, got)
})
}
+1 -6
View File
@@ -183,12 +183,7 @@ func newFile(ctx context.Context, obj fs.Object, fi stdfs.FileInfo) (stdfs.File,
return nil, f.err
}
// Account the transfer
acc := f.transfer.Account(ctx, f.reader)
h, err := acc.WithReadAtSeeker()
if err != nil {
return nil, err
}
f.reader = h
f.reader = f.transfer.Account(ctx, f.reader)
return f, f.err
}
+1 -5
View File
@@ -167,11 +167,7 @@ func ArchiveList(ctx context.Context, src fs.Fs, srcFile string, listFn archives
}
// account and buffer the transfer
// in = tr.Account(ctx, in).WithBuffer()
acc := tr.Account(ctx, in0)
in, err := acc.WithReadAtSeeker()
if err != nil {
return err
}
in := tr.Account(ctx, in0)
// identify format
format, _, err := archives.Identify(ctx, "", in)
+1 -3
View File
@@ -85,8 +85,6 @@ var logReplacements = []string{
`^NOTICE: .*?: Replacing invalid UTF-8 characters in "[^"]*"$`, dropMe,
// ignore rclone debug messages
`^DEBUG : .*$`, dropMe,
// ignore SFTP host key messages
`^NOTICE: .*?No host key validation is being performed.*$`, dropMe,
// ignore dropbox info messages
`^NOTICE: too_many_(requests|write_operations)/\.*: Too many requests or write operations.*$`, dropMe,
`^NOTICE: .*?: Forced to upload files to set modification times on this backend.$`, dropMe,
@@ -331,7 +329,7 @@ func testBisync(ctx context.Context, t *testing.T, path1, path2 string) {
baseDir, err := os.Getwd()
require.NoError(t, err, "get current directory")
randName := time.Now().Format("150405") + random.String(8) // some bucket backends don't like dots, keep this short to avoid linux errors
randName := time.Now().Format("150405") + random.String(2) // some bucket backends don't like dots, keep this short to avoid linux errors
tempDir := filepath.Join(os.TempDir(), randName)
workDir := filepath.Join(tempDir, "workdir")
+1 -1
View File
@@ -196,7 +196,7 @@ func Bisync(ctx context.Context, fs1, fs2 fs.Fs, optArg *Options) (err error) {
}
if b.critical {
if b.retryable && b.opt.Resilient && !b.opt.Resync {
if b.retryable && b.opt.Resilient {
fs.Errorf(nil, Color(terminal.RedFg, "Bisync critical error: %v"), err)
fs.Error(nil, Color(terminal.YellowFg, "Bisync aborted. Error is retryable without --resync due to --resilient mode."))
} else {
+5 -4
View File
@@ -18,10 +18,11 @@ import (
func addRC() {
rc.Add(rc.Call{
Path: "sync/bisync",
Fn: rcBisync,
Title: shortHelp,
Help: rcHelp,
Path: "sync/bisync",
AuthRequired: true,
Fn: rcBisync,
Title: shortHelp,
Help: rcHelp,
})
}
+1 -1
View File
@@ -54,7 +54,7 @@ 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:
/home/ncw/.cache/rclone/bisync)
~/.cache/rclone/bisync)
See [bisync command help](https://rclone.org/commands/rclone_bisync/)
and [full bisync description](https://rclone.org/bisync/)
-10
View File
@@ -165,16 +165,6 @@ func (b *bisyncRun) resolve(ctxMove context.Context, path1, path2, file, alias s
},
}
if b.opt.ConflictLoser == ConflictLoserPathname {
switch winningPath {
case 1: // keep path1, rename path2
r.path1.newName = r.path1.oldName
case 2: // keep path2, rename path1
r.path2.newName = r.path2.oldName
}
// case 0 keeps default
}
// handle auto-numbering
// note that we still queue copies for both files, whether or not we renamed
// we also set these for ConflictLoserDelete in case there is no winner.
@@ -1 +1 @@
"file1.txt.path2"
"file2.txt"
@@ -1,6 +1,6 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -8,5 +8,3 @@
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt.path2"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
@@ -1,6 +1,6 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -8,4 +8,4 @@
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
- 33 - - 2005-01-02T00:00:00.000000000+0000 "file2.txt"
@@ -1,6 +1,5 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -8,3 +7,4 @@
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
- 0 - - 2000-01-01T00:00:00.000000000+0000 "file2.txt"
@@ -1,6 +1,6 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2004-07-25T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -8,5 +8,3 @@
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt.path2"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file2.txt"
@@ -1,6 +1,6 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2005-01-02T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -1,6 +1,5 @@
# bisync listing v1 from test
- 109 - - 2000-01-01T00:00:00.000000000+0000 "RCLONE_TEST"
- 33 - - 2006-03-04T00:00:00.000000000+0000 "file1.txt"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path1"
- 33 - - 2004-07-23T00:00:00.000000000+0000 "file1.txt..path2"
- 33 - - 2002-08-26T00:00:00.000000000+0000 "file1.txt.apple1"
@@ -8,3 +7,4 @@
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.cloud1"
- 33 - - 2001-08-26T00:00:00.000000000+0000 "file1.txt.dinosaur1"
- 33 - - 2003-07-23T00:00:00.000000000+0000 "file1.txt.local1"
- 0 - - 2000-01-01T00:00:00.000000000+0000 "file2.txt"
-53
View File
@@ -305,56 +305,3 @@ INFO : - Path1 Do queued copies to - P
INFO : Updating listings
INFO : Validating listings for Path1 "{path1/}" vs Path2 "{path2/}"
INFO : Bisync successful
(48) : test --conflict-resolve newer --conflict-loser pathname --conflict-suffix path
(49) : touch-glob 2004-07-23 {datadir/} file1R.txt
(50) : copy-as {datadir/}file1R.txt {path2/} file1.txt
(51) : touch-glob 2004-07-25 {datadir/} file1L.txt
(52) : copy-as {datadir/}file1L.txt {path1/} file1.txt
(53) : test bisync run with --conflict-resolve=newer --conflict-loser=pathname --conflict-suffix=path
(54) : bisync conflict-resolve=newer conflict-loser=pathname conflict-suffix=path
INFO : Setting --ignore-listing-checksum as neither --checksum nor --compare checksum are set.
INFO : Bisyncing with Comparison Settings:
{
"Modtime": true,
"Size": true,
"Checksum": false,
"NoSlowHash": false,
"SlowHashSyncOnly": false,
"DownloadHash": false
}
INFO : Synching Path1 "{path1/}" with Path2 "{path2/}"
INFO : Building Path1 and Path2 listings
INFO : Path1 checking for diffs
INFO : - Path1 File changed: time (older) - file1.txt
INFO : - Path1 File is new - file2.txt
INFO : Path1: 2 changes:  1 new,  1 modified,  0 deleted
INFO : (Modified:  0 newer,  1 older)
INFO : Path2 checking for diffs
INFO : - Path2 File changed: time (older) - file1.txt
INFO : - Path2 File is new - file2.txt
INFO : Path2: 2 changes:  1 new,  1 modified,  0 deleted
INFO : (Modified:  0 newer,  1 older)
INFO : Applying changes
INFO : Checking potential conflicts...
ERROR : file1.txt: {hashtype} differ
NOTICE: {path2String}: 1 differences found
NOTICE: {path2String}: 1 errors while checking
NOTICE: {path2String}: 1 matching files
INFO : Finished checking the potential conflicts. 1 differences found
NOTICE: - WARNING New or changed in both paths - file1.txt
INFO : file1.txt: Path1 is newer. Path1: 2004-07-25 00:00:00 +0000 UTC, Path2: 2004-07-23 00:00:00 +0000 UTC, Difference: 48h0m0s
INFO : file1.txt: The winner is: Path1
NOTICE: - Path1 Not renaming Path1 copy, as it was determined the winner - {path1/}file1.txt
NOTICE: - Path1 Queue copy to Path2 - {path2/}file1.txt
NOTICE: - Path2 Renaming Path2 copy - {path2/}file1.txt.path2
NOTICE: - Path2 Queue copy to Path1 - {path1/}file1.txt.path2
NOTICE: - WARNING New or changed in both paths - file2.txt
INFO : Files are equal! Skipping: file2.txt
INFO : - Path2 Do queued copies to - Path1
INFO : - Path1 Do queued copies to - Path2
INFO : Updating listings
INFO : Validating listings for Path1 "{path1/}" vs Path2 "{path2/}"
INFO : Bisync successful
+1 -11
View File
@@ -64,14 +64,4 @@ copy-as {datadir/}file1L.txt {path1/} file1.txt
copy-as {datadir/}file1L.txt {path2/} file2.txt
test bisync run with --conflict-resolve=newer --conflict-loser=delete
bisync conflict-resolve=newer conflict-loser=delete
test --conflict-resolve newer --conflict-loser pathname --conflict-suffix path
touch-glob 2004-07-23 {datadir/} file1R.txt
copy-as {datadir/}file1R.txt {path2/} file1.txt
touch-glob 2004-07-25 {datadir/} file1L.txt
copy-as {datadir/}file1L.txt {path1/} file1.txt
test bisync run with --conflict-resolve=newer --conflict-loser=pathname --conflict-suffix=path
# result should be -- "file1.txt", "file1.txt.path2"
bisync conflict-resolve=newer conflict-loser=pathname conflict-suffix=path
bisync conflict-resolve=newer conflict-loser=delete
+4 -4
View File
@@ -124,12 +124,12 @@ func waitFor(fn func() bool) (ok bool) {
//
// returns an error, and an error channel for the serve process to
// report an error when fusermount is called.
func mount(VFS *vfs.VFS, mountPath string, opt *mountlib.Options) (<-chan error, func() error, string, error) {
func mount(VFS *vfs.VFS, mountPath string, opt *mountlib.Options) (<-chan error, func() error, error) {
// Get mountpoint using OS specific logic
f := VFS.Fs()
mountpoint, err := getMountpoint(f, mountPath, opt)
if err != nil {
return nil, nil, "", err
return nil, nil, err
}
fs.Debugf(nil, "Mounting on %q (%q)", mountpoint, opt.VolumeName)
@@ -205,7 +205,7 @@ func mount(VFS *vfs.VFS, mountPath string, opt *mountlib.Options) (<-chan error,
select {
case err := <-errChan:
err = fmt.Errorf("mount stopped before calling Init: %w", err)
return nil, nil, "", err
return nil, nil, err
case <-fsys.ready:
}
@@ -220,5 +220,5 @@ func mount(VFS *vfs.VFS, mountPath string, opt *mountlib.Options) (<-chan error,
}
}
return errChan, unmount, mountpoint, nil
return errChan, unmount, nil
}
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff. Show more