Compare commits

..
Author SHA1 Message Date
Nick Craig-Wood 13a1d23bb8 mega: fix nil pointer panic when login with session keys fails - fixes #9232
When LoginWithKeys failed (e.g. after clearing Mega trash or with a
stale session), the error was silently ignored and only logged at debug
level. This left the filesystem uninitialized so GetRoot() returned
nil, causing a nil pointer dereference panic in findDir.

This returns the login error instead of swallowing it, and adds a nil
check for GetRoot() in findRoot, and adds defensive nil node checks in
findDir and findObject.
2026-03-05 12:30:43 +00:00
584 changed files with 10409 additions and 65993 deletions

No files matched your search

-78
View File
@@ -1,78 +0,0 @@
# CODEOWNERS for rclone
#
# Maps paths to the maintainers auto-requested for review when a pull request
# touches matching files. Patterns are evaluated top to bottom and the LAST
# matching pattern wins, so the catch-all below is overridden by the more
# specific subsystem/backend lines that follow.
#
# Every owner listed here has write access to the repo (GitHub ignores owners
# without it). Assignments are derived from `git log` history per directory:
# each area lists its dominant contributor(s) alongside @ncw, the project lead
# and global fallback.
# Global fallback - everything not matched below
* @ncw
# -----------------------------------------------------------------------------
# Core subsystems
# -----------------------------------------------------------------------------
/fs/ @ncw
/vfs/ @ncw
/lib/ @ncw
/cmd/ @ncw
/librclone/ @ncw
/fstest/ @ncw
/lib/encoder/ @ncw @klauspost
/fs/sync/ @ncw @nielash
/fs/operations/ @ncw @nielash
/cmd/bisync/ @nielash @ivandeex @ncw
/cmd/serve/ @albertony @ncw
/cmd/selfupdate/ @ivandeex @ncw
/cmd/mount2/ @ncw @darthShadow
/cmd/gitannex/ @dmcardle @ncw
# -----------------------------------------------------------------------------
# Backends - keyed to the dominant / specialist maintainer per `git log`
# -----------------------------------------------------------------------------
# albertony
/backend/jottacloud/ @albertony @buengese @ncw
/backend/local/ @ncw @albertony @nielash
/backend/netstorage/ @albertony @ncw
/backend/hdfs/ @albertony @ncw
# buengese
/backend/yandex/ @ncw @buengese
/backend/zoho/ @buengese @ncw
/backend/fichier/ @ncw @buengese
/backend/compress/ @ncw @buengese
# ivandeex
/backend/chunker/ @ncw @ivandeex
/backend/mailru/ @ncw @ivandeex
/backend/ftp/ @ncw @ivandeex
/backend/sia/ @ncw @ivandeex
# Other maintainer-owned backends (see MAINTAINERS.md)
/backend/cache/ @ncw @remusb
/backend/union/ @ncw @Max-Sum @albertony
/backend/filescom/ @ncw @childish-sambino
# Microsoft Azure
/backend/azureblob/ @ncw @sandeepkru @darthShadow
# Single-maintainer specialist backends
/backend/onedrive/ @ncw @Cnly @nielash
/backend/iclouddrive/ @lostb1t @ncw
/backend/pikpak/ @wiserain @ncw
/backend/protondrive/ @henrybear327 @ncw
/backend/seafile/ @ncw @creativeprojects
/backend/filen/ @Enduriel @ncw
/backend/storj/ @ncw @calebcase
/backend/combine/ @ncw @nielash
# -----------------------------------------------------------------------------
# Repo plumbing
# -----------------------------------------------------------------------------
/.github/ @ncw
+31
View File
@@ -0,0 +1,31 @@
<!--
Welcome :-) We understand you are having a problem with rclone; we want to help you with that!
If you've just got a question or aren't sure if you've found a bug then please use the rclone forum:
https://forum.rclone.org/
instead of filing an issue for a quick response.
If you are reporting a bug or asking for a new feature then please use one of the templates here:
https://github.com/rclone/rclone/issues/new
otherwise fill in the form below.
Thank you
The Rclone Developers
-->
#### Output of `rclone version`
#### Describe the issue
+74
View File
@@ -0,0 +1,74 @@
---
name: Bug report
about: Report a problem with rclone
---
<!--
We understand you are having a problem with rclone; we want to help you with that!
**STOP and READ**
**YOUR POST WILL BE REMOVED IF IT IS LOW QUALITY**:
Please show the effort you've put into solving the problem and please be specific.
People are volunteering their time to help! Low effort posts are not likely to get good answers!
If you think you might have found a bug, try to replicate it with the latest beta (or stable).
The update instructions are available at https://rclone.org/commands/rclone_selfupdate/
If you can still replicate it or just got a question then please use the rclone forum:
https://forum.rclone.org/
for a quick response instead of filing an issue on this repo.
If nothing else helps, then please fill in the info below which helps us help you.
**DO NOT REDACT** any information except passwords/keys/personal info.
You should use 3 backticks to begin and end your paste to make it readable.
Make sure to include a log obtained with '-vv'.
You can also use '-vv --log-file bug.log' and a service such as https://pastebin.com or https://gist.github.com/
Thank you
The Rclone Developers
-->
#### The associated forum post URL from `https://forum.rclone.org`
#### What is the problem you are having with rclone?
#### What is your rclone version (output from `rclone version`)
#### Which OS you are using and how many bits (e.g. Windows 7, 64 bit)
#### Which cloud storage system are you using? (e.g. Google Drive)
#### The command you were trying to run (e.g. `rclone copy /tmp remote:tmp`)
#### A log from the command with the `-vv` flag (e.g. output from `rclone -vv copy /tmp remote:tmp`)
<!--- Please keep the note below for others who read your bug report. -->
#### How to use GitHub
* Please use the 👍 [reaction](https://blog.github.com/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) to show that you are affected by the same issue.
* Please don't comment if you have no relevant information to add. It's just extra noise for everyone subscribed to this issue.
* Subscribe to receive notifications on status change and new comments.
+51
View File
@@ -0,0 +1,51 @@
---
name: Feature request
about: Suggest a new feature or enhancement for rclone
---
<!--
Welcome :-)
So you've got an idea to improve rclone? We love that!
You'll be glad to hear we've incorporated hundreds of ideas from contributors already.
Probably the latest beta (or stable) release has your feature, so try to update your rclone.
The update instructions are available at https://rclone.org/commands/rclone_selfupdate/
If it still isn't there, here is a checklist of things to do:
1. Search the old issues for your idea and +1 or comment on an existing issue if possible.
2. Discuss on the forum: https://forum.rclone.org/
3. Make a feature request issue (this is the right place!).
4. Be prepared to get involved making the feature :-)
Looking forward to your great idea!
The Rclone Developers
-->
#### The associated forum post URL from `https://forum.rclone.org`
#### What is your current rclone version (output from `rclone version`)?
#### What problem are you are trying to solve?
#### How do you think rclone should be changed to solve that?
<!--- Please keep the note below for others who read your feature request. -->
#### How to use GitHub
* Please use the 👍 [reaction](https://blog.github.com/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) to show that you are affected by the same issue.
* Please don't comment if you have no relevant information to add. It's just extra noise for everyone subscribed to this issue.
* Subscribe to receive notifications on status change and new comments.
-124
View File
@@ -1,124 +0,0 @@
name: Bug report
description: Report a reproducible problem with rclone
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
We want to help you with rclone - thank you for taking the time to fill this in!
**This tracker is for reproducible bugs only.** If you have a question, are
not sure whether something is a bug, or want help with a configuration, please
use the [rclone forum](https://forum.rclone.org/) instead - you will get a much
quicker answer there.
Before filing, please **test with the [latest beta or stable](https://rclone.org/commands/rclone_selfupdate/)**
(downloads at <https://beta.rclone.org/>) as your problem may already be fixed.
**Do not redact** any information except passwords, keys and personal info.
- type: checkboxes
id: acknowledgements
attributes:
label: Before you start
description: Please confirm the following. Issues that skip these steps may be closed.
options:
- label: I have searched the [forum](https://forum.rclone.org/) and the existing issues for this problem.
required: true
- label: I have tested with the latest beta or stable release and can still reproduce the problem.
required: true
- label: This is a reproducible bug, not a usage question (questions belong on the forum).
required: true
- type: input
id: forum-url
attributes:
label: Associated forum post URL
description: If you discussed this on the forum first (encouraged), paste the link here.
placeholder: https://forum.rclone.org/t/...
validations:
required: false
- type: textarea
id: problem
attributes:
label: What is the problem you are having with rclone?
description: Describe the problem and the exact steps to reproduce it.
validations:
required: true
- type: textarea
id: version
attributes:
label: rclone version
description: The full output of `rclone version`.
placeholder: |
rclone v1.75.0
- os/version: ubuntu 24.04 (64 bit)
- os/kernel: 6.8.0-111-generic (x86_64)
- os/type: linux
- os/arch: amd64
- go/version: go1.26.4
- go/linking: dynamic
- go/tags: none
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating system
description: Choose the operating system you are using with rclone.
options:
- Windows
- macOS
- Linux
- FreeBSD
- NetBSD
- OpenBSD
- Plan 9
- Solaris
- Android
- iOS
- Other
validations:
required: true
- type: input
id: backend
attributes:
label: Which cloud storage system are you using?
description: e.g. Google Drive, S3, Dropbox, local disk. List all involved.
validations:
required: true
- type: textarea
id: config
attributes:
label: Output of `rclone config redacted`
description: |
Run `rclone config redacted` (or `rclone config redacted <remote>` for a
single remote). This command automatically replaces passwords and tokens
with `XXX`, so it should be safe to paste but please double-check before posting.
render: ini
validations:
required: true
- type: textarea
id: command
attributes:
label: The command you were trying to run
description: e.g. `rclone copy /tmp remote:tmp`
render: shell
validations:
required: true
- type: textarea
id: log
attributes:
label: A log from the command with the `-vv` flag
description: |
e.g. output from `rclone -vv copy /tmp remote:tmp`. For long logs (> 100 lines) use
`-vv --log-file bug.log` and attach it here or send to a service such as
<https://gist.github.com/> or <https://pastebin.com/> and link it here.
render: shell
validations:
required: true
- type: textarea
id: extra
attributes:
label: Anything else?
description: Anything else that might help us, e.g. a minimal way to replicate the problem.
validations:
required: false
+2 -5
View File
@@ -1,8 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Rclone Forum - questions & support
- name: Rclone Forum Community Support
url: https://forum.rclone.org/
about: Have a question, need help, or not sure if it's a bug? Please ask here for a quick answer.
- name: Rclone Documentation
url: https://rclone.org/docs/
about: The docs answer many "how do I..." questions, including per-backend guides.
about: Please ask and answer questions here.
-68
View File
@@ -1,68 +0,0 @@
name: Feature request
description: Suggest a new feature or enhancement for rclone
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
So you've got an idea to improve rclone? We love that - we've already
incorporated hundreds of ideas from contributors!
Please **search first**: your idea may already exist in the latest
[beta or stable](https://rclone.org/commands/rclone_selfupdate/), or already
be requested. It is often worth [discussing on the forum](https://forum.rclone.org/)
to refine the idea or checking to see if rclone can do it already before filing it here.
- type: checkboxes
id: acknowledgements
attributes:
label: Before you start
options:
- label: I have searched the [forum](https://forum.rclone.org/) and the existing issues and this hasn't already been requested.
required: true
- label: I have checked the latest beta and this feature doesn't already exist.
required: true
- type: input
id: forum-url
attributes:
label: Associated forum post URL
description: If you discussed this on the forum first (encouraged), paste the link here.
placeholder: https://forum.rclone.org/t/...
validations:
required: false
- type: textarea
id: version
attributes:
label: rclone version
description: The full output of `rclone version`, not just the version number.
placeholder: |
rclone v1.75.0
- os/version: ubuntu 24.04 (64 bit)
- os/kernel: 6.8.0-111-generic (x86_64)
- os/type: linux
- os/arch: amd64
- go/version: go1.26.4
- go/linking: dynamic
- go/tags: none
validations:
required: true
- type: textarea
id: problem
attributes:
label: What problem are you trying to solve?
description: Describe the use case and what is difficult or impossible today.
validations:
required: true
- type: textarea
id: solution
attributes:
label: How do you think rclone should be changed to solve that?
validations:
required: true
- type: checkboxes
id: involvement
attributes:
label: Getting involved
description: Features are much more likely to happen if someone helps make them.
options:
- label: I'm willing to help implement, test or fund this feature.
required: false
+11 -36
View File
@@ -1,54 +1,29 @@
<!--
Thank you for contributing to rclone!
Thank you very much for contributing code or documentation to rclone! Please
fill out the following questions to make it easier for us to review your
changes.
Please discuss anything more than a trivial fix in an issue FIRST - see the
"Linked issue" section below. Then fill in the questions to help us review.
You do not need to check all the boxes below all at once, feel free to take
your time and add more commits. If you're done and ready for review, please
check the last box.
-->
#### What does this change do?
<!-- Describe the change here. -->
#### Linked issue
#### What is the purpose of this change?
<!--
Put `Fixes #1234` here if this closes an issue, or `#1234` to link without closing.
IMPORTANT: Anything beyond a trivial fix (typo, doc tweak, small obvious bug fix)
should be discussed and agreed in an issue BEFORE you open a pull request.
Pull requests for larger changes that have not been discussed in an issue first
may be closed. This saves everyone's time if the change needs a different approach
or isn't a good fit.
Describe the changes here
-->
Fixes #
#### For new or changed backends
#### Was the change discussed in an issue or in the forum before?
<!--
Backend pull requests are often sent without the integration tests having been run.
We cannot merge a backend change until it passes the integration tests.
To be merged, a backend change REQUIRES:
1. A clean run of `go run ./fstest/test_all -backends <remote>` (summarise the
result below or paste a screenshot of the test_all output in the web browser).
2. A test account so the maintainers can run the integration tests daily against
the backend on the integration test server.
If the tests aren't quite passing yet and you need help getting them
to pass, then submit the PR and we can help getting you over the line.
See https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#writing-a-new-backend
and https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#integration-tests
Link issues and relevant forum posts here.
-->
#### Checklist
- [ ] This change is trivial **OR** it has been discussed and agreed in the linked issue.
- [ ] I have read the [contribution guidelines](https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#submitting-a-new-feature-or-bug-fix).
- [ ] **(If I used AI tools to help write this code)** I have read and understood the [AI-assisted contributions guidance](https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#ai-assisted-contributions), and I have tested and take ownership of this change myself.
- [ ] I have added tests for all changes in this PR if appropriate.
- [ ] I have added documentation for the changes if appropriate.
- [ ] All commit messages are in [house style](https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#commit-messages).
- [ ] **(Backend changes only)** `test_all` passes for this backend and if submitting a new backend can provide a test account for the integration tester - see [CONTRIBUTING.md](https://github.com/rclone/rclone/blob/master/CONTRIBUTING.md#integration-tests).
- [ ] This Pull Request is ready for review.
- [ ] I'm done, this Pull Request is ready for review :-)
-2
View File
@@ -4,5 +4,3 @@ updates:
directory: "/"
schedule:
interval: "daily"
cooldown:
default-days: 7
+17 -136
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@v7
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Install Go
id: setup-go
uses: actions/setup-go@v7
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@v6
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@v6
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: |
@@ -165,11 +120,6 @@ jobs:
sudo chown root:$USER /etc/fuse.conf
sudo apt-get update
sudo apt-get install -y fuse3 libfuse-dev rpm pkg-config git-annex git-annex-remote-rclone nfs-common
# The podman static bundle in runner image ubuntu24/20260726.254 and
# later ships a non-setuid fusermount3 in /usr/local/bin which
# shadows the setuid one from the fuse3 package and breaks FUSE
# mounts with "Operation not permitted", so remove it.
sudo rm -f /usr/local/bin/fusermount /usr/local/bin/fusermount3
if: matrix.os == 'ubuntu-latest'
- name: Install Libraries on macOS
@@ -252,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
@@ -275,31 +216,23 @@ jobs:
echo "runner-os-version=$ImageOS" >> $GITHUB_OUTPUT
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Install Go
id: setup-go
uses: actions/setup-go@v7
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@v6
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@v6
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') }}
@@ -366,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
@@ -382,50 +306,16 @@ 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@v7
uses: actions/checkout@v6
with:
fetch-depth: 0
# Upgrade together with NDK version
- name: Set up Go
id: setup-go
uses: actions/setup-go@v7
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@v6
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@v6
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: |
@@ -501,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')
@@ -56,7 +52,7 @@ jobs:
df -h .
- name: Checkout Repository
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
fetch-depth: 0
@@ -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: |
@@ -104,7 +100,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: manifest,manifest-descriptor # Important for digest annotation (used by Github packages)
with:
@@ -126,14 +122,14 @@ jobs:
type=raw,value=beta,enable={{is_default_branch}}
- name: Setup QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Load Go Build Cache for Docker
id: go-cache
uses: actions/cache@v6
uses: actions/cache@v5
with:
key: ${{ runner.os }}-${{ steps.imageos.outputs.result }}-go-${{ env.CACHE_NAME }}-${{ env.PLATFORM }}-${{ hashFiles('**/go.mod') }}-${{ hashFiles('**/go.sum') }}
restore-keys: |
@@ -152,7 +148,7 @@ jobs:
skip-extraction: ${{ steps.go-cache.outputs.cache-hit }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
@@ -163,7 +159,7 @@ jobs:
- name: Build and Publish Image Digest
id: build
uses: docker/build-push-action@v7
uses: docker/build-push-action@v6
with:
file: Dockerfile
context: .
@@ -214,7 +210,7 @@ jobs:
- name: Extract Metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v6
uses: docker/metadata-action@v5
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
with:
@@ -265,16 +261,16 @@ jobs:
env.write(f"ANNOTATIONS={annotations_string}\n")
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v4
uses: docker/login-action@v3
with:
registry: ghcr.io
# This is the user that triggered the Workflow. In this case, it will
@@ -14,9 +14,6 @@ on:
type: boolean
default: true
permissions:
contents: read
jobs:
build_docker_volume_plugin:
if: inputs.manual || github.repository == 'rclone/rclone'
@@ -33,7 +30,7 @@ jobs:
sudo rm -rf /usr/share/dotnet || true
df -h .
- name: Checkout master
uses: actions/checkout@v7
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Build and publish docker plugin
-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:
-134
View File
@@ -1,134 +0,0 @@
# AGENTS.md
This file provides guidance to AI coding agents (e.g. Claude Code, Codex, Cursor, Gemini CLI, and similar tools) when working with code in this repository.
Rclone welcomes AI-assisted contributions, but the expectation is that you, the human submitter, understand every line you propose and have compiled and tested it against real rclone code - not just generated it. See the "AI-assisted contributions" section of [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
## Project Overview
Rclone is a command-line program to sync files and directories to and from cloud storage providers. It's written in Go and supports 70+ backends (cloud storage systems). Think "rsync for cloud storage".
## General Notes
**We take backwards compatibility very seriously.** PRs should not change the observable behaviour of existing commands, flags or rc API without very good reason. Rclone does not try to preserve a stable Go API but try not to change it gratuitously.
Rclone operates with a lot of different backends, so **compatibility is key**. It is the backend integration tests which guarantee that compatibility. Changes should consider both known and unknown backends and should take care not to break functionality of existing installations.
The core parts of rclone under `fs` and `vfs` need to work with all backends and **backend specific hacks won't be merged**. Fixes likely need to go in the relevant backend or if new behaviour is really needed, a new Feature flag needs to be added.
**Changes should be kept to the minimum.** Work hard to make the most elegant, smallest change you can. Do not refactor or re-order code unless necessary as this makes review more challenging. Re-use existing test scaffolding, existing or library routines (e.g. `lib`) where possible.
Make sure added tests **actually test the code you have written** and test the intention behind the change. If you are fixing a problem, write the tests first to reproduce the problem before starting on the fix.
## Build and Test Commands
```bash
# Build rclone (simple)
go build
# Build with version info (preferred)
make
# Run all unit tests (no cloud credentials needed)
make quicktest
# or equivalently:
RCLONE_CONFIG="/notfound" go test ./...
# Run tests for a specific package
cd backend/memory && go test -v
# or from root:
go test -v ./backend/memory/
# Run a single test
go test -v -run TestIntegration/FsCheckWrap ./backend/memory/
# Run tests with race detector
make racequicktest
# Lint (requires golangci-lint)
golangci-lint run ./...
# Run backend integration tests (requires configured TestRemote remote)
cd backend/drive && go test -v
# Run sync/operations integration tests against a remote
cd fs/sync && go test -v -remote TestDrive:
cd fs/operations && go test -v -remote TestDrive:
# Run integration tests via test framework
go run ./fstest/test_all -backends drive
```
## Architecture
### Entry Point and Plugin Registration
`rclone.go` is the main entry point. It imports `backend/all` and `cmd/all` which use Go's `init()` pattern to register all backends and commands. Each backend calls `fs.Register()` with a `fs.RegInfo` struct during init.
### Core Interfaces (`fs/`)
The `fs` package defines the core abstractions:
- **`fs.Fs`** (`fs/types.go`): The filesystem interface every backend must implement (List, NewObject, Put, Mkdir, Rmdir).
- **`fs.Object`** (`fs/types.go`): Interface for a file/object (Open, Update, Remove, SetModTime).
- **`fs.Features`** (`fs/features.go`): Optional capabilities a backend can declare (Purge, Copy, Move, DirMove, etc.). Backends set function pointers for operations they support; nil means not supported.
- **`fs.RegInfo`** (`fs/registry.go`): Registration metadata for a backend including its name, config options, and NewFs constructor.
### Backend Structure (`backend/`)
Each backend is a single Go package (e.g., `backend/s3/`, `backend/drive/`). Key conventions:
- Main implementation in a single file (e.g., `s3.go`) - **do not** split into `fs.go`/`object.go`.
- API types go in a separate `api/types.go` file.
- Test file (e.g., `s3_test.go`) uses `fstests.Run()` from `fstest/fstests` for standardized integration tests.
- Register in `backend/all/all.go` via blank import.
- HTTP-based backends should use `lib/rest` for HTTP calls and `fs/fshttp` for the HTTP client.
- Use `lib/dircache` for directory-ID-based remotes, `lib/oauthutil` for OAuth, `lib/pacer` for rate limiting.
### Command Structure (`cmd/`)
Each command is a package under `cmd/` registered in `cmd/all/all.go` via blank import. Commands use cobra via `cmd.Main()`.
### Key Subsystems
- **`fs/operations/`**: Core file operations (Copy, Move, Delete, etc.)
- **`fs/sync/`**: Directory sync logic
- **`fs/march/`**: Parallel directory tree walker used by sync
- **`fs/filter/`**: Include/exclude filtering
- **`fs/accounting/`**: Transfer statistics and bandwidth limiting
- **`fs/config/`**: Configuration file management
- **`vfs/`**: Virtual filesystem layer (used by mount, serve)
- **`librclone/`**: C-compatible library interface for embedding rclone
- **`fstest/`**: Integration test framework; `fstest/fstests/` has the generic backend test suite
## Commit Message Convention
Prefix with the directory of the change, then a colon: `drive: add team drive support - fixes #885`. For cross-cutting changes use a broader prefix like `fs` or `operations`.
Make the first line of your commit message a summary of the change that a user (not a developer) of rclone would like to read. So write `drive: fix server side copy of big files` instead of `drive: no longer set the MimeType in Move or Copy`. This is important because these lines go into the change log which is read by users.
## Code Commenting Style
Comments describe the code as it is now, for a future reader who has no knowledge of the change that introduced it.
Every exported type, function, field, and constant has a **godoc comment** that starts with its name and is phrased as a present-tense statement of what it is or does (`// Mkdir makes the directory (container, bucket)`)
**Document the contract** callers need - preconditions, what's returned, which sentinel errors are returned and when, and any "shouldn't return an error if it already exists" style caveats - rather than the implementation.
**Keep comments terse**: a single line for most things, with extra paragraphs (separated by blank `//` lines) reserved for genuine subtlety.
Inline comments inside function bodies should **explain why** - a non-obvious API quirk, a workaround, a gotcha, or an ordering constraint - and may cite an external reference (forum thread, vendor docs, RFC) when that's what makes the behaviour non-obvious; skip comments that merely restate what the code plainly does.
Use `FIXME` and `TODO` for known shortcomings.
**Do not write comments that narrate the change itself** or compare against the previous behaviour (no "now we also handle...", "changed to...", "previously this returned...", or references to bug/PR numbers in the code) - that context belongs in the commit message, not in source that will outlive the change.
Code comments should only refer to **current** behaviour - and shouldn't describe behaviour that is trivially deducible from reading the code.
## Linting Configuration
Uses golangci-lint v2 with config in `.golangci.yml`. Enabled linters: errcheck, govet, ineffassign, staticcheck, unused, gocritic, misspell, revive, unconvert. The `goimports` formatter is also enabled.
## Documentation
- Backend option docs come from `Help:` fields in the Go source Options structs, not from markdown files.
- Command docs are in the command source code (e.g., `cmd/ls/ls.go`).
- Don't commit autogenerated doc changes from `make backenddocs` or `make commanddocs`.
- Website docs are in `docs/content/` as markdown, built with Hugo (`make serve` to preview).
-6
View File
@@ -1,6 +0,0 @@
# CLAUDE.md
Guidance for this repository lives in AGENTS.md, shared with all AI coding
agents. Claude Code reads it via the import below.
@AGENTS.md
+4 -42
View File
@@ -113,36 +113,6 @@ GitHub.
You may sometimes be asked to [base your changes on the latest master](#basing-your-changes-on-the-latest-master)
or [squash your commits](#squashing-your-commits).
## AI-assisted contributions
You are welcome to use AI coding assistants (Claude Code, Codex, Cursor, Gemini
CLI, and similar) to help write your contribution. Rclone has an
[AGENTS.md](AGENTS.md) file at the top of the repository describing the project's
conventions; point your tool at it so the code it produces matches rclone's
style.
However, the same standard applies to every pull request whether or not a tool
was involved: **you are responsible for the code you submit.** Before you open a
pull request please make sure that:
- You understand every line of the change and can explain why it is correct. If
a reviewer asks a question about it, you should be able to answer without
going back to the tool.
- You have actually built and run it. At a minimum `go build` and
`make quicktest` must pass, and for a backend change you should run the
[backend tests](#backend-testing) against a real remote where you can.
- The change is a genuine fix or feature that you have verified solves the
problem, not a plausible-looking guess. Unverified, AI-generated pull requests
that do not compile, do not pass the tests, invent APIs that do not exist, or
do not actually do what the description claims waste maintainer time and are
likely to be closed.
- You have trimmed the comments. AI tools tend to add verbose comments that
restate what the code plainly does or narrate the change being made; please
cut these down to match the [code commenting style](AGENTS.md#code-commenting-style).
In short: an AI assistant is a tool to help *you* contribute, not a substitute
for understanding and testing your own work.
## Using Git and GitHub
### Committing your changes
@@ -653,22 +623,14 @@ Or if you want to run the integration tests manually:
- If your remote defines `ListR` check with this also
- `go test -v -remote TestRemote: -fast-list`
Before a new or changed backend can be merged we require:
- A clean run of `go run ./fstest/test_all -backends remote` (please include the
result in your pull request).
- A test account for the backend so the maintainers can add it to the
[integration test server](https://integration.rclone.org) and keep the backend
working as rclone evolves. A backend that we cannot test is likely to break and
may be removed.
See the [testing](#testing) section for more information on integration tests.
### Backend documentation
Add your backend to the docs. Keep lists of remotes in alphabetical
order of full name of remote (e.g. `drive` is ordered as `Google
Drive`) but with the local file system last.
Add your backend to the docs - you'll need to pick an icon for it from
[fontawesome](http://fontawesome.io/icons/). Keep lists of remotes in
alphabetical order of full name of remote (e.g. `drive` is ordered as
`Google Drive`) but with the local file system last.
First add a data file about your backend in
`docs/data/backends/remote.yaml` - this is used to build the overview
+21 -28
View File
@@ -2,34 +2,27 @@
Current active maintainers of rclone are:
| Name | GitHub ID |
| :--------------- | :---------------- |
| Nick Craig-Wood | @ncw |
| Stefan Breunig | @breunigs |
| Ishuah Kariuki | @ishuah |
| Remus Bunduc | @remusb |
| Fabian Möller | @B4dM4n |
| Alex Chen | @Cnly |
| Sandeep Ummadi | @sandeepkru |
| Sebastian Bünger | @buengese |
| Ivan Andreev | @ivandeex |
| Max Sum | @Max-Sum |
| Fred | @creativeprojects |
| Caleb Case | @calebcase |
| wiserain | @wiserain |
| albertony | @albertony |
| Chun-Hung Tseng | @henrybear327 |
| Hideo Aoyama | @boukendesho |
| nielash | @nielash |
| Dan McArdle | @dmcardle |
| Sam Harrison | @childish-sambino |
| Enduriel | @Enduriel |
Per-area ownership of code (which backend or command each maintainer looks
after) is defined in [.github/CODEOWNERS](.github/CODEOWNERS), which GitHub uses
to auto-request reviews. Two responsibilities don't map to a code path: @ncw
looks after overall project health, and @boukendesho maintains the snap
packaging.
| 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 |
## This is a work in progress draft
Generated
+2577 -7670
View File
File diff suppressed because it is too large. Load diff
Generated
+968 -5149
View File
File diff suppressed because it is too large. Load diff
Generated
+918 -5426
View File
File diff suppressed because it is too large. Load diff
+1 -27
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 ./...
@@ -171,7 +146,6 @@ MANUAL.txt: MANUAL.md
commanddocs: rclone
go generate ./lib/transform
go generate ./cmd/bisync
-@rmdir -p '$$HOME/.config/rclone'
XDG_CACHE_HOME="" XDG_CONFIG_HOME="" HOME="\$$HOME" USER="\$$USER" rclone gendocs --config=/notfound docs/content/
@[ ! -e '$$HOME' ] || (echo 'Error: created unwanted directory named $$HOME' && exit 1)
-6
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/)
@@ -112,7 +109,6 @@ directories to and from different cloud storage providers.
- RackCorp Object Storage [:page_facing_up:](https://rclone.org/s3/#RackCorp)
- rsync.net [:page_facing_up:](https://rclone.org/sftp/#rsync-net)
- Scaleway [:page_facing_up:](https://rclone.org/s3/#scaleway)
- Scality (RING / ARTESCA) [:page_facing_up:](https://rclone.org/s3/#scality)
- Seafile [:page_facing_up:](https://rclone.org/seafile/)
- Seagate Lyve Cloud [:page_facing_up:](https://rclone.org/s3/#lyve)
- SeaweedFS [:page_facing_up:](https://rclone.org/s3/#seaweedfs)
@@ -127,12 +123,10 @@ directories to and from different cloud storage providers.
- Synology C2 Object Storage [:page_facing_up:](https://rclone.org/s3/#synology-c2)
- Tencent Cloud Object Storage (COS) [:page_facing_up:](https://rclone.org/s3/#tencent-cos)
- Uloz.to [:page_facing_up:](https://rclone.org/ulozto/)
- US3 Object Storage [:page_facing_up:](https://rclone.org/s3/#us3)
- Wasabi [:page_facing_up:](https://rclone.org/s3/#wasabi)
- WebDAV [:page_facing_up:](https://rclone.org/webdav/)
- Yandex Disk [:page_facing_up:](https://rclone.org/yandex/)
- Zadara Object Storage [:page_facing_up:](https://rclone.org/s3/#zadara)
- Zero Services (ZERO-Z3) [:page_facing_up:](https://rclone.org/s3/#zero-z3)
- Zoho WorkDrive [:page_facing_up:](https://rclone.org/zoho/)
- Zata.ai [:page_facing_up:](https://rclone.org/s3/#Zata)
- The local filesystem [:page_facing_up:](https://rclone.org/local/)
+27 -31
View File
@@ -11,12 +11,11 @@ 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
- make tag
- edit docs/content/changelog.md # duplicate logs from point rels removed automatically
- edit docs/content/changelog.md # make sure to remove duplicate logs from point
releases
- make tidy
- make doc
@@ -33,20 +32,16 @@ This file describes how to make the various kinds of releases
- make sign_upload
- make check_sign
- make upload
- make upload_test_website # check sponsors are correct/unchanged
- make upload_website
- make upload_github
- make startdev # make startstable for stable branch
- \# announce with forum post, twitter post, and post to annoucements list
- \# announce with forum post, twitter post, patreon post
## Update dependencies
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 +54,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 +97,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 +191,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.75.0
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"
-58
View File
@@ -6,7 +6,6 @@ import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path"
@@ -220,60 +219,3 @@ func TestArchiveSquashfs(t *testing.T) {
run(t, "mksquashfs", input, output)
})
}
// TestArchiveSquashfsIssue9004 lists and reads squashfs images that exercise
// two layouts go-diskfs used to choke on (fixed in go-diskfs v1.9.4):
//
// - 1.sqfs: a single empty directory, so the image has no fragment table
// (its fragment-table start holds the "not present" sentinel).
// - 2.sqfs: a small tree whose superblock has the NO_XATTRS flag set while
// inodes still carry a (non-sentinel) xattr index - the shape squashfs-
// tools-ng can emit. Built by packing a two-file tree with xattrs via
// `gensquashfs -x`, then setting the NO_XATTRS superblock flag; the tree
// content is trivial placeholder data.
//
// Both images used to fail to list. Regression test for #9004.
func TestArchiveSquashfsIssue9004(t *testing.T) {
fstest.Initialise()
ctx := context.Background()
testdata, err := filepath.Abs(filepath.Join("squashfs", "testdata"))
require.NoError(t, err)
archiveFor := func(t *testing.T, name string) fs.Fs {
f, err := cache.Get(ctx, ":archive:"+filepath.Join(testdata, name))
require.NoError(t, err)
return f
}
t.Run("EmptyDir", func(t *testing.T) {
// 1.sqfs is a single empty directory - it must list without error.
entries, err := archiveFor(t, "1.sqfs").List(ctx, "")
require.NoError(t, err)
assert.Equal(t, 0, len(entries))
})
t.Run("NoXattrTree", func(t *testing.T) {
f := archiveFor(t, "2.sqfs")
entries, err := f.List(ctx, "")
require.NoError(t, err)
names := make([]string, 0, len(entries))
for _, e := range entries {
names = append(names, path.Base(e.Remote()))
}
assert.Contains(t, names, "alpha")
assert.Contains(t, names, "beta")
// A file in the tree must be readable with its real content.
obj, err := f.NewObject(ctx, "beta/sample.xml")
require.NoError(t, err)
assert.Greater(t, obj.Size(), int64(0))
rc, err := obj.Open(ctx)
require.NoError(t, err)
data, err := io.ReadAll(rc)
require.NoError(t, err)
require.NoError(t, rc.Close())
assert.Equal(t, int(obj.Size()), len(data))
assert.True(t, bytes.HasPrefix(data, []byte("<?xml")))
})
}
+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)
-5
View File
@@ -161,10 +161,5 @@ func (c *cache) Writable() (backend.WritableFile, error) {
return nil, errCacheNotImplemented
}
// Path returns the path to the underlying storage - not applicable here
func (c *cache) Path() string {
return ""
}
// check interfaces
var _ backend.Storage = (*cache)(nil)
+31 -67
View File
@@ -5,7 +5,6 @@ import (
"context"
"fmt"
"io"
"os"
"path"
"strings"
"time"
@@ -43,38 +42,15 @@ type Fs struct {
root string // position to read from within the archive
}
// recoverParsePanic converts a panic raised while parsing a squashfs image
// into an error assigned through err.
func recoverParsePanic(err *error) {
if r := recover(); r != nil {
*err = fmt.Errorf("invalid or corrupt squashfs image: %v", r)
}
}
// recoveringReadCloser wraps a reader returned by the go-diskfs parser so
// panics raised while reading become errors.
//
// The parser reads file data lazily, so an image which opens cleanly can
// still panic on the first Read.
type recoveringReadCloser struct {
io.ReadCloser
}
func (r recoveringReadCloser) Read(p []byte) (n int, err error) {
defer recoverParsePanic(&err)
return r.ReadCloser.Read(p)
}
// New constructs an Fs from the (wrappedFs, remote) with the objects
// prefix with prefix and rooted at root
func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (_ fs.Fs, err error) {
defer recoverParsePanic(&err)
func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (fs.Fs, error) {
// FIXME vfs cache?
// FIXME could factor out ReadFileHandle and just use that rather than the full VFS
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)
@@ -180,17 +156,6 @@ func (f *Fs) toNative(remote string) (string, error) {
return native, nil
}
// This turns a native path with a leading / into a path suitable for
// the squashfs library which requires io/fs.ValidPath paths with no
// leading / and "." for the root directory.
func toIOFS(native string) string {
native = strings.Trim(native, "/")
if native == "" {
return "."
}
return native
}
// Turn a (nativeDir, leaf) into a remote
func (f *Fs) fromNative(nativeDir string, leaf string) string {
// fs.Debugf(nil, "nativeDir = %q, leaf = %q, root=%q", nativeDir, leaf, f.root)
@@ -204,12 +169,13 @@ func (f *Fs) fromNative(nativeDir string, leaf string) string {
}
// Convert a FileInfo into an Object from native dir
func (f *Fs) objectFromFileInfo(nativeDir string, item os.FileInfo) *Object {
func (f *Fs) objectFromFileInfo(nativeDir string, item squashfs.FileStat) *Object {
return &Object{
fs: f,
remote: f.fromNative(nativeDir, item.Name()),
size: item.Size(),
modTime: item.ModTime(),
item: item,
}
}
@@ -224,38 +190,38 @@ func (f *Fs) objectFromFileInfo(nativeDir string, item os.FileInfo) *Object {
// found.
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
defer log.Trace(f, "dir=%q", dir)("entries=%v, err=%v", &entries, &err)
defer recoverParsePanic(&err)
nativeDir, err := f.toNative(dir)
if err != nil {
return nil, err
}
items, err := f.sqfs.ReadDir(toIOFS(nativeDir))
items, err := f.sqfs.ReadDir(nativeDir)
if err != nil {
return nil, fmt.Errorf("read squashfs: couldn't read directory: %w", err)
}
entries = make(fs.DirEntries, 0, len(items))
for _, item := range items {
for _, fi := range items {
item, ok := fi.(squashfs.FileStat)
if !ok {
return nil, fmt.Errorf("internal error: unexpected type for %q: %T", fi.Name(), fi)
}
// fs.Debugf(item.Name(), "entry = %#v", item)
var entry fs.DirEntry
if err != nil {
return nil, fmt.Errorf("error reading item %q: %q", item.Name(), err)
}
if item.IsDir() {
remote := f.fromNative(nativeDir, item.Name())
info, err := item.Info()
if err != nil {
return nil, fmt.Errorf("error reading item %q: %w", item.Name(), err)
}
entry = fs.NewDir(remote, info.ModTime())
} else if item.Type().IsRegular() {
info, err := item.Info()
if err != nil {
return nil, fmt.Errorf("error reading item %q: %w", item.Name(), err)
}
entry = f.objectFromFileInfo(nativeDir, info)
var remote = f.fromNative(nativeDir, item.Name())
entry = fs.NewDir(remote, item.ModTime())
} else {
fs.Debugf(item.Name(), "FIXME Not regular file - skipping")
continue
if item.Mode().IsRegular() {
entry = f.objectFromFileInfo(nativeDir, item)
} else {
fs.Debugf(item.Name(), "FIXME Not regular file - skipping")
continue
}
}
entries = append(entries, entry)
}
@@ -266,14 +232,13 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// newObjectNative finds the object at the native path passed in
func (f *Fs) newObjectNative(nativePath string) (o fs.Object, err error) {
defer recoverParsePanic(&err)
// get the path and filename
dir, leaf := path.Split(nativePath)
dir = strings.TrimRight(dir, "/")
leaf = strings.Trim(leaf, "/")
// FIXME need to detect directory not found
fis, err := f.sqfs.ReadDir(toIOFS(dir))
fis, err := f.sqfs.ReadDir(dir)
if err != nil {
return nil, fs.ErrorObjectNotFound
@@ -284,11 +249,11 @@ func (f *Fs) newObjectNative(nativePath string) (o fs.Object, err error) {
if fi.IsDir() {
return nil, fs.ErrorNotAFile
}
info, err := fi.Info()
if err != nil {
return nil, fmt.Errorf("error reading item %q: %w", fi.Name(), err)
item, ok := fi.(squashfs.FileStat)
if !ok {
return nil, fmt.Errorf("internal error: unexpected type for %q: %T", fi.Name(), fi)
}
o = f.objectFromFileInfo(dir, info)
o = f.objectFromFileInfo(dir, item)
break
}
}
@@ -363,6 +328,7 @@ type Object struct {
remote string
size int64
modTime time.Time
item squashfs.FileStat
}
// Fs returns read only access to the Fs that this object is part of
@@ -419,7 +385,6 @@ func (o *Object) Hash(ctx context.Context, ht hash.Type) (string, error) {
// Open opens the file for read. Call Close() on the returned io.ReadCloser
func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.ReadCloser, err error) {
defer recoverParsePanic(&err)
var offset, limit int64 = 0, -1
for _, option := range options {
switch x := option.(type) {
@@ -440,7 +405,8 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.Read
}
fs.Debugf(o, "Opening %q", remote)
fh, err := o.fs.sqfs.OpenFile(toIOFS(remote), os.O_RDONLY)
//fh, err := o.fs.sqfs.OpenFile(remote, os.O_RDONLY)
fh, err := o.item.Open()
if err != nil {
return nil, err
}
@@ -452,15 +418,13 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (rc io.Read
return nil, err
}
}
rc = recoveringReadCloser{fh}
// If limited then don't return everything
if limit >= 0 {
fs.Debugf(nil, "limit=%d, offset=%d, options=%v", limit, offset, options)
return readers.NewLimitedReadCloser(rc, limit), nil
return readers.NewLimitedReadCloser(fh, limit), nil
}
return rc, nil
return fh, nil
}
// Update in to the object with the modTime given of the given size
-25
View File
@@ -1,25 +0,0 @@
package squashfs
import (
"io"
"testing"
"github.com/stretchr/testify/assert"
)
// panickingReader panics on Read, standing in for the go-diskfs parser
// hitting an unchecked slice while reading a malformed image.
type panickingReader struct{}
func (panickingReader) Read([]byte) (int, error) { panic("boom") }
func (panickingReader) Close() error { return nil }
// Test that a panic raised while reading file data becomes an error. The
// parser reads lazily, so an image can open cleanly and only panic here.
func TestRecoveringReadCloser(t *testing.T) {
var rc io.ReadCloser = recoveringReadCloser{panickingReader{}}
_, err := rc.Read(make([]byte, 16))
assert.ErrorContains(t, err, "invalid or corrupt squashfs image")
assert.ErrorContains(t, err, "boom")
}
Binary file not shown.
Binary file not shown.
@@ -1,89 +0,0 @@
//go:build !plan9
package archive
import (
"context"
"encoding/binary"
"os"
"path/filepath"
"testing"
_ "github.com/rclone/rclone/backend/local"
"github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// squashfsSuperblock builds a minimal 96-byte squashfs superblock with the
// given attacker-controllable fields. It mirrors the on-disk layout the
// go-diskfs parser reads, and is only used to construct deliberately malformed
// images for the tests below.
func squashfsSuperblock(blockSize uint32, blockLog, compression uint16, rootInode, inodeTableStart uint64) []byte {
const u64max = ^uint64(0)
b := make([]byte, 96)
binary.LittleEndian.PutUint32(b[0:], 0x73717368) // "hsqs" magic
binary.LittleEndian.PutUint32(b[4:], 1) // inode count
binary.LittleEndian.PutUint32(b[8:], 0) // modtime
binary.LittleEndian.PutUint32(b[12:], blockSize)
binary.LittleEndian.PutUint32(b[16:], 0) // fragment count
binary.LittleEndian.PutUint16(b[20:], compression)
binary.LittleEndian.PutUint16(b[22:], blockLog)
binary.LittleEndian.PutUint16(b[24:], 0x0210) // no fragments/xattrs
binary.LittleEndian.PutUint16(b[26:], 0) // id count
binary.LittleEndian.PutUint16(b[28:], 4) // version major
binary.LittleEndian.PutUint16(b[30:], 0) // version minor
binary.LittleEndian.PutUint64(b[32:], rootInode)
binary.LittleEndian.PutUint64(b[40:], 96) // bytes used
binary.LittleEndian.PutUint64(b[48:], u64max)
binary.LittleEndian.PutUint64(b[56:], u64max)
binary.LittleEndian.PutUint64(b[64:], inodeTableStart)
binary.LittleEndian.PutUint64(b[72:], inodeTableStart)
binary.LittleEndian.PutUint64(b[80:], u64max)
binary.LittleEndian.PutUint64(b[88:], u64max)
return b
}
// TestArchiveSquashfsMalformed feeds the archive backend squashfs images whose
// superblock/metadata make the go-diskfs parser panic. See GHSA-6jcg-q3wp-x2f4.
func TestArchiveSquashfsMalformed(t *testing.T) {
fstest.Initialise()
ctx := context.Background()
// Variant 1: zero block size reaches an integer division in the parser.
zeroBlock := squashfsSuperblock(0, 0, 1, 0, 96)
// Variant 2: an out-of-range root inode byte offset reaches an unchecked
// slice against an empty, uncompressed metadata block.
oob := append(squashfsSuperblock(65536, 16, 1, 12336, 96), 0x00, 0x80)
binary.LittleEndian.PutUint64(oob[40:], uint64(len(oob)))
for _, tc := range []struct {
name string
image []byte
}{
{"ZeroBlockSize", zeroBlock},
{"OutOfRangeInodeOffset", oob},
} {
t.Run(tc.name, func(t *testing.T) {
// A directory per image: the fs cache keys on the parent
// directory, so sharing one would hand the second subtest a
// cached listing which does not contain its image.
path := filepath.Join(t.TempDir(), tc.name+".sqfs")
require.NoError(t, os.WriteFile(path, tc.image, 0o644))
// The whole point is that this returns rather than panicking and
// killing the test binary (and, in production, the serve daemon).
f, err := cache.Get(ctx, ":archive:"+path)
if err == nil {
// The image parsed, so the panic must surface from a later
// lazily-parsed operation instead.
_, err = f.List(ctx, "")
}
require.Error(t, err, "a malformed squashfs image must error, not panic")
assert.Contains(t, err.Error(), "invalid or corrupt squashfs image",
"error should come from the recover, not an unrelated failure")
})
}
}
+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)
-169
View File
@@ -1,169 +0,0 @@
//go:build !plan9 && !solaris && !js
// Parallel listing support for azureblob, built on the Apache Arrow
// listing format.
//
// The Arrow listing exposes the server-side startFrom (inclusive) and endBefore
// (exclusive) name-range parameters, which let a listing be sharded by
// blob-name range and listed concurrently.
package azureblob
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/rclone/rclone/backend/azureblob/arrowlist"
"github.com/rclone/rclone/fs"
"golang.org/x/sync/errgroup"
)
// listArrowParallel lists (containerName, directory) by splitting the blob name
// keyspace into shards and listing them concurrently. opts must already request
// the Arrow format; it is cloned per shard with StartFrom/EndBefore set. It
// returns the number of raw items seen. directory/prefix are already normalised
// by the caller.
func (f *Fs) listArrowParallel(ctx context.Context, containerName, directory, prefix string, addContainer bool, opts *arrowlist.ListBlobsHierarchyOptions, delimiter string, fn listFn) (int, error) {
// Parallel listing needs the arrowlist client (server-side endBefore is
// only honoured on the Arrow path) - without it fall back to sequential.
if _, err := f.arrowCntSVC(containerName); err != nil {
fs.Debugf(f, "Not using parallel Arrow listing: %v", err)
return f.listBlobsPager(ctx, containerName, directory, prefix, addContainer, opts, delimiter, fn)
}
// Split the keyspace by a single-case character ladder (see
// arrowLadderBoundaries for why single-case matters).
points := arrowLadderBoundaries(directory, arrowShardTarget(f.opt.ListParallelism))
if len(points) < 1 {
// Couldn't usefully split - list sequentially.
return f.listBlobsPager(ctx, containerName, directory, prefix, addContainer, opts, delimiter, fn)
}
// Build half-open [startFrom, endBefore) shards from the sorted boundary
// points p0..pk: ["", p0), [p0, p1), ..., [pk, "").
type shard struct{ startFrom, endBefore string }
shards := make([]shard, 0, len(points)+1)
prev := ""
for _, p := range points {
shards = append(shards, shard{prev, p})
prev = p
}
shards = append(shards, shard{prev, ""})
// fn (and the list.Helper behind it) is not concurrency-safe, so serialise
// delivery. Only the cheap callback is locked, not the HTTP/decode work.
var fnMu sync.Mutex
safeFn := func(remote string, item *container.BlobItem, isDir bool) error {
fnMu.Lock()
defer fnMu.Unlock()
return fn(remote, item, isDir)
}
// Schedule every shard; SetLimit bounds concurrency, so more shards than
// workers gives free load balancing as workers pick up the next shard.
var total int64
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(f.opt.ListParallelism)
for _, sh := range shards {
if gCtx.Err() != nil {
break
}
g.Go(func() error {
// Clone opts per shard so concurrent shards don't share StartFrom/EndBefore.
shardOpts := *opts
if sh.startFrom != "" {
startFrom := sh.startFrom
shardOpts.StartFrom = &startFrom
} else {
shardOpts.StartFrom = nil
}
if sh.endBefore != "" {
endBefore := sh.endBefore
shardOpts.EndBefore = &endBefore
} else {
shardOpts.EndBefore = nil
}
n, err := f.listBlobsPager(gCtx, containerName, directory, prefix, addContainer, &shardOpts, delimiter, safeFn)
atomic.AddInt64(&total, int64(n))
return err
})
}
err := g.Wait()
found := int(atomic.LoadInt64(&total))
if isEndBeforeUnsupported(err) {
// The account can't honour the shards' endBefore bounds, so parallel
// listing can't be used on it.
f.arrowXMLFallback.Store(true)
if found == 0 {
// No shard delivered anything yet (the normal case - Arrow listing
// enablement is per account so every shard fails on its first
// page) so it is safe to relist sequentially.
fs.Debugf(f, "Parallel Arrow listing not supported by this account (%v) - listing sequentially", err)
return f.listBlobsPager(ctx, containerName, directory, prefix, addContainer, opts, delimiter, fn)
}
// Some entries were already delivered so a rerun would duplicate them.
return found, fmt.Errorf("parallel listing aborted after partial results (retry, or unset list_parallelism): %w", err)
}
return found, err
}
// isEndBeforeUnsupported reports whether err means the service can't honour
// the endBefore listing bound, so sharded parallel listing must not be used.
//
// This happens two ways: the arrowlist pager's ErrEndBeforeXMLFallback (the
// server answered XML with endBefore set), or the service rejecting the
// endBefore parameter with 400 OperationNotSupportedWithFeatureMissing "The
// requested operation is not allowed as EndBefore parameter support is
// missing on this account" - endBefore is only supported on the Arrow
// listing path of accounts with Blob Listing with Apache Arrow enabled.
func isEndBeforeUnsupported(err error) bool {
if errors.Is(err, arrowlist.ErrEndBeforeXMLFallback) {
return true
}
var respErr *azcore.ResponseError
return errors.As(err, &respErr) && respErr.ErrorCode == "OperationNotSupportedWithFeatureMissing"
}
// arrowShardTarget is the number of ladder boundaries to use for the given
// parallelism (a few per worker for load balancing).
func arrowShardTarget(parallelism int) int {
return parallelism * 4
}
// arrowLadderBoundaries returns up to target sorted ENCODED-space boundaries of
// the form directory+c, used to split the keyspace into shards.
//
// The partition is always correct (no dup/gap) regardless of the alphabet: keys
// whose next byte is outside the alphabet simply fall into an adjacent shard;
// the alphabet only affects balance. A single-case (digit+lowercase) alphabet
// is deliberate: the boundaries are then monotonic under BOTH byte order (the
// listing order) AND the service's case-insensitive startFrom/endBefore
// validation, so server-side endBefore is accepted. (A mixed-case ladder gives
// pairs like [".../Z", ".../a") which are byte-ascending but rejected 400 as
// "endbefore precedes startfrom".) directory is already encoded; the alphabet
// is ASCII (encoder-invariant) and ascending, so the result is sorted.
func arrowLadderBoundaries(directory string, target int) []string {
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
if target < 1 {
return nil
}
if target > len(alphabet) {
target = len(alphabet)
}
points := make([]string, 0, target)
last := -1
for i := 0; i < target; i++ {
idx := i * len(alphabet) / target
if idx == last {
continue
}
last = idx
points = append(points, directory+string(alphabet[idx]))
}
return points
}
-221
View File
@@ -1,221 +0,0 @@
//go:build !plan9 && !solaris && !js
package azureblob
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/rclone/rclone/backend/azureblob/arrowlist"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// testArrowList exercises the experimental Apache Arrow listing.
//
// It is skipped automatically if Arrow listing is not enabled on the test
// account (the server returns XML, or 409 on HNS accounts).
func (f *Fs) testArrowList(t *testing.T) {
ctx := context.Background()
containerName, _ := f.split("probe")
if containerName == "" {
t.Skip("Arrow list test needs a container in the remote root")
}
// withArrow runs fn with UseArrowList temporarily set.
withArrow := func(on bool, fn func()) {
old := f.opt.UseArrowList
f.opt.UseArrowList = on
defer func() { f.opt.UseArrowList = old }()
fn()
}
// withParallel runs fn with ListParallelism temporarily set.
withParallel := func(n int, fn func()) {
old := f.opt.ListParallelism
f.opt.ListParallelism = n
defer func() { f.opt.ListParallelism = old }()
fn()
}
// Create a set of known objects under a unique directory: flat files plus
// one in a subdirectory (so we exercise both the flat and delimited paths).
dir := "arrow-list-" + random.String(8)
// Includes upper-case and digit first-characters: these byte-sort between
// the digit and lowercase ladder boundaries, so they verify the server's
// endBefore filtering is byte-ordered (not case-insensitive, which would
// drop them from a shard and make parallel != sequential).
objects := []string{"a.txt", "b.txt", "c.txt", "d.txt", "e.txt", "sub/x.txt", "Foo.txt", "Zoo.txt", "0num.txt", "9end.txt"}
wantSizes := map[string]int64{}
created := make([]string, 0, len(objects))
for i, n := range objects {
contents := random.String(10 + i)
remote := dir + "/" + n
item := fstest.NewItem(remote, contents, fstest.Time("2001-05-06T04:05:06.499Z"))
_ = fstests.PutTestContents(ctx, t, f, &item, contents, true)
created = append(created, remote)
wantSizes[remote] = int64(len(contents))
}
defer func() {
for _, remote := range created {
if o, err := f.NewObject(ctx, remote); err == nil {
_ = o.Remove(ctx)
}
}
}()
// listing returns remote->size for dir (dirs reported as size -1).
listing := func(recurse bool) (map[string]int64, error) {
got := map[string]int64{}
add := func(entries fs.DirEntries) error {
for _, e := range entries {
if o, ok := e.(fs.Object); ok {
got[e.Remote()] = o.Size()
} else {
got[e.Remote()] = -1
}
}
return nil
}
if recurse {
return got, f.ListR(ctx, dir, add)
}
entries, err := f.List(ctx, dir)
if err != nil {
return nil, err
}
_ = add(entries)
return got, nil
}
// Probe: is Arrow available? If not, skip cleanly.
var probeErr error
withArrow(true, func() { _, probeErr = listing(true) })
if probeErr != nil {
if strings.Contains(probeErr.Error(), "OperationNotSupportedWithFeatureMissing") || strings.Contains(probeErr.Error(), "409") {
t.Skipf("Arrow listing not available on this account: %v", probeErr)
}
require.NoError(t, probeErr)
}
// Arrow listing must equal XML listing, recursively and per-directory
// (including the "sub" subdirectory).
t.Run("EqualsXML", func(t *testing.T) {
for _, recurse := range []bool{true, false} {
var xml, arrow map[string]int64
var err error
withArrow(false, func() { xml, err = listing(recurse) })
require.NoError(t, err)
withArrow(true, func() { arrow, err = listing(recurse) })
require.NoError(t, err)
assert.Equal(t, xml, arrow, "recurse=%v: Arrow listing differs from XML", recurse)
}
// Recursive Arrow listing contains every object with the right size.
var arrow map[string]int64
withArrow(true, func() { arrow, _ = listing(true) })
for remote, size := range wantSizes {
assert.Equal(t, size, arrow[remote], remote)
}
// Single-directory Arrow listing reports "sub" as a directory.
var entries fs.DirEntries
withArrow(true, func() {
var err error
entries, err = f.List(ctx, dir)
require.NoError(t, err)
})
foundSubDir := false
for _, e := range entries {
if e.Remote() == dir+"/sub" {
_, isObj := e.(fs.Object)
foundSubDir = !isObj
}
}
assert.True(t, foundSubDir, "expected %q to be listed as a directory", dir+"/sub")
})
// Parallel listing must equal sequential listing, recursively and
// per-directory, including the "sub" subdirectory.
t.Run("ParallelEqualsSequential", func(t *testing.T) {
for _, recurse := range []bool{true, false} {
var seq, par map[string]int64
var err error
withArrow(true, func() {
withParallel(0, func() { seq, err = listing(recurse) })
require.NoError(t, err)
withParallel(8, func() { par, err = listing(recurse) })
require.NoError(t, err)
})
assert.Equal(t, seq, par, "recurse=%v: parallel listing differs from sequential", recurse)
}
})
// A tiny list_chunk forces each shard to span multiple Arrow pages, so this
// exercises pagination (startFrom+endBefore+marker resent together) inside a
// shard. The "sub/" boundary puts a.txt..e.txt in one shard => >1 page at
// chunk size 2.
t.Run("ParallelMultiPage", func(t *testing.T) {
oldChunk := f.opt.ListChunkSize
f.opt.ListChunkSize = 2
defer func() { f.opt.ListChunkSize = oldChunk }()
var seq, par map[string]int64
var err error
withArrow(true, func() {
withParallel(0, func() { seq, err = listing(true) })
require.NoError(t, err)
withParallel(8, func() { par, err = listing(true) })
require.NoError(t, err)
})
assert.Equal(t, seq, par)
for remote, size := range wantSizes {
assert.Equal(t, size, par[remote], remote)
}
})
}
func TestArrowLadderBoundaries(t *testing.T) {
for _, tc := range []struct {
directory string
target int
}{
{"", 8},
{"dir/", 16},
{"dir/", 100}, // capped at alphabet size
{"dir/", 1},
} {
points := arrowLadderBoundaries(tc.directory, tc.target)
require.NotEmpty(t, points)
assert.LessOrEqual(t, len(points), 62)
for i, p := range points {
assert.True(t, strings.HasPrefix(p, tc.directory), "boundary %q lacks prefix %q", p, tc.directory)
if i > 0 {
assert.Less(t, points[i-1], p, "boundaries not strictly ascending")
}
}
}
assert.Nil(t, arrowLadderBoundaries("dir/", 0))
// alphabet is single-case (digit+lowercase) so boundaries are monotonic
// under both byte order and case-insensitive order
pts := arrowLadderBoundaries("dir/", 36)
for _, p := range pts {
assert.Equal(t, p, strings.ToLower(p), "boundary must be lowercase: %q", p)
}
}
func TestIsEndBeforeUnsupported(t *testing.T) {
assert.True(t, isEndBeforeUnsupported(arrowlist.ErrEndBeforeXMLFallback))
assert.True(t, isEndBeforeUnsupported(fmt.Errorf("wrapped: %w", arrowlist.ErrEndBeforeXMLFallback)))
assert.True(t, isEndBeforeUnsupported(&azcore.ResponseError{ErrorCode: "OperationNotSupportedWithFeatureMissing"}))
assert.False(t, isEndBeforeUnsupported(&azcore.ResponseError{ErrorCode: "ContainerNotFound"}))
assert.False(t, isEndBeforeUnsupported(errors.New("some other error")))
assert.False(t, isEndBeforeUnsupported(nil))
}
-421
View File
@@ -1,421 +0,0 @@
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Adapted from internal/arrow/arrow.go in the Azure SDK for Go
// github.com/Azure/azure-sdk-for-go/sdk/storage/azblob at commit
// c6fa341ca22b (branch feature/storage/bifrost), retyped onto the SDK's
// public type aliases so it compiles against the released azblob module.
package arrowlist
import (
"encoding/base64"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/lease"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/ipc"
"github.com/apache/arrow-go/v18/arrow/memory"
)
const (
// ArrowContentType is the Content-Type for Apache Arrow IPC stream responses.
ArrowContentType = "application/vnd.apache.arrow.stream"
// ArrowAcceptHeader is the Accept header value to request Arrow format.
ArrowAcceptHeader = ArrowContentType
// resourceTypeBlobPrefix is the ResourceType value that identifies a virtual directory prefix
// in hierarchy listing responses. In XML, prefixes are separate <BlobPrefix> elements;
// in Arrow, all rows share the same schema and are distinguished by this field value.
resourceTypeBlobPrefix = "blobprefix"
)
// HandleFlatListResponse parses an Arrow IPC stream response into a ContainerClientListBlobFlatSegmentResponse.
func HandleFlatListResponse(resp *http.Response) (container.ListBlobsFlatResponse, error) {
result := container.ListBlobsFlatResponse{}
// Extract response headers
extractResponseHeaders(resp, &result.ClientRequestID, &result.ContentType, &result.Date, &result.RequestID, &result.Version)
// Parse Arrow IPC stream
items, nextMarker, err := parseArrowStream(resp.Body)
if err != nil {
return result, fmt.Errorf("failed to parse Arrow IPC response: %w", err)
}
result.ListBlobsFlatSegmentResponse = container.ListBlobsFlatSegmentResponse{
Segment: &container.BlobFlatListSegment{
BlobItems: items,
},
NextMarker: nextMarker,
}
return result, nil
}
// HandleHierarchyListResponse parses an Arrow IPC stream response into a ContainerClientListBlobHierarchySegmentResponse.
func HandleHierarchyListResponse(resp *http.Response) (container.ListBlobsHierarchyResponse, error) {
result := container.ListBlobsHierarchyResponse{}
extractResponseHeaders(resp, &result.ClientRequestID, &result.ContentType, &result.Date, &result.RequestID, &result.Version)
items, nextMarker, err := parseArrowStream(resp.Body)
if err != nil {
return result, fmt.Errorf("failed to parse Arrow IPC response: %w", err)
}
// Separate blob items from blob prefixes based on ResourceType field.
var blobItems []*container.BlobItem
var blobPrefixes []*container.BlobPrefix
for _, item := range items {
if item.Properties != nil && item.Properties.ResourceType != nil && *item.Properties.ResourceType == resourceTypeBlobPrefix {
blobPrefixes = append(blobPrefixes, &container.BlobPrefix{
Name: item.Name,
Properties: item.Properties,
})
} else {
blobItems = append(blobItems, item)
}
}
result.ListBlobsHierarchySegmentResponse = container.ListBlobsHierarchySegmentResponse{
Segment: &container.BlobHierarchyListSegment{
BlobItems: blobItems,
BlobPrefixes: blobPrefixes,
},
NextMarker: nextMarker,
}
return result, nil
}
func extractResponseHeaders(resp *http.Response, clientRequestID, contentType **string, date **time.Time, requestID, version **string) {
if val := resp.Header.Get("x-ms-client-request-id"); val != "" {
*clientRequestID = &val
}
if val := resp.Header.Get("Content-Type"); val != "" {
*contentType = &val
}
if val := resp.Header.Get("Date"); val != "" {
if t, err := time.Parse(time.RFC1123, val); err == nil {
*date = &t
}
}
if val := resp.Header.Get("x-ms-request-id"); val != "" {
*requestID = &val
}
if val := resp.Header.Get("x-ms-version"); val != "" {
*version = &val
}
}
// parseArrowStream reads an Arrow IPC stream and converts it to BlobItems.
func parseArrowStream(body io.Reader) ([]*container.BlobItem, *string, error) {
reader, err := ipc.NewReader(body, ipc.WithAllocator(memory.DefaultAllocator))
if err != nil {
return nil, nil, fmt.Errorf("failed to create Arrow IPC reader: %w", err)
}
defer reader.Release()
// Extract NextMarker from schema metadata
var nextMarker *string
var numRecords int
if md := reader.Schema().Metadata(); md.Len() > 0 {
if idx := md.FindKey("NextMarker"); idx >= 0 {
val := md.Values()[idx]
if val != "" {
nextMarker = &val
}
}
if idx := md.FindKey("NumberOfRecords"); idx >= 0 {
if n, err := strconv.Atoi(md.Values()[idx]); err == nil {
numRecords = n
}
}
}
// Build column index for the schema
schema := reader.Schema()
colIndex := buildColumnIndex(schema)
// Pre-allocate if we know the count
items := make([]*container.BlobItem, 0, numRecords)
// Iterate over record batches
for reader.Next() {
rec := reader.RecordBatch()
rows := int(rec.NumRows())
for row := 0; row < rows; row++ {
item := &container.BlobItem{
Properties: &container.BlobProperties{},
}
populateBlobItem(item, rec, row, colIndex)
items = append(items, item)
}
}
if err := reader.Err(); err != nil {
return nil, nil, fmt.Errorf("error reading Arrow record batches: %w", err)
}
return items, nextMarker, nil
}
// columnIndex maps column names to their indices in the record batch for O(1) lookup.
type columnIndex map[string]int
func buildColumnIndex(schema *arrow.Schema) columnIndex {
idx := make(columnIndex, len(schema.Fields()))
for i, f := range schema.Fields() {
idx[f.Name] = i
}
return idx
}
// populateBlobItem fills a BlobItem from a single row across all columns.
func populateBlobItem(item *container.BlobItem, rec arrow.RecordBatch, row int, colIdx columnIndex) {
// Top-level BlobItem fields
item.Name = getStringField(rec, row, colIdx, "Name")
item.Deleted = getBoolField(rec, row, colIdx, "Deleted")
item.Snapshot = getStringField(rec, row, colIdx, "Snapshot")
item.VersionID = getStringField(rec, row, colIdx, "VersionId")
item.IsCurrentVersion = getBoolField(rec, row, colIdx, "IsCurrentVersion")
item.HasVersionsOnly = getBoolField(rec, row, colIdx, "HasVersionsOnly")
// Metadata maps
item.Metadata = getMapField(rec, row, colIdx, "Metadata")
item.OrMetadata = getMapField(rec, row, colIdx, "OrMetadata")
// Tags
if tags := getMapField(rec, row, colIdx, "Tags"); tags != nil {
var blobTags []*container.BlobTag
for k, v := range tags {
key := k
blobTags = append(blobTags, &container.BlobTag{Key: &key, Value: v})
}
item.BlobTags = &container.BlobTags{BlobTagSet: blobTags}
}
// BlobProperties fields
p := item.Properties
p.CreationTime = getTimestampField(rec, row, colIdx, "Creation-Time")
p.LastModified = getTimestampField(rec, row, colIdx, "Last-Modified")
p.ETag = getETagField(rec, row, colIdx, "Etag")
p.ContentLength = getInt64Field(rec, row, colIdx, "Content-Length")
p.ContentType = getStringField(rec, row, colIdx, "Content-Type")
p.ContentEncoding = getStringField(rec, row, colIdx, "Content-Encoding")
p.ContentLanguage = getStringField(rec, row, colIdx, "Content-Language")
p.ContentDisposition = getStringField(rec, row, colIdx, "Content-Disposition")
p.CacheControl = getStringField(rec, row, colIdx, "Cache-Control")
p.ContentMD5 = getBase64BytesField(rec, row, colIdx, "Content-MD5")
p.BlobType = getEnumField[container.BlobType](rec, row, colIdx, "BlobType")
p.AccessTier = getEnumField[container.AccessTier](rec, row, colIdx, "AccessTier")
p.AccessTierInferred = getBoolField(rec, row, colIdx, "AccessTierInferred")
p.AccessTierChangeTime = getTimestampField(rec, row, colIdx, "AccessTierChangeTime")
p.LeaseState = getEnumField[lease.StateType](rec, row, colIdx, "LeaseState")
p.LeaseStatus = getEnumField[lease.StatusType](rec, row, colIdx, "LeaseStatus")
p.LeaseDuration = getEnumField[lease.DurationType](rec, row, colIdx, "LeaseDuration")
p.ServerEncrypted = getBoolField(rec, row, colIdx, "ServerEncrypted")
p.CustomerProvidedKeySHA256 = getStringField(rec, row, colIdx, "CustomerProvidedKeySha256")
p.EncryptionScope = getStringField(rec, row, colIdx, "EncryptionScope")
p.IncrementalCopy = getBoolField(rec, row, colIdx, "IncrementalCopy")
p.IsSealed = getBoolField(rec, row, colIdx, "Sealed")
p.ArchiveStatus = getEnumField[container.ArchiveStatus](rec, row, colIdx, "ArchiveStatus")
p.RehydratePriority = getEnumField[blob.RehydratePriority](rec, row, colIdx, "RehydratePriority")
p.CopyID = getStringField(rec, row, colIdx, "CopyId")
p.CopyStatus = getEnumField[blob.CopyStatusType](rec, row, colIdx, "CopyStatus")
p.CopySource = getStringField(rec, row, colIdx, "CopySource")
p.CopyProgress = getStringField(rec, row, colIdx, "CopyProgress")
p.CopyCompletionTime = getTimestampField(rec, row, colIdx, "CopyCompletionTime")
p.CopyStatusDescription = getStringField(rec, row, colIdx, "CopyStatusDescription")
p.DestinationSnapshot = getStringField(rec, row, colIdx, "CopyDestinationSnapshot")
p.ImmutabilityPolicyExpiresOn = getTimestampField(rec, row, colIdx, "ImmutabilityPolicyUntilDate")
p.ImmutabilityPolicyMode = getEnumField[container.ImmutabilityPolicyMode](rec, row, colIdx, "ImmutabilityPolicyMode")
p.LegalHold = getBoolField(rec, row, colIdx, "LegalHold")
p.DeletedTime = getTimestampField(rec, row, colIdx, "DeletedTime")
p.RemainingRetentionDays = getInt32Field(rec, row, colIdx, "RemainingRetentionDays")
p.LastAccessedOn = getTimestampField(rec, row, colIdx, "LastAccessTime")
p.TagCount = getInt32Field(rec, row, colIdx, "TagCount")
p.BlobSequenceNumber = getInt64Field(rec, row, colIdx, "x-ms-blob-sequence-number")
p.ResourceType = getStringField(rec, row, colIdx, "ResourceType")
// Content-CRC64 is a string field in Arrow but not directly mapped to BlobProperties.
// The field exists in the Arrow schema but has no corresponding field in the Go SDK BlobProperties.
// It is silently ignored for forward compatibility.
}
// Field accessor helpers that safely handle missing columns and null values.
func getStringField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *string {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
if arr, ok := col.(*array.String); ok {
val := arr.Value(row)
return &val
}
return nil
}
func getBoolField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *bool {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
if arr, ok := col.(*array.Boolean); ok {
val := arr.Value(row)
return &val
}
return nil
}
func getTimestampField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *time.Time {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
if arr, ok := col.(*array.Timestamp); ok {
val := arr.Value(row)
// Arrow timestamps are stored as int64 with a unit; convert to time.Time
dt := val.ToTime(arr.DataType().(*arrow.TimestampType).Unit)
return &dt
}
return nil
}
func getInt64Field(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *int64 {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
if arr, ok := col.(*array.Uint64); ok {
val := int64(arr.Value(row))
return &val
}
if arr, ok := col.(*array.Int64); ok {
val := arr.Value(row)
return &val
}
return nil
}
func getInt32Field(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *int32 {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
if arr, ok := col.(*array.Uint64); ok {
val := int32(arr.Value(row))
return &val
}
if arr, ok := col.(*array.Int32); ok {
val := arr.Value(row)
return &val
}
return nil
}
func getETagField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *azcore.ETag {
s := getStringField(rec, row, colIdx, name)
if s == nil {
return nil
}
etag := azcore.ETag(*s)
return &etag
}
func getBase64BytesField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) []byte {
s := getStringField(rec, row, colIdx, name)
if s == nil {
return nil
}
decoded, err := base64.StdEncoding.DecodeString(*s)
if err != nil {
return nil
}
return decoded
}
// getEnumField returns a pointer to a string-typed enum value.
type stringEnum interface {
~string
}
func getEnumField[T stringEnum](rec arrow.RecordBatch, row int, colIdx columnIndex, name string) *T {
s := getStringField(rec, row, colIdx, name)
if s == nil {
return nil
}
val := T(*s)
return &val
}
func getMapField(rec arrow.RecordBatch, row int, colIdx columnIndex, name string) map[string]*string {
idx, ok := colIdx[name]
if !ok {
return nil
}
col := rec.Column(idx)
if col.IsNull(row) {
return nil
}
mapArr, ok := col.(*array.Map)
if !ok {
return nil
}
// Get the offsets for this row's map entries
start := int(mapArr.Offsets()[row])
end := int(mapArr.Offsets()[row+1])
if start == end {
return nil
}
keys := mapArr.Keys().(*array.String)
values := mapArr.Items().(*array.String)
result := make(map[string]*string, end-start)
for i := start; i < end; i++ {
k := keys.Value(i)
if values.IsNull(i) {
result[k] = nil
} else {
v := values.Value(i)
result[k] = &v
}
}
return result
}
-374
View File
@@ -1,374 +0,0 @@
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Adapted from internal/arrow/arrow_test.go in the Azure SDK for Go
// github.com/Azure/azure-sdk-for-go/sdk/storage/azblob at commit
// c6fa341ca22b (branch feature/storage/bifrost).
package arrowlist
import (
"bytes"
"io"
"net/http"
"testing"
"github.com/apache/arrow-go/v18/arrow"
arrowArray "github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/ipc"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/stretchr/testify/require"
)
// coreSchema returns a basic Arrow schema for testing with common blob fields.
func coreSchema(md *arrow.Metadata) *arrow.Schema {
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "Creation-Time", Type: &arrow.TimestampType{Unit: arrow.Microsecond}, Nullable: true},
{Name: "Last-Modified", Type: &arrow.TimestampType{Unit: arrow.Microsecond}, Nullable: true},
{Name: "BlobType", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "Etag", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "Content-Length", Type: arrow.PrimitiveTypes.Uint64, Nullable: true},
{Name: "Content-Type", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "ServerEncrypted", Type: arrow.FixedWidthTypes.Boolean, Nullable: true},
{Name: "AccessTier", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "LeaseState", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "LeaseStatus", Type: arrow.BinaryTypes.String, Nullable: true},
}
return arrow.NewSchema(fields, md)
}
// buildArrowStream constructs a synthetic Arrow IPC stream from a schema and a populate function.
func buildArrowStream(t *testing.T, schema *arrow.Schema, populate func(builder *arrowArray.RecordBuilder)) []byte {
t.Helper()
alloc := memory.DefaultAllocator
var buf bytes.Buffer
w := ipc.NewWriter(&buf, ipc.WithSchema(schema), ipc.WithAllocator(alloc))
builder := arrowArray.NewRecordBuilder(alloc, schema)
defer builder.Release()
populate(builder)
rec := builder.NewRecordBatch()
defer rec.Release()
require.NoError(t, w.Write(rec))
require.NoError(t, w.Close())
return buf.Bytes()
}
func makeHTTPResponse(data []byte, headers map[string]string) *http.Response {
h := http.Header{}
h.Set("Content-Type", ArrowContentType)
for k, v := range headers {
h.Set(k, v)
}
return &http.Response{
StatusCode: http.StatusOK,
Header: h,
Body: io.NopCloser(bytes.NewReader(data)),
}
}
func TestHandleFlatListResponse_BasicParsing(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker", "NumberOfRecords"}, []string{"marker123", "2"})
schema := coreSchema(&md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob1.txt")
b.Field(1).(*arrowArray.TimestampBuilder).Append(arrow.Timestamp(1700000000000000))
b.Field(2).(*arrowArray.TimestampBuilder).Append(arrow.Timestamp(1700000000000000))
b.Field(3).(*arrowArray.StringBuilder).Append("BlockBlob")
b.Field(4).(*arrowArray.StringBuilder).Append("0x1234")
b.Field(5).(*arrowArray.Uint64Builder).Append(1024)
b.Field(6).(*arrowArray.StringBuilder).Append("application/octet-stream")
b.Field(7).(*arrowArray.BooleanBuilder).Append(true)
b.Field(8).(*arrowArray.StringBuilder).Append("Hot")
b.Field(9).(*arrowArray.StringBuilder).Append("available")
b.Field(10).(*arrowArray.StringBuilder).Append("unlocked")
b.Field(0).(*arrowArray.StringBuilder).Append("blob2.txt")
b.Field(1).(*arrowArray.TimestampBuilder).Append(arrow.Timestamp(1700000001000000))
b.Field(2).(*arrowArray.TimestampBuilder).Append(arrow.Timestamp(1700000001000000))
b.Field(3).(*arrowArray.StringBuilder).Append("BlockBlob")
b.Field(4).(*arrowArray.StringBuilder).Append("0x5678")
b.Field(5).(*arrowArray.Uint64Builder).Append(2048)
b.Field(6).(*arrowArray.StringBuilder).Append("text/plain")
b.Field(7).(*arrowArray.BooleanBuilder).Append(false)
b.Field(8).(*arrowArray.StringBuilder).Append("Cool")
b.Field(9).(*arrowArray.StringBuilder).Append("available")
b.Field(10).(*arrowArray.StringBuilder).Append("unlocked")
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.NotNil(t, result.NextMarker)
require.Equal(t, "marker123", *result.NextMarker)
require.Len(t, result.Segment.BlobItems, 2)
item := result.Segment.BlobItems[0]
require.Equal(t, "blob1.txt", *item.Name)
require.Equal(t, "BlockBlob", string(*item.Properties.BlobType))
require.Equal(t, int64(1024), *item.Properties.ContentLength)
require.Equal(t, "Hot", string(*item.Properties.AccessTier))
}
func TestHandleFlatListResponse_EmptyRecordBatch(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker", "NumberOfRecords"}, []string{"", "0"})
schema := coreSchema(&md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
// No rows added
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Nil(t, result.NextMarker)
require.Empty(t, result.Segment.BlobItems)
}
func TestHandleFlatListResponse_NullFields(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
schema := coreSchema(&md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob.txt")
b.Field(1).(*arrowArray.TimestampBuilder).AppendNull()
b.Field(2).(*arrowArray.TimestampBuilder).AppendNull()
b.Field(3).(*arrowArray.StringBuilder).AppendNull()
b.Field(4).(*arrowArray.StringBuilder).AppendNull()
b.Field(5).(*arrowArray.Uint64Builder).AppendNull()
b.Field(6).(*arrowArray.StringBuilder).AppendNull()
b.Field(7).(*arrowArray.BooleanBuilder).AppendNull()
b.Field(8).(*arrowArray.StringBuilder).AppendNull()
b.Field(9).(*arrowArray.StringBuilder).AppendNull()
b.Field(10).(*arrowArray.StringBuilder).AppendNull()
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Len(t, result.Segment.BlobItems, 1)
item := result.Segment.BlobItems[0]
require.Equal(t, "blob.txt", *item.Name)
require.Nil(t, item.Properties.CreationTime)
require.Nil(t, item.Properties.BlobType)
require.Nil(t, item.Properties.ETag)
require.Nil(t, item.Properties.ContentLength)
require.Nil(t, item.Properties.ContentType)
require.Nil(t, item.Properties.ServerEncrypted)
}
func TestHandleFlatListResponse_UnknownColumnsIgnored(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "FutureField", Type: arrow.BinaryTypes.String, Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob.txt")
b.Field(1).(*arrowArray.StringBuilder).Append("some-future-value")
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Len(t, result.Segment.BlobItems, 1)
require.Equal(t, "blob.txt", *result.Segment.BlobItems[0].Name)
}
func TestHandleFlatListResponse_MultiRecordBatch(t *testing.T) {
alloc := memory.DefaultAllocator
md := arrow.NewMetadata([]string{"NextMarker", "NumberOfRecords"}, []string{"", "3"})
schema := coreSchema(&md)
var buf bytes.Buffer
w := ipc.NewWriter(&buf, ipc.WithSchema(schema), ipc.WithAllocator(alloc))
// First batch: 2 rows
builder := arrowArray.NewRecordBuilder(alloc, schema)
for i := 0; i < 2; i++ {
builder.Field(0).(*arrowArray.StringBuilder).Append("batch1_blob")
for j := 1; j < 11; j++ {
builder.Field(j).AppendNull()
}
}
rec := builder.NewRecordBatch()
require.NoError(t, w.Write(rec))
rec.Release()
builder.Release()
// Second batch: 1 row
builder = arrowArray.NewRecordBuilder(alloc, schema)
builder.Field(0).(*arrowArray.StringBuilder).Append("batch2_blob")
for j := 1; j < 11; j++ {
builder.Field(j).AppendNull()
}
rec = builder.NewRecordBatch()
require.NoError(t, w.Write(rec))
rec.Release()
builder.Release()
require.NoError(t, w.Close())
resp := makeHTTPResponse(buf.Bytes(), nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Len(t, result.Segment.BlobItems, 3)
}
func TestHandleHierarchyListResponse_SeparatesBlobsAndPrefixes(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "ResourceType", Type: arrow.BinaryTypes.String, Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
// A regular blob
b.Field(0).(*arrowArray.StringBuilder).Append("folder/file.txt")
b.Field(1).(*arrowArray.StringBuilder).AppendNull()
// A blob prefix (virtual directory)
b.Field(0).(*arrowArray.StringBuilder).Append("folder/subfolder/")
b.Field(1).(*arrowArray.StringBuilder).Append("blobprefix")
})
resp := makeHTTPResponse(data, nil)
result, err := HandleHierarchyListResponse(resp)
require.NoError(t, err)
require.Len(t, result.Segment.BlobItems, 1)
require.Equal(t, "folder/file.txt", *result.Segment.BlobItems[0].Name)
require.Len(t, result.Segment.BlobPrefixes, 1)
require.Equal(t, "folder/subfolder/", *result.Segment.BlobPrefixes[0].Name)
}
func TestHandleFlatListResponse_ResponseHeaders(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob.txt")
})
resp := makeHTTPResponse(data, map[string]string{
"x-ms-request-id": "req-123",
"x-ms-version": "2026-10-06",
"x-ms-client-request-id": "client-req-456",
"Date": "Mon, 01 Jan 2024 00:00:00 GMT",
})
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Equal(t, "req-123", *result.RequestID)
require.Equal(t, "2026-10-06", *result.Version)
require.Equal(t, "client-req-456", *result.ClientRequestID)
require.NotNil(t, result.Date)
}
func TestHandleFlatListResponse_MapFields(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "Metadata", Type: arrow.MapOf(arrow.BinaryTypes.String, arrow.BinaryTypes.String), Nullable: true},
{Name: "Tags", Type: arrow.MapOf(arrow.BinaryTypes.String, arrow.BinaryTypes.String), Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob.txt")
metaBuilder := b.Field(1).(*arrowArray.MapBuilder)
metaBuilder.Append(true)
metaBuilder.KeyBuilder().(*arrowArray.StringBuilder).Append("key1")
metaBuilder.ItemBuilder().(*arrowArray.StringBuilder).Append("value1")
tagBuilder := b.Field(2).(*arrowArray.MapBuilder)
tagBuilder.Append(true)
tagBuilder.KeyBuilder().(*arrowArray.StringBuilder).Append("env")
tagBuilder.ItemBuilder().(*arrowArray.StringBuilder).Append("prod")
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
require.Len(t, result.Segment.BlobItems, 1)
item := result.Segment.BlobItems[0]
require.NotNil(t, item.Metadata)
require.Equal(t, "value1", *item.Metadata["key1"])
require.NotNil(t, item.BlobTags)
require.Len(t, item.BlobTags.BlobTagSet, 1)
}
func TestHandleFlatListResponse_BooleanFields(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "Deleted", Type: arrow.FixedWidthTypes.Boolean, Nullable: true},
{Name: "IsCurrentVersion", Type: arrow.FixedWidthTypes.Boolean, Nullable: true},
{Name: "ServerEncrypted", Type: arrow.FixedWidthTypes.Boolean, Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("blob.txt")
b.Field(1).(*arrowArray.BooleanBuilder).Append(true)
b.Field(2).(*arrowArray.BooleanBuilder).Append(false)
b.Field(3).(*arrowArray.BooleanBuilder).Append(true)
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
item := result.Segment.BlobItems[0]
require.True(t, *item.Deleted)
require.False(t, *item.IsCurrentVersion)
require.True(t, *item.Properties.ServerEncrypted)
}
func TestHandleFlatListResponse_VersionAndSnapshot(t *testing.T) {
md := arrow.NewMetadata([]string{"NextMarker"}, []string{""})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "VersionId", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "Snapshot", Type: arrow.BinaryTypes.String, Nullable: true},
{Name: "IsCurrentVersion", Type: arrow.FixedWidthTypes.Boolean, Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
data := buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append("versioned-blob.txt")
b.Field(1).(*arrowArray.StringBuilder).Append("2024-01-01T00:00:00.0000000Z")
b.Field(2).(*arrowArray.StringBuilder).Append("snap-123")
b.Field(3).(*arrowArray.BooleanBuilder).Append(true)
})
resp := makeHTTPResponse(data, nil)
result, err := HandleFlatListResponse(resp)
require.NoError(t, err)
item := result.Segment.BlobItems[0]
require.Equal(t, "2024-01-01T00:00:00.0000000Z", *item.VersionID)
require.Equal(t, "snap-123", *item.Snapshot)
require.True(t, *item.IsCurrentVersion)
}
-259
View File
@@ -1,259 +0,0 @@
//go:build !plan9 && !solaris && !js
// Package arrowlist implements the experimental "Blob Listing with Apache
// Arrow" feature on top of the released Azure azblob SDK.
//
// The Azure SDK for Go has support for Arrow listing on the unreleased
// feature/storage/bifrost branch (commit c6fa341ca22b) where the listing
// pagers decode Arrow IPC stream responses into the ordinary ListBlobs
// response types. Until that ships in a tagged azblob release this package
// fills the gap: it exposes the same options and pager interface as the
// experimental SDK, built only on the public API of the released SDK plus
// copies of two small internal auth policies (see sharedkey.go and
// challenge_policy.go).
//
// This package is temporary. When Arrow listing ships in a released azblob
// the whole package should be deleted and its callers pointed back at
// container.Client.NewListBlobsHierarchyPager - the option and response
// types here are deliberately source compatible with the SDK's to make that
// a mechanical change.
package arrowlist
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
)
const (
// moduleName and moduleVersion identify this package in the azcore
// telemetry policy's User-Agent fragment.
moduleName = "github.com/rclone/rclone/backend/azureblob/arrowlist"
moduleVersion = "v0.0.1"
// serviceVersion is the x-ms-version sent with listing requests. Arrow
// responses and the startFrom/endBefore parameters need at least
// 2026-06-06.
serviceVersion = "2026-06-06"
// tokenScope is the OAuth scope for Azure Storage, as used by the SDK's
// own clients.
tokenScope = "https://storage.azure.com/.default"
)
// ErrEndBeforeXMLFallback is returned by the pager when the server answered
// with XML instead of Arrow while EndBefore was set. The service only honours
// endBefore on the Arrow listing path, so an XML page could silently contain
// blobs outside the requested range and cannot be used.
var ErrEndBeforeXMLFallback = errors.New("arrow listing fell back to XML with endBefore set")
// ListBlobsHierarchyOptions provides the configuration for
// Client.NewListBlobsHierarchyPager.
//
// It mirrors the experimental SDK's container.ListBlobsHierarchyOptions:
// the released SDK's options are embedded (providing Include, Marker,
// MaxResults, Prefix and StartFrom by promotion) with the two fields the
// released SDK lacks added alongside.
type ListBlobsHierarchyOptions struct {
container.ListBlobsHierarchyOptions
// EndBefore limits listing to blobs whose full container path is
// lexically before it (exclusive). Only honoured on Arrow responses.
EndBefore *string
// UseArrowFormat requests the response as an Apache Arrow IPC stream.
UseArrowFormat *bool
}
// ClientOptions contains the optional parameters for client creation.
type ClientOptions struct {
azcore.ClientOptions
}
// Client issues Arrow listing requests to a single container.
type Client struct {
endpoint string
azClient *azcore.Client
}
// newClient creates a Client for the container at containerURL sending
// requests through a pipeline with the given auth policy (which may be nil
// for anonymous or SAS access).
func newClient(containerURL string, authPolicy policy.Policy, options *ClientOptions) (*Client, error) {
if options == nil {
options = &ClientOptions{}
}
plOpts := runtime.PipelineOptions{}
if authPolicy != nil {
plOpts.PerRetry = []policy.Policy{authPolicy}
}
azClient, err := azcore.NewClient(moduleName, moduleVersion, plOpts, &options.ClientOptions)
if err != nil {
return nil, err
}
return &Client{
endpoint: containerURL,
azClient: azClient,
}, nil
}
// NewClient creates a Client authenticating with a token credential.
func NewClient(containerURL string, cred azcore.TokenCredential, options *ClientOptions) (*Client, error) {
return newClient(containerURL, NewStorageChallengePolicy(cred, tokenScope, false), options)
}
// NewClientWithNoCredential creates a Client with no authentication, for
// anonymous access or a containerURL carrying a SAS token in its query.
func NewClientWithNoCredential(containerURL string, options *ClientOptions) (*Client, error) {
return newClient(containerURL, nil, options)
}
// NewClientWithSharedKeyCredential creates a Client signing requests with the
// account's shared key.
func NewClientWithSharedKeyCredential(containerURL string, cred *SharedKeyCredential, options *ClientOptions) (*Client, error) {
return newClient(containerURL, NewSharedKeyCredPolicy(cred), options)
}
// NewListBlobsHierarchyPager returns a pager over the container's blobs,
// requesting Arrow responses when o.UseArrowFormat is set and returning the
// same response type as container.Client.NewListBlobsHierarchyPager.
//
// If the service does not support Arrow listing (the feature not enabled on
// the account, or an HNS account) it answers with XML, which is decoded
// transparently - unless EndBefore is set, in which case the fetcher returns
// ErrEndBeforeXMLFallback (see there).
func (c *Client) NewListBlobsHierarchyPager(delimiter string, o *ListBlobsHierarchyOptions) *runtime.Pager[container.ListBlobsHierarchyResponse] {
// Copy the options so advancing the Marker doesn't mutate the caller's struct.
opts := ListBlobsHierarchyOptions{}
if o != nil {
opts = *o
}
useArrow := opts.UseArrowFormat != nil && *opts.UseArrowFormat
return runtime.NewPager(runtime.PagingHandler[container.ListBlobsHierarchyResponse]{
More: func(page container.ListBlobsHierarchyResponse) bool {
return page.NextMarker != nil && len(*page.NextMarker) > 0
},
Fetcher: func(ctx context.Context, page *container.ListBlobsHierarchyResponse) (container.ListBlobsHierarchyResponse, error) {
if page != nil {
opts.Marker = page.NextMarker
}
req, err := c.listCreateRequest(ctx, delimiter, &opts, useArrow)
if err != nil {
return container.ListBlobsHierarchyResponse{}, err
}
resp, err := c.azClient.Pipeline().Do(req)
if err != nil {
return container.ListBlobsHierarchyResponse{}, err
}
if !runtime.HasStatusCode(resp, http.StatusOK) {
return container.ListBlobsHierarchyResponse{}, runtime.NewResponseError(resp)
}
if useArrow && resp.Header.Get("Content-Type") == ArrowContentType {
return HandleHierarchyListResponse(resp)
}
if opts.EndBefore != nil {
return container.ListBlobsHierarchyResponse{}, ErrEndBeforeXMLFallback
}
return handleXMLResponse(resp)
},
})
}
// listCreateRequest builds the ListBlobs request, mirroring the generated
// request builders in the SDK.
func (c *Client) listCreateRequest(ctx context.Context, delimiter string, opts *ListBlobsHierarchyOptions, useArrow bool) (*policy.Request, error) {
req, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
// Reading the existing query first preserves any SAS token in the endpoint.
reqQP := req.Raw().URL.Query()
reqQP.Set("comp", "list")
reqQP.Set("restype", "container")
reqQP.Set("delimiter", delimiter)
if include := formatInclude(opts.Include); include != "" {
reqQP.Set("include", include)
}
if opts.Marker != nil {
reqQP.Set("marker", *opts.Marker)
}
if opts.MaxResults != nil {
reqQP.Set("maxresults", strconv.FormatInt(int64(*opts.MaxResults), 10))
}
if opts.Prefix != nil {
reqQP.Set("prefix", *opts.Prefix)
}
if opts.StartFrom != nil {
reqQP.Set("startFrom", *opts.StartFrom)
}
if useArrow && opts.EndBefore != nil {
reqQP.Set("endBefore", *opts.EndBefore)
}
req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")
if useArrow {
// Stream the Arrow body rather than buffering it in the pipeline.
runtime.SkipBodyDownload(req)
req.Raw().Header["Accept"] = []string{ArrowAcceptHeader}
} else {
req.Raw().Header["Accept"] = []string{"application/xml"}
}
req.Raw().Header["x-ms-version"] = []string{serviceVersion}
return req, nil
}
// handleXMLResponse decodes an XML ListBlobs response, mirroring the SDK's
// generated ListBlobHierarchySegmentHandleResponse.
func handleXMLResponse(resp *http.Response) (container.ListBlobsHierarchyResponse, error) {
result := container.ListBlobsHierarchyResponse{}
extractResponseHeaders(resp, &result.ClientRequestID, &result.ContentType, &result.Date, &result.RequestID, &result.Version)
if err := runtime.UnmarshalAsXML(resp, &result.ListBlobsHierarchySegmentResponse); err != nil {
return container.ListBlobsHierarchyResponse{}, err
}
return result, nil
}
// formatInclude renders the include datasets as the comma separated query
// parameter value, in the same order as the SDK's unexported
// ListBlobsInclude.format.
func formatInclude(l container.ListBlobsInclude) string {
var include []string
if l.Copy {
include = append(include, "copy")
}
if l.Deleted {
include = append(include, "deleted")
}
if l.DeletedWithVersions {
include = append(include, "deletedwithversions")
}
if l.ImmutabilityPolicy {
include = append(include, "immutabilitypolicy")
}
if l.LegalHold {
include = append(include, "legalhold")
}
if l.Metadata {
include = append(include, "metadata")
}
if l.Snapshots {
include = append(include, "snapshots")
}
if l.Tags {
include = append(include, "tags")
}
if l.UncommittedBlobs {
include = append(include, "uncommittedblobs")
}
if l.Versions {
include = append(include, "versions")
}
if l.Permissions {
include = append(include, "permissions")
}
return strings.Join(include, ",")
}
@@ -1,199 +0,0 @@
//go:build !plan9 && !solaris && !js
package arrowlist
import (
"context"
"encoding/base64"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/apache/arrow-go/v18/arrow"
arrowArray "github.com/apache/arrow-go/v18/arrow/array"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// arrowPage builds a one row Arrow IPC listing page with the given blob name
// and NextMarker.
func arrowPage(t *testing.T, name, nextMarker string) []byte {
md := arrow.NewMetadata([]string{"NextMarker", "NumberOfRecords"}, []string{nextMarker, "1"})
fields := []arrow.Field{
{Name: "Name", Type: arrow.BinaryTypes.String, Nullable: false},
{Name: "Content-Length", Type: arrow.PrimitiveTypes.Uint64, Nullable: true},
}
schema := arrow.NewSchema(fields, &md)
return buildArrowStream(t, schema, func(b *arrowArray.RecordBuilder) {
b.Field(0).(*arrowArray.StringBuilder).Append(name)
b.Field(1).(*arrowArray.Uint64Builder).Append(42)
})
}
func TestPagerArrow(t *testing.T) {
var requests []*http.Request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.Clone(context.Background()))
w.Header().Set("Content-Type", ArrowContentType)
if r.URL.Query().Get("marker") == "" {
_, _ = w.Write(arrowPage(t, "blob1.txt", "marker1"))
} else {
_, _ = w.Write(arrowPage(t, "blob2.txt", ""))
}
}))
defer srv.Close()
// SAS style query on the endpoint must be preserved in requests.
client, err := NewClientWithNoCredential(srv.URL+"/testcontainer?sv=fakesas", nil)
require.NoError(t, err)
opts := &ListBlobsHierarchyOptions{
ListBlobsHierarchyOptions: container.ListBlobsHierarchyOptions{
Include: container.ListBlobsInclude{Metadata: true, Tags: true},
Prefix: to.Ptr("dir/"),
MaxResults: to.Ptr(int32(1000)),
StartFrom: to.Ptr("testcontainer/dir/a"),
},
EndBefore: to.Ptr("testcontainer/dir/n"),
UseArrowFormat: to.Ptr(true),
}
pager := client.NewListBlobsHierarchyPager("/", opts)
var names []string
for pager.More() {
page, err := pager.NextPage(context.Background())
require.NoError(t, err)
assert.Equal(t, ArrowContentType, *page.ContentType)
for _, item := range page.Segment.BlobItems {
names = append(names, *item.Name)
assert.Equal(t, int64(42), *item.Properties.ContentLength)
}
}
assert.Equal(t, []string{"blob1.txt", "blob2.txt"}, names)
require.Len(t, requests, 2)
q := requests[0].URL.Query()
assert.Equal(t, "list", q.Get("comp"))
assert.Equal(t, "container", q.Get("restype"))
assert.Equal(t, "/", q.Get("delimiter"))
assert.Equal(t, "metadata,tags", q.Get("include"))
assert.Equal(t, "dir/", q.Get("prefix"))
assert.Equal(t, "1000", q.Get("maxresults"))
assert.Equal(t, "testcontainer/dir/a", q.Get("startFrom"))
assert.Equal(t, "testcontainer/dir/n", q.Get("endBefore"))
assert.Equal(t, "fakesas", q.Get("sv"))
assert.Empty(t, q.Get("marker"))
assert.Equal(t, ArrowAcceptHeader, requests[0].Header.Get("Accept"))
assert.Equal(t, serviceVersion, requests[0].Header.Get("x-ms-version"))
assert.Equal(t, "marker1", requests[1].URL.Query().Get("marker"))
// The caller's options must not have been mutated by paging.
assert.Nil(t, opts.Marker)
}
const xmlListResponse = `<?xml version="1.0" encoding="utf-8"?>
<EnumerationResults ServiceEndpoint="https://example.com/" ContainerName="testcontainer">
<Blobs>
<Blob>
<Name>file.txt</Name>
<Properties>
<Last-Modified>Mon, 01 Jan 2024 00:00:00 GMT</Last-Modified>
<Etag>0x8D1</Etag>
<Content-Length>7</Content-Length>
<BlobType>BlockBlob</BlobType>
</Properties>
</Blob>
<BlobPrefix>
<Name>subdir/</Name>
</BlobPrefix>
</Blobs>
<NextMarker />
</EnumerationResults>`
func TestPagerXMLFallback(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(xmlListResponse))
}))
defer srv.Close()
client, err := NewClientWithNoCredential(srv.URL+"/testcontainer", nil)
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: to.Ptr(true),
})
page, err := pager.NextPage(context.Background())
require.NoError(t, err)
assert.False(t, pager.More())
assert.Equal(t, "application/xml", *page.ContentType)
require.Len(t, page.Segment.BlobItems, 1)
assert.Equal(t, "file.txt", *page.Segment.BlobItems[0].Name)
assert.Equal(t, int64(7), *page.Segment.BlobItems[0].Properties.ContentLength)
require.Len(t, page.Segment.BlobPrefixes, 1)
assert.Equal(t, "subdir/", *page.Segment.BlobPrefixes[0].Name)
}
func TestPagerXMLFallbackWithEndBefore(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/xml")
_, _ = w.Write([]byte(xmlListResponse))
}))
defer srv.Close()
client, err := NewClientWithNoCredential(srv.URL+"/testcontainer", nil)
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
EndBefore: to.Ptr("testcontainer/n"),
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.ErrorIs(t, err, ErrEndBeforeXMLFallback)
}
func TestPagerSharedKeyAuth(t *testing.T) {
var gotAuth, gotDate string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotDate = r.Header.Get("x-ms-date")
w.Header().Set("Content-Type", ArrowContentType)
_, _ = w.Write(arrowPage(t, "blob.txt", ""))
}))
defer srv.Close()
cred, err := NewSharedKeyCredential("testaccount", base64.StdEncoding.EncodeToString([]byte("testkey")))
require.NoError(t, err)
client, err := NewClientWithSharedKeyCredential(srv.URL+"/testcontainer", cred, nil)
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.NoError(t, err)
assert.True(t, strings.HasPrefix(gotAuth, "SharedKey testaccount:"), "Authorization = %q", gotAuth)
assert.NotEmpty(t, gotDate)
}
func TestPagerResponseError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("x-ms-error-code", string(bloberror.ContainerNotFound))
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
client, err := NewClientWithNoCredential(srv.URL+"/testcontainer", nil)
require.NoError(t, err)
pager := client.NewListBlobsHierarchyPager("/", &ListBlobsHierarchyOptions{
UseArrowFormat: to.Ptr(true),
})
_, err = pager.NextPage(context.Background())
require.Error(t, err)
assert.True(t, bloberror.HasCode(err, bloberror.ContainerNotFound), "expected ContainerNotFound, got %v", err)
}
@@ -1,121 +0,0 @@
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Adapted from internal/shared/challenge_policy.go in the Azure SDK for Go
// github.com/Azure/azure-sdk-for-go/sdk/storage/azblob at v1.8.0. The
// released SDK does not export its storage bearer-challenge policy, which is
// needed for token authentication with the same semantics as the SDK's own
// clients.
package arrowlist
import (
"errors"
"net/http"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
)
type storageAuthorizer struct {
scopes []string
tenantID string
}
// NewStorageChallengePolicy returns a bearer token policy for cred which
// handles the storage service's authentication challenges.
func NewStorageChallengePolicy(cred azcore.TokenCredential, audience string, allowHTTP bool) policy.Policy {
s := storageAuthorizer{scopes: []string{audience}}
return runtime.NewBearerTokenPolicy(cred, []string{audience}, &policy.BearerTokenOptions{
AuthorizationHandler: policy.AuthorizationHandler{
OnRequest: s.onRequest,
OnChallenge: s.onChallenge,
},
InsecureAllowCredentialWithHTTP: allowHTTP,
})
}
func (s *storageAuthorizer) onRequest(req *policy.Request, authNZ func(policy.TokenRequestOptions) error) error {
return authNZ(policy.TokenRequestOptions{Scopes: s.scopes})
}
func (s *storageAuthorizer) onChallenge(req *policy.Request, resp *http.Response, authNZ func(policy.TokenRequestOptions) error) error {
// parse the challenge
err := s.parseChallenge(resp)
if err != nil {
return err
}
// TODO: Set tenantID when policy.TokenRequestOptions supports it. https://github.com/Azure/azure-sdk-for-go/issues/19841
return authNZ(policy.TokenRequestOptions{Scopes: s.scopes})
}
type challengePolicyError struct {
err error
}
func (c *challengePolicyError) Error() string {
return c.err.Error()
}
func (*challengePolicyError) NonRetriable() {
// marker method
}
func (c *challengePolicyError) Unwrap() error {
return c.err
}
// parses Tenant ID from auth challenge
// https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/authorize
func parseTenant(url string) string {
if url == "" {
return ""
}
parts := strings.Split(url, "/")
if len(parts) >= 3 {
tenant := parts[3]
tenant = strings.ReplaceAll(tenant, ",", "")
return tenant
}
return ""
}
func (s *storageAuthorizer) parseChallenge(resp *http.Response) error {
authHeader := resp.Header.Get("WWW-Authenticate")
if authHeader == "" {
return &challengePolicyError{err: errors.New("response has no WWW-Authenticate header for challenge authentication")}
}
// Strip down to auth and resource
// Format is "Bearer authorization_uri=\"<site>\" resource_id=\"<site>\""
authHeader = strings.ReplaceAll(authHeader, "Bearer ", "")
parts := strings.Split(authHeader, " ")
vals := map[string]string{}
for _, part := range parts {
subParts := strings.Split(part, "=")
if len(subParts) == 2 {
stripped := strings.ReplaceAll(subParts[1], "\"", "")
stripped = strings.TrimSuffix(stripped, ",")
vals[subParts[0]] = stripped
}
}
s.tenantID = parseTenant(vals["authorization_uri"])
scope := vals["resource_id"]
if scope == "" {
return &challengePolicyError{err: errors.New("could not find a valid resource in the WWW-Authenticate header")}
}
if !strings.HasSuffix(scope, "/.default") {
scope += "/.default"
}
s.scopes = []string{scope}
return nil
}
-318
View File
@@ -1,318 +0,0 @@
//go:build !plan9 && !solaris && !js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Adapted from internal/exported/shared_key_credential.go in the Azure SDK
// for Go github.com/Azure/azure-sdk-for-go/sdk/storage/azblob at v1.8.0,
// with the internal header constants inlined. The released SDK does not
// export its shared key signing policy, so a copy is needed to sign the
// Arrow listing requests this package sends through its own pipeline.
package arrowlist
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/rclone/rclone/fs"
)
// NewSharedKeyCredential creates an immutable SharedKeyCredential containing the
// storage account's name and either its primary or secondary key.
func NewSharedKeyCredential(accountName string, accountKey string) (*SharedKeyCredential, error) {
c := SharedKeyCredential{accountName: accountName}
if err := c.SetAccountKey(accountKey); err != nil {
return nil, err
}
return &c, nil
}
// SharedKeyCredential contains an account's name and its primary or secondary key.
type SharedKeyCredential struct {
// Only the NewSharedKeyCredential method should set these; all other methods should treat them as read-only
accountName string
accountKey atomic.Value // []byte
}
// AccountName returns the Storage account's name.
func (c *SharedKeyCredential) AccountName() string {
return c.accountName
}
// SetAccountKey replaces the existing account key with the specified account key.
func (c *SharedKeyCredential) SetAccountKey(accountKey string) error {
_bytes, err := base64.StdEncoding.DecodeString(accountKey)
if err != nil {
return fmt.Errorf("decode account key: %w", err)
}
c.accountKey.Store(_bytes)
return nil
}
// ComputeHMACSHA256 generates a hash signature for an HTTP request or for a SAS.
func (c *SharedKeyCredential) computeHMACSHA256(message string) (string, error) {
h := hmac.New(sha256.New, c.accountKey.Load().([]byte))
_, err := h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil)), err
}
func (c *SharedKeyCredential) buildStringToSign(req *http.Request) (string, error) {
// https://docs.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services
headers := req.Header
contentLength := getHeader("Content-Length", headers)
if contentLength == "0" {
contentLength = ""
}
canonicalizedResource, err := c.buildCanonicalizedResource(req.URL)
if err != nil {
return "", err
}
stringToSign := strings.Join([]string{
req.Method,
getHeader("Content-Encoding", headers),
getHeader("Content-Language", headers),
contentLength,
getHeader("Content-MD5", headers),
getHeader("Content-Type", headers),
"", // Empty date because x-ms-date is expected (as per web page above)
getHeader("If-Modified-Since", headers),
getHeader("If-Match", headers),
getHeader("If-None-Match", headers),
getHeader("If-Unmodified-Since", headers),
getHeader("Range", headers),
c.buildCanonicalizedHeader(headers),
canonicalizedResource,
}, "\n")
return stringToSign, nil
}
func getHeader(key string, headers map[string][]string) string {
if headers == nil {
return ""
}
if v, ok := headers[key]; ok {
if len(v) > 0 {
return v[0]
}
}
return ""
}
func getWeightTables() [][]int {
tableLv0 := [...]int{
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x71c, 0x0, 0x71f, 0x721, 0x723, 0x725,
0x0, 0x0, 0x0, 0x72d, 0x803, 0x0, 0x0, 0x733, 0x0, 0xd03, 0xd1a, 0xd1c, 0xd1e,
0xd20, 0xd22, 0xd24, 0xd26, 0xd28, 0xd2a, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25, 0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51,
0xe70, 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99, 0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9,
0x0, 0x0, 0x0, 0x743, 0x744, 0x748, 0xe02, 0xe09, 0xe0a, 0xe1a, 0xe21, 0xe23, 0xe25,
0xe2c, 0xe32, 0xe35, 0xe36, 0xe48, 0xe51, 0xe70, 0xe7c, 0xe7e, 0xe89, 0xe8a, 0xe91, 0xe99,
0xe9f, 0xea2, 0xea4, 0xea6, 0xea7, 0xea9, 0x0, 0x74c, 0x0, 0x750, 0x0,
}
tableLv2 := [...]int{
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8012, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8212, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
}
tables := [][]int{tableLv0[:], tableLv2[:]}
return tables
}
// NewHeaderStringComparer performs a multi-level, weight-based comparison of two strings
func compareHeaders(lhs, rhs string, tables [][]int) int {
currLevel, i, j := 0, 0, 0
n := len(tables)
lhsLen := len(lhs)
rhsLen := len(rhs)
for currLevel < n {
if currLevel == (n-1) && i != j {
if i > j {
return -1
}
if i < j {
return 1
}
return 0
}
var w1, w2 int
// Check bounds before accessing lhs[i]
if i < lhsLen {
w1 = tables[currLevel][lhs[i]]
} else {
w1 = 0x1
}
// Check bounds before accessing rhs[j]
if j < rhsLen {
w2 = tables[currLevel][rhs[j]]
} else {
w2 = 0x1
}
if w1 == 0x1 && w2 == 0x1 {
i = 0
j = 0
currLevel++
} else if w1 == w2 {
i++
j++
} else if w1 == 0 {
i++
} else if w2 == 0 {
j++
} else {
if w1 < w2 {
return -1
}
if w1 > w2 {
return 1
}
return 0
}
}
return 0
}
func (c *SharedKeyCredential) buildCanonicalizedHeader(headers http.Header) string {
cm := map[string][]string{}
for k, v := range headers {
headerName := strings.TrimSpace(strings.ToLower(k))
if strings.HasPrefix(headerName, "x-ms-") {
cm[headerName] = v // NOTE: the value must not have any whitespace around it.
}
}
if len(cm) == 0 {
return ""
}
keys := make([]string, 0, len(cm))
for key := range cm {
keys = append(keys, key)
}
tables := getWeightTables()
// Sort the keys using the custom comparator
sort.Slice(keys, func(i, j int) bool {
return compareHeaders(keys[i], keys[j], tables) < 0
})
ch := bytes.NewBufferString("")
for i, key := range keys {
if i > 0 {
ch.WriteRune('\n')
}
ch.WriteString(key)
ch.WriteRune(':')
ch.WriteString(strings.Join(cm[key], ","))
}
return ch.String()
}
func (c *SharedKeyCredential) buildCanonicalizedResource(u *url.URL) (string, error) {
// https://docs.microsoft.com/en-us/rest/api/storageservices/authentication-for-the-azure-storage-services
cr := bytes.NewBufferString("/")
cr.WriteString(c.accountName)
if len(u.Path) > 0 {
// Any portion of the CanonicalizedResource string that is derived from
// the resource's URI should be encoded exactly as it is in the URI.
// -- https://msdn.microsoft.com/en-gb/library/azure/dd179428.aspx
cr.WriteString(u.EscapedPath())
} else {
// a slash is required to indicate the root path
cr.WriteString("/")
}
// params is a map[string][]string; param name is key; params values is []string
params, err := url.ParseQuery(u.RawQuery) // Returns URL decoded values
if err != nil {
return "", fmt.Errorf("failed to parse query params: %w", err)
}
if len(params) > 0 { // There is at least 1 query parameter
var paramNames []string // We use this to sort the parameter key names
for paramName := range params {
paramNames = append(paramNames, paramName) // paramNames must be lowercase
}
sort.Strings(paramNames)
for _, paramName := range paramNames {
paramValues := params[paramName]
sort.Strings(paramValues)
// Join the sorted key values separated by ','
// Then prepend "keyName:"; then add this string to the buffer
cr.WriteString("\n" + strings.ToLower(paramName) + ":" + strings.Join(paramValues, ","))
}
}
return cr.String(), nil
}
// ComputeHMACSHA256 is a helper for computing the signed string outside of this package.
func ComputeHMACSHA256(cred *SharedKeyCredential, message string) (string, error) {
return cred.computeHMACSHA256(message)
}
// SharedKeyCredPolicy is a pipeline policy that signs each request with the
// account's shared key.
type SharedKeyCredPolicy struct {
cred *SharedKeyCredential
}
// NewSharedKeyCredPolicy creates a SharedKeyCredPolicy signing with cred.
func NewSharedKeyCredPolicy(cred *SharedKeyCredential) *SharedKeyCredPolicy {
return &SharedKeyCredPolicy{cred: cred}
}
// Do signs the request and sends it via the next policy in the pipeline.
func (s *SharedKeyCredPolicy) Do(req *policy.Request) (*http.Response, error) {
// skip adding the authorization header if no SharedKeyCredential was provided.
// this prevents a panic that might be hard to diagnose and allows testing
// against http endpoints that don't require authentication.
if s.cred == nil {
return req.Next()
}
if d := getHeader("x-ms-date", req.Raw().Header); d == "" {
req.Raw().Header.Set("x-ms-date", time.Now().UTC().Format(http.TimeFormat))
}
stringToSign, err := s.cred.buildStringToSign(req.Raw())
if err != nil {
return nil, err
}
signature, err := s.cred.computeHMACSHA256(stringToSign)
if err != nil {
return nil, err
}
authHeader := strings.Join([]string{"SharedKey ", s.cred.AccountName(), ":", signature}, "")
req.Raw().Header.Set("Authorization", authHeader)
response, err := req.Next()
if err != nil && response != nil && response.StatusCode == http.StatusForbidden {
// Service failed to authenticate request, log it
fs.Debugf(nil, "azureblob arrowlist: HTTP Forbidden status, String-to-Sign: %q", stringToSign)
}
return response, err
}
-11
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),
}
@@ -297,13 +293,6 @@ func (tr transporter) Do(req *http.Request) (*http.Response, error) {
return tr.RoundTripper.RoundTrip(req)
}
// Transporter returns the policy.Transporter rclone uses for Azure SDK
// clients (an fshttp based transport with the APN user agent), for callers
// which build their own azcore pipelines.
func Transporter(ctx context.Context) policy.Transporter {
return newTransporter(ctx)
}
// NewClientOpts should be passed to configure NewClient
type NewClientOpts[Client, ClientOptions, SharedKeyCredential any] struct {
DefaultBaseURL string // Base URL, eg blob.core.windows.net
+47 -289
View File
@@ -22,20 +22,16 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
"github.com/rclone/rclone/backend/azureblob/arrowlist"
"github.com/rclone/rclone/backend/azureblob/auth"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/chunksize"
@@ -51,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"
)
@@ -72,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"))
@@ -239,42 +224,6 @@ minutes per megabyte on average, it will time out (
avoid the time out.`,
Default: maxListChunkSize,
Advanced: true,
}, {
Name: "use_arrow_list",
Help: `Use the experimental Apache Arrow listing format.
If set, directory listings are fetched using the ListBlobs Apache
Arrow response format instead of XML. This can be faster for very
large containers.
This is EXPERIMENTAL and requires the "Blob Listing with Apache Arrow"
preview feature to be enabled on the storage account. It is NOT
supported on accounts with a hierarchical namespace (ADLS Gen2) -
those return a 409 error. If the feature is not enabled the server
returns XML and the listing transparently falls back to the normal XML
path (logged at debug level).
Not supported with connection_string auth - falls back to normal
listing.`,
Default: false,
Advanced: true,
Hide: fs.OptionHideBoth,
}, {
Name: "list_parallelism",
Help: `Number of parallel shards to list a directory with.
EXPERIMENTAL. If set greater than 1, the blob name keyspace of each
directory is split into this many ranges which are listed concurrently
using the Arrow startFrom/endBefore range parameters. This can
dramatically speed up listing containers with millions of objects, for
both recursive (ListR) and single directory listings.
This has no effect unless "use_arrow_list" is also set, as Arrow is the
only listing path that supports server-side name ranges. The default of
0 (or 1) lists sequentially.`,
Default: 0,
Advanced: true,
Hide: fs.OptionHideBoth,
}, {
Name: "access_tier",
Help: `Access tier of blob: hot, cool, cold or archive.
@@ -401,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,
}}),
})
}
@@ -428,8 +364,6 @@ type Options struct {
UseCopyBlob bool `config:"use_copy_blob"`
UploadConcurrency int `config:"upload_concurrency"`
ListChunkSize uint `config:"list_chunk"`
UseArrowList bool `config:"use_arrow_list"`
ListParallelism int `config:"list_parallelism"`
AccessTier string `config:"access_tier"`
ArchiveTierDelete bool `config:"archive_tier_delete"`
DisableCheckSum bool `config:"disable_checksum"`
@@ -439,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
@@ -449,11 +382,8 @@ type Fs struct {
opt Options // parsed config options
ci *fs.ConfigInfo // global config
features *fs.Features // optional features
cntSVCcacheMu sync.Mutex // mutex to protect cntSVCcache and arrowCntSVCcache
cntSVCcacheMu sync.Mutex // mutex to protect cntSVCcache
cntSVCcache map[string]*container.Client // reference to containerClient per container
arrowCntSVCcache map[string]*arrowlist.Client // reference to arrowlist client per container
arrowClientOpts *arrowlist.ClientOptions // client options for the arrowlist clients
arrowXMLFallback atomic.Bool // set once the server answers XML so parallel listing is not retried
svc *service.Client // client to access azblob
cred azcore.TokenCredential // how to generate tokens (may be nil)
usingSharedKeyCred bool // set if using shared key credentials
@@ -467,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
@@ -477,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
}
// ------------------------------------------------------------
@@ -653,9 +580,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
if opt.ListChunkSize > maxListChunkSize {
return nil, fmt.Errorf("blob list size can't be greater than %v - was %v", maxListChunkSize, opt.ListChunkSize)
}
if opt.ListParallelism > 1 && !opt.UseArrowList {
fs.Logf(nil, "azureblob: list_parallelism has no effect without use_arrow_list - listing sequentially")
}
if opt.AccessTier == "" {
opt.AccessTier = string(defaultAccessTier)
@@ -671,15 +595,14 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
ci := fs.GetConfig(ctx)
f := &Fs{
name: name,
opt: *opt,
ci: ci,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
copyToken: pacer.NewTokenDispenser(opt.CopyTotalConcurrency),
cache: bucket.NewCache(),
cntSVCcache: make(map[string]*container.Client, 1),
arrowCntSVCcache: make(map[string]*arrowlist.Client, 1),
name: name,
opt: *opt,
ci: ci,
pacer: fs.NewPacer(ctx, pacer.NewS3(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant))),
uploadToken: pacer.NewTokenDispenser(ci.Transfers),
copyToken: pacer.NewTokenDispenser(opt.CopyTotalConcurrency),
cache: bucket.NewCache(),
cntSVCcache: make(map[string]*container.Client, 1),
}
f.publicAccess = container.PublicAccessType(opt.PublicAccess)
f.setRoot(root)
@@ -711,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
},
}
@@ -726,15 +646,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
f.usingSharedKeyCred = res.UsingSharedKeyCred
f.anonymous = res.Anonymous
// Client options for the arrowlist clients, using the same transport and
// gzip policy as the SDK clients built above.
f.arrowClientOpts = &arrowlist.ClientOptions{
ClientOptions: azcore.ClientOptions{
Transport: auth.Transporter(ctx),
PerCallPolicies: []policy.Policy{setAcceptEncodingGzip{}},
},
}
// if using Container level SAS put the container client into the cache
if opt.SASURL != "" && res.Container != "" {
_ = f.cntSVC(res.Container)
@@ -773,44 +684,6 @@ func (f *Fs) cntSVC(containerName string) (containerClient *container.Client) {
return containerClient
}
// errArrowAuthUnsupported is returned by arrowCntSVC when the configured
// credentials can't be used for Arrow listing.
var errArrowAuthUnsupported = errors.New("credentials not supported for Arrow listing (connection_string auth is not supported)")
// return the arrowlist client for the container passed in
//
// Returns errArrowAuthUnsupported if the configured credentials can't be
// reused for the arrowlist client's pipeline.
func (f *Fs) arrowCntSVC(containerName string) (client *arrowlist.Client, err error) {
// The container URL includes any SAS token in its query
url := f.cntSVC(containerName).URL()
f.cntSVCcacheMu.Lock()
defer f.cntSVCcacheMu.Unlock()
if client, ok := f.arrowCntSVCcache[containerName]; ok {
return client, nil
}
switch {
case f.usingSharedKeyCred:
// Covers account+key and the emulator (auth fills in Account/Key)
var cred *arrowlist.SharedKeyCredential
cred, err = arrowlist.NewSharedKeyCredential(f.opt.Account, f.opt.Key)
if err == nil {
client, err = arrowlist.NewClientWithSharedKeyCredential(url, cred, f.arrowClientOpts)
}
case f.cred != nil:
client, err = arrowlist.NewClient(url, f.cred, f.arrowClientOpts)
case f.anonymous || f.opt.SASURL != "":
client, err = arrowlist.NewClientWithNoCredential(url, f.arrowClientOpts)
default:
return nil, errArrowAuthUnsupported
}
if err != nil {
return nil, err
}
f.arrowCntSVCcache[containerName] = client
return client, nil
}
// Return an Object from a path
//
// If it can't be found it returns the error fs.ErrorObjectNotFound.
@@ -1187,77 +1060,19 @@ func (f *Fs) list(ctx context.Context, containerName, directory, prefix string,
delimiter = "/"
}
opts := &arrowlist.ListBlobsHierarchyOptions{
ListBlobsHierarchyOptions: container.ListBlobsHierarchyOptions{
// Copy, Metadata, Snapshots, UncommittedBlobs, Deleted, Tags, Versions, LegalHold, ImmutabilityPolicy, DeletedWithVersions bool
Include: container.ListBlobsInclude{
Copy: false,
Metadata: true,
Snapshots: false,
UncommittedBlobs: false,
Deleted: false,
},
Prefix: &directory,
MaxResults: &maxResults,
pager := f.cntSVC(containerName).NewListBlobsHierarchyPager(delimiter, &container.ListBlobsHierarchyOptions{
// Copy, Metadata, Snapshots, UncommittedBlobs, Deleted, Tags, Versions, LegalHold, ImmutabilityPolicy, DeletedWithVersions bool
Include: container.ListBlobsInclude{
Copy: false,
Metadata: true,
Snapshots: false,
UncommittedBlobs: false,
Deleted: false,
},
}
// Experimental: request the Apache Arrow listing format. The arrowlist
// pager requests an Arrow IPC stream and decodes it, falling back to XML
// if the account doesn't have Arrow listing enabled. Skip the
// maxResults==1 probe (isEmpty) which doesn't benefit.
useArrow := f.opt.UseArrowList && maxResults != 1
if useArrow {
opts.UseArrowFormat = to.Ptr(true)
}
var foundItems int
var err error
if useArrow && f.opt.ListParallelism > 1 && !f.arrowXMLFallback.Load() {
// Arrow exposes server-side startFrom/endBefore name ranges, so the
// keyspace can be sharded and listed concurrently.
foundItems, err = f.listArrowParallel(ctx, containerName, directory, prefix, addContainer, opts, delimiter, fn)
} else {
foundItems, err = f.listBlobsPager(ctx, containerName, directory, prefix, addContainer, opts, delimiter, fn)
}
if err != nil {
return err
}
if f.opt.DirectoryMarkers && foundItems == 0 && directory != "" {
// Determine whether the directory exists or not by whether it has a marker
_, err := f.readMetaData(ctx, containerName, directory)
if err != nil {
if err == fs.ErrorObjectNotFound {
return fs.ErrorDirNotFound
}
return err
}
}
return nil
}
// listBlobsPager runs the hierarchy listing described by opts, calling fn for
// each blob and subdirectory, and returns the number of raw items seen.
// delimiter selects flat (recurse) vs hierarchical listing. If opts requests
// the Apache Arrow format the listing goes through the arrowlist pager
// (falling back to the SDK pager if the credentials don't support it); if the
// service then answers with XML (Arrow listing not enabled) a debug message
// is logged.
func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefix string, addContainer bool, opts *arrowlist.ListBlobsHierarchyOptions, delimiter string, fn listFn) (foundItems int, err error) {
useArrow := opts.UseArrowFormat != nil && *opts.UseArrowFormat
var pager *runtime.Pager[container.ListBlobsHierarchyResponse]
if useArrow {
arrowSVC, err := f.arrowCntSVC(containerName)
if err != nil {
fs.Debugf(f, "Not using Arrow listing: %v", err)
useArrow = false
} else {
pager = arrowSVC.NewListBlobsHierarchyPager(delimiter, opts)
}
}
if pager == nil {
pager = f.cntSVC(containerName).NewListBlobsHierarchyPager(delimiter, &opts.ListBlobsHierarchyOptions)
}
checkedArrow := false
Prefix: &directory,
MaxResults: &maxResults,
})
foundItems := 0
for pager.More() {
var response container.ListBlobsHierarchyResponse
err := f.pacer.Call(func() (bool, error) {
@@ -1267,22 +1082,12 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
return f.shouldRetry(ctx, err)
})
// If Arrow was requested but the service answered with XML, Arrow
// listing is not enabled on this account; the listing is still correct
// but not accelerated.
if useArrow && !checkedArrow && err == nil {
checkedArrow = true
if response.ContentType == nil || !strings.HasPrefix(*response.ContentType, arrowlist.ArrowContentType) {
fs.Debugf(f, "Apache Arrow listing requested but server returned XML - Blob Listing with Apache Arrow may not be enabled on this account")
}
}
if err != nil {
// Check http error code along with service code, current SDK doesn't populate service code correctly sometimes
if storageErr, ok := err.(*azcore.ResponseError); ok && (storageErr.ErrorCode == string(bloberror.ContainerNotFound) || storageErr.StatusCode == http.StatusNotFound) {
return foundItems, fs.ErrorDirNotFound
return fs.ErrorDirNotFound
}
return foundItems, err
return err
}
// Advance marker to next
// marker = response.NextMarker
@@ -1302,12 +1107,7 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
fs.Debugf(f, "Odd name received %q", remote)
continue
}
// ContentLength is documented as nullable in the Arrow listing schema
size := int64(-1)
if file.Properties.ContentLength != nil {
size = *file.Properties.ContentLength
}
isDirectory := isDirectoryMarker(size, file.Metadata, remote)
isDirectory := isDirectoryMarker(*file.Properties.ContentLength, file.Metadata, remote)
if isDirectory {
// Don't insert the root directory
if remote == f.opt.Enc.ToStandardPath(directory) {
@@ -1323,7 +1123,7 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
// Send object
err = fn(remote, file, isDirectory)
if err != nil {
return foundItems, err
return err
}
}
// Send the subdirectories
@@ -1338,13 +1138,6 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
fs.Debugf(f, "Odd directory name received %q", remote)
continue
}
// Don't insert the root directory. The Arrow listing returns a
// directory marker blob with the same name as the listed directory
// as a BlobPrefix, whereas XML returns it as a blob (handled
// above).
if remote == f.opt.Enc.ToStandardPath(directory) {
continue
}
remote = remote[len(prefix):]
// Trim one slash off the remote name
remote, _ = strings.CutSuffix(remote, "/")
@@ -1357,11 +1150,21 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
// Send object
err = fn(remote, nil, true)
if err != nil {
return foundItems, err
return err
}
}
}
return foundItems, nil
if f.opt.DirectoryMarkers && foundItems == 0 && directory != "" {
// Determine whether the directory exists or not by whether it has a marker
_, err := f.readMetaData(ctx, containerName, directory)
if err != nil {
if err == fs.ErrorObjectNotFound {
return fs.ErrorDirNotFound
}
return err
}
}
return nil
}
// Convert a list item into a DirEntry
@@ -2198,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
@@ -2327,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
}
@@ -2351,16 +2143,7 @@ func (o *Object) decodeMetaDataFromDownloadResponse(info *blob.DownloadStreamRes
}
// NOTE - Client library always returns MD5 as base64 decoded string, Object needs to maintain
// this as base64 encoded string.
//
// On a range request the service returns the whole-blob MD5 in the
// x-ms-blob-content-md5 header (BlobContentMD5) and leaves Content-MD5
// (ContentMD5) empty, so prefer BlobContentMD5. Never overwrite a known
// hash with an empty one, or a ranged read would drop the object's MD5.
if md5 := info.BlobContentMD5; len(md5) > 0 {
o.md5 = base64.StdEncoding.EncodeToString(md5)
} else if len(info.ContentMD5) > 0 {
o.md5 = base64.StdEncoding.EncodeToString(info.ContentMD5)
}
o.md5 = base64.StdEncoding.EncodeToString(info.ContentMD5)
if info.ContentType == nil {
o.mimeType = ""
} else {
@@ -2395,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
}
@@ -2440,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
}
@@ -2622,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,66 +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)
t.Run("ArrowList", f.testArrowList)
}
// helper to read blob properties for an object
+5 -17
View File
@@ -58,9 +58,6 @@ const (
maxFileSize = 4 * fs.Tebi
defaultChunkSize = 4 * fs.Mebi
storageDefaultBaseURL = "file.core.windows.net"
// smbTimePrecision is the precision the server stores
// modtimes with (100 ns FILETIME ticks)
smbTimePrecision = 100 * time.Nanosecond
)
func init() {
@@ -176,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)
@@ -253,10 +246,10 @@ func (f *Fs) Features() *fs.Features {
// Precision return the precision of this Fs
//
// The SMB last write time properties are ISO 8601 with 100 ns (FILETIME) precision
// One second. FileREST API times are in RFC1123 which in the example shows a precision of seconds
// Source: https://learn.microsoft.com/en-us/rest/api/storageservices/representation-of-date-time-values-in-headers
func (f *Fs) Precision() time.Duration {
return smbTimePrecision
return time.Second
}
// Hashes returns the supported hash sets.
@@ -601,10 +594,7 @@ func (o *Object) SetModTime(ctx context.Context, t time.Time) error {
if err != nil {
return fmt.Errorf("unable to set modTime: %w", err)
}
// Truncate to the precision the server stores the modtime with
// to keep the in-memory modtime identical to the one a fresh
// listing returns.
o.modTime = t.Truncate(smbTimePrecision)
o.modTime = t
return nil
}
@@ -775,12 +765,10 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return fmt.Errorf("update: failed to set properties: %w", err)
}
// Make sure Object is in sync, truncating the modtime to the
// precision the server stores it with so it is identical to the
// one a fresh listing returns
// Make sure Object is in sync
o.size = size
o.md5 = md5Hash
o.modTime = modTime.Truncate(smbTimePrecision)
o.modTime = modTime
o.contentType = contentType
return nil
}
+5 -10
View File
@@ -503,19 +503,15 @@ func NewFs(ctx context.Context, name, rootPath string, m configmap.Mapper) (fs.F
}
go func() {
// Wait on the timer and the stop channel together so that a stop
// signalled by StopBackgroundRunners is honoured immediately.
timer := time.NewTimer(time.Duration(f.opt.ChunkCleanInterval))
defer timer.Stop()
for {
time.Sleep(time.Duration(f.opt.ChunkCleanInterval))
select {
case <-f.cleanupChan:
fs.Infof(f, "stopping cleanup")
return
case <-timer.C:
default:
fs.Debugf(f, "starting cleanup")
f.CleanUpCache(false)
timer.Reset(time.Duration(f.opt.ChunkCleanInterval))
}
}
}()
@@ -567,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
}
+1 -1
View File
@@ -1104,7 +1104,7 @@ func (o *Object) Remote() string {
newPath, err := o.u.pathAdjustment.do(o.Object.String())
if err != nil {
fs.Errorf(o.Object, "Bad object: %v", err)
return ""
return err.Error()
}
return newPath
}
+6 -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"`
}
@@ -57,6 +57,7 @@ type Item struct {
FileHash any `json:"file_hash"`
Public bool `json:"public"`
Thumbnail bool `json:"thumbnail"`
MuxStatus any `json:"mux_status"`
ThumbnailURL any `json:"thumbnail_url"`
WorkspaceID int `json:"workspace_id"`
IsEncrypted int `json:"is_encrypted"`
@@ -76,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"`
}
@@ -170,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"`
}
@@ -221,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)
}
}()
}
+14 -76
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
@@ -208,10 +207,7 @@ func driveOAuthOptions() []fs.Option {
opts := []fs.Option{}
for _, opt := range oauthutil.SharedOptions {
if opt.Name == config.ConfigClientID {
opt.Help = "Google Application Client Id\nLeave blank to use rclone's shared client_id, or if you are using a service account.\nThe shared client_id is being retired and will stop working during 2026, so creating your own is now strongly recommended.\nSee https://rclone.org/drive/#making-your-own-client-id for how to create your own."
}
if opt.Name == config.ConfigClientSecret {
opt.Help = "Google Application Client Secret\nLeave blank to use rclone's shared client_id, or if you are using a service account.\nIf you created your own client_id then enter its client secret here."
opt.Help = "Google Application Client Id\nSetting your own is recommended.\nSee https://rclone.org/drive/#making-your-own-client-id for how to create your own.\nIf you leave this blank, it will use an internal key which is low performance."
}
opts = append(opts, opt)
}
@@ -225,7 +221,7 @@ func init() {
Description: "Google Drive",
NewFs: NewFs,
CommandHelp: commandHelp,
Config: func(ctx context.Context, name string, m configmap.Mapper, configIn fs.ConfigIn) (*fs.ConfigOut, error) {
Config: func(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
// Parse config into Options struct
opt := new(Options)
err := configstruct.Set(m, opt)
@@ -233,7 +229,7 @@ func init() {
return nil, fmt.Errorf("couldn't parse config into struct: %w", err)
}
switch configIn.State {
switch config.State {
case "":
// Fill in the scopes
driveConfig.Scopes = driveScopes(opt.Scope)
@@ -244,43 +240,24 @@ func init() {
}
if opt.ServiceAccountFile == "" && opt.ServiceAccountCredentials == "" && !opt.EnvAuth {
return fs.ConfigGoto("client_id")
return oauthutil.ConfigOut("teamdrive", &oauthutil.Options{
OAuth2Config: driveConfig,
})
}
return fs.ConfigGoto("teamdrive")
case "client_id":
if clientID, _ := m.Get(config.ConfigClientID); clientID != "" {
return fs.ConfigGoto("oauth")
}
return oauthutil.SharedClientIDConfigConfirm("client_id_warning", "Google Drive", "https://rclone.org/drive/#making-your-own-client-id")
case "client_id_warning":
if configIn.Result == "true" {
// Continue using the shared client_id
return fs.ConfigGoto("oauth")
}
return fs.ConfigInput("client_id_set", config.ConfigClientID, "Google Application Client Id")
case "client_id_set":
m.Set(config.ConfigClientID, configIn.Result)
return fs.ConfigInput("client_secret_set", config.ConfigClientSecret, "Google Application Client Secret")
case "client_secret_set":
m.Set(config.ConfigClientSecret, configIn.Result)
return fs.ConfigGoto("oauth")
case "oauth":
return oauthutil.ConfigOut("teamdrive", &oauthutil.Options{
OAuth2Config: driveConfig,
})
case "teamdrive":
if opt.TeamDriveID == "" {
return fs.ConfigConfirm("teamdrive_ok", false, "config_change_team_drive", "Configure this as a Shared Drive (Team Drive)?\n")
}
return fs.ConfigConfirm("teamdrive_change", false, "config_change_team_drive", fmt.Sprintf("Change current Shared Drive (Team Drive) ID %q?\n", opt.TeamDriveID))
case "teamdrive_ok":
if configIn.Result == "false" {
if config.Result == "false" {
m.Set("team_drive", "")
return nil, nil
}
return fs.ConfigGoto("teamdrive_config")
case "teamdrive_change":
if configIn.Result == "false" {
if config.Result == "false" {
return nil, nil
}
return fs.ConfigGoto("teamdrive_config")
@@ -301,14 +278,14 @@ func init() {
return teamDrive.Id, teamDrive.Name
})
case "teamdrive_final":
driveID := configIn.Result
driveID := config.Result
m.Set("team_drive", driveID)
m.Set("root_folder_id", "")
opt.TeamDriveID = driveID
opt.RootFolderID = ""
return nil, nil
}
return nil, fmt.Errorf("unknown state %q", configIn.State)
return nil, fmt.Errorf("unknown state %q", config.State)
},
MetadataInfo: &fs.MetadataInfo{
System: systemMetadataInfo,
@@ -1325,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)
@@ -1710,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 == "" {
@@ -2439,40 +2412,12 @@ func (f *Fs) resolveShortcut(ctx context.Context, item *drive.File) (newItem *dr
return newItem, nil
}
// shortcutLoop reports whether a folder shortcut at remote pointing to
// the directory targetID would create a recursive loop.
//
// This is the case when targetID is the ID of remote's parent or any
// other ancestor directory, as descending into it would list an
// ancestor again forever. The ancestor IDs are looked up in the
// directory cache which is always populated for the parents of remote
// as they are listed before their children.
func (f *Fs) shortcutLoop(remote, targetID string) bool {
for dir := path.Dir(remote); ; dir = path.Dir(dir) {
if dir == "." {
dir = ""
}
if id, ok := f.dirCache.Get(dir); ok && actualID(id) == targetID {
return true
}
if dir == "" {
return false
}
}
}
// itemToDirEntry converts a drive.File to an fs.DirEntry.
// When the drive.File cannot be represented as an fs.DirEntry
// (nil, nil) is returned.
func (f *Fs) itemToDirEntry(ctx context.Context, remote string, item *drive.File) (entry fs.DirEntry, err error) {
switch {
case item.MimeType == driveFolderType:
// A folder shortcut pointing at one of its own ancestors
// would make rclone recurse forever, so drop it.
if isShortcutID(item.Id) && f.shortcutLoop(remote, actualID(item.Id)) {
fs.Errorf(remote, "Ignoring folder shortcut as it points to an ancestor directory creating a loop")
return nil, nil
}
// cache the directory ID for later lookups
f.dirCache.Put(remote, item.Id)
// cache the resource key for later lookups
@@ -3089,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))
-107
View File
@@ -24,7 +24,6 @@ import (
"github.com/rclone/rclone/fs/sync"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/dircache"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -146,34 +145,6 @@ func TestInternalFindExportFormat(t *testing.T) {
}
}
func TestShortcutLoop(t *testing.T) {
f := &Fs{}
f.dirCache = dircache.New("", "root", f)
// root is FolderX with ID "X"
f.dirCache.Put("", "X")
// a real subfolder
f.dirCache.Put("sub", "sub-id")
// a nested subfolder reached via a shortcut, composite ID
f.dirCache.Put("sub/nested", joinID("nested-id", "shortcut-id"))
for _, test := range []struct {
name string
remote string
targetID string
want bool
}{
{"shortcut to the root itself", "loop", "X", true},
{"shortcut to the parent", "sub/loop", "sub-id", true},
{"shortcut to a grandparent", "sub/nested/loop", "X", true},
{"shortcut to a composite ancestor", "sub/nested/loop", "nested-id", true},
{"shortcut to an unrelated folder", "sub/loop", "other-id", false},
{"shortcut to a sibling", "sub/loop", "sub-id2", false},
} {
got := f.shortcutLoop(test.remote, test.targetID)
assert.Equal(t, test.want, got, test.name)
}
}
func TestMimeTypesToExtension(t *testing.T) {
for mimeType, extension := range _mimeTypeToExtension {
extensions, err := mime.ExtensionsByType(mimeType)
@@ -710,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) {
@@ -807,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)
}
+32 -133
View File
@@ -150,20 +150,14 @@ var (
// Gets an oauth config with the right scopes
func getOauthConfig(m configmap.Mapper) *oauthutil.Config {
impersonate, _ := m.Get("impersonate")
impersonateAdmin, _ := m.Get("impersonate_admin")
// If not impersonating, use standard scopes
if impersonate == "" && impersonateAdmin == "" {
if impersonate, _ := m.Get("impersonate"); impersonate == "" {
return dropboxConfig
}
// Make a copy of the config
config := *dropboxConfig
// Make a copy of the scopes with extra scopes requires appended
config.Scopes = append(config.Scopes, "team_data.member")
if impersonate != "" {
config.Scopes = append(config.Scopes, "members.read")
}
config.Scopes = append(config.Scopes, "members.read", "team_data.member")
return &config
}
@@ -212,29 +206,6 @@ You will have to use your own App (setting your own client_id and
client_secret) to use this option as currently rclone's default set of
permissions doesn't include "members.read". This can be added once
v1.55 or later is in use everywhere.
`,
Default: "",
Advanced: true,
Sensitive: true,
}, {
Name: "impersonate_admin",
Help: `Team admin ID to use when performing actions as a team administrator.
This sets the Dropbox-API-Select-Admin header with the given team
member ID (for example "dbmid:...").
This takes a team member ID directly rather than an email address.
Note that if you want to use impersonate_admin, you should make sure this
flag is set when running "rclone config" as this will cause rclone to
request the "team_data.member" scope which it won't normally.
Using the "team_data.member" scope will require a Dropbox Team Admin
to approve during the OAuth flow.
You will have to use your own App (setting your own client_id and
client_secret) to use this option as currently rclone's default set of
permissions doesn't include "team_data.member".
`,
Default: "",
Advanced: true,
@@ -267,36 +238,6 @@ See also --dropbox-root-namespace for an alternative way to work with shared
folders.`,
Default: false,
Advanced: true,
}, {
Name: "skip_shared_folders",
Help: `Instructs rclone to skip all shared folders.
When set, any folder that is a shared folder mount point will be
excluded from directory listings, regardless of ownership.
This is useful if you prefer to back up shared folders separately
using a separate remote configured with the shared folder namespace.`,
Default: false,
Advanced: true,
}, {
Name: "skip_unowned_folders",
Help: `Instructs rclone to skip shared folders not owned by the current user.
When set, any folder that is a shared folder mount point and not
owned by the current user will be excluded from directory listings.
This is useful when backing up multiple Dropbox accounts that share
common folders, to avoid duplicating the shared data across accounts.
Note: In Dropbox Business, 'Team Folders' are owned by the Team.
For standard team members, these folders evaluate as 'unowned'
(editor/viewer access) and will be excluded by this flag. To back up
Team Folders, do not use this flag or run the backup using a Team Admin
account.
If --dropbox-skip-shared-folders is also enabled, this flag has no effect.
This makes an extra API call per shared folder mount point.`,
Default: false,
Advanced: true,
}, {
Name: "pacer_min_sleep",
Default: defaultMinSleep,
@@ -361,23 +302,20 @@ will fail to download them.
// Options defines the configuration for this backend
type Options struct {
ChunkSize fs.SizeSuffix `config:"chunk_size"`
Impersonate string `config:"impersonate"`
ImpersonateAdmin string `config:"impersonate_admin"`
SharedFiles bool `config:"shared_files"`
SharedFolders bool `config:"shared_folders"`
SkipSharedFolders bool `config:"skip_shared_folders"`
SkipUnownedFolders bool `config:"skip_unowned_folders"`
BatchMode string `config:"batch_mode"`
BatchSize int `config:"batch_size"`
BatchTimeout fs.Duration `config:"batch_timeout"`
AsyncBatch bool `config:"async_batch"`
PacerMinSleep fs.Duration `config:"pacer_min_sleep"`
Enc encoder.MultiEncoder `config:"encoding"`
RootNsid string `config:"root_namespace"`
ExportFormats fs.CommaSepList `config:"export_formats"`
SkipExports bool `config:"skip_exports"`
ShowAllExports bool `config:"show_all_exports"`
ChunkSize fs.SizeSuffix `config:"chunk_size"`
Impersonate string `config:"impersonate"`
SharedFiles bool `config:"shared_files"`
SharedFolders bool `config:"shared_folders"`
BatchMode string `config:"batch_mode"`
BatchSize int `config:"batch_size"`
BatchTimeout fs.Duration `config:"batch_timeout"`
AsyncBatch bool `config:"async_batch"`
PacerMinSleep fs.Duration `config:"pacer_min_sleep"`
Enc encoder.MultiEncoder `config:"encoding"`
RootNsid string `config:"root_namespace"`
ExportFormats fs.CommaSepList `config:"export_formats"`
SkipExports bool `config:"skip_exports"`
ShowAllExports bool `config:"show_all_exports"`
}
// Fs represents a remote dropbox server
@@ -599,10 +537,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
cfg.AsMemberID = memberIDs[0].MemberInfo.Profile.MemberProfile.TeamMemberId
}
if opt.ImpersonateAdmin != "" {
cfg.AsAdminID = opt.ImpersonateAdmin
}
f.srv = files.New(cfg)
f.svc = files.New(ucfg)
f.sharing = sharing.New(cfg)
@@ -1008,12 +942,13 @@ func (f *Fs) listReceivedFiles(ctx context.Context, callback func(fs.DirEntry) e
}
}
for _, entry := range res.Entries {
fmt.Printf("%+v\n", entry)
entryPath := entry.Name
o := &Object{
fs: f,
url: entry.PreviewUrl,
remote: entryPath,
modTime: time.Time(*entry.TimeInvited),
modTime: *entry.TimeInvited,
}
if err != nil {
return err
@@ -1153,26 +1088,6 @@ func (f *Fs) ListP(ctx context.Context, dir string, callback fs.ListRCallback) (
leaf := f.opt.Enc.ToStandardName(path.Base(entryPath))
remote := path.Join(dir, leaf)
if folderInfo != nil {
if folderInfo.SharingInfo != nil && folderInfo.SharingInfo.SharedFolderId != "" {
if f.opt.SkipSharedFolders {
fs.Debugf(remote, "Skipping shared folder")
continue
}
if f.opt.SkipUnownedFolders {
var sfMeta *sharing.SharedFolderMetadata
err = f.pacer.Call(func() (bool, error) {
var apiErr error
sfMeta, apiErr = f.sharing.GetFolderMetadata(sharing.NewGetMetadataArgs(folderInfo.SharingInfo.SharedFolderId))
return shouldRetry(ctx, apiErr)
})
if err != nil {
fs.Errorf(remote, "Failed to get shared folder metadata (defaulting to include): %v", err)
} else if sfMeta != nil && sfMeta.AccessType != nil && sfMeta.AccessType.Tag != sharing.AccessLevelOwner {
fs.Debugf(remote, "Skipping unowned shared folder")
continue
}
}
}
d := fs.NewDir(remote, time.Time{}).SetID(folderInfo.Id)
err = list.Add(d)
if err != nil {
@@ -1267,11 +1182,15 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error)
encRoot := f.opt.Enc.FromStandardPath(root)
if check {
// ListFolder reports a missing path and a path that is a file, so it
// checks that the directory exists and is empty in a single request.
// check directory exists
_, err = f.getDirMetadata(ctx, root)
if err != nil {
return fmt.Errorf("Rmdir: %w", err)
}
// check directory empty
arg := files.NewListFolderArg(encRoot)
arg.Recursive = false
arg.Limit = 1
if root == "/" {
arg.Path = "" // Specify root folder as empty string
}
@@ -1281,20 +1200,9 @@ func (f *Fs) purgeCheck(ctx context.Context, dir string, check bool) (err error)
return shouldRetry(ctx, err)
})
if err != nil {
switch e := err.(type) {
case files.ListFolderAPIError:
if e.EndpointError != nil && e.EndpointError.Path != nil {
switch e.EndpointError.Path.Tag {
case files.LookupErrorNotFound:
err = fs.ErrorDirNotFound
case files.LookupErrorNotFolder:
err = fs.ErrorIsFile
}
}
}
return fmt.Errorf("Rmdir: %w", err)
}
if len(res.Entries) != 0 || res.HasMore {
if len(res.Entries) != 0 {
return errors.New("directory not empty")
}
}
@@ -1469,7 +1377,7 @@ func (f *Fs) PublicLink(ctx context.Context, remote string, expire fs.Duration,
},
}
if expire < fs.DurationOff {
expiryTime := dropbox.DBXTime(time.Now().Add(time.Duration(expire)).UTC().Round(time.Second))
expiryTime := time.Now().Add(time.Duration(expire)).UTC().Round(time.Second)
createArg.Settings.Expires = &expiryTime
}
@@ -1883,7 +1791,7 @@ func (o *Object) setMetadataForExport(info *files.FileMetadata) {
func (o *Object) setMetadataFromEntry(info *files.FileMetadata) error {
o.id = info.Id
o.bytes = int64(info.Size)
o.modTime = time.Time(info.ClientModified)
o.modTime = info.ClientModified
o.hash = info.ContentHash
if !info.IsDownloadable {
@@ -2042,21 +1950,12 @@ func (o *Object) uploadChunked(ctx context.Context, in0 io.Reader, commitInfo *f
// write chunks
in := readers.NewCountingReader(in0)
bufSize := chunkSize
if size >= 0 && size < bufSize {
bufSize = size
}
buf := make([]byte, int(bufSize))
buf := make([]byte, int(chunkSize))
cursor := files.UploadSessionCursor{
SessionId: res.SessionId,
Offset: 0,
}
appendArg := files.UploadSessionAppendArg{
Cursor: &cursor,
// A known-size upload which fits in a single chunk can close the
// session with its only append, saving an empty append request
Close: size >= 0 && size <= chunkSize,
}
appendArg := files.UploadSessionAppendArg{Cursor: &cursor}
for currentChunk := 1; ; currentChunk++ {
cursor.Offset = in.BytesRead()
@@ -2186,7 +2085,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
commitInfo := files.NewCommitInfo(o.fs.opt.Enc.FromStandardPath(o.remotePath()))
commitInfo.Mode.Tag = "overwrite"
// The Dropbox API only accepts timestamps in UTC with second precision.
clientModified := dropbox.DBXTime(src.ModTime(ctx).UTC().Round(time.Second))
clientModified := src.ModTime(ctx).UTC().Round(time.Second)
commitInfo.ClientModified = &clientModified
// Don't attempt to create filenames that are too long
if cErr := checkPathLength(commitInfo.Path); cErr != nil {
@@ -2212,7 +2111,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
// This will only happen if we are uploading async batches
if entry == nil {
o.bytes = size
o.modTime = time.Time(*commitInfo.ClientModified)
o.modTime = *commitInfo.ClientModified
o.hash = "" // we don't have this
return nil
}
+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,
+4 -38
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),
@@ -710,10 +682,7 @@ func (o *Object) Storable() bool {
// SetModTime sets the metadata on the object to set the modification date
func (o *Object) SetModTime(ctx context.Context, t time.Time) error {
// The server stores modtimes with millisecond precision so round
// here too to keep the in-memory modtime identical to the one a
// fresh listing returns.
o.file.LastModified = t.Round(time.Millisecond)
o.file.LastModified = t
return o.fs.filen.UpdateMeta(ctx, o.file)
}
@@ -755,10 +724,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
fs.Logf(option, "Unsupported mandatory option: %v", option)
}
}
// The server stores modtimes with millisecond precision so round
// here too to keep the in-memory modtime identical to the one a
// fresh listing returns.
newModTime := src.ModTime(ctx).Round(time.Millisecond)
newModTime := src.ModTime(ctx)
newIncomplete, err := o.file.NewFromBase(o.fs.filen.FileEncryptionVersion)
if err != nil {
return err
+1 -18
View File
@@ -866,24 +866,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
return err
}
// The server computes the MD5 asynchronously after upload so
// retry reading the metadata for a short time until it appears.
const maxTries = 10
for tries := 1; ; tries++ {
err = o.readMetaData(ctx)
if err != nil {
return err
}
if o.md5 != "" || tries >= maxTries {
break
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(tries) * 100 * time.Millisecond):
}
}
return nil
return o.readMetaData(ctx)
}
// Remove an object
+4 -23
View File
@@ -637,18 +637,6 @@ func (f *Fs) drainPool(ctx context.Context) (err error) {
return err
}
// commandEncoding hardens the user-configured filename encoding so that it
// can never restore a raw CR or LF.
//
// The FTP control channel is line oriented and the ftp library writes command
// arguments (paths) straight onto it without escaping, so a filename
// containing CR/LF would otherwise be able to inject an independent FTP
// command. CR/LF are therefore always encoded to safe symbols regardless of
// the configured encoding, which is what the default encoding already does.
func commandEncoding(enc encoder.MultiEncoder) encoder.MultiEncoder {
return enc | encoder.EncodeCrLf
}
// NewFs constructs an Fs from the path, container:path
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (ff fs.Fs, err error) {
// defer fs.Trace(nil, "name=%q, root=%q", name, root)("fs=%v, err=%v", &ff, &err)
@@ -658,7 +646,6 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (ff fs.Fs
if err != nil {
return nil, err
}
opt.Enc = commandEncoding(opt.Enc)
pass := ""
if opt.AskPassword && opt.Pass == "" {
pass = config.GetPassword("FTP server password")
@@ -1248,10 +1235,7 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
path = o.fs.opt.Enc.FromStandardPath(path)
err = c.SetTime(path, modTime.In(time.UTC))
if err == nil && o.info != nil {
// The server stores modtimes with second precision so
// truncate here too to keep the in-memory modtime identical
// to the one a fresh listing returns.
o.info.ModTime = modTime.Truncate(time.Second)
o.info.ModTime = modTime
o.info.precise = true
}
o.fs.putFtpConnection(&c, err)
@@ -1406,12 +1390,9 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
o.fs.putFtpConnection(&c, nil)
if o.fs.opt.NoCheckUpload {
o.info = &FileInfo{
Name: o.remote,
Size: uint64(src.Size()),
// The server stores modtimes with second precision so
// truncate here too to keep the in-memory modtime
// identical to the one a fresh listing returns.
ModTime: src.ModTime(ctx).Truncate(time.Second),
Name: o.remote,
Size: uint64(src.Size()),
ModTime: src.ModTime(ctx),
precise: true,
IsDir: false,
}
+1 -32
View File
@@ -12,34 +12,11 @@ import (
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/fstests"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/readers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A filename containing raw CR/LF must never survive encoding into an FTP
// command argument, whatever encoding the user configured, otherwise it could
// inject an independent FTP command onto the line-oriented control channel.
func TestCommandEncodingNeutralisesCRLF(t *testing.T) {
// Internal Standard-encoded name as produced by e.g. a Unix local
// source, carrying raw CR/LF.
for _, std := range []string{
"victim\r\nDELE other-secret\r\nNOOP",
"victim␍␊DELE other-secret␍␊NOOP",
} {
for _, configured := range []encoder.MultiEncoder{
encoder.EncodeSlash, // "Slash" - omits Ctl and CrLf
encoder.EncodeZero, // "None"
encoder.Display | encoder.EncodeRightSpace, // the FTP default
} {
got := commandEncoding(configured).FromStandardPath(std)
assert.NotContains(t, got, "\r", "encoding %v leaked raw CR: %q", configured, got)
assert.NotContains(t, got, "\n", "encoding %v leaked raw LF: %q", configured, got)
}
}
}
type settings map[string]any
func deriveFs(ctx context.Context, t *testing.T, f fs.Fs, opts settings) fs.Fs {
@@ -75,21 +52,13 @@ func (f *Fs) testUploadTimeout(t *testing.T) {
ci.Timeout = saveTimeout
}()
ci.LowLevelRetries = 1
ci.Timeout = fs.Duration(idleTimeout)
upload := func(concurrency int, shutTimeout time.Duration) (obj fs.Object, err error) {
// Use the saved (long) timeout while NewFs dials the FTP control
// connection and reads the welcome banner. On slow CI servers this
// can take longer than idleTimeout, which would cause a spurious
// i/o timeout before the test can run. The connection's idle
// deadline is captured at dial time, so the data connection
// dialled later inside Put will still get idleTimeout - which is
// what the test is actually trying to exercise.
ci.Timeout = saveTimeout
fixFs := deriveFs(ctx, t, f, settings{
"concurrency": concurrency,
"shut_timeout": shutTimeout,
})
ci.Timeout = fs.Duration(idleTimeout)
// Make test object
fileTime := fstest.Time("2020-03-08T09:30:00.000000000Z")
+4 -42
View File
@@ -94,23 +94,6 @@ var (
}
)
// gphotosOAuthOptions returns a copy of oauthutil.SharedOptions with
// the client_id help tailored for Google Photos. It copies the shared
// options rather than mutating the global slice.
func gphotosOAuthOptions() []fs.Option {
opts := []fs.Option{}
for _, opt := range oauthutil.SharedOptions {
if opt.Name == config.ConfigClientID {
opt.Help = "OAuth Client Id.\n\nCreating your own is now strongly recommended.\nIf you leave this blank rclone uses a shared client_id which is being retired and will stop working during 2026.\nSee https://rclone.org/googlephotos/#making-your-own-client-id for how to create your own."
}
if opt.Name == config.ConfigClientSecret {
opt.Help = "OAuth Client Secret.\n\nLeave blank to use rclone's shared client_id.\nIf you created your own client_id then enter its client secret here."
}
opts = append(opts, opt)
}
return opts
}
// Register with Fs
func init() {
fs.Register(&fs.RegInfo{
@@ -118,7 +101,7 @@ func init() {
Prefix: "gphotos",
Description: "Google Photos",
NewFs: NewFs,
Config: func(ctx context.Context, name string, m configmap.Mapper, configIn fs.ConfigIn) (*fs.ConfigOut, error) {
Config: func(ctx context.Context, name string, m configmap.Mapper, config fs.ConfigIn) (*fs.ConfigOut, error) {
// Parse config into Options struct
opt := new(Options)
err := configstruct.Set(m, opt)
@@ -126,7 +109,7 @@ func init() {
return nil, fmt.Errorf("couldn't parse config into struct: %w", err)
}
switch configIn.State {
switch config.State {
case "":
// Fill in the scopes
if opt.ReadOnly {
@@ -134,25 +117,6 @@ func init() {
} else {
oauthConfig.Scopes = scopesReadWrite
}
return fs.ConfigGoto("client_id")
case "client_id":
if clientID, _ := m.Get(config.ConfigClientID); clientID != "" {
return fs.ConfigGoto("oauth")
}
return oauthutil.SharedClientIDConfigConfirm("client_id_warning", "Google Photos", "https://rclone.org/googlephotos/#making-your-own-client-id")
case "client_id_warning":
if configIn.Result == "true" {
// Continue using the shared client_id
return fs.ConfigGoto("oauth")
}
return fs.ConfigInput("client_id_set", config.ConfigClientID, "OAuth Client Id")
case "client_id_set":
m.Set(config.ConfigClientID, configIn.Result)
return fs.ConfigInput("client_secret_set", config.ConfigClientSecret, "OAuth Client Secret")
case "client_secret_set":
m.Set(config.ConfigClientSecret, configIn.Result)
return fs.ConfigGoto("oauth")
case "oauth":
return oauthutil.ConfigOut("warning1", &oauthutil.Options{
OAuth2Config: oauthConfig,
})
@@ -172,9 +136,9 @@ IMPORTANT: Due to Google policy changes rclone can now only download photos it u
case "warning_done":
return nil, nil
}
return nil, fmt.Errorf("unknown state %q", configIn.State)
return nil, fmt.Errorf("unknown state %q", config.State)
},
Options: append(append(gphotosOAuthOptions(), []fs.Option{{
Options: append(append(oauthutil.SharedOptions, []fs.Option{{
Name: "read_only",
Default: false,
Help: `Set to make the Google Photos backend read only.
@@ -385,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 {
-54
View File
@@ -69,66 +69,12 @@ func (f *Fs) testUploadFromCrypt(t *testing.T) {
_ = operations.Purge(ctx, f, dirName)
}
func (f *Fs) testUpdateStoresHash(t *testing.T) {
// make a temporary local remote
tempRoot, err := fstest.LocalRemote()
require.NoError(t, err)
defer func() {
_ = os.RemoveAll(tempRoot)
}()
// make a temporary crypt remote as source
ctx := context.Background()
pass := obscure.MustObscure("crypt")
remote := fmt.Sprintf(`:crypt,remote="%s",password="%s":`, tempRoot, pass)
cryptFs, err := fs.NewFs(ctx, remote)
require.NoError(t, err)
const dirName = "update_hash_1"
const fileName = dirName + "/file_update_1"
const longTime = fs.ModTimeNotSupported
hashType := f.keepHashes.GetOne()
// upload initial file to hasher via Put
src1 := putFile(ctx, t, cryptFs, fileName, "initial content")
in1, err := src1.Open(ctx)
require.NoError(t, err)
dst, err := f.Put(ctx, in1, src1)
require.NoError(t, err)
require.NotNil(t, dst)
// verify hash was stored after Put
var hash1 string
if f.opt.MaxAge > 0 {
hash1, err = f.getRawHash(ctx, hashType, fileName, anyFingerprint, longTime)
assert.NoError(t, err)
assert.NotEmpty(t, hash1)
}
// update the file with new content via Update (this is what sync does for replacements)
src2 := putFile(ctx, t, cryptFs, fileName, "updated content")
in2, err := src2.Open(ctx)
require.NoError(t, err)
err = dst.Update(ctx, in2, src2)
require.NoError(t, err)
// verify hash was stored after Update and is different from the original
if f.opt.MaxAge > 0 {
hash2, err := f.getRawHash(ctx, hashType, fileName, anyFingerprint, longTime)
assert.NoError(t, err)
assert.NotEmpty(t, hash2, "hash should be stored after Update")
assert.NotEqual(t, hash1, hash2, "hash should change after Update with different content")
}
_ = operations.Purge(ctx, f, dirName)
}
// InternalTest dispatches all internal tests
func (f *Fs) InternalTest(t *testing.T) {
if !kv.Supported() {
t.Skip("hasher is not supported on this OS")
}
t.Run("UploadFromCrypt", f.testUploadFromCrypt)
t.Run("UpdateStoresHash", f.testUpdateStoresHash)
}
var _ fstests.InternalTester = (*Fs)(nil)
+41 -57
View File
@@ -131,62 +131,10 @@ func (o *Object) updateHashes(ctx context.Context) error {
return nil
}
// wrapInHashingReader wraps in with a hashing reader if needed and
// returns the (possibly wrapped) reader. After the transfer completes
// successfully, call the returned storeHashes function to store the
// computed hashes.
func (f *Fs) wrapInHashingReader(ctx context.Context, in io.Reader, src fs.ObjectInfo) (wrapIn io.Reader, storeHashes func(o *Object)) {
var (
common hash.Set
rehash bool
hashes hashMap
)
if fsrc := src.Fs(); fsrc != nil {
common = fsrc.Hashes().Overlap(f.keepHashes)
// Rehash if source does not have all required hashes or hashing is slow
rehash = fsrc.Features().SlowHash || common != f.keepHashes
}
wrapIn = in
if rehash {
r, err := f.newHashingReader(ctx, in, func(sums hashMap) {
hashes = sums
})
fs.Debugf(src, "Rehash in-fly due to incomplete or slow source set %v (err: %v)", common, err)
if err == nil {
wrapIn = r
} else {
rehash = false
}
}
storeHashes = func(o *Object) {
if !rehash {
hashes = hashMap{}
for _, ht := range common.Array() {
if h, e := src.Hash(ctx, ht); e == nil && h != "" {
hashes[ht] = h
}
}
}
if len(hashes) > 0 {
err := o.putHashes(ctx, hashes)
fs.Debugf(o, "Applied %d source hashes, err: %v", len(hashes), err)
}
}
return wrapIn, storeHashes
}
// Update the object with the given data, time and size.
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
wrapIn, storeHashes := o.f.wrapInHashingReader(ctx, in, src)
_ = o.f.pruneHash(src.Remote())
err := o.Object.Update(ctx, wrapIn, src, options...)
if err != nil {
return err
}
storeHashes(o)
return nil
return o.Object.Update(ctx, in, src, options...)
}
// Remove an object.
@@ -241,15 +189,51 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (r io.ReadC
// Put data into the remote path with given modTime and size
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
wrapIn, storeHashes := f.wrapInHashingReader(ctx, in, src)
var (
o fs.Object
common hash.Set
rehash bool
hashes hashMap
)
if fsrc := src.Fs(); fsrc != nil {
common = fsrc.Hashes().Overlap(f.keepHashes)
// Rehash if source does not have all required hashes or hashing is slow
rehash = fsrc.Features().SlowHash || common != f.keepHashes
}
wrapIn := in
if rehash {
r, err := f.newHashingReader(ctx, in, func(sums hashMap) {
hashes = sums
})
fs.Debugf(src, "Rehash in-fly due to incomplete or slow source set %v (err: %v)", common, err)
if err == nil {
wrapIn = r
} else {
rehash = false
}
}
_ = f.pruneHash(src.Remote())
oResult, err := f.Fs.Put(ctx, wrapIn, src, options...)
o, err := f.wrapObject(oResult, err)
o, err = f.wrapObject(oResult, err)
if err != nil {
return nil, err
}
storeHashes(o.(*Object))
return o, nil
if !rehash {
hashes = hashMap{}
for _, ht := range common.Array() {
if h, e := src.Hash(ctx, ht); e == nil && h != "" {
hashes[ht] = h
}
}
}
if len(hashes) > 0 {
err := o.(*Object).putHashes(ctx, hashes)
fs.Debugf(o, "Applied %d source hashes, err: %v", len(hashes), err)
}
return o, err
}
type hashingReader struct {
+1 -4
View File
@@ -50,10 +50,7 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
if err != nil {
return err
}
// Chtimes sets the modtime with second precision so truncate
// here too to keep the in-memory modtime identical to the one a
// fresh listing returns.
o.modTime = modTime.Truncate(time.Second)
o.modTime = modTime
return nil
}
+1 -4
View File
@@ -888,10 +888,7 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
if err != nil {
return err
}
// The server stores modtimes with second precision so truncate
// here too to keep the in-memory modtime identical to the one a
// fresh listing returns.
o.modTime = modTime.Truncate(time.Second)
o.modTime = modTime
return nil
}
-13
View File
@@ -156,7 +156,6 @@ type Fs struct {
endpoint *url.URL
endpointURL string // endpoint as a string
httpClient *http.Client
fileName string // set if we are pointing to a file
}
// Object is a remote object that has been stat'd (so it exists, but is not necessarily open for reading)
@@ -298,7 +297,6 @@ func (f *Fs) httpConnection(ctx context.Context, opt *Options) (isFile bool, err
if isFile {
// Correct root if definitely pointing to a file
f.fileName = path.Base(f.root)
f.root = path.Dir(f.root)
if f.root == "." || f.root == "/" {
f.root = ""
@@ -566,17 +564,6 @@ func (f *Fs) readDir(ctx context.Context, dir string) (names []string, err error
// This should return ErrDirNotFound if the directory isn't
// found.
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
// pointed at a single file: only that file is visible
if f.fileName != "" {
if dir != "" {
return nil, fs.ErrorDirNotFound
}
obj, err := f.NewObject(ctx, f.fileName)
if err != nil {
return nil, err
}
return fs.DirEntries{obj}, nil
}
if !strings.HasSuffix(dir, "/") && dir != "" {
dir += "/"
}
+1 -13
View File
@@ -331,19 +331,7 @@ func TestIsAFileRoot(t *testing.T) {
f, err := NewFs(context.Background(), remoteName, "one%.txt", m)
assert.Equal(t, err, fs.ErrorIsFile)
entries, err := f.List(context.Background(), "")
require.NoError(t, err)
require.Equal(t, 1, len(entries))
e := entries[0]
assert.Equal(t, "one%.txt", e.Remote())
assert.Equal(t, int64(5+lineEndSize), e.Size())
_, ok := e.(*Object)
assert.True(t, ok)
_, err = f.List(context.Background(), "anysub")
assert.Equal(t, fs.ErrorDirNotFound, err)
testListRoot(t, f, false)
}
func TestIsAFileSubDir(t *testing.T) {
-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
+48 -118
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,48 @@ 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 c.Session.Requires2FA() {
return nil
}
err = c.Session.AuthWithToken(ctx)
if err == nil {
c.saveCachedWebservices()
if c.sessionSaveCallback != nil {
err = c.Session.AuthWithToken(ctx)
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 +148,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
File diff suppressed because it is too large. Load diff
-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())
}
-237
View File
@@ -1,237 +0,0 @@
package api
import (
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"math/big"
)
// RFC 5054 2048-bit group parameters for SRP-6a (g=2, SHA-256).
var (
srpN = mustParseBigHex(
"AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050" +
"A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50" +
"E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B8" +
"55F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773B" +
"CA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748" +
"544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB37861602790" +
"04E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8" +
"E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F" +
"9E4AFF73")
srpG = big.NewInt(2)
srpNLenBytes = 2048 / 8
srpHashFunc = sha256.New
)
func mustParseBigHex(s string) *big.Int {
b, ok := new(big.Int).SetString(s, 16)
if !ok {
panic("srp: bad hex constant for N")
}
return b
}
// srpClient implements the client side of SRP-6a for Apple's iCloud auth.
type srpClient struct {
a *big.Int // client secret
A *big.Int // client public value
k *big.Int // multiplier
M1 []byte
M2 []byte
K []byte
}
// newSRPClient generates a random 32-byte secret and computes the public value A.
func newSRPClient() (*srpClient, error) {
secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, fmt.Errorf("srp: rand.Read failed: %w", err)
}
a := new(big.Int).SetBytes(secret)
A := new(big.Int).Exp(srpG, a, srpN)
k := getMultiplier()
return &srpClient{
a: a,
A: A,
k: k,
}, nil
}
// getABytes returns the padded public value A.
func (c *srpClient) getABytes() []byte {
return padToN(c.A)
}
// processChallenge computes the session key and proof values from the server challenge.
// username is the Apple ID, derivedKey is the output of derivePassword, salt and B come
// from the server's init response (raw bytes, already base64-decoded).
func (c *srpClient) processChallenge(username, derivedKey, salt, serverB []byte) error {
B := new(big.Int).SetBytes(serverB)
// Validate B (RFC 5054)
if B.Cmp(big.NewInt(0)) <= 0 || B.Cmp(srpN) >= 0 {
return fmt.Errorf("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)
aBytes := padToN(c.A)
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.
// For "s2k": PBKDF2(SHA256(password), salt, iterations, 32, SHA256)
// For "s2k_fo": PBKDF2(hex(SHA256(password)), salt, iterations, 32, SHA256)
func derivePassword(password string, salt []byte, iterations int, protocol string) ([]byte, error) {
passHash := sha256.Sum256([]byte(password))
var passInput string
switch protocol {
case "s2k":
passInput = string(passHash[:])
case "s2k_fo":
passInput = hex.EncodeToString(passHash[:])
default:
return nil, fmt.Errorf("unsupported SRP protocol: %q", protocol)
}
return pbkdf2.Key(sha256.New, passInput, salt, iterations, 32)
}
// padToN pads a big.Int to the SRP group size (256 bytes for 2048-bit).
func padToN(n *big.Int) []byte {
b := n.Bytes()
if len(b) >= srpNLenBytes {
return b
}
padded := make([]byte, srpNLenBytes)
copy(padded[srpNLenBytes-len(b):], b)
return padded
}
func srpHash(data []byte) []byte {
h := srpHashFunc()
h.Write(data)
return h.Sum(nil)
}
func hashToInt(h hash.Hash) *big.Int {
return new(big.Int).SetBytes(h.Sum(nil))
}
// getMultiplier computes k = H(N | pad(g))
func getMultiplier() *big.Int {
h := srpHashFunc()
nBytes := srpN.Bytes()
gBytes := srpG.Bytes()
// pad g to same length as N
for len(gBytes) < len(nBytes) {
gBytes = append([]byte{0}, gBytes...)
}
h.Write(nBytes)
h.Write(gBytes)
return hashToInt(h)
}
// calculateX computes x = H(salt | H(":" | password))
// Apple's variant: NoUserNameInX - username is omitted from the inner hash.
// The "password" here is actually the derived key from derivePassword.
func calculateX(salt, derivedKey []byte) *big.Int {
h := srpHashFunc()
// Apple omits username (NoUserNameInX), only writes ":" + derivedKey
h.Write([]byte(":"))
h.Write(derivedKey)
digest := h.Sum(nil)
h2 := srpHashFunc()
h2.Write(salt)
h2.Write(digest)
return new(big.Int).SetBytes(h2.Sum(nil))
}
// calculateU computes u = H(pad(A) | pad(B))
func calculateU(A, B *big.Int) *big.Int {
h := srpHashFunc()
h.Write(padToN(A))
h.Write(padToN(B))
return hashToInt(h)
}
// calculateS computes the client-side shared secret:
// S = (B - k * g^x) ^ (a + u*x) mod N
func calculateS(k, x, a, B, u *big.Int) []byte {
// g^x mod N
gx := new(big.Int).Exp(srpG, x, srpN)
// k * g^x
kgx := new(big.Int).Mul(k, gx)
// B - k*g^x
diff := new(big.Int).Sub(B, kgx)
// u*x
ux := new(big.Int).Mul(u, x)
// a + u*x
exp := new(big.Int).Add(a, ux)
// (B - k*g^x) ^ (a + u*x) mod N
S := new(big.Int).Exp(diff, exp, srpN)
// Ensure positive
S.Mod(S, srpN)
return padToN(S)
}
// calculateK computes K = H(S)
func calculateK(S []byte) []byte {
return srpHash(S)
}
// calculateM1 computes the client proof (Apple/iCloud variant):
// M1 = H(H(g) XOR H(N) | H(username) | salt | A | B | K)
func calculateM1(username, salt, A, B, K []byte) []byte {
hg := srpHash(padToN(srpG))
hn := srpHash(srpN.Bytes())
hi := srpHash(username)
hxor := make([]byte, len(hg))
for i := range hg {
hxor[i] = hg[i] ^ hn[i]
}
h := srpHashFunc()
h.Write(hxor)
h.Write(hi)
h.Write(salt)
h.Write(A)
h.Write(B)
h.Write(K)
return h.Sum(nil)
}
// calculateM2 computes the server proof: M2 = H(A | M1 | K)
func calculateM2(A, M1, K []byte) []byte {
h := srpHashFunc()
h.Write(A)
h.Write(M1)
h.Write(K)
return h.Sum(nil)
}
-411
View File
@@ -1,411 +0,0 @@
package api
import (
"crypto/sha256"
"encoding/hex"
"math/big"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPadToN(t *testing.T) {
t.Run("pads small value to 256 bytes", func(t *testing.T) {
result := padToN(big.NewInt(1))
assert.Equal(t, srpNLenBytes, len(result))
assert.Equal(t, byte(0), result[0])
assert.Equal(t, byte(1), result[srpNLenBytes-1])
})
t.Run("pads zero to 256 bytes", func(t *testing.T) {
result := padToN(big.NewInt(0))
assert.Equal(t, srpNLenBytes, len(result))
for _, b := range result {
assert.Equal(t, byte(0), b)
}
})
t.Run("preserves value that fills N", func(t *testing.T) {
// Use N itself - already 256 bytes
result := padToN(srpN)
assert.Equal(t, srpNLenBytes, len(result))
assert.Equal(t, srpN.Bytes(), result)
})
t.Run("round-trips through big.Int", func(t *testing.T) {
original := big.NewInt(123456789)
padded := padToN(original)
recovered := new(big.Int).SetBytes(padded)
assert.Equal(t, 0, original.Cmp(recovered))
})
}
func TestGetMultiplier(t *testing.T) {
k := getMultiplier()
// k must be non-zero and less than N
assert.True(t, k.Sign() > 0, "multiplier must be positive")
assert.True(t, k.Cmp(srpN) < 0, "multiplier must be less than N")
// k is deterministic
k2 := getMultiplier()
assert.Equal(t, 0, k.Cmp(k2), "multiplier must be deterministic")
// k = H(N | pad(g)) - verify by manual computation
h := srpHashFunc()
nBytes := srpN.Bytes()
gBytes := srpG.Bytes()
for len(gBytes) < len(nBytes) {
gBytes = append([]byte{0}, gBytes...)
}
h.Write(nBytes)
h.Write(gBytes)
expected := new(big.Int).SetBytes(h.Sum(nil))
assert.Equal(t, 0, expected.Cmp(k), "multiplier must equal H(N|pad(g))")
}
func TestDerivePassword(t *testing.T) {
salt := []byte("test_salt_value!")
password := "test_password"
t.Run("s2k produces 32-byte key", func(t *testing.T) {
key, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
t.Run("s2k_fo produces 32-byte key", func(t *testing.T) {
key, err := derivePassword(password, salt, 1000, "s2k_fo")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
t.Run("s2k and s2k_fo produce different keys", func(t *testing.T) {
key1, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword(password, salt, 1000, "s2k_fo")
require.NoError(t, err)
assert.NotEqual(t, key1, key2, "s2k and s2k_fo must produce different keys")
})
t.Run("deterministic output", func(t *testing.T) {
key1, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword(password, salt, 1000, "s2k")
require.NoError(t, err)
assert.Equal(t, key1, key2)
})
t.Run("different passwords produce different keys", func(t *testing.T) {
key1, err := derivePassword("password1", salt, 1000, "s2k")
require.NoError(t, err)
key2, err := derivePassword("password2", salt, 1000, "s2k")
require.NoError(t, err)
assert.NotEqual(t, key1, key2)
})
t.Run("s2k uses raw SHA256 bytes", func(t *testing.T) {
// Verify that s2k uses SHA256(password) as the PBKDF2 input.
// Two passwords with the same SHA256 hash would produce the same key,
// while two passwords with different SHA256 hashes must produce different keys.
key1, err := derivePassword("hello", salt, 10, "s2k")
require.NoError(t, err)
key2, err := derivePassword("world", salt, 10, "s2k")
require.NoError(t, err)
assert.NotEqual(t, key1, key2)
})
t.Run("s2k_fo uses hex-encoded SHA256", func(t *testing.T) {
// For s2k_fo, the PBKDF2 input is hex(SHA256(password)), which is
// a 64-character ASCII string, not raw 32-byte hash.
key, err := derivePassword("hello", salt, 10, "s2k_fo")
require.NoError(t, err)
assert.Equal(t, 32, len(key))
})
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) {
salt := []byte("some_salt")
derivedKey := []byte("some_derived_key_value_32_bytes!")
x := calculateX(salt, derivedKey)
// x must be positive and less than the hash output space
assert.True(t, x.Sign() > 0, "x must be positive")
// x is deterministic
x2 := calculateX(salt, derivedKey)
assert.Equal(t, 0, x.Cmp(x2), "x must be deterministic")
// Verify manually: x = H(salt | H(":" | derivedKey))
h1 := srpHashFunc()
h1.Write([]byte(":"))
h1.Write(derivedKey)
inner := h1.Sum(nil)
h2 := srpHashFunc()
h2.Write(salt)
h2.Write(inner)
expected := new(big.Int).SetBytes(h2.Sum(nil))
assert.Equal(t, 0, expected.Cmp(x), "x must equal H(salt | H(\":\" | derivedKey))")
}
func TestCalculateU(t *testing.T) {
A := big.NewInt(12345)
B := big.NewInt(67890)
u := calculateU(A, B)
assert.True(t, u.Sign() > 0, "u must be positive")
// u is deterministic
u2 := calculateU(A, B)
assert.Equal(t, 0, u.Cmp(u2))
// u changes when inputs change
u3 := calculateU(A, big.NewInt(99999))
assert.NotEqual(t, 0, u.Cmp(u3), "u must change when B changes")
// Verify: u = H(pad(A) | pad(B))
h := srpHashFunc()
h.Write(padToN(A))
h.Write(padToN(B))
expected := new(big.Int).SetBytes(h.Sum(nil))
assert.Equal(t, 0, expected.Cmp(u))
}
func TestCalculateK(t *testing.T) {
S := []byte("some_shared_secret_value_32bytes")
K := calculateK(S)
// K is a SHA-256 hash, so 32 bytes
assert.Equal(t, sha256.Size, len(K))
// K is deterministic
K2 := calculateK(S)
assert.Equal(t, K, K2)
// Verify: K = H(S)
expected := srpHash(S)
assert.Equal(t, expected, K)
}
func TestCalculateM1(t *testing.T) {
username := []byte("test@example.com")
salt := []byte("test_salt")
A := make([]byte, srpNLenBytes)
B := make([]byte, srpNLenBytes)
K := make([]byte, 32)
// Fill with non-zero values
A[srpNLenBytes-1] = 0x42
B[srpNLenBytes-1] = 0x43
K[0] = 0x44
m1 := calculateM1(username, salt, A, B, K)
// M1 is a SHA-256 hash
assert.Equal(t, sha256.Size, len(m1))
// M1 is deterministic
m1b := calculateM1(username, salt, A, B, K)
assert.Equal(t, m1, m1b)
// M1 changes when username changes
m1c := calculateM1([]byte("other@example.com"), salt, A, B, K)
assert.NotEqual(t, m1, m1c)
// Verify: M1 = H(H(g) XOR H(N) | H(username) | salt | A | B | K)
hg := srpHash(padToN(srpG))
hn := srpHash(srpN.Bytes())
hi := srpHash(username)
hxor := make([]byte, len(hg))
for i := range hg {
hxor[i] = hg[i] ^ hn[i]
}
h := srpHashFunc()
h.Write(hxor)
h.Write(hi)
h.Write(salt)
h.Write(A)
h.Write(B)
h.Write(K)
expected := h.Sum(nil)
assert.Equal(t, expected, m1)
}
func TestCalculateM2(t *testing.T) {
A := make([]byte, srpNLenBytes)
M1 := make([]byte, 32)
K := make([]byte, 32)
A[srpNLenBytes-1] = 0x01
M1[0] = 0x02
K[0] = 0x03
m2 := calculateM2(A, M1, K)
assert.Equal(t, sha256.Size, len(m2))
// Verify: M2 = H(A | M1 | K)
h := srpHashFunc()
h.Write(A)
h.Write(M1)
h.Write(K)
assert.Equal(t, h.Sum(nil), m2)
}
func TestNewSRPClient(t *testing.T) {
client, err := newSRPClient()
require.NoError(t, err)
// A must be non-zero and in range [1, N-1]
assert.True(t, client.A.Sign() > 0, "A must be positive")
assert.True(t, client.A.Cmp(srpN) < 0, "A must be less than N")
// A = g^a mod N
expectedA := new(big.Int).Exp(srpG, client.a, srpN)
assert.Equal(t, 0, expectedA.Cmp(client.A), "A must equal g^a mod N")
// getABytes returns padded A
aBytes := client.getABytes()
assert.Equal(t, srpNLenBytes, len(aBytes))
recoveredA := new(big.Int).SetBytes(aBytes)
assert.Equal(t, 0, client.A.Cmp(recoveredA))
// Two clients should have different secrets (probabilistic, but 2^256 collision chance)
client2, err := newSRPClient()
require.NoError(t, err)
assert.NotEqual(t, 0, client.a.Cmp(client2.a), "two clients must have different secrets")
}
func TestProcessChallenge(t *testing.T) {
// Use a fixed secret for deterministic testing
fixedSecret := make([]byte, 32)
fixedSecret[31] = 0x42 // small non-zero value
a := new(big.Int).SetBytes(fixedSecret)
A := new(big.Int).Exp(srpG, a, srpN)
k := getMultiplier()
client := &srpClient{
a: a,
A: A,
k: k,
}
username := []byte("testuser@apple.com")
derivedKey := make([]byte, 32)
for i := range derivedKey {
derivedKey[i] = byte(i)
}
salt := []byte("fixed_salt_for_test!")
// Compute a valid B: B = (k*v + g^b) mod N where v = g^x mod N
x := calculateX(salt, derivedKey)
v := new(big.Int).Exp(srpG, x, srpN)
bSecret := make([]byte, 32)
bSecret[31] = 0x99
b := new(big.Int).SetBytes(bSecret)
// B = (k*v + g^b) mod N
kv := new(big.Int).Mul(k, v)
gb := new(big.Int).Exp(srpG, b, srpN)
B := new(big.Int).Add(kv, gb)
B.Mod(B, srpN)
serverB := padToN(B)
err := client.processChallenge(username, derivedKey, salt, serverB)
require.NoError(t, err)
// M1, M2, K must be populated
assert.NotNil(t, client.M1)
assert.NotNil(t, client.M2)
assert.NotNil(t, client.K)
assert.Equal(t, sha256.Size, len(client.M1))
assert.Equal(t, sha256.Size, len(client.M2))
assert.Equal(t, sha256.Size, len(client.K))
// M1 and M2 must be different
assert.NotEqual(t, client.M1, client.M2)
// Results must be deterministic - run again with same inputs
client2 := &srpClient{
a: new(big.Int).Set(a),
A: new(big.Int).Set(A),
k: new(big.Int).Set(k),
}
err = client2.processChallenge(username, derivedKey, salt, serverB)
require.NoError(t, err)
assert.Equal(t, client.M1, client2.M1, "M1 must be deterministic")
assert.Equal(t, client.M2, client2.M2, "M2 must be deterministic")
assert.Equal(t, client.K, client2.K, "K must be deterministic")
// Verify the server could also compute S and get the same K.
// Server computes: S_server = (A * v^u)^b mod N
u := calculateU(A, B)
vu := new(big.Int).Exp(v, u, srpN)
avu := new(big.Int).Mul(A, vu)
avu.Mod(avu, srpN)
sServer := new(big.Int).Exp(avu, b, srpN)
sServer.Mod(sServer, srpN)
kServer := calculateK(padToN(sServer))
assert.Equal(t, client.K, kServer, "client and server must derive the same session key")
}
func 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())
assert.True(t, len(nHex) > 0)
assert.Equal(t, "ac6bdb41", nHex[:8], "N must start with known prefix")
// g must be 2
assert.Equal(t, int64(2), srpG.Int64())
// N byte length must match expected
assert.Equal(t, 256, srpNLenBytes)
assert.Equal(t, 256, len(srpN.Bytes()))
}
func TestSRPHash(t *testing.T) {
data := []byte("hello world")
hash := srpHash(data)
// Must be SHA-256 output
assert.Equal(t, sha256.Size, len(hash))
// Must equal standard sha256
expected := sha256.Sum256(data)
assert.Equal(t, expected[:], hash)
}
-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)
})
}
}
+11 -24
View File
@@ -32,12 +32,6 @@ const (
)
var systemMetadataInfo = map[string]fs.MetadataHelp{
"mtime": {
Help: "Time of last modification, read from the file's updatedAt field",
Type: "RFC 3339",
Example: "2006-01-02T15:04:05.999999999Z07:00",
ReadOnly: true,
},
"btime": {
Help: "Time of file birth (creation) read from Last-Modified header",
Type: "RFC 3339",
@@ -599,12 +593,12 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
var offset int64
var count int64
fs.FixRangeOption(options, o.Size())
fs.FixRangeOption(options, -1)
partialContent := false
for _, option := range options {
switch x := option.(type) {
case *fs.RangeOption:
offset, count = x.Decode(o.Size())
offset, count = x.Decode(-1)
partialContent = true
case *fs.SeekOption:
offset = x.Offset
@@ -632,13 +626,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
if partialContent {
if count > 0 {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+count-1))
} else {
req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
}
}
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+count-1))
resp, err := client.Do(req)
if err != nil {
@@ -648,9 +636,13 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
end := resp.ContentLength
if partialContent && resp.StatusCode == http.StatusOK {
// The server ignored the Range request so skip to the
// offset and limit what is read ourselves
_, err = io.CopyN(io.Discard, resp.Body, offset)
skip := offset
if offset < 0 {
skip = end + offset + 1
}
_, err = io.CopyN(io.Discard, resp.Body, skip)
if err != nil {
if resp != nil {
_ = resp.Body.Close()
@@ -658,11 +650,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
return nil, err
}
limit := end - offset
if count > 0 && count < limit {
limit = count
}
return readers.NewLimitedReadCloser(resp.Body, limit), nil
return readers.NewLimitedReadCloser(resp.Body, end-skip), nil
}
return resp.Body, nil
@@ -765,7 +753,6 @@ func uploadFile(ctx context.Context, f *Fs, in io.Reader, srcRemote string, opti
// Metadata returns the metadata for the object
func (o *Object) Metadata(ctx context.Context) (metadata fs.Metadata, err error) {
metadata.Set("mtime", o.file.UpdatedAt.Format(time.RFC3339Nano))
metadata.Set("btime", o.file.CreatedAt.Format(time.RFC3339))
metadata.Set("size", strconv.FormatUint(o.file.Size, 10))
metadata.Set("file-type", o.file.FileType)
+26 -185
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 + ":")
}
@@ -343,7 +307,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
fs.Debugf(f, "getUserInfo returned 401, attempting re-auth")
authErr := f.refreshOrReLogin(ctx)
if authErr != nil {
return nil, fmt.Errorf("failed to fetch user info (re-auth failed: %w): %w", authErr, err)
return nil, fmt.Errorf("failed to fetch user info (re-auth failed): %w", err)
}
userInfo, err = getUserInfo(ctx, &userInfoConfig{Token: f.cfg.Token})
if err == nil {
@@ -830,80 +794,6 @@ func (f *Fs) About(ctx context.Context) (*fs.Usage, error) {
return usage, nil
}
// Move moves a file to a new location
func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object, error) {
srcObj, ok := src.(*Object)
if !ok {
return nil, fs.ErrorCantMove
}
if srcObj.uuid == "" {
return nil, fs.ErrorCantMove
}
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, true)
if err != nil {
return nil, err
}
// Parse name and extension from the leaf
baseName := f.opt.Encoding.FromStandardName(leaf)
newName := strings.TrimSuffix(baseName, path.Ext(baseName))
newType := strings.TrimPrefix(path.Ext(baseName), ".")
// Move the file server-side
err = f.pacer.Call(func() (bool, error) {
err := files.MoveFile(ctx, f.cfg, srcObj.uuid, directoryID, newName, newType)
return f.shouldRetry(ctx, err)
})
if err != nil {
return nil, err
}
dstObj := &Object{
f: f,
remote: remote,
id: srcObj.id,
uuid: srcObj.uuid,
size: srcObj.size,
modTime: srcObj.modTime,
}
return dstObj, nil
}
// DirMove moves src, srcRemote to this remote at dstRemote
// using server-side move operations.
//
// Will only be called if src.Fs().Name() == f.Name()
//
// If it isn't possible then return fs.ErrorCantDirMove
//
// If destination exists then return fs.ErrorDirExists
func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string) error {
srcFs, ok := src.(*Fs)
if !ok {
return fs.ErrorCantDirMove
}
srcID, _, _, dstDirectoryID, dstLeaf, err := f.dirCache.DirMove(ctx, srcFs.dirCache, srcFs.root, srcRemote, f.root, dstRemote)
if err != nil {
return err
}
encodedLeaf := f.opt.Encoding.FromStandardName(dstLeaf)
err = f.pacer.Call(func() (bool, error) {
err := folders.MoveFolder(ctx, f.cfg, srcID, dstDirectoryID, encodedLeaf)
return f.shouldRetry(ctx, err)
})
if err != nil {
return err
}
srcFs.dirCache.FlushDir(srcRemote)
return nil
}
// Shutdown the backend, closing any background tasks and any cached
// connections.
func (f *Fs) Shutdown(ctx context.Context) error {
@@ -994,62 +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
}
if tooLarge := fileTooLargeError(uploadErr); tooLarge != nil {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return o.f.tooLargeError(remote, tooLarge)
}
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 tooLarge := fileTooLargeError(err); tooLarge != nil {
o.restoreBackupFile(ctx, backupUUID, origName, origType)
return o.f.tooLargeError(remote, tooLarge)
}
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
@@ -1114,25 +974,6 @@ func isEmptyFileLimitError(err error) bool {
strings.Contains(errMsg, "you can not have empty files")
}
// fileTooLargeError extracts the SDK's FileTooLargeError from a wrapped error
// chain, returning it (or nil) so callers can branch on the size limit.
func fileTooLargeError(err error) *sdkerrors.FileTooLargeError {
var tooLarge *sdkerrors.FileTooLargeError
if errors.As(err, &tooLarge) {
return tooLarge
}
return nil
}
// tooLargeError formats a per-file, non-retryable error for the sync engine.
// fserrors.NoRetryError signals "skip this file but continue the sync."
func (f *Fs) tooLargeError(remote string, tooLarge *sdkerrors.FileTooLargeError) error {
return fserrors.NoRetryError(fmt.Errorf("%s: file size %s exceeds account upload limit of %s",
remote,
fs.SizeSuffix(tooLarge.Size),
fs.SizeSuffix(tooLarge.MaxSize)))
}
// recoverFromTimeoutConflict attempts to recover from a timeout or conflict error
func (o *Object) recoverFromTimeoutConflict(ctx context.Context, uploadErr error, remote, dirID string) (*buckets.CreateMetaResponse, error) {
if !isTimeoutError(uploadErr) && !isConflictError(uploadErr) {
-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,
},
})
}
-296
View File
@@ -1,296 +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 {
if tooLarge := fileTooLargeError(err); tooLarge != nil {
return info, nil, f.tooLargeError(remote, tooLarge)
}
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
}
+4 -8
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),
}}...),
})
}
@@ -1451,7 +1449,7 @@ func (f *Fs) createOrUpdate(ctx context.Context, file string, createTime time.Ti
return info, nil
}
// copyOrMove copies or moves directories or files depending on the method parameter
// copyOrMoves copies or moves directories or files depending on the method parameter
func (f *Fs) copyOrMove(ctx context.Context, method, src, dest string) (info *api.JottaFile, err error) {
opts := rest.Opts{
Method: "POST",
@@ -1876,10 +1874,8 @@ func (o *Object) SetModTime(ctx context.Context, modTime time.Time) error {
return err
}
// update local metadata - the server stores modtimes with second
// precision so truncate here too to keep the in-memory modtime
// identical to the one a fresh listing returns
o.modTime = modTime.Truncate(time.Second)
// update local metadata
o.modTime = modTime
return nil
}
+43 -169
View File
@@ -14,23 +14,19 @@ import (
"bytes"
"context"
"crypto/md5"
"crypto/tls"
"encoding/json"
"errors"
"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"
@@ -45,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
)
@@ -59,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)
@@ -80,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)
@@ -130,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)
@@ -159,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
@@ -208,75 +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 retry, err := f.shouldRetry(ctx, resp, err); retry || err != nil {
return retry, 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"`
@@ -339,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)},
@@ -368,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)
}
@@ -517,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 {
@@ -555,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
}
@@ -632,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
}
@@ -644,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,
@@ -656,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)
})
@@ -815,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
}
@@ -1015,14 +897,6 @@ func (f *Fs) shouldRetry(ctx context.Context, resp *http.Response, err error) (b
if fserrors.ContextError(ctx, &err) {
return false, err
}
// The API is fronted by bot protection which under load
// intermittently returns an HTML challenge page with a 200
// status instead of JSON. This surfaces as a JSON syntax error,
// so retry it to let the pacer back off until the block lifts.
var syntaxErr *json.SyntaxError
if errors.As(err, &syntaxErr) {
return true, err
}
return fserrors.ShouldRetry(err) || fserrors.ShouldRetryHTTP(resp, retryErrorCodes), err
}
+2 -9
View File
@@ -42,10 +42,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
// Create destination
dstObj, err := f.newObject(remote)
if err != nil {
return nil, err
}
dstObj := f.newObject(remote)
err = dstObj.mkdirAll()
if err != nil {
return nil, err
@@ -59,11 +56,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
}
dstPath, err := f.localPath(remote)
if err != nil {
return nil, err
}
err = Clone(srcPath, dstPath)
err = Clone(srcPath, f.localPath(remote))
if err != nil {
return nil, err
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !linux
package local
import (
"io"
"os"
)
func newFadviseReadCloser(o *Object, f *os.File, offset, limit int64) io.ReadCloser {
return f
}
+165
View File
@@ -0,0 +1,165 @@
//go:build linux
package local
import (
"io"
"os"
"github.com/rclone/rclone/fs"
"golang.org/x/sys/unix"
)
// fadvise provides means to automate freeing pages in kernel page cache for
// a given file descriptor as the file is sequentially processed (read or
// written).
//
// When copying a file to a remote backend all the file content is read by
// kernel and put to page cache to make future reads faster.
// This causes memory pressure visible in both memory usage and CPU consumption
// and can even cause OOM errors in applications consuming large amounts memory.
//
// In case of an upload to a remote backend, there is no benefits from caching.
//
// fadvise would orchestrate calling POSIX_FADV_DONTNEED
//
// POSIX_FADV_DONTNEED attempts to free cached pages associated
// with the specified region. This is useful, for example, while
// streaming large files. A program may periodically request the
// kernel to free cached data that has already been used, so that
// more useful cached pages are not discarded instead.
//
// Requests to discard partial pages are ignored. It is
// preferable to preserve needed data than discard unneeded data.
// If the application requires that data be considered for
// discarding, then offset and len must be page-aligned.
//
// The implementation may attempt to write back dirty pages in
// the specified region, but this is not guaranteed. Any
// unwritten dirty pages will not be freed. If the application
// wishes to ensure that dirty pages will be released, it should
// call fsync(2) or fdatasync(2) first.
type fadvise struct {
o *Object
fd int
lastPos int64
curPos int64
windowSize int64
freePagesCh chan offsetLength
doneCh chan struct{}
}
type offsetLength struct {
offset int64
length int64
}
const (
defaultAllowPages = 32
defaultWorkerQueueSize = 64
)
func newFadvise(o *Object, fd int, offset int64) *fadvise {
f := &fadvise{
o: o,
fd: fd,
lastPos: offset,
curPos: offset,
windowSize: int64(os.Getpagesize()) * defaultAllowPages,
freePagesCh: make(chan offsetLength, defaultWorkerQueueSize),
doneCh: make(chan struct{}),
}
go f.worker()
return f
}
// sequential configures readahead strategy in Linux kernel.
//
// Under Linux, POSIX_FADV_NORMAL sets the readahead window to the
// default size for the backing device; POSIX_FADV_SEQUENTIAL doubles
// this size, and POSIX_FADV_RANDOM disables file readahead entirely.
func (f *fadvise) sequential(limit int64) bool {
l := int64(0)
if limit > 0 {
l = limit
}
if err := unix.Fadvise(f.fd, f.curPos, l, unix.FADV_SEQUENTIAL); err != nil {
fs.Debugf(f.o, "fadvise sequential failed on file descriptor %d: %s", f.fd, err)
return false
}
return true
}
func (f *fadvise) next(n int) {
f.curPos += int64(n)
f.freePagesIfNeeded()
}
func (f *fadvise) freePagesIfNeeded() {
if f.curPos >= f.lastPos+f.windowSize {
f.freePages()
}
}
func (f *fadvise) freePages() {
f.freePagesCh <- offsetLength{f.lastPos, f.curPos - f.lastPos}
f.lastPos = f.curPos
}
func (f *fadvise) worker() {
for p := range f.freePagesCh {
if err := unix.Fadvise(f.fd, p.offset, p.length, unix.FADV_DONTNEED); err != nil {
fs.Debugf(f.o, "fadvise dontneed failed on file descriptor %d: %s", f.fd, err)
}
}
close(f.doneCh)
}
func (f *fadvise) wait() {
close(f.freePagesCh)
<-f.doneCh
}
type fadviseReadCloser struct {
*fadvise
inner io.ReadCloser
}
// newFadviseReadCloser wraps os.File so that reading from that file would
// remove already consumed pages from kernel page cache.
// In addition to that it instructs kernel to double the readahead window to
// make sequential reads faster.
// See also fadvise.
func newFadviseReadCloser(o *Object, f *os.File, offset, limit int64) io.ReadCloser {
r := fadviseReadCloser{
fadvise: newFadvise(o, int(f.Fd()), offset),
inner: f,
}
// If syscall failed it's likely that the subsequent syscalls to that
// file descriptor would also fail. In that case return the provided os.File
// pointer.
if !r.sequential(limit) {
r.wait()
return f
}
return r
}
func (f fadviseReadCloser) Read(p []byte) (n int, err error) {
n, err = f.inner.Read(p)
f.next(n)
return
}
func (f fadviseReadCloser) Close() error {
f.freePages()
f.wait()
return f.inner.Close()
}
+63 -250
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,25 +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"`
FatalIfNoSpace bool `config:"fatal_if_no_space"`
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
@@ -437,7 +397,6 @@ type Directory struct {
var (
errLinksAndCopyLinks = errors.New("can't use -l/--links with -L/--copy-links")
errLinksNeedsSuffix = errors.New("need \"" + fs.LinkSuffix + "\" suffix to refer to symlink when using -l/--links")
errPathEscapes = errors.New("file name is not a path within the local root - check the encoding")
)
// NewFs constructs an Fs from the path
@@ -577,12 +536,9 @@ func translateLink(remote, localPath string) (newLocalPath string, isTranslatedL
}
// newObject makes a half completed Object
func (f *Fs) newObject(remote string) (*Object, error) {
func (f *Fs) newObject(remote string) *Object {
translatedLink := false
localPath, err := f.localPath(remote)
if err != nil {
return nil, err
}
localPath := f.localPath(remote)
if f.opt.TranslateSymlinks {
// Possibly receive a new name for localPath
@@ -594,17 +550,14 @@ func (f *Fs) newObject(remote string) (*Object, error) {
remote: remote,
path: localPath,
translatedLink: translatedLink,
}, nil
}
}
// Return an Object from a path
//
// May return nil if an error occurred
func (f *Fs) newObjectWithInfo(remote string, info os.FileInfo) (fs.Object, error) {
o, err := f.newObject(remote)
if err != nil {
return nil, err
}
o := f.newObject(remote)
if info != nil {
o.setMetadata(info)
} else {
@@ -637,15 +590,12 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
}
// Create new directory object from the info passed in
func (f *Fs) newDirectory(dir string, fi os.FileInfo) (*Directory, error) {
o, err := f.newObject(dir)
if err != nil {
return nil, err
}
func (f *Fs) newDirectory(dir string, fi os.FileInfo) *Directory {
o := f.newObject(dir)
o.setMetadata(fi)
return &Directory{
Object: *o,
}, nil
}
}
// List the objects and directories in dir into entries. The
@@ -660,10 +610,7 @@ func (f *Fs) newDirectory(dir string, fi os.FileInfo) (*Directory, error) {
func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err error) {
filter, useFilter := filter.GetConfig(ctx), filter.GetUseFilter(ctx)
fsDirPath, err := f.localPath(dir)
if err != nil {
return nil, err
}
fsDirPath := f.localPath(dir)
_, err = os.Stat(fsDirPath)
if err != nil {
return nil, fs.ErrorDirNotFound
@@ -765,10 +712,7 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
// Ignore directories which are symlinks. These are junction points under windows which
// are kind of a souped up symlink. Unix doesn't have directories which are symlinks.
if (mode&symlinkFlag) == 0 && f.dev == readDevice(fi, f.opt.OneFileSystem) {
d, err := f.newDirectory(newRemote, fi)
if err != nil {
return nil, err
}
d := f.newDirectory(newRemote, fi)
entries = append(entries, d)
}
} else {
@@ -811,29 +755,15 @@ func (f *Fs) cleanRemote(dir, filename string) (remote string) {
return
}
// localPath returns the OS path for the object called name, which is
// always underneath f.root.
//
// It returns errPathEscapes if name resolves outside f.root which can
// happen depending on the encoding.
func (f *Fs) localPath(name string) (string, error) {
native := filepath.FromSlash(f.opt.Enc.FromStandardPath(name))
localPath := filepath.Join(f.root, native)
rel, err := filepath.Rel(f.root, localPath)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fserrors.NoRetryError(fmt.Errorf("%q: %w", name, errPathEscapes))
}
return localPath, nil
func (f *Fs) localPath(name string) string {
return filepath.Join(f.root, filepath.FromSlash(f.opt.Enc.FromStandardPath(name)))
}
// Put the Object to the local filesystem
func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
// Temporary Object under construction - info filled in by Update()
o, err := f.newObject(src.Remote())
if err != nil {
return nil, err
}
err = o.Update(ctx, in, src, options...)
o := f.newObject(src.Remote())
err := o.Update(ctx, in, src, options...)
if err != nil {
return nil, err
}
@@ -847,11 +777,8 @@ 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, err := f.localPath(dir)
if err != nil {
return err
}
err = f.mkdirAll(localPath)
localPath := f.localPath(dir)
err := file.MkdirAll(localPath, 0777)
if err != nil {
return err
}
@@ -867,14 +794,10 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
// DirSetModTime sets the directory modtime for dir
func (f *Fs) DirSetModTime(ctx context.Context, dir string, modTime time.Time) error {
localPath, err := f.localPath(dir)
if err != nil {
return err
}
o := Object{
fs: f,
remote: dir,
path: localPath,
path: f.localPath(dir),
}
return o.SetModTime(ctx, modTime)
}
@@ -888,10 +811,7 @@ func (f *Fs) DirSetModTime(ctx context.Context, dir string, modTime time.Time) e
// It returns the directory that was created.
func (f *Fs) MkdirMetadata(ctx context.Context, dir string, metadata fs.Metadata) (fs.Directory, error) {
// Find and or create the directory
localPath, err := f.localPath(dir)
if err != nil {
return nil, err
}
localPath := f.localPath(dir)
fi, err := f.lstat(localPath)
if errors.Is(err, os.ErrNotExist) {
err := f.Mkdir(ctx, dir)
@@ -907,10 +827,7 @@ func (f *Fs) MkdirMetadata(ctx context.Context, dir string, metadata fs.Metadata
}
// Create directory object
d, err := f.newDirectory(dir, fi)
if err != nil {
return nil, err
}
d := f.newDirectory(dir, fi)
// Set metadata on the directory object if provided
if metadata != nil {
@@ -931,16 +848,13 @@ func (f *Fs) MkdirMetadata(ctx context.Context, dir string, metadata fs.Metadata
//
// If it isn't empty it will return an error
func (f *Fs) Rmdir(ctx context.Context, dir string) error {
localPath, err := f.localPath(dir)
if err != nil {
return err
}
localPath := f.localPath(dir)
if fi, err := os.Stat(localPath); err != nil {
return err
} else if !fi.IsDir() {
return fs.ErrorIsFile
}
err = os.Remove(localPath)
err := os.Remove(localPath)
if runtime.GOOS == "windows" && errors.Is(err, iofs.ErrPermission) { // https://github.com/golang/go/issues/26295
if os.Chmod(localPath, 0o600) == nil {
err = os.Remove(localPath)
@@ -1030,16 +944,13 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
}
// Temporary Object under construction
dstObj, err := f.newObject(remote)
if err != nil {
return nil, err
}
dstObj := f.newObject(remote)
dstObj.fs.objectMetaMu.RLock()
dstObjMode := dstObj.mode
dstObj.fs.objectMetaMu.RUnlock()
// Check it is a file if it exists
err = dstObj.lstat()
err := dstObj.lstat()
if os.IsNotExist(err) {
// OK
} else if err != nil {
@@ -1105,17 +1016,11 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
fs.Debugf(srcFs, "Can't move directory - not same remote type")
return fs.ErrorCantDirMove
}
srcPath, err := srcFs.localPath(srcRemote)
if err != nil {
return err
}
dstPath, err := f.localPath(dstRemote)
if err != nil {
return err
}
srcPath := srcFs.localPath(srcRemote)
dstPath := f.localPath(dstRemote)
// Check if destination exists
_, err = os.Lstat(dstPath)
_, err := os.Lstat(dstPath)
if !os.IsNotExist(err) {
return fs.ErrorDirExists
}
@@ -1263,7 +1168,7 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
var fd *os.File
fd, err = file.Open(o.path)
if fd != nil {
in = fd
in = newFadviseReadCloser(o, fd, 0, 0)
}
} else {
in, err = o.openTranslatedLink(0, -1)
@@ -1469,7 +1374,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (in io.Read
if err != nil {
return
}
wrappedFd := readers.NewLimitedReadCloser(fd, limit)
wrappedFd := readers.NewLimitedReadCloser(newFadviseReadCloser(o, fd, offset, limit), limit)
if offset != 0 {
// seek the object
_, err = fd.Seek(offset, io.SeekStart)
@@ -1490,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 {
@@ -1579,19 +1410,8 @@ func (nwc nopWriterCloser) Close() error {
return nil
}
// isDiskFullError returns true if err indicates the underlying filesystem
// has run out of space.
func isDiskFullError(err error) bool {
return errors.Is(err, file.ErrDiskFull) || fserrors.IsErrNoSpace(err)
}
// Update the object from in with modTime and size
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (err error) {
defer func() {
if err != nil && o.fs.opt.FatalIfNoSpace && isDiskFullError(err) {
err = fserrors.FatalError(err)
}
}()
var out io.WriteCloser
var hasher *hash.MultiHasher
@@ -1620,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
}
@@ -1663,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
@@ -1719,12 +1544,9 @@ var sparseWarning sync.Once
// It truncates any existing object
func (f *Fs) OpenWriterAt(ctx context.Context, remote string, size int64) (fs.WriterAtCloser, error) {
// Temporary Object under construction
o, err := f.newObject(remote)
if err != nil {
return nil, err
}
o := f.newObject(remote)
err = o.mkdirAll()
err := o.mkdirAll()
if err != nil {
return nil, err
}
@@ -1733,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
}
@@ -1881,18 +1703,9 @@ func cleanRootPath(s string, noUNC bool, enc encoder.MultiEncoder) string {
if runtime.GOOS == "windows" {
s = vol + s
}
// UNC paths on Windows must be absolute, so make the path absolute
// there. On other platforms filepath.Abs would prepend the current
// directory, but the resulting absolute string is not guaranteed to
// refer to the same directory as the original relative path - for
// example when the current directory is shadowed by a mount or has been
// removed - so just clean it lexically instead.
if runtime.GOOS == "windows" {
if s2, err := filepath.Abs(s); err == nil {
s = s2
}
} else {
s = filepath.Clean(s)
s2, err := filepath.Abs(s)
if err == nil {
s = s2
}
if !noUNC {
// Convert to UNC. It does nothing on non windows platforms.
@@ -1,98 +0,0 @@
//go:build !plan9
// Tests for the FatalIfNoSpace option and isDiskFullError helper.
//
// Kept in a separate file with a !plan9 build tag because syscall.ENOSPC
// is not portable to plan9, mirroring the split in
// fs/fserrors/enospc_error.go vs fs/fserrors/enospc_error_notsupported.go.
package local
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"syscall"
"testing"
"time"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/file"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// errReader is an io.Reader that always returns the configured error,
// used to inject a synthetic disk-full failure into Update's io.Copy.
type errReader struct{ err error }
func (r errReader) Read(p []byte) (int, error) { return 0, r.err }
// TestIsDiskFullError covers the helper used by the Update defer.
func TestIsDiskFullError(t *testing.T) {
cases := []struct {
name string
err error
want bool
}{
{"nil", nil, false},
{"unrelated error", errors.New("unrelated error"), false},
{"syscall.ENOSPC direct", syscall.ENOSPC, true},
{"syscall.ENOSPC wrapped", fmt.Errorf("io.Copy: %w", syscall.ENOSPC), true},
{"file.ErrDiskFull direct", file.ErrDiskFull, true},
{"file.ErrDiskFull wrapped", fmt.Errorf("preallocate: %w", file.ErrDiskFull), true},
{"os.PathError wrapping ENOSPC", &os.PathError{Op: "write", Path: "/foo", Err: syscall.ENOSPC}, true},
{"os.SyscallError wrapping ENOSPC", os.NewSyscallError("write", syscall.ENOSPC), true},
{"os.PathError wrapping unrelated", &os.PathError{Op: "write", Path: "/foo", Err: syscall.EPERM}, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.Equal(t, c.want, isDiskFullError(c.err))
})
}
}
// updateWithReader runs Update with an injected reader error and the given
// FatalIfNoSpace setting, returning the error from Update.
func updateWithReader(t *testing.T, fatalIfNoSpace bool, readerErr error) error {
t.Helper()
r := fstest.NewRun(t)
f := r.Flocal.(*Fs)
f.opt.FatalIfNoSpace = fatalIfNoSpace
src := object.NewStaticObjectInfo("test.txt", time.Now(), 100, true, nil, f)
o := &Object{
fs: f,
remote: "test.txt",
path: filepath.Join(r.LocalName, "test.txt"),
}
return o.Update(context.Background(), errReader{err: readerErr}, src)
}
// TestUpdateFatalIfNoSpaceOff verifies an ENOSPC during a write is NOT
// wrapped as fatal when the option is off.
func TestUpdateFatalIfNoSpaceOff(t *testing.T) {
err := updateWithReader(t, false, syscall.ENOSPC)
require.Error(t, err)
assert.False(t, fserrors.IsFatalError(err), "ENOSPC must not be fatal when FatalIfNoSpace=false")
}
// TestUpdateFatalIfNoSpaceOn verifies an ENOSPC during a write IS wrapped as
// fatal when the option is on.
func TestUpdateFatalIfNoSpaceOn(t *testing.T) {
err := updateWithReader(t, true, syscall.ENOSPC)
require.Error(t, err)
assert.True(t, fserrors.IsFatalError(err), "ENOSPC must be fatal when FatalIfNoSpace=true")
}
// TestUpdateFatalIfNoSpaceOnButNotDiskFull verifies non-disk-full errors are
// NOT wrapped as fatal even when the option is on.
func TestUpdateFatalIfNoSpaceOnButNotDiskFull(t *testing.T) {
err := updateWithReader(t, true, errors.New("unrelated network error"))
require.Error(t, err)
assert.False(t, fserrors.IsFatalError(err), "non-disk-full errors must not be fatal regardless of option")
}
-301
View File
@@ -10,7 +10,6 @@ import (
"path/filepath"
"runtime"
"sort"
"sync"
"testing"
"time"
@@ -18,12 +17,10 @@ import (
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/lib/readers"
"github.com/stretchr/testify/assert"
@@ -207,251 +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))
}
// TestEncodingEscapeBlocked checks that a name from a malicious source can't
// be decoded into path syntax which writes outside the destination.
func TestEncodingEscapeBlocked(t *testing.T) {
ctx := context.Background()
outer := t.TempDir()
// What a source backend which encodes Dot returns from Remote() for an
// object called "../marker.txt" - e.g. s3 listing the key
// "tenant/../marker.txt" with the remote rooted at "tenant".
remote := encoder.OS.ToStandardPath("../marker.txt")
require.Equal(t, "../marker.txt", remote)
// A file outside the destination the attacker wants to overwrite.
marker := filepath.Join(outer, "marker.txt")
require.NoError(t, os.WriteFile(marker, []byte("original"), 0600))
// An encoding without Dot decodes the name back into "..".
fRaw, err := NewFs(ctx, "local", filepath.Join(outer, "dst"), configmap.Simple{"encoding": "Slash"})
require.NoError(t, err)
f := fRaw.(*Fs)
require.ErrorIs(t, putFile(ctx, f, remote, "PWNED"), errPathEscapes)
got, err := os.ReadFile(marker)
require.NoError(t, err)
require.Equal(t, "original", string(got), "a file outside the destination was overwritten")
// The other entry points which resolve a name are refused too.
require.ErrorIs(t, f.Mkdir(ctx, remote), errPathEscapes)
require.ErrorIs(t, f.Rmdir(ctx, remote), errPathEscapes)
_, err = f.NewObject(ctx, remote)
require.ErrorIs(t, err, errPathEscapes)
// Ordinary names in the same configuration still work.
require.NoError(t, putFile(ctx, f, "sub/file.txt", "hello"))
got, err = os.ReadFile(filepath.Join(f.root, "sub", "file.txt"))
require.NoError(t, err)
require.Equal(t, "hello", string(got))
// The entry points which take a name as a destination refuse it too.
src, err := f.NewObject(ctx, "sub/file.txt")
require.NoError(t, err)
_, err = f.Move(ctx, src, remote)
require.ErrorIs(t, err, errPathEscapes)
require.ErrorIs(t, f.DirMove(ctx, f, "sub", remote), errPathEscapes)
_, err = f.OpenWriterAt(ctx, remote, 5)
require.ErrorIs(t, err, errPathEscapes)
_, err = f.List(ctx, remote)
require.ErrorIs(t, err, errPathEscapes)
// With the default encoding the name is stored literally as fullwidth
// dots, inside the destination.
dRaw, err := NewFs(ctx, "local", filepath.Join(outer, "default"), configmap.Simple{"encoding": encoder.OS.String()})
require.NoError(t, err)
d := dRaw.(*Fs)
require.NoError(t, putFile(ctx, d, remote, "safe"))
got, err = os.ReadFile(filepath.Join(d.root, "..", "marker.txt"))
require.NoError(t, err)
require.Equal(t, "safe", string(got))
if runtime.GOOS == "windows" {
// A backslash is a path separator on Windows, so an encoding
// without BackSlash escapes the root even though it has Dot.
wRaw, err := NewFs(ctx, "local", filepath.Join(outer, "win"), configmap.Simple{"encoding": "Slash,Dot"})
require.NoError(t, err)
require.ErrorIs(t, putFile(ctx, wRaw, `..\marker.txt`, "PWNED"), errPathEscapes)
got, err := os.ReadFile(marker)
require.NoError(t, err)
require.Equal(t, "original", string(got), "a file outside the destination was overwritten")
}
}
// TestLocalPath checks which names localPath refuses. It must refuse
// exactly those which resolve outside the root - names which are merely
// unusual on the host platform are the OS's business, not ours.
func TestLocalPath(t *testing.T) {
ctx := context.Background()
fRaw, err := NewFs(ctx, "local", t.TempDir(), configmap.Simple{"encoding": "Raw"})
require.NoError(t, err)
f := fRaw.(*Fs)
const refused = "!"
for _, test := range []struct {
name string
want string // slash separated path relative to the root, or refused
}{
{name: "", want: "."},
{name: "file.txt", want: "file.txt"},
{name: "sub/file.txt", want: "sub/file.txt"},
{name: "sub/../file.txt", want: "file.txt"},
{name: "..", want: refused},
{name: "../marker.txt", want: refused},
{name: "sub/../../marker.txt", want: refused},
// Windows reserved device names are ordinary file names to
// rclone, which addresses the destination with \\?\ paths.
{name: "NUL", want: "NUL"},
{name: "sub/aux.c", want: "sub/aux.c"},
// An absolute name resolves relative to the root, as it always has.
{name: "/etc/passwd", want: "etc/passwd"},
} {
got, err := f.localPath(test.name)
if test.want == refused {
assert.ErrorIs(t, err, errPathEscapes, test.name)
assert.True(t, fserrors.IsNoRetryError(err), test.name)
continue
}
if assert.NoError(t, err, test.name) {
assert.Equal(t, filepath.Join(f.root, filepath.FromSlash(test.want)), got, test.name)
}
}
}
func TestHashWithTypeNone(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
@@ -719,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)
-26
View File
@@ -30,29 +30,3 @@ func TestCleanWindows(t *testing.T) {
}
}
}
// Relative roots must stay relative so the OS resolves them against the
// live working directory rather than a canonicalised string that may no
// longer refer to the same directory (#9510).
var testsRelative = [][2]string{
{".", "."},
{"./", "."},
{"sub/dir", "sub/dir"},
{"sub/dir/", "sub/dir"},
{"./sub/dir", "sub/dir"},
{"sub/../dir", "dir"},
{"..", ".."},
}
func TestCleanRootPathRelative(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("non-windows only")
}
for _, test := range testsRelative {
got := cleanRootPath(test[0], true, encoder.OS)
expect := test[1]
if got != expect {
t.Fatalf("got %q, expected %q", got, expect)
}
}
}
-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
}
Loaded 100 of 584 files, more files were not shown because too many files have changed in this diff. Show more