Compare commits
166
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be8d6044ea | ||
|
|
bd07f481e2 | ||
|
|
56059c47c8 | ||
|
|
35ab21109b | ||
|
|
fc7a57b447 | ||
|
|
028f2b4568 | ||
|
|
62e770eb54 | ||
|
|
652bbb0908 | ||
|
|
4df376e2db | ||
|
|
68e43e5b88 | ||
|
|
1dcc246e03 | ||
|
|
4cc69c2a62 | ||
|
|
8d97a50c4a | ||
|
|
7c2405c035 | ||
|
|
10335538d1 | ||
|
|
a7b1599204 | ||
|
|
518f43dee9 | ||
|
|
43d3374465 | ||
|
|
10875eec70 | ||
|
|
40eaa114c1 | ||
|
|
a34b606abf | ||
|
|
37aa0cb629 | ||
|
|
a7f0259e55 | ||
|
|
323b0b4559 | ||
|
|
26175553a7 | ||
|
|
4a944dff0f | ||
|
|
e9b9b48a68 | ||
|
|
3a14789eb4 | ||
|
|
47027efd12 | ||
|
|
2f43b99abe | ||
|
|
133ced103a | ||
|
|
317c885857 | ||
|
|
a34f1f153a | ||
|
|
e7d4d425bc | ||
|
|
01a9d67e06 | ||
|
|
aece53963a | ||
|
|
291016ea75 | ||
|
|
7e57142de1 | ||
|
|
722c14d806 | ||
|
|
89b8a59e8b | ||
|
|
1b500594d3 | ||
|
|
9b495f2717 | ||
|
|
f6290108df | ||
|
|
ed9f1d836e | ||
|
|
59ea591bcb | ||
|
|
2cc9088374 | ||
|
|
d8dbeb9de4 | ||
|
|
9cf1af177a | ||
|
|
bb42b076af | ||
|
|
0992024791 | ||
|
|
48ac01c2b8 | ||
|
|
b928e8ddd0 | ||
|
|
9ac7855da9 | ||
|
|
5d20bd2832 | ||
|
|
2f84013eec | ||
|
|
675f9c3684 | ||
|
|
b8a697888c | ||
|
|
dddf808b47 | ||
|
|
451346f01c | ||
|
|
6fadaa46aa | ||
|
|
563919b0c0 | ||
|
|
1ecdeb4466 | ||
|
|
b85a681721 | ||
|
|
61b8a90db8 | ||
|
|
419c5f9844 | ||
|
|
50d2430b4a | ||
|
|
cd6941ed93 | ||
|
|
8290a478c8 | ||
|
|
d89f30a136 | ||
|
|
f8899ca982 | ||
|
|
d77c1bf5c6 | ||
|
|
19bf14aea4 | ||
|
|
353167fd38 | ||
|
|
09e1967c73 | ||
|
|
1d1eb94c34 | ||
|
|
fd3b9bd383 | ||
|
|
6676f2673e | ||
|
|
f6af51420f | ||
|
|
a755455609 | ||
|
|
0e6ed13131 | ||
|
|
96d2633836 | ||
|
|
f625ac98a6 | ||
|
|
19068b6608 | ||
|
|
ee40507d38 | ||
|
|
b4cb0426a3 | ||
|
|
5977137b3b | ||
|
|
512f6193a2 | ||
|
|
46cf167c22 | ||
|
|
2d24951658 | ||
|
|
ad9ad335f4 | ||
|
|
7d3e148212 | ||
|
|
2ff47e8274 | ||
|
|
f3bec5b1aa | ||
|
|
d418a5a882 | ||
|
|
db96e30c5e | ||
|
|
111fda1287 | ||
|
|
10d999e3ee | ||
|
|
6a7dcf12c3 | ||
|
|
fecd1d578a | ||
|
|
af92ea943d | ||
|
|
b46bb7647b | ||
|
|
3f6b38c9d9 | ||
|
|
a1fba2e8c1 | ||
|
|
dca3902fef | ||
|
|
06387f878a | ||
|
|
13ae25b561 | ||
|
|
5ea1851d52 | ||
|
|
2b65691945 | ||
|
|
5de8a01717 | ||
|
|
4d50f6d878 | ||
|
|
34ad19a1eb | ||
|
|
5bc26e57b4 | ||
|
|
8d15b2bb75 | ||
|
|
c062ec1b12 | ||
|
|
7b647c729b | ||
|
|
4347404119 | ||
|
|
366b188a5a | ||
|
|
0dd95c2840 | ||
|
|
efba10c065 | ||
|
|
cc53a4cdac | ||
|
|
89c6cb0911 | ||
|
|
a5f9653807 | ||
|
|
620ce60d00 | ||
|
|
fa75e2b178 | ||
|
|
b5055efecf | ||
|
|
ab8a00e159 | ||
|
|
70700de356 | ||
|
|
277d3ea146 | ||
|
|
fc65a1b9cb | ||
|
|
b1677718cd | ||
|
|
4dde74364b | ||
|
|
bb7b312b19 | ||
|
|
43162d20e0 | ||
|
|
ba3a6c17ce | ||
|
|
7c1a79e071 | ||
|
|
0d582bfffe | ||
|
|
459501873b | ||
|
|
f1590144a4 | ||
|
|
9d25ce63a3 | ||
|
|
18c39dc283 | ||
|
|
79ccf3d26b | ||
|
|
d659d10afd | ||
|
|
b8431d4f50 | ||
|
|
6c566ca014 | ||
|
|
cd7cef72db | ||
|
|
33ee8c0ef8 | ||
|
|
bb0633ee43 | ||
|
|
347738843f | ||
|
|
4d547c4b7b | ||
|
|
ab95b42328 | ||
|
|
409ba3b1f4 | ||
|
|
274342326c | ||
|
|
97eee1fecf | ||
|
|
98274d294a | ||
|
|
34aeb94efa | ||
|
|
de09fecf1c | ||
|
|
b7b89b0708 | ||
|
|
4079b6f493 | ||
|
|
bc482e79ff | ||
|
|
7ef04886b9 | ||
|
|
b70ebaba7b | ||
|
|
b03a9f8ea3 | ||
|
|
8a2bed2f71 | ||
|
|
df2a2d1127 | ||
|
|
2e18447255 | ||
|
|
ef6bae24c5 |
No files matched your search
@@ -37,7 +37,7 @@ jobs:
|
||||
include:
|
||||
- job_name: linux
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
gotags: cmount
|
||||
build_flags: '-include "^linux/"'
|
||||
check: true
|
||||
@@ -48,14 +48,14 @@ jobs:
|
||||
|
||||
- job_name: linux_386
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
goarch: 386
|
||||
gotags: cmount
|
||||
quicktest: true
|
||||
|
||||
- job_name: mac_amd64
|
||||
os: macos-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
gotags: 'cmount'
|
||||
build_flags: '-include "^darwin/amd64" -cgo'
|
||||
quicktest: true
|
||||
@@ -64,14 +64,14 @@ jobs:
|
||||
|
||||
- job_name: mac_arm64
|
||||
os: macos-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
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.6'
|
||||
go: '~1.26.9'
|
||||
gotags: cmount
|
||||
cgo: '0'
|
||||
build_flags: '-include "^windows/"'
|
||||
@@ -81,14 +81,14 @@ jobs:
|
||||
|
||||
- job_name: other_os
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
build_flags: '-exclude "^(windows/|darwin/|linux/)"'
|
||||
compile_all: true
|
||||
deploy: true
|
||||
|
||||
- job_name: go1.26
|
||||
os: ubuntu-latest
|
||||
go: '~1.26.6'
|
||||
go: '~1.26.9'
|
||||
quicktest: true
|
||||
racequicktest: true
|
||||
|
||||
@@ -284,7 +284,7 @@ jobs:
|
||||
id: setup-go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '~1.26.6'
|
||||
go-version: '~1.26.9'
|
||||
check-latest: true
|
||||
cache: false
|
||||
|
||||
@@ -399,7 +399,7 @@ jobs:
|
||||
id: setup-go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '~1.26.6'
|
||||
go-version: '~1.26.9'
|
||||
# Caching is handled explicitly below to share the module cache
|
||||
# with the other jobs - see the build job for the rationale.
|
||||
cache: false
|
||||
|
||||
@@ -39,6 +39,7 @@ RUN echo "**** Install Dependencies ****" && \
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
fuse3 \
|
||||
mailcap \
|
||||
tzdata && \
|
||||
echo "Enable user_allow_other in fuse" && \
|
||||
echo "user_allow_other" >> /etc/fuse.conf
|
||||
|
||||
Generated
+1813
-1041
File diff suppressed because it is too large.
Load diff
Generated
+795
-150
File diff suppressed because it is too large.
Load diff
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/rclone/rclone/fs/config/configstruct"
|
||||
"github.com/rclone/rclone/fs/fspath"
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
"github.com/rclone/rclone/lib/sanitize"
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
@@ -529,14 +530,14 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
||||
// isDirectChild reports whether remote names an entry directly in dir
|
||||
// ("" being the root), with no ".." or other components in between.
|
||||
func isDirectChild(dir, remote string) bool {
|
||||
if remote == "" || remote == "." || remote == ".." || strings.HasSuffix(remote, "/") {
|
||||
return false
|
||||
if dir != "" {
|
||||
var ok bool
|
||||
remote, ok = strings.CutPrefix(remote, dir+"/")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
parent := path.Dir(remote)
|
||||
if parent == "." || parent == "/" {
|
||||
parent = ""
|
||||
}
|
||||
return parent == dir && path.Clean(remote) == remote
|
||||
return sanitize.Leaf(remote) == nil
|
||||
}
|
||||
|
||||
// NewObject creates a new remote archive file object
|
||||
|
||||
@@ -175,6 +175,18 @@ func testArchive(t *testing.T, archiveName string, archiveFn func(t *testing.T,
|
||||
checkTree(ctx, "SubDir", t, ":archive:"+zipFile+"/"+subDir, filepath.Join(input, subDir), 0)
|
||||
|
||||
// Now check a single file
|
||||
//
|
||||
// The filter below applies to both sides, so check first that the
|
||||
// archive exposes only that file without it
|
||||
Fsingle, err := cache.Get(ctx, ":archive:"+zipFile+"/"+aFile)
|
||||
require.NoError(t, err)
|
||||
entries, err := Fsingle.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
_, err = Fsingle.List(ctx, subDir)
|
||||
assert.Equal(t, fs.ErrorDirNotFound, err)
|
||||
_, err = Fsingle.NewObject(ctx, subDir)
|
||||
assert.Equal(t, fs.ErrorObjectNotFound, err)
|
||||
fiCtx, fi := filter.AddConfig(ctx)
|
||||
require.NoError(t, fi.AddRule("+ "+aFile))
|
||||
require.NoError(t, fi.AddRule("- *"))
|
||||
@@ -379,3 +391,27 @@ func TestArchiveEscapingArchiver(t *testing.T) {
|
||||
_, err = f.NewObject(ctx, "test.escaping/file.txt")
|
||||
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
|
||||
}
|
||||
|
||||
// TestIsDirectChild checks the guard which decides whether an entry
|
||||
// returned by an archiver belongs directly in the directory listed.
|
||||
func TestIsDirectChild(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
dir, remote string
|
||||
want bool
|
||||
}{
|
||||
{"", "a.txt", true},
|
||||
{"", "/a.txt", false},
|
||||
{"", "a.txt/", false},
|
||||
{"", "../a.txt", false},
|
||||
{"", "sub/a.txt", false},
|
||||
{"d", "d/a.txt", true},
|
||||
{"d", "d", false},
|
||||
{"d", "d/", false},
|
||||
{"d", "d//a.txt", false},
|
||||
{"d", "d/../a.txt", false},
|
||||
{"d", "dd/a.txt", false},
|
||||
{"d", "a.txt", false},
|
||||
} {
|
||||
assert.Equal(t, test.want, isDirectChild(test.dir, test.remote), "dir=%q remote=%q", test.dir, test.remote)
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ type Fs struct {
|
||||
prefix string // position for objects
|
||||
prefixSlash string // position for objects with a slash on
|
||||
root string // position to read from within the archive
|
||||
file string // remote of the single file root points at, if any
|
||||
}
|
||||
|
||||
// recoverParsePanic converts a panic raised while parsing a squashfs image
|
||||
@@ -115,10 +116,13 @@ func New(ctx context.Context, wrappedFs fs.Fs, remote, prefix, root string) (_ f
|
||||
_, err := f.newObjectNative(native)
|
||||
if err == nil {
|
||||
// If it pointed to a file, find the directory above
|
||||
// and remember the file so that only it is listed
|
||||
f.root = path.Dir(f.root)
|
||||
if f.root == "." || f.root == "/" {
|
||||
f.root = ""
|
||||
}
|
||||
f.file = f.prefixSlash + path.Base(native)
|
||||
singleObject = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,7 +154,9 @@ func (f *Fs) Name() string {
|
||||
|
||||
// Root of the remote (as passed into NewFs)
|
||||
func (f *Fs) Root() string {
|
||||
return f.root
|
||||
// Include the file so the fs cache can tell this Fs apart from
|
||||
// the one for the directory containing it
|
||||
return path.Join(f.root, f.file)
|
||||
}
|
||||
|
||||
// Features returns the optional features of this Fs
|
||||
@@ -227,6 +233,10 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
||||
defer log.Trace(f, "dir=%q", dir)("entries=%v, err=%v", &entries, &err)
|
||||
defer recoverParsePanic(&err)
|
||||
|
||||
if f.file != "" && dir != "" {
|
||||
return nil, fs.ErrorDirNotFound
|
||||
}
|
||||
|
||||
nativeDir, err := f.toNative(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -265,6 +275,9 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
||||
fs.Debugf(item.Name(), "FIXME Not regular file - skipping")
|
||||
continue
|
||||
}
|
||||
if f.file != "" && entry.Remote() != f.file {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, entry)
|
||||
}
|
||||
|
||||
@@ -316,6 +329,9 @@ func (f *Fs) newObjectNative(nativePath string) (o fs.Object, err error) {
|
||||
func (f *Fs) NewObject(ctx context.Context, remote string) (o fs.Object, err error) {
|
||||
defer log.Trace(f, "remote=%q", remote)("obj=%v, err=%v", &o, &err)
|
||||
|
||||
if f.file != "" && remote != f.file {
|
||||
return nil, fs.ErrorObjectNotFound
|
||||
}
|
||||
nativePath, err := f.toNative(remote)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
+12
-10
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -144,6 +145,13 @@ func (f *Fs) readZip() (singleObject bool, err error) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
isDir := strings.HasSuffix(file.Name, "/")
|
||||
// A file entry whose last component is "", "." or ".." names
|
||||
// a directory rather than a file, so skip
|
||||
if !isDir && sanitize.Leaf(path.Base(file.Name)) != nil {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
remote = path.Join(f.prefix, remote)
|
||||
if f.root != "" {
|
||||
// Ignore all files outside the root, requiring a path
|
||||
@@ -158,19 +166,12 @@ func (f *Fs) readZip() (singleObject bool, err error) {
|
||||
remote = strings.TrimPrefix(remote, f.root+"/")
|
||||
}
|
||||
}
|
||||
if strings.HasSuffix(file.Name, "/") {
|
||||
if isDir {
|
||||
dir := fs.NewDir(remote, file.Modified)
|
||||
dt.AddDir(dir)
|
||||
} else {
|
||||
if remote == "" {
|
||||
// A file at the root itself can only be the
|
||||
// archive member f.root points at - with no root
|
||||
// it is a crafted name for the archive's own
|
||||
// directory, which can't be a file
|
||||
if f.root == "" {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
// A file at the root is the archive member f.root points at
|
||||
remote = path.Base(f.root)
|
||||
singleObject = true
|
||||
dt = dirtree.New()
|
||||
@@ -217,7 +218,8 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
||||
return nil, fs.ErrorDirNotFound
|
||||
}
|
||||
fs.Debugf(f, "dir=%q, entries=%v", dir, entries)
|
||||
return entries, nil
|
||||
// Return a copy as callers may filter the listing in place
|
||||
return slices.Clone(entries), nil
|
||||
}
|
||||
|
||||
// NewObject finds the Object at remote.
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -105,10 +106,12 @@ func TestReadZipRootBoundary(t *testing.T) {
|
||||
assert.Equal(t, []string{"a.txt"}, remotes)
|
||||
}
|
||||
|
||||
// A file entry whose name refers to the archive's own root (".", "/",
|
||||
// "./" or "") must be skipped, not turn the whole archive into a single
|
||||
// file which hides every other entry.
|
||||
func TestReadZipRootNamedEntry(t *testing.T) {
|
||||
// A file entry whose name refers to a directory (".", "/", "./", "" or
|
||||
// "sub/.") must be skipped, not turn the archive or the directory
|
||||
// mounted as its root into a single file which hides every other
|
||||
// entry, or become an object named for the archive itself when the
|
||||
// archive is found by listing its directory.
|
||||
func TestReadZipDirNamedFileEntry(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
name := writeZip(t, dir, "dot.zip",
|
||||
@@ -117,14 +120,53 @@ func TestReadZipRootNamedEntry(t *testing.T) {
|
||||
"./",
|
||||
"",
|
||||
"good.txt",
|
||||
"sub/",
|
||||
"sub/.",
|
||||
"sub/good.txt",
|
||||
)
|
||||
|
||||
localFs, err := cache.Get(ctx, dir)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, test := range []struct {
|
||||
prefix, root string
|
||||
want []string
|
||||
}{
|
||||
{"", "", []string{"good.txt", "sub/good.txt"}},
|
||||
{"sub/dot.zip", "", []string{"sub/dot.zip/good.txt", "sub/dot.zip/sub/good.txt"}},
|
||||
{"", "sub", []string{"good.txt"}},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("prefix=%q,root=%q", test.prefix, test.root), func(t *testing.T) {
|
||||
f, err := New(ctx, localFs, name, test.prefix, test.root)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, allRemotes(t, f))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Listings are served from a cache which must survive callers
|
||||
// filtering the returned slice in place, as fs/list does.
|
||||
func TestListCacheNotAliased(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
name := writeZip(t, dir, "test.zip", "a.txt", "b.txt", "c.txt")
|
||||
|
||||
localFs, err := cache.Get(ctx, dir)
|
||||
require.NoError(t, err)
|
||||
f, err := New(ctx, localFs, name, "", "")
|
||||
require.NoError(t, err)
|
||||
|
||||
remotes := allRemotes(t, f)
|
||||
assert.Equal(t, []string{"good.txt"}, remotes)
|
||||
entries, err := f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 3)
|
||||
// Compact in place, dropping the first entry
|
||||
copy(entries, entries[1:])
|
||||
|
||||
entries, err = f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
var remotes []string
|
||||
for _, entry := range entries {
|
||||
remotes = append(remotes, entry.Remote())
|
||||
}
|
||||
assert.Equal(t, []string{"a.txt", "b.txt", "c.txt"}, remotes)
|
||||
}
|
||||
+11
-18
@@ -18,24 +18,20 @@ import (
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// arrowContentType is the Content-Type of an Apache Arrow IPC stream listing
|
||||
// response, used to tell whether the service honoured an Arrow request.
|
||||
const arrowContentType = "application/vnd.apache.arrow.stream"
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
func (f *Fs) listArrowParallel(ctx context.Context, containerName, directory, prefix string, addContainer bool, opts *container.ListBlobsHierarchyOptions, delimiter string, fn listFn) (int, error) {
|
||||
// Split the keyspace by a single-case character ladder (see
|
||||
// arrowLadderBoundaries for why single-case matters).
|
||||
points := arrowLadderBoundaries(directory, arrowShardTarget(f.opt.ListParallelism))
|
||||
@@ -115,16 +111,13 @@ func (f *Fs) listArrowParallel(ctx context.Context, containerName, directory, pr
|
||||
// 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.
|
||||
// The service rejects 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. (The SDK pager would silently
|
||||
// accept an XML page with endBefore set, but the service never sends one.)
|
||||
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"
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"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"
|
||||
@@ -212,9 +211,8 @@ func TestArrowLadderBoundaries(t *testing.T) {
|
||||
}
|
||||
|
||||
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.True(t, isEndBeforeUnsupported(fmt.Errorf("wrapped: %w", &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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+49
-120
@@ -26,15 +26,12 @@ import (
|
||||
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
|
||||
"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"
|
||||
@@ -242,40 +239,38 @@ avoid the time out.`,
|
||||
Advanced: true,
|
||||
}, {
|
||||
Name: "use_arrow_list",
|
||||
Help: `Use the experimental Apache Arrow listing format.
|
||||
Help: `Use the 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.
|
||||
Arrow response format instead of XML. Arrow responses are smaller and
|
||||
much cheaper to parse, making listings of large containers several
|
||||
times faster. Combine with "list_parallelism" for the biggest gains.
|
||||
|
||||
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.`,
|
||||
"Blob Listing with Apache Arrow" is in public preview at Microsoft and
|
||||
is only supported on flat namespace accounts. On accounts with a
|
||||
hierarchical namespace (ADLS Gen2), or where the feature is otherwise
|
||||
unavailable, the server returns XML and the listing transparently
|
||||
falls back to the normal XML path (logged at debug level).`,
|
||||
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.
|
||||
If set greater than 1, the blob name keyspace of each directory is
|
||||
split into 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. Speed keeps improving up to a
|
||||
parallelism of around 30.
|
||||
|
||||
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.`,
|
||||
only listing path that supports server-side name ranges. If the
|
||||
account does not support range listing (e.g. it has a hierarchical
|
||||
namespace) the listing falls back to sequential. 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.
|
||||
@@ -450,10 +445,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)
|
||||
@@ -672,15 +665,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)
|
||||
@@ -727,15 +719,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)
|
||||
@@ -774,44 +757,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.
|
||||
@@ -1188,27 +1133,25 @@ 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,
|
||||
opts := &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,
|
||||
}
|
||||
// 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.
|
||||
// Request the Apache Arrow listing format. The SDK 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)
|
||||
opts.ResponseFormat = container.StorageResponseFormatArrow
|
||||
}
|
||||
|
||||
var foundItems int
|
||||
@@ -1239,25 +1182,11 @@ func (f *Fs) list(ctx context.Context, containerName, directory, prefix string,
|
||||
// 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)
|
||||
}
|
||||
// the Apache Arrow format and the service 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 *container.ListBlobsHierarchyOptions, delimiter string, fn listFn) (foundItems int, err error) {
|
||||
useArrow := opts.ResponseFormat == container.StorageResponseFormatArrow
|
||||
pager := f.cntSVC(containerName).NewListBlobsHierarchyPager(delimiter, opts)
|
||||
checkedArrow := false
|
||||
for pager.More() {
|
||||
var response container.ListBlobsHierarchyResponse
|
||||
@@ -1273,7 +1202,7 @@ func (f *Fs) listBlobsPager(ctx context.Context, containerName, directory, prefi
|
||||
// but not accelerated.
|
||||
if useArrow && !checkedArrow && err == nil {
|
||||
checkedArrow = true
|
||||
if response.ContentType == nil || !strings.HasPrefix(*response.ContentType, arrowlist.ArrowContentType) {
|
||||
if response.ContentType == nil || !strings.HasPrefix(*response.ContentType, arrowContentType) {
|
||||
fs.Debugf(f, "Apache Arrow listing requested but server returned XML - Blob Listing with Apache Arrow may not be enabled on this account")
|
||||
}
|
||||
}
|
||||
|
||||
+25
-1
@@ -191,6 +191,11 @@ If the custom endpoint rewrites the requests for authentication,
|
||||
e.g., in Cloudflare Workers, this header needs to be handled properly.
|
||||
Leave blank if you want to use the endpoint provided by Backblaze.
|
||||
|
||||
Rclone will not follow a redirect from this endpoint which downgrades
|
||||
HTTPS to HTTP, and will not send the "Authorization" header or the
|
||||
SSE-C key headers once a redirect has left the host and port of this
|
||||
endpoint.
|
||||
|
||||
The URL provided here SHOULD have the protocol and SHOULD NOT have
|
||||
a trailing slash or specify the /file/bucket subpath as rclone will
|
||||
request files with "{download_url}/file/{bucket_name}/{path}".
|
||||
@@ -529,6 +534,25 @@ func (f *Fs) setRoot(root string) {
|
||||
f.rootBucket, f.rootDirectory = bucket.Split(f.root)
|
||||
}
|
||||
|
||||
// redirectSecretHeaders are the request headers carrying secrets that
|
||||
// must not be forwarded when a redirect leaves the original host.
|
||||
var redirectSecretHeaders = []string{
|
||||
"Authorization",
|
||||
sseAlgorithmHeader,
|
||||
sseKeyHeader,
|
||||
sseMd5Header,
|
||||
}
|
||||
|
||||
// newClient makes the http client used for all B2 requests.
|
||||
//
|
||||
// The download_url option sends the requests to a host the user does
|
||||
// not control so it strips headers on cross host redirects.
|
||||
func newClient(ctx context.Context) *http.Client {
|
||||
client := fshttp.NewClient(ctx)
|
||||
client.CheckRedirect = rest.StripHeadersOnCrossHostRedirectFn(redirectSecretHeaders...)
|
||||
return client
|
||||
}
|
||||
|
||||
// NewFs constructs an Fs from the path, bucket:path
|
||||
func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, error) {
|
||||
// Parse config into Options struct
|
||||
@@ -581,7 +605,7 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
name: name,
|
||||
opt: *opt,
|
||||
ci: ci,
|
||||
srv: rest.NewClient(fshttp.NewClient(ctx)).SetErrorHandler(errorHandler),
|
||||
srv: rest.NewClient(newClient(ctx)).SetErrorHandler(errorHandler),
|
||||
cache: bucket.NewCache(),
|
||||
_bucketID: make(map[string]string, 1),
|
||||
_bucketType: make(map[string]string, 1),
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
@@ -617,3 +619,60 @@ func (f *Fs) InternalTest(t *testing.T) {
|
||||
}
|
||||
|
||||
var _ fstests.InternalTester = (*Fs)(nil)
|
||||
|
||||
// redirectTestHeaders is a deliberately literal copy of
|
||||
// redirectSecretHeaders so that a header dropped from the production
|
||||
// list fails TestRedirectSecretHeaders rather than silently losing
|
||||
// test coverage.
|
||||
var redirectTestHeaders = map[string]string{
|
||||
"Authorization": "secret-token",
|
||||
"X-Bz-Server-Side-Encryption-Customer-Algorithm": "AES256",
|
||||
"X-Bz-Server-Side-Encryption-Customer-Key": "secret-key",
|
||||
"X-Bz-Server-Side-Encryption-Customer-Key-Md5": "secret-md5",
|
||||
}
|
||||
|
||||
func TestRedirectSecretHeaders(t *testing.T) {
|
||||
want := make([]string, 0, len(redirectTestHeaders))
|
||||
for header := range redirectTestHeaders {
|
||||
want = append(want, header)
|
||||
}
|
||||
sort.Strings(want)
|
||||
got := append([]string(nil), redirectSecretHeaders...)
|
||||
sort.Strings(got)
|
||||
assert.Equal(t, want, got)
|
||||
}
|
||||
|
||||
// redirectTestRequest makes a GET request to rawURL carrying the
|
||||
// secret headers plus a harmless marker header.
|
||||
func redirectTestRequest(t *testing.T, rawURL string) *http.Request {
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, rawURL, nil)
|
||||
require.NoError(t, err)
|
||||
for header, value := range redirectTestHeaders {
|
||||
req.Header.Set(header, value)
|
||||
}
|
||||
req.Header.Set("X-Bz-Test-Mode", "marker")
|
||||
return req
|
||||
}
|
||||
|
||||
func TestClientStripsSecretHeadersOnCrossHostRedirect(t *testing.T) {
|
||||
client := newClient(context.Background())
|
||||
|
||||
redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
for header := range redirectTestHeaders {
|
||||
assert.Empty(t, r.Header.Get(header), "%s should have been stripped", header)
|
||||
}
|
||||
assert.Equal(t, "marker", r.Header.Get("X-Bz-Test-Mode"))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer redirectServer.Close()
|
||||
|
||||
initialServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, redirectServer.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer initialServer.Close()
|
||||
|
||||
resp, err := client.Do(redirectTestRequest(t, initialServer.URL))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.NoError(t, resp.Body.Close())
|
||||
}
|
||||
+1
-1
@@ -1461,7 +1461,7 @@ func (f *Fs) changeNotifyRunner(ctx context.Context, notifyFunc func(string, fs.
|
||||
// Item in the cache has the same or newer SequenceID than
|
||||
// this event. Ignore this event, it must be old.
|
||||
f.itemMetaCacheMu.Unlock()
|
||||
fs.Debugf(f, "%s ignored due to old SequenceID (%q)", eventDetails, itemMeta.SequenceID)
|
||||
fs.Debugf(f, "%s ignored due to old SequenceID (%d)", eventDetails, itemMeta.SequenceID)
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -801,9 +801,12 @@ func (f *Fs) processEntries(ctx context.Context, origEntries fs.DirEntries, dirP
|
||||
fs.Debugf(f, "skip orphan data chunk %q", remote)
|
||||
break
|
||||
}
|
||||
if mainObject == nil && !f.useMeta {
|
||||
if mainObject == nil && !f.useMeta && !isSpecial {
|
||||
// this is the "nometa" case
|
||||
// create dummy chunked object without metadata
|
||||
//
|
||||
// not for temporary or control chunks as they may be all
|
||||
// that is left of an interrupted upload
|
||||
mainObject = f.newObject(mainRemote, nil, nil)
|
||||
byRemote[mainRemote] = mainObject
|
||||
if !badEntry[mainRemote] {
|
||||
|
||||
@@ -627,6 +627,22 @@ func testChunkNumberOverflow(t *testing.T, f *Fs) {
|
||||
_ = file.Remove(ctx)
|
||||
}
|
||||
|
||||
// testOrphanTempChunks checks that temporary chunks left behind by an
|
||||
// interrupted upload are not listed and don't break the listing
|
||||
func testOrphanTempChunks(t *testing.T, f *Fs) {
|
||||
const dir = "orphan"
|
||||
ctx := context.Background()
|
||||
defer func() {
|
||||
_ = operations.Purge(ctx, f.base, dir)
|
||||
}()
|
||||
|
||||
modTime := fstest.Time("2001-02-03T04:05:06.499999999Z")
|
||||
item := fstest.Item{Path: f.makeChunkName(path.Join(dir, "interrupted"), 0, "", "abc123"), ModTime: modTime}
|
||||
fstests.PutTestContents(ctx, t, f.base, &item, "data", true)
|
||||
|
||||
fstest.CheckListingWithRoot(t, f, dir, nil, nil, f.Precision())
|
||||
}
|
||||
|
||||
func testMetadataInput(t *testing.T, f *Fs) {
|
||||
const minChunkForTest = 50
|
||||
if f.opt.ChunkSize < minChunkForTest {
|
||||
@@ -928,6 +944,9 @@ func (f *Fs) InternalTest(t *testing.T) {
|
||||
t.Run("BackwardsCompatibility", func(t *testing.T) {
|
||||
testBackwardsCompatibility(t, f)
|
||||
})
|
||||
t.Run("OrphanTempChunks", func(t *testing.T) {
|
||||
testOrphanTempChunks(t, f)
|
||||
})
|
||||
t.Run("ChunkerServerSideMove", func(t *testing.T) {
|
||||
testChunkerServerSideMove(t, f)
|
||||
})
|
||||
|
||||
@@ -1080,6 +1080,35 @@ type ObjectMetadata struct {
|
||||
CompressionMetadataZstd *SzstdMetadata // Metadata for Zstd compression
|
||||
}
|
||||
|
||||
// validate checks metadata read from the wrapped remote before it is used to
|
||||
// construct a compressed reader.
|
||||
func (meta *ObjectMetadata) validate() error {
|
||||
if meta.Mode != Gzip {
|
||||
return nil
|
||||
}
|
||||
if meta.CompressionMetadataGzip == nil {
|
||||
return errors.New("missing gzip metadata")
|
||||
}
|
||||
if meta.CompressionMetadataGzip.BlockSize <= 0 {
|
||||
return fmt.Errorf("invalid gzip block size %d", meta.CompressionMetadataGzip.BlockSize)
|
||||
}
|
||||
if meta.Size != meta.CompressionMetadataGzip.Size {
|
||||
return errors.New("gzip metadata size does not match object size")
|
||||
}
|
||||
if meta.Size < 0 {
|
||||
return errors.New("invalid gzip object size")
|
||||
}
|
||||
blockSize := int64(meta.CompressionMetadataGzip.BlockSize)
|
||||
blocks := meta.Size / blockSize
|
||||
if meta.Size%blockSize != 0 {
|
||||
blocks++
|
||||
}
|
||||
if int64(len(meta.CompressionMetadataGzip.BlockData)) < blocks {
|
||||
return errors.New("gzip block data is incomplete")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Object with external metadata
|
||||
type Object struct {
|
||||
fs.Object // Wraps around data object for this object
|
||||
@@ -1103,6 +1132,9 @@ func readMetadata(ctx context.Context, mo fs.Object) (meta *ObjectMetadata, err
|
||||
if err = jr.Decode(meta); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = meta.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/buengese/sgzip"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/drive"
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
_ "github.com/rclone/rclone/backend/s3"
|
||||
@@ -14,6 +16,93 @@ import (
|
||||
"github.com/rclone/rclone/fstest/fstests"
|
||||
)
|
||||
|
||||
func TestObjectMetadataValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
meta ObjectMetadata
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "nil gzip metadata",
|
||||
meta: ObjectMetadata{Mode: Gzip},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "zero block size",
|
||||
meta: ObjectMetadata{
|
||||
Mode: Gzip,
|
||||
Size: 1024,
|
||||
CompressionMetadataGzip: &sgzip.GzipMetadata{
|
||||
BlockSize: 0,
|
||||
Size: 1024,
|
||||
BlockData: []uint32{0},
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "negative block size",
|
||||
meta: ObjectMetadata{
|
||||
Mode: Gzip,
|
||||
Size: 1024,
|
||||
CompressionMetadataGzip: &sgzip.GzipMetadata{
|
||||
BlockSize: -1,
|
||||
Size: 1024,
|
||||
BlockData: []uint32{0},
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "mismatched sizes",
|
||||
meta: ObjectMetadata{
|
||||
Mode: Gzip,
|
||||
Size: 1024,
|
||||
CompressionMetadataGzip: &sgzip.GzipMetadata{
|
||||
BlockSize: 512,
|
||||
Size: 2048,
|
||||
BlockData: []uint32{0, 1},
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "short block data",
|
||||
meta: ObjectMetadata{
|
||||
Mode: Gzip,
|
||||
Size: 1025,
|
||||
CompressionMetadataGzip: &sgzip.GzipMetadata{
|
||||
BlockSize: 512,
|
||||
Size: 1025,
|
||||
BlockData: []uint32{0, 1},
|
||||
},
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "valid",
|
||||
meta: ObjectMetadata{
|
||||
Mode: Gzip,
|
||||
Size: 1025,
|
||||
CompressionMetadataGzip: &sgzip.GzipMetadata{
|
||||
BlockSize: 512,
|
||||
Size: 1025,
|
||||
BlockData: []uint32{0, 1, 2},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := test.meta.validate()
|
||||
if (err != nil) != test.want {
|
||||
t.Fatalf("validate() error = %v, want error: %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var defaultOpt = fstests.Opt{
|
||||
RemoteName: "TestCompress:",
|
||||
NilObject: (*Object)(nil),
|
||||
|
||||
@@ -118,8 +118,8 @@ func (mode NameEncryptionMode) String() (out string) {
|
||||
return out
|
||||
}
|
||||
|
||||
// fileNameEncoding are the encoding methods dealing with encrypted file names
|
||||
type fileNameEncoding interface {
|
||||
// FileNameEncoding is the interface for the encoding methods dealing with encrypted file names
|
||||
type FileNameEncoding interface {
|
||||
EncodeToString(src []byte) string
|
||||
DecodeString(s string) ([]byte, error)
|
||||
}
|
||||
@@ -154,7 +154,7 @@ func (caseInsensitiveBase32Encoding) DecodeString(s string) ([]byte, error) {
|
||||
}
|
||||
|
||||
// NewNameEncoding creates a NameEncoding from a string
|
||||
func NewNameEncoding(s string) (enc fileNameEncoding, err error) {
|
||||
func NewNameEncoding(s string) (enc FileNameEncoding, err error) {
|
||||
s = strings.ToLower(s)
|
||||
switch s {
|
||||
case "base32":
|
||||
@@ -176,7 +176,7 @@ type Cipher struct {
|
||||
nameTweak [nameCipherBlockSize]byte // used to tweak the name crypto
|
||||
block gocipher.Block
|
||||
mode NameEncryptionMode
|
||||
fileNameEnc fileNameEncoding
|
||||
fileNameEnc FileNameEncoding
|
||||
buffers sync.Pool // encrypt/decrypt buffers
|
||||
cryptoRand io.Reader // read crypto random numbers from here
|
||||
dirNameEncrypt bool
|
||||
@@ -185,7 +185,7 @@ type Cipher struct {
|
||||
}
|
||||
|
||||
// newCipher initialises the cipher. If salt is "" then it uses a built in salt val
|
||||
func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bool, enc fileNameEncoding) (*Cipher, error) {
|
||||
func newCipher(mode NameEncryptionMode, password, salt string, dirNameEncrypt bool, enc FileNameEncoding) (*Cipher, error) {
|
||||
c := &Cipher{
|
||||
mode: mode,
|
||||
fileNameEnc: enc,
|
||||
|
||||
+33
-17
@@ -692,13 +692,27 @@ func (f *Fs) Mkdir(ctx context.Context, dir string) error {
|
||||
|
||||
// deleteObject removes an object by ID
|
||||
func (f *Fs) deleteObject(ctx context.Context, id string) error {
|
||||
if f.opt.HardDelete {
|
||||
// Deleting forever doesn't invalidate the server's cache of
|
||||
// the parent folder listing, so the entry keeps being listed
|
||||
// for about a second. Moving to the trash first does.
|
||||
err := f.deleteEntry(ctx, id, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return f.deleteEntry(ctx, id, f.opt.HardDelete)
|
||||
}
|
||||
|
||||
// deleteEntry moves the entry with ID to the trash or deletes it forever
|
||||
func (f *Fs) deleteEntry(ctx context.Context, id string, deleteForever bool) error {
|
||||
opts := rest.Opts{
|
||||
Method: "POST",
|
||||
Path: "/file-entries/delete",
|
||||
}
|
||||
request := api.DeleteRequest{
|
||||
EntryIDs: []string{id},
|
||||
DeleteForever: f.opt.HardDelete,
|
||||
DeleteForever: deleteForever,
|
||||
}
|
||||
var result api.DeleteResponse
|
||||
err := f.pacer.Call(func() (bool, error) {
|
||||
@@ -1040,17 +1054,28 @@ func (f *Fs) copy(ctx context.Context, id, newDirID string) (item *api.Item, err
|
||||
}
|
||||
|
||||
// copy and rename a file or folder to directoryID with leaf
|
||||
func (f *Fs) copyTo(ctx context.Context, srcID, srcLeaf, dstLeaf, dstDirectoryID string) (info *api.Item, err error) {
|
||||
// Can have duplicates so don't have to be careful here
|
||||
|
||||
//
|
||||
// If existing is set it is removed once the copy has succeeded.
|
||||
func (f *Fs) copyTo(ctx context.Context, srcID, dstLeaf, dstDirectoryID string, existing fs.Object) (info *api.Item, err error) {
|
||||
// Copy to dstDirectoryID first
|
||||
info, err = f.copy(ctx, srcID, dstDirectoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The server names the copy "name (1)" if the destination
|
||||
// directory already has an entry called "name" and refuses to
|
||||
// rename it to "name" until that entry is removed.
|
||||
if existing != nil {
|
||||
fs.Debugf(existing, "Server side copy: removing existing object after successful copy")
|
||||
err = existing.Remove(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Rename if required
|
||||
if srcLeaf != dstLeaf {
|
||||
if info.Name != f.opt.Enc.FromStandardName(dstLeaf) {
|
||||
info, err = f.rename(ctx, info.ID.String(), dstLeaf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1074,8 +1099,6 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
|
||||
fs.Debugf(src, "Can't copy - not same remote type")
|
||||
return nil, fs.ErrorCantCopy
|
||||
}
|
||||
srcLeaf := path.Base(srcObj.remote)
|
||||
|
||||
srcPath := srcObj.fs.rootSlash() + srcObj.remote
|
||||
dstPath := f.rootSlash() + remote
|
||||
if srcPath == dstPath {
|
||||
@@ -1084,15 +1107,8 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
|
||||
|
||||
// Find existing object
|
||||
existingObj, err := f.NewObject(ctx, remote)
|
||||
if err == nil {
|
||||
defer func() {
|
||||
// Don't remove existing object if returning an error
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
fs.Debugf(existingObj, "Server side copy: removing existing object after successful copy")
|
||||
err = existingObj.Remove(ctx)
|
||||
}()
|
||||
if err != nil {
|
||||
existingObj = nil
|
||||
}
|
||||
|
||||
// Create temporary object
|
||||
@@ -1102,7 +1118,7 @@ func (f *Fs) Copy(ctx context.Context, src fs.Object, remote string) (dst fs.Obj
|
||||
}
|
||||
|
||||
// Copy the object
|
||||
info, err := f.copyTo(ctx, srcObj.id, srcLeaf, dstLeaf, dstDirectoryID)
|
||||
info, err := f.copyTo(ctx, srcObj.id, dstLeaf, dstDirectoryID, existingObj)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -633,13 +633,8 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
return f, nil // our root it empty so we probably want to list shared folders
|
||||
}
|
||||
|
||||
dir := path.Dir(f.root)
|
||||
if dir == "." {
|
||||
dir = f.root
|
||||
}
|
||||
|
||||
// root is not empty so we have find the right shared folder if it exists
|
||||
id, err := f.findSharedFolder(ctx, dir)
|
||||
id, err := f.findSharedFolder(ctx, sharedFolderName(f.root))
|
||||
if err != nil {
|
||||
// if we didn't find the specified shared folder we have to bail out here
|
||||
return nil, err
|
||||
@@ -947,13 +942,21 @@ func (f *Fs) listSharedFolders(ctx context.Context, callback func(fs.DirEntry) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// sharedFolderName returns the shared folder name in root, which is its first
|
||||
// path component. root must be the trimmed root as produced by setRoot (no
|
||||
// leading slash).
|
||||
func sharedFolderName(root string) string {
|
||||
name, _, _ := strings.Cut(root, "/")
|
||||
return name
|
||||
}
|
||||
|
||||
// findSharedFolder find the id for a given shared folder name
|
||||
// somewhat annoyingly there is no endpoint to query a shared folder by it's name
|
||||
// so our only option is to iterate over all shared folders
|
||||
func (f *Fs) findSharedFolder(ctx context.Context, name string) (id string, err error) {
|
||||
errFoundFile := errors.New("found file")
|
||||
err = f.listSharedFolders(ctx, func(entry fs.DirEntry) error {
|
||||
if entry.(*fs.Dir).Remote() == name {
|
||||
if strings.EqualFold(entry.(*fs.Dir).Remote(), name) {
|
||||
id = entry.(*fs.Dir).ID()
|
||||
return errFoundFile
|
||||
}
|
||||
@@ -1035,7 +1038,7 @@ func (f *Fs) listReceivedFiles(ctx context.Context, callback func(fs.DirEntry) e
|
||||
func (f *Fs) findSharedFile(ctx context.Context, name string) (o *Object, err error) {
|
||||
errFoundFile := errors.New("found file")
|
||||
err = f.listReceivedFiles(ctx, func(entry fs.DirEntry) error {
|
||||
if entry.(*Object).remote == name {
|
||||
if strings.EqualFold(entry.(*Object).remote, name) {
|
||||
o = entry.(*Object)
|
||||
return errFoundFile
|
||||
}
|
||||
|
||||
@@ -188,6 +188,21 @@ func TestInternalCheckPathLength(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalSharedFolderName(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
root string
|
||||
want string
|
||||
}{
|
||||
{root: "", want: ""},
|
||||
{root: "SharedFolder", want: "SharedFolder"},
|
||||
{root: "SharedFolder/subdir", want: "SharedFolder"},
|
||||
{root: "SharedFolder/subdir/deeper", want: "SharedFolder"},
|
||||
{root: "SharedFolder/subdir/deeper/deepest", want: "SharedFolder"},
|
||||
} {
|
||||
assert.Equal(t, test.want, sharedFolderName(test.root), test.root)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaperExportRemote(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
info := &files.FileMetadata{
|
||||
@@ -475,3 +490,48 @@ func TestFindSharedFileResolvesDecodedName(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, encodedName, o.remote)
|
||||
}
|
||||
|
||||
// sharedFoldersHandler serves a single shared folder from list_folders.
|
||||
func sharedFoldersHandler(name, id string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.URL.Path, "list_folders") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
resp := sharing.ListFoldersResult{
|
||||
Entries: []*sharing.SharedFolderMetadata{{Name: name, SharedFolderId: id}},
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
}
|
||||
|
||||
// The Dropbox backend advertises CaseInsensitive: true, so a shared folder
|
||||
// lookup must match regardless of the case of the requested name.
|
||||
func TestInternalFindSharedFolderCaseInsensitive(t *testing.T) {
|
||||
f := newSharingTestFs(t, sharedFoldersHandler("TestFolder", "folder-id"))
|
||||
|
||||
for _, name := range []string{"TestFolder", "testfolder", "TESTFOLDER"} {
|
||||
id, err := f.findSharedFolder(context.Background(), name)
|
||||
require.NoError(t, err, name)
|
||||
assert.Equal(t, "folder-id", id, name)
|
||||
}
|
||||
|
||||
_, err := f.findSharedFolder(context.Background(), "no-such-folder")
|
||||
assert.ErrorIs(t, err, fs.ErrorDirNotFound)
|
||||
}
|
||||
|
||||
// The Dropbox backend advertises CaseInsensitive: true, so a received file
|
||||
// lookup must match regardless of the case of the requested name.
|
||||
func TestInternalFindSharedFileCaseInsensitive(t *testing.T) {
|
||||
f := newSharingTestFs(t, receivedFilesHandler(t, "TestFile.txt"))
|
||||
|
||||
for _, name := range []string{"TestFile.txt", "testfile.txt", "TESTFILE.TXT"} {
|
||||
o, err := f.findSharedFile(context.Background(), name)
|
||||
require.NoError(t, err, name)
|
||||
assert.Equal(t, "TestFile.txt", o.remote, name)
|
||||
}
|
||||
|
||||
_, err := f.findSharedFile(context.Background(), "no-such-file.txt")
|
||||
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/Files-com/files-sdk-go/v3/file"
|
||||
file_migration "github.com/Files-com/files-sdk-go/v3/filemigration"
|
||||
"github.com/Files-com/files-sdk-go/v3/folder"
|
||||
files_sdk_lib "github.com/Files-com/files-sdk-go/v3/lib"
|
||||
"github.com/Files-com/files-sdk-go/v3/session"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config"
|
||||
@@ -176,6 +177,13 @@ func shouldRetry(ctx context.Context, err error) (bool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// Errors from the upload storage servers are of this type
|
||||
var httpErr files_sdk_lib.ResponseError
|
||||
if errors.As(err, &httpErr) && slices.Contains(retryErrorCodes, httpErr.StatusCode) {
|
||||
fs.Debugf(nil, "Retrying HTTP error %v", err)
|
||||
return true, err
|
||||
}
|
||||
|
||||
return fserrors.ShouldRetry(err), err
|
||||
}
|
||||
|
||||
@@ -858,7 +866,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
file.UploadWithProvidedMtime(src.ModTime(ctx)),
|
||||
}
|
||||
|
||||
err := o.fs.pacer.Call(func() (bool, error) {
|
||||
err := o.fs.pacer.CallNoRetry(func() (bool, error) {
|
||||
err := o.fs.fileClient.Upload(uploadOpts...)
|
||||
return shouldRetry(ctx, err)
|
||||
})
|
||||
|
||||
+10
-30
@@ -283,7 +283,7 @@ func (f *Fs) httpConnection(ctx context.Context, opt *Options) (isFile bool, err
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
u, err := rest.URLJoin(base, rest.URLPathEscape(f.root))
|
||||
u, err := rest.URLJoinRoot(base, f.root)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -526,40 +526,20 @@ func addHeaders(req *http.Request, opt *Options) {
|
||||
// rest.ErrHTTPSDowngrade and strips the configured headers when the
|
||||
// redirect chain has left the originally requested host at any point.
|
||||
func checkRedirect(opt *Options) func(req *http.Request, via []*http.Request) error {
|
||||
headers := make([]string, 0, len(opt.Headers)/2)
|
||||
for i := 0; i < len(opt.Headers); i += 2 {
|
||||
headers = append(headers, opt.Headers[i])
|
||||
}
|
||||
stripHeaders := rest.StripHeadersOnCrossHostRedirectFn(headers...)
|
||||
return func(req *http.Request, via []*http.Request) error {
|
||||
if err := rest.RefuseHTTPSDowngradeRedirectFn(req, via); err != nil {
|
||||
if errors.Is(err, rest.ErrHTTPSDowngrade) {
|
||||
err = fmt.Errorf("%w (the configured headers would be sent to the plaintext target)", err)
|
||||
}
|
||||
return err
|
||||
err := stripHeaders(req, via)
|
||||
if errors.Is(err, rest.ErrHTTPSDowngrade) {
|
||||
err = fmt.Errorf("%w (the configured headers would be sent to the plaintext target)", err)
|
||||
}
|
||||
if redirectLeavesHost(req, via) {
|
||||
for i := 0; i < len(opt.Headers); i += 2 {
|
||||
req.Header.Del(opt.Headers[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// redirectLeavesHost reports whether any hop in the redirect chain
|
||||
// via plus the pending request req is to a different host from the
|
||||
// original request via[0].
|
||||
//
|
||||
// net/http copies the headers afresh from the original request for
|
||||
// every hop, so once the chain has visited another host the headers
|
||||
// must be stripped from every subsequent hop, even one back to the
|
||||
// original host, as the other host chose the URL.
|
||||
func redirectLeavesHost(req *http.Request, via []*http.Request) bool {
|
||||
origin := via[0].URL
|
||||
for _, hop := range via {
|
||||
if !rest.SameHost(hop.URL, origin) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return !rest.SameHost(req.URL, origin)
|
||||
}
|
||||
|
||||
// Adds the configured headers to the request if any
|
||||
func (f *Fs) addHeaders(req *http.Request) {
|
||||
addHeaders(req, &f.opt)
|
||||
|
||||
@@ -760,3 +760,34 @@ func TestRedirectStripsHeadersOnHostChange(t *testing.T) {
|
||||
assert.Empty(t, got.Values(headers[i]), "header %q leaked to redirect target", headers[i])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootCannotChangeHost(t *testing.T) {
|
||||
// A root starting with "//" is a network-path reference under the
|
||||
// URL standard. It must not be able to move the remote (and the
|
||||
// configured headers) to a host other than the configured one.
|
||||
var requests int
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
_, _ = w.Write([]byte("hello"))
|
||||
}))
|
||||
defer other.Close()
|
||||
|
||||
m := prepareServer(t)
|
||||
otherHost := strings.TrimPrefix(other.URL, "http://")
|
||||
for _, root := range []string{
|
||||
"//" + otherHost + "/",
|
||||
"//" + otherHost + "/one%.txt",
|
||||
"//" + otherHost,
|
||||
"//user:pass@" + otherHost + "/",
|
||||
} {
|
||||
f, err := NewFs(context.Background(), remoteName, root, m)
|
||||
assert.ErrorContains(t, err, "must not change the scheme, host or user", root)
|
||||
assert.Nil(t, f, root)
|
||||
}
|
||||
assert.Equal(t, 0, requests, "request sent to the other host")
|
||||
|
||||
// A same-origin absolute path must still work
|
||||
f, err := NewFs(context.Background(), remoteName, "/", m)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, m["url"]+"/", f.String())
|
||||
}
|
||||
@@ -92,7 +92,7 @@ func (f *Fs) findItem(ctx context.Context, dir string) (item *api.DriveItem, fou
|
||||
item, resp, err = f.service.GetItemByPath(ctx, path.Join(f.root, dir))
|
||||
return shouldRetry(ctx, resp, err)
|
||||
}); err != nil {
|
||||
if item == nil && resp.StatusCode == 404 {
|
||||
if item == nil && resp != nil && resp.StatusCode == 404 {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
|
||||
@@ -477,7 +477,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) (err error) {
|
||||
FolderPath: f.EncodePath(path.Join(f.root, dir)),
|
||||
})
|
||||
|
||||
if res.StatusCode == http.StatusNotFound {
|
||||
if res != nil && res.StatusCode == http.StatusNotFound {
|
||||
return false, fs.ErrorDirNotFound
|
||||
}
|
||||
|
||||
@@ -502,7 +502,7 @@ func (f *Fs) Purge(ctx context.Context, dir string) (err error) {
|
||||
FolderPath: f.EncodePath(remote),
|
||||
})
|
||||
|
||||
if res.StatusCode == http.StatusNotFound {
|
||||
if res != nil && res.StatusCode == http.StatusNotFound {
|
||||
return false, fs.ErrorDirNotFound
|
||||
}
|
||||
|
||||
|
||||
+236
-109
@@ -475,8 +475,10 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(childFolders) > 0 {
|
||||
return fs.ErrorDirectoryNotEmpty
|
||||
for _, e := range childFolders {
|
||||
if !recent.stale(e.UUID, id, e.PlainName) {
|
||||
return fs.ErrorDirectoryNotEmpty
|
||||
}
|
||||
}
|
||||
|
||||
var childFiles []folders.File
|
||||
@@ -488,8 +490,10 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(childFiles) > 0 {
|
||||
return fs.ErrorDirectoryNotEmpty
|
||||
for _, e := range childFiles {
|
||||
if !recent.stale(e.UUID, id, joinNameExt(e.PlainName, e.Type)) {
|
||||
return fs.ErrorDirectoryNotEmpty
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the directory
|
||||
@@ -503,6 +507,7 @@ func (f *Fs) Rmdir(ctx context.Context, dir string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recent.deleted(id)
|
||||
|
||||
f.dirCache.FlushDir(dir)
|
||||
return nil
|
||||
@@ -521,6 +526,9 @@ func (f *Fs) FindLeaf(ctx context.Context, pathID, leaf string) (string, bool, e
|
||||
return "", false, err
|
||||
}
|
||||
for _, e := range entries {
|
||||
if recent.stale(e.UUID, pathID, e.PlainName) {
|
||||
continue
|
||||
}
|
||||
if f.opt.Encoding.ToStandardName(e.PlainName) == leaf {
|
||||
return e.UUID, true, nil
|
||||
}
|
||||
@@ -557,46 +565,166 @@ func (f *Fs) CreateDir(ctx context.Context, pathID, leaf string) (string, error)
|
||||
return resp.UUID, nil
|
||||
}
|
||||
|
||||
// preUploadCheck checks if a file exists in the given directory
|
||||
// Returns the file metadata if it exists, nil if not
|
||||
func (f *Fs) preUploadCheck(ctx context.Context, leaf, directoryID string) (*folders.File, error) {
|
||||
// Parse name and extension from the leaf
|
||||
baseName := f.opt.Encoding.FromStandardName(leaf)
|
||||
name := strings.TrimSuffix(baseName, path.Ext(baseName))
|
||||
ext := strings.TrimPrefix(path.Ext(baseName), ".")
|
||||
// splitNameExt splits a basename into the (plainName, type) pair that Internxt
|
||||
// stores a file under.
|
||||
func splitNameExt(baseName string) (name, ext string) {
|
||||
ext = path.Ext(baseName)
|
||||
if ext == baseName {
|
||||
return baseName, ""
|
||||
}
|
||||
return strings.TrimSuffix(baseName, ext), strings.TrimPrefix(ext, ".")
|
||||
}
|
||||
|
||||
checkResult, err := files.CheckFilesExistence(ctx, f.cfg, directoryID, []files.FileExistenceCheck{
|
||||
{
|
||||
PlainName: name,
|
||||
Type: ext,
|
||||
OriginalFile: struct{}{},
|
||||
},
|
||||
// joinNameExt reassembles the basename a stored (plainName, type) pair
|
||||
// displays as, the way List builds its entries.
|
||||
func joinNameExt(name, ext string) string {
|
||||
if ext == "" {
|
||||
return name
|
||||
}
|
||||
return name + "." + ext
|
||||
}
|
||||
|
||||
// legacyNameExt splits a basename at the final dot, the way this backend used
|
||||
// to before it adopted the convention the other clients share. It differs from
|
||||
// splitNameExt only for a name whose sole dot leads it: ".bashrc" splits into
|
||||
// an empty name of type "bashrc".
|
||||
func legacyNameExt(baseName string) (name, ext string) {
|
||||
return strings.TrimSuffix(baseName, path.Ext(baseName)), strings.TrimPrefix(path.Ext(baseName), ".")
|
||||
}
|
||||
|
||||
// existenceCheck builds a lookup criterion for one (plainName, type) spelling.
|
||||
func existenceCheck(name, ext string) files.FileExistenceCheck {
|
||||
return files.FileExistenceCheck{
|
||||
PlainName: name,
|
||||
Type: ext,
|
||||
OriginalFile: struct{}{},
|
||||
}
|
||||
}
|
||||
|
||||
// staleWindow is how long the API may carry on returning an item from
|
||||
// where it was before this process moved or deleted it.
|
||||
const staleWindow = time.Minute
|
||||
|
||||
// location is where this process last put an item. An empty parentUUID
|
||||
// means the item was deleted.
|
||||
type location struct {
|
||||
parentUUID string
|
||||
name string // encoded name, including any extension
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// recentChanges holds the files and folders this process has moved or
|
||||
// deleted recently, keyed by UUID.
|
||||
//
|
||||
// The API serves lookups and listings from read replicas which lag behind
|
||||
// writes, so an item can be returned from its old location for a while after
|
||||
// it was moved or deleted. Acting on such a stale entry can be destructive,
|
||||
// eg overwriting it would delete the file from where it was moved to.
|
||||
type recentChanges struct {
|
||||
mu sync.Mutex
|
||||
items map[string]location
|
||||
lastPrune time.Time
|
||||
}
|
||||
|
||||
// recent is shared by all the Fs in the process as UUIDs are global.
|
||||
var recent = recentChanges{items: map[string]location{}}
|
||||
|
||||
// set records the new location of uuid, pruning expired entries.
|
||||
func (r *recentChanges) set(uuid string, loc location) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
now := time.Now()
|
||||
if now.Sub(r.lastPrune) > staleWindow {
|
||||
for k, v := range r.items {
|
||||
if now.After(v.expires) {
|
||||
delete(r.items, k)
|
||||
}
|
||||
}
|
||||
r.lastPrune = now
|
||||
}
|
||||
loc.expires = now.Add(staleWindow)
|
||||
r.items[uuid] = loc
|
||||
}
|
||||
|
||||
// moved records that uuid was moved to name in parentUUID.
|
||||
func (r *recentChanges) moved(uuid, parentUUID, name string) {
|
||||
r.set(uuid, location{parentUUID: parentUUID, name: name})
|
||||
}
|
||||
|
||||
// deleted records that uuid was deleted.
|
||||
func (r *recentChanges) deleted(uuid string) {
|
||||
r.set(uuid, location{})
|
||||
}
|
||||
|
||||
// stale reports whether an API result saying uuid is called name in
|
||||
// parentUUID is out of date because of a change made by this process.
|
||||
func (r *recentChanges) stale(uuid, parentUUID, name string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
loc, ok := r.items[uuid]
|
||||
if !ok || time.Now().After(loc.expires) {
|
||||
return false
|
||||
}
|
||||
return loc.parentUUID != parentUUID || loc.name != name
|
||||
}
|
||||
|
||||
// findFile looks up a single file by name within directoryID. Returns
|
||||
// (nil, nil) when the file does not exist; surfaces transport/API errors.
|
||||
func (f *Fs) findFile(ctx context.Context, leaf, directoryID string) (*folders.File, error) {
|
||||
encodedName := f.opt.Encoding.FromStandardName(leaf)
|
||||
name, ext := splitNameExt(encodedName)
|
||||
checks := []files.FileExistenceCheck{existenceCheck(name, ext)}
|
||||
if encodedName != name {
|
||||
checks = append(checks, existenceCheck(encodedName, ""))
|
||||
}
|
||||
if legacyName, legacyExt := legacyNameExt(encodedName); legacyExt != "" && legacyName != name {
|
||||
checks = append(checks, existenceCheck(legacyName, legacyExt))
|
||||
}
|
||||
|
||||
var checkResult *files.CheckFilesExistenceResponse
|
||||
err := f.pacer.Call(func() (bool, error) {
|
||||
var err error
|
||||
checkResult, err = files.CheckFilesExistence(ctx, f.cfg, directoryID, checks)
|
||||
if isNotFoundError(err) {
|
||||
return true, err
|
||||
}
|
||||
return f.shouldRetry(ctx, err)
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
// If existence check fails, assume file doesn't exist to allow upload to proceed
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var uuid string
|
||||
for _, result := range checkResult.Files {
|
||||
if !result.FileExists() || result.UUID == "" {
|
||||
continue
|
||||
}
|
||||
if recent.stale(result.UUID, directoryID, joinNameExt(result.PlainName, result.Type)) {
|
||||
fs.Debugf(f, "Ignoring stale lookup of %q (UUID: %s) which was moved or deleted", leaf, result.UUID)
|
||||
continue
|
||||
}
|
||||
if joinNameExt(result.PlainName, result.Type) == encodedName {
|
||||
uuid = result.UUID
|
||||
break
|
||||
}
|
||||
}
|
||||
if uuid == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if len(checkResult.Files) > 0 && checkResult.Files[0].FileExists() {
|
||||
result := checkResult.Files[0]
|
||||
if result.Type != ext {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
existingUUID := result.UUID
|
||||
if existingUUID != "" {
|
||||
fileMeta, err := files.GetFileMeta(ctx, f.cfg, existingUUID)
|
||||
if err == nil && fileMeta != nil {
|
||||
return convertFileMetaToFile(fileMeta), nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
var fileMeta *files.FileMeta
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
var err error
|
||||
fileMeta, err = files.GetFileMeta(ctx, f.cfg, uuid)
|
||||
return f.shouldRetry(ctx, err)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
if fileMeta == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return convertFileMetaToFile(fileMeta), nil
|
||||
}
|
||||
|
||||
// convertFileMetaToFile converts files.FileMeta to folders.File
|
||||
@@ -634,6 +762,9 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
|
||||
return nil, err
|
||||
}
|
||||
for _, e := range foldersList {
|
||||
if recent.stale(e.UUID, dirID, e.PlainName) {
|
||||
continue
|
||||
}
|
||||
remote := path.Join(dir, f.opt.Encoding.ToStandardName(e.PlainName))
|
||||
out = append(out, fs.NewDir(remote, e.ModificationTime))
|
||||
}
|
||||
@@ -651,6 +782,9 @@ func (f *Fs) List(ctx context.Context, dir string) (fs.DirEntries, error) {
|
||||
if len(e.Type) > 0 {
|
||||
remote += "." + e.Type
|
||||
}
|
||||
if recent.stale(e.UUID, dirID, remote) {
|
||||
continue
|
||||
}
|
||||
remote = path.Join(dir, f.opt.Encoding.ToStandardName(remote))
|
||||
out = append(out, newObjectWithFile(f, remote, &e))
|
||||
}
|
||||
@@ -675,8 +809,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if file already exists
|
||||
existingFile, err := f.preUploadCheck(ctx, leaf, directoryID)
|
||||
existingFile, err := f.findFile(ctx, leaf, directoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -724,44 +857,28 @@ func (f *Fs) Remove(ctx context.Context, remote string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recent.deleted(dirID)
|
||||
f.dirCache.FlushDir(remote)
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewObject creates a new object
|
||||
// NewObject creates a new object by looking up a single file's metadata.
|
||||
func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||
parentDir := path.Dir(remote)
|
||||
|
||||
if parentDir == "." {
|
||||
parentDir = ""
|
||||
}
|
||||
|
||||
dirID, err := f.dirCache.FindDir(ctx, parentDir, false)
|
||||
leaf, directoryID, err := f.dirCache.FindPath(ctx, remote, false)
|
||||
if err != nil {
|
||||
return nil, fs.ErrorObjectNotFound
|
||||
if err == fs.ErrorDirNotFound {
|
||||
return nil, fs.ErrorObjectNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var files []folders.File
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
var err error
|
||||
files, err = folders.ListAllFiles(ctx, f.cfg, dirID)
|
||||
return f.shouldRetry(ctx, err)
|
||||
})
|
||||
file, err := f.findFile(ctx, leaf, directoryID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
targetName := path.Base(remote)
|
||||
for _, e := range files {
|
||||
name := e.PlainName
|
||||
if len(e.Type) > 0 {
|
||||
name += "." + e.Type
|
||||
}
|
||||
decodedName := f.opt.Encoding.ToStandardName(name)
|
||||
if decodedName == targetName {
|
||||
return newObjectWithFile(f, remote, &e), nil
|
||||
}
|
||||
if file == nil {
|
||||
return nil, fs.ErrorObjectNotFound
|
||||
}
|
||||
return nil, fs.ErrorObjectNotFound
|
||||
return newObjectWithFile(f, remote, file), nil
|
||||
}
|
||||
|
||||
// newObjectWithFile returns a new object by file info
|
||||
@@ -865,19 +982,23 @@ func (f *Fs) Move(ctx context.Context, src fs.Object, remote string) (fs.Object,
|
||||
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), ".")
|
||||
newName, newType := splitNameExt(f.opt.Encoding.FromStandardName(leaf))
|
||||
|
||||
// Move the file server-side
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
err := files.MoveFile(ctx, f.cfg, srcObj.uuid, directoryID, newName, newType)
|
||||
// The move is checked against lagging read replicas so it can
|
||||
// fail with 404 if the destination directory was just created
|
||||
// or 409 if a file at the destination was just deleted.
|
||||
if err != nil && isStaleReadError(err, true) {
|
||||
return true, err
|
||||
}
|
||||
return f.shouldRetry(ctx, err)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recent.moved(srcObj.uuid, directoryID, joinNameExt(newName, newType))
|
||||
|
||||
dstObj := &Object{
|
||||
f: f,
|
||||
@@ -913,11 +1034,17 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
||||
encodedLeaf := f.opt.Encoding.FromStandardName(dstLeaf)
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
err := folders.MoveFolder(ctx, f.cfg, srcID, dstDirectoryID, encodedLeaf)
|
||||
// Moving a large folder can outlast the gateway timeout (520/502)
|
||||
// yet still complete, in which case the retry reports this.
|
||||
if err != nil && isConflictError(err) && strings.Contains(err.Error(), "already moved to that location") {
|
||||
return false, nil
|
||||
}
|
||||
return f.shouldRetry(ctx, err)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recent.moved(srcID, dstDirectoryID, encodedLeaf)
|
||||
|
||||
srcFs.dirCache.FlushDir(srcRemote)
|
||||
return nil
|
||||
@@ -965,9 +1092,7 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||
remote := o.remote
|
||||
|
||||
origBaseName := path.Base(remote)
|
||||
origName := strings.TrimSuffix(origBaseName, path.Ext(origBaseName))
|
||||
origType := strings.TrimPrefix(path.Ext(origBaseName), ".")
|
||||
origName, origType := splitNameExt(path.Base(remote))
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
_, dirID, err := o.f.dirCache.FindPath(ctx, remote, true)
|
||||
@@ -984,11 +1109,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
|
||||
// Step 1: If file exists, rename to backup (preserves old file during upload)
|
||||
if oldUUID != "" {
|
||||
// Generate unique backup name
|
||||
baseName := path.Base(remote)
|
||||
name := strings.TrimSuffix(baseName, path.Ext(baseName))
|
||||
ext := strings.TrimPrefix(path.Ext(baseName), ".")
|
||||
|
||||
name, ext := splitNameExt(path.Base(remote))
|
||||
backupSuffix := fmt.Sprintf(".rclone-backup-%s", random.String(8))
|
||||
backupName = o.f.opt.Encoding.FromStandardName(name + backupSuffix)
|
||||
backupType = ext
|
||||
@@ -1061,6 +1182,11 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
return o.f.tooLargeError(remote, tooLarge)
|
||||
}
|
||||
|
||||
if err != nil && isStaleReadError(err, backupUUID != "") {
|
||||
o.restoreBackupFile(ctx, backupUUID, origName, origType)
|
||||
return fserrors.RetryError(err)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
meta, err = o.recoverFromTimeoutConflict(ctx, err, remote, dirID)
|
||||
}
|
||||
@@ -1099,6 +1225,7 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
backupName, backupType, backupUUID, err)
|
||||
// Don't fail the upload just because backup deletion failed
|
||||
} else {
|
||||
recent.deleted(backupUUID)
|
||||
fs.Debugf(o.f, "Successfully deleted backup file")
|
||||
}
|
||||
}
|
||||
@@ -1118,6 +1245,19 @@ func isTimeoutError(err error) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// isNotFoundError reports whether err is a 404 from the API.
|
||||
func isNotFoundError(err error) bool {
|
||||
var httpErr *sdkerrors.HTTPError
|
||||
return errors.As(err, &httpErr) && httpErr.StatusCode() == 404
|
||||
}
|
||||
|
||||
// isStaleReadError reports whether err is the API contradicting a write this
|
||||
// backend has already made, which it does because lookups are served by read
|
||||
// replicas that lag behind the primary.
|
||||
func isStaleReadError(err error, renamed bool) bool {
|
||||
return isNotFoundError(err) || (renamed && isConflictError(err))
|
||||
}
|
||||
|
||||
// isConflictError checks if an error indicates a file conflict (409)
|
||||
func isConflictError(err error) bool {
|
||||
errMsg := err.Error()
|
||||
@@ -1159,40 +1299,22 @@ func (o *Object) recoverFromTimeoutConflict(ctx context.Context, uploadErr error
|
||||
}
|
||||
|
||||
baseName := path.Base(remote)
|
||||
encodedName := o.f.opt.Encoding.FromStandardName(baseName)
|
||||
|
||||
var meta *buckets.CreateMetaResponse
|
||||
checkErr := o.f.pacer.Call(func() (bool, error) {
|
||||
existingFile, err := o.f.preUploadCheck(ctx, encodedName, dirID)
|
||||
if err != nil {
|
||||
return o.f.shouldRetry(ctx, err)
|
||||
}
|
||||
if existingFile != nil {
|
||||
name := strings.TrimSuffix(baseName, path.Ext(baseName))
|
||||
ext := strings.TrimPrefix(path.Ext(baseName), ".")
|
||||
|
||||
meta = &buckets.CreateMetaResponse{
|
||||
UUID: existingFile.UUID,
|
||||
FileID: existingFile.FileID,
|
||||
Name: name,
|
||||
PlainName: name,
|
||||
Type: ext,
|
||||
Size: existingFile.Size,
|
||||
}
|
||||
o.id = existingFile.FileID
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
|
||||
if checkErr != nil {
|
||||
existingFile, err := o.f.findFile(ctx, baseName, dirID)
|
||||
if err != nil || existingFile == nil {
|
||||
return nil, uploadErr
|
||||
}
|
||||
|
||||
if meta != nil {
|
||||
return meta, nil
|
||||
}
|
||||
|
||||
return nil, uploadErr
|
||||
name, ext := splitNameExt(baseName)
|
||||
o.id = existingFile.FileID
|
||||
return &buckets.CreateMetaResponse{
|
||||
UUID: existingFile.UUID,
|
||||
FileID: existingFile.FileID,
|
||||
Name: name,
|
||||
PlainName: name,
|
||||
Type: ext,
|
||||
Size: existingFile.Size,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// restoreBackupFile restores a backup file after upload failure
|
||||
@@ -1210,8 +1332,13 @@ func (o *Object) restoreBackupFile(ctx context.Context, backupUUID, origName, or
|
||||
|
||||
// Remove deletes a file
|
||||
func (o *Object) Remove(ctx context.Context) error {
|
||||
return o.f.pacer.Call(func() (bool, error) {
|
||||
err := o.f.pacer.Call(func() (bool, error) {
|
||||
err := files.DeleteFile(ctx, o.f.cfg, o.uuid)
|
||||
return o.f.shouldRetry(ctx, err)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recent.deleted(o.uuid)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package internxt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/internxt/rclone-adapter/config"
|
||||
"github.com/internxt/rclone-adapter/endpoints"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/lib/encoder"
|
||||
"github.com/rclone/rclone/lib/pacer"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// storedFile is a file as the service holds it: a (plainName, type) pair
|
||||
// split however the client that uploaded it chose to split it.
|
||||
type storedFile struct {
|
||||
uuid string
|
||||
plainName string
|
||||
fileType string
|
||||
}
|
||||
|
||||
// wireType renders a stored type the way the service does: a file with no
|
||||
// extension comes back as JSON null, not an empty string.
|
||||
func wireType(fileType string) any {
|
||||
if fileType == "" {
|
||||
return nil
|
||||
}
|
||||
return fileType
|
||||
}
|
||||
|
||||
// existenceServer answers the existence check and file meta endpoints from
|
||||
// files, matching plainName exactly and only constraining type when the
|
||||
// criterion supplies one, as the service does.
|
||||
func existenceServer(t *testing.T, stored []storedFile) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasSuffix(r.URL.Path, "/meta") {
|
||||
uuid := strings.Split(strings.TrimPrefix(r.URL.Path, "/drive/files/"), "/")[0]
|
||||
for _, f := range stored {
|
||||
if f.uuid == uuid {
|
||||
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{
|
||||
"uuid": f.uuid, "plainName": f.plainName, "type": wireType(f.fileType),
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Files []struct {
|
||||
PlainName string `json:"plainName"`
|
||||
Type string `json:"type"`
|
||||
} `json:"files"`
|
||||
}
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&req))
|
||||
var existent []map[string]any
|
||||
for _, f := range stored {
|
||||
for _, c := range req.Files {
|
||||
if c.PlainName == f.plainName && (c.Type == "" || c.Type == f.fileType) {
|
||||
existent = append(existent, map[string]any{
|
||||
"exists": true, "status": "EXISTS",
|
||||
"uuid": f.uuid, "plainName": f.plainName, "type": wireType(f.fileType),
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"existentFiles": existent}))
|
||||
}))
|
||||
}
|
||||
|
||||
func testFs(t *testing.T, server *httptest.Server) *Fs {
|
||||
t.Helper()
|
||||
f := &Fs{
|
||||
opt: Options{Encoding: encoder.EncodeInvalidUtf8},
|
||||
cfg: &config.Config{
|
||||
HTTPClient: server.Client(),
|
||||
Endpoints: endpoints.NewConfig(server.URL),
|
||||
},
|
||||
}
|
||||
f.pacer = fs.NewPacer(context.Background(), pacer.NewDefault(pacer.MinSleep(minSleep), pacer.MaxSleep(maxSleep), pacer.DecayConstant(decayConstant)))
|
||||
return f
|
||||
}
|
||||
|
||||
func TestSplitJoinNameExt(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
baseName string
|
||||
name string
|
||||
ext string
|
||||
}{
|
||||
{"foo.txt", "foo", "txt"},
|
||||
{"foo.tar.gz", "foo.tar", "gz"},
|
||||
{"README", "README", ""},
|
||||
{".bashrc", ".bashrc", ""},
|
||||
{"..hidden", ".", "hidden"},
|
||||
{"", "", ""},
|
||||
} {
|
||||
name, ext := splitNameExt(test.baseName)
|
||||
assert.Equal(t, test.name, name, test.baseName)
|
||||
assert.Equal(t, test.ext, ext, test.baseName)
|
||||
assert.Equal(t, test.baseName, joinNameExt(name, ext), test.baseName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindFile(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
what string
|
||||
stored []storedFile
|
||||
leaf string
|
||||
wantUUID string
|
||||
}{{
|
||||
what: "split as rclone splits it",
|
||||
stored: []storedFile{{"uuid-1", "foo.tar", "gz"}},
|
||||
leaf: "foo.tar.gz",
|
||||
wantUUID: "uuid-1",
|
||||
}, {
|
||||
what: "whole name stored as plainName by another client",
|
||||
stored: []storedFile{{"uuid-2", "foo.tar.gz", ""}},
|
||||
leaf: "foo.tar.gz",
|
||||
wantUUID: "uuid-2",
|
||||
}, {
|
||||
what: "extensionless name is not confused with an extended one",
|
||||
stored: []storedFile{{"uuid-3", "README", "md"}, {"uuid-4", "README", ""}},
|
||||
leaf: "README",
|
||||
wantUUID: "uuid-4",
|
||||
}, {
|
||||
what: "dotfile stored the way the web client splits it",
|
||||
stored: []storedFile{{"uuid-6", ".bashrc", ""}},
|
||||
leaf: ".bashrc",
|
||||
wantUUID: "uuid-6",
|
||||
}, {
|
||||
what: "dotfile stored the way older rclone versions split it",
|
||||
stored: []storedFile{{"uuid-7", "", "bashrc"}},
|
||||
leaf: ".bashrc",
|
||||
wantUUID: "uuid-7",
|
||||
}, {
|
||||
what: "trailing dot kept in plainName by a rename",
|
||||
stored: []storedFile{{"uuid-8", "trailing.", ""}},
|
||||
leaf: "trailing.",
|
||||
wantUUID: "uuid-8",
|
||||
}, {
|
||||
what: "missing file",
|
||||
stored: []storedFile{{"uuid-5", "other", "txt"}},
|
||||
leaf: "foo.txt",
|
||||
}} {
|
||||
t.Run(test.what, func(t *testing.T) {
|
||||
server := existenceServer(t, test.stored)
|
||||
defer server.Close()
|
||||
file, err := testFs(t, server).findFile(context.Background(), test.leaf, "dir-uuid")
|
||||
require.NoError(t, err)
|
||||
if test.wantUUID == "" {
|
||||
assert.Nil(t, file)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, file)
|
||||
assert.Equal(t, test.wantUUID, file.UUID)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindFileIgnoresStale(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
server := existenceServer(t, []storedFile{{"uuid-moved", "foo", "txt"}, {"uuid-deleted", "bar", "txt"}, {"uuid-renamed", "baz", "txt"}})
|
||||
defer server.Close()
|
||||
f := testFs(t, server)
|
||||
|
||||
recent.moved("uuid-moved", "other-dir-uuid", "foo.txt.bak")
|
||||
recent.deleted("uuid-deleted")
|
||||
recent.moved("uuid-renamed", "dir-uuid", "baz.txt")
|
||||
|
||||
file, err := f.findFile(ctx, "foo.txt", "dir-uuid")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, file, "moved away")
|
||||
|
||||
file, err = f.findFile(ctx, "bar.txt", "dir-uuid")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, file, "deleted")
|
||||
|
||||
file, err = f.findFile(ctx, "baz.txt", "dir-uuid")
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, file, "moved here")
|
||||
assert.Equal(t, "uuid-renamed", file.UUID)
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"io"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/internxt/rclone-adapter/buckets"
|
||||
@@ -263,9 +262,7 @@ func (w *internxtChunkWriter) Close(ctx context.Context) error {
|
||||
}
|
||||
|
||||
// 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), ".")
|
||||
name, ext := splitNameExt(w.f.opt.Encoding.FromStandardName(path.Base(w.remote)))
|
||||
|
||||
var meta *buckets.CreateMetaResponse
|
||||
err = w.f.pacer.Call(func() (bool, error) {
|
||||
|
||||
+41
-25
@@ -438,6 +438,7 @@ 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")
|
||||
errLinkNameInvalid = errors.New("translated link needs a file name before the \"" + fs.LinkSuffix + "\" suffix")
|
||||
)
|
||||
|
||||
// NewFs constructs an Fs from the path
|
||||
@@ -565,30 +566,26 @@ func (f *Fs) caseInsensitive() bool {
|
||||
return runtime.GOOS == "windows" || runtime.GOOS == "darwin"
|
||||
}
|
||||
|
||||
// translateLink checks whether the remote is a translated link
|
||||
// and returns a new path, removing the suffix as needed,
|
||||
// It also returns whether this is a translated link at all
|
||||
//
|
||||
// for regular files, localPath is returned unchanged
|
||||
func translateLink(remote, localPath string) (newLocalPath string, isTranslatedLink bool) {
|
||||
isTranslatedLink = strings.HasSuffix(remote, fs.LinkSuffix)
|
||||
newLocalPath = strings.TrimSuffix(localPath, fs.LinkSuffix)
|
||||
return newLocalPath, isTranslatedLink
|
||||
}
|
||||
|
||||
// newObject makes a half completed Object
|
||||
func (f *Fs) newObject(remote string) (*Object, error) {
|
||||
translatedLink := false
|
||||
localPath, err := f.localPath(remote)
|
||||
name, translatedLink := remote, false
|
||||
if f.opt.TranslateSymlinks {
|
||||
name, translatedLink = strings.CutSuffix(remote, fs.LinkSuffix)
|
||||
}
|
||||
if translatedLink {
|
||||
// Check this makes a valid native file name
|
||||
native := f.nativePath(name)
|
||||
switch native[strings.LastIndex(native, string(filepath.Separator))+1:] {
|
||||
case "", ".", "..":
|
||||
return nil, fserrors.NoRetryError(fmt.Errorf("%q: %w", remote, errLinkNameInvalid))
|
||||
}
|
||||
}
|
||||
// Check the name after any suffix removal
|
||||
localPath, err := f.localPath(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if f.opt.TranslateSymlinks {
|
||||
// Possibly receive a new name for localPath
|
||||
localPath, translatedLink = translateLink(remote, localPath)
|
||||
}
|
||||
|
||||
return &Object{
|
||||
fs: f,
|
||||
remote: remote,
|
||||
@@ -637,15 +634,23 @@ func (f *Fs) NewObject(ctx context.Context, remote string) (fs.Object, error) {
|
||||
}
|
||||
|
||||
// Create new directory object from the info passed in
|
||||
//
|
||||
// Directories are never translated links, so the name is used as is
|
||||
// whatever suffix it has.
|
||||
func (f *Fs) newDirectory(dir string, fi os.FileInfo) (*Directory, error) {
|
||||
o, err := f.newObject(dir)
|
||||
localPath, err := f.localPath(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.setMetadata(fi)
|
||||
return &Directory{
|
||||
Object: *o,
|
||||
}, nil
|
||||
d := &Directory{
|
||||
Object: Object{
|
||||
fs: f,
|
||||
remote: dir,
|
||||
path: localPath,
|
||||
},
|
||||
}
|
||||
d.setMetadata(fi)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// List the objects and directories in dir into entries. The
|
||||
@@ -785,6 +790,12 @@ func (f *Fs) List(ctx context.Context, dir string) (entries fs.DirEntries, err e
|
||||
continue
|
||||
}
|
||||
fso, err := f.newObjectWithInfo(newRemote, fi)
|
||||
if errors.Is(err, errLinkNameInvalid) {
|
||||
// Skip a badly named ".rclonelink" file
|
||||
fs.Errorf(newRemote, "Listing error: %v", err)
|
||||
_ = accounting.Stats(ctx).Error(err)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -814,14 +825,19 @@ func (f *Fs) cleanRemote(dir, filename string) (remote string) {
|
||||
return
|
||||
}
|
||||
|
||||
// nativePath returns name in the OS encoding with OS path separators,
|
||||
// relative to f.root, without cleaning it.
|
||||
func (f *Fs) nativePath(name string) string {
|
||||
return filepath.FromSlash(f.opt.Enc.FromStandardPath(name))
|
||||
}
|
||||
|
||||
// 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)
|
||||
localPath := filepath.Join(f.root, f.nativePath(name))
|
||||
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))
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//go:build windows
|
||||
|
||||
package local
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func TestUpdateFatalIfNoSpaceWindows(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
}{
|
||||
{"ERROR_DISK_FULL", windows.ERROR_DISK_FULL},
|
||||
{"openat PathError", &os.PathError{Op: "openat", Path: "test.txt", Err: windows.ERROR_DISK_FULL}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Run("off", func(t *testing.T) {
|
||||
err := updateWithReader(t, false, test.err)
|
||||
require.Error(t, err)
|
||||
assert.False(t, fserrors.IsFatalError(err))
|
||||
})
|
||||
t.Run("on", func(t *testing.T) {
|
||||
err := updateWithReader(t, true, test.err)
|
||||
require.Error(t, err)
|
||||
assert.True(t, fserrors.IsFatalError(err))
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,19 @@ func TestVerifyCopy(t *testing.T) {
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
// skipIfNoSymlinks skips the test if this process can't create symlinks.
|
||||
//
|
||||
// Windows grants the privilege only to an elevated process or one running with
|
||||
// Developer Mode enabled, so an ordinary user gets ERROR_PRIVILEGE_NOT_HELD.
|
||||
func skipIfNoSymlinks(t *testing.T) {
|
||||
t.Helper()
|
||||
if err := os.Symlink("target", filepath.Join(t.TempDir(), "link")); err != nil {
|
||||
t.Skipf("Skipping as symlinks are unavailable: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSymlink(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
@@ -265,6 +277,7 @@ func linksMode(f *Fs) {
|
||||
// faithful backup of the source) but must refuse to write through it, so
|
||||
// nothing lands outside the destination (CWE-59).
|
||||
func TestSymlinkEscapeWriteThroughBlocked(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// A directory outside the destination the attacker wants to write into
|
||||
@@ -300,6 +313,7 @@ func TestSymlinkEscapeWriteThroughBlocked(t *testing.T) {
|
||||
// re-validated against the root, so the write-through is refused and nothing
|
||||
// escapes.
|
||||
func TestSymlinkEscapeNestedBlocked(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
evil := t.TempDir()
|
||||
@@ -351,6 +365,7 @@ func TestSymlinkEscapeConcurrent(t *testing.T) {
|
||||
// use: an in-tree symlink to a sibling directory can still be created and
|
||||
// written through, since that write stays inside the destination.
|
||||
func TestSymlinkInTreeWriteThroughWorks(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
|
||||
r := fstest.NewRun(t)
|
||||
@@ -606,6 +621,154 @@ func TestLocalPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestLinkSuffixEscapeBlocked checks that in --links mode a name which
|
||||
// passes the root check with its ".rclonelink" suffix can't escape the
|
||||
// destination once the suffix is removed: "...rclonelink" must not
|
||||
// become "..", the parent of the root.
|
||||
func TestLinkSuffixEscapeBlocked(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
outer := t.TempDir()
|
||||
newLinksFs := func(dir, encoding string) *Fs {
|
||||
fRaw, err := NewFs(ctx, "local", filepath.Join(outer, dir), configmap.Simple{"encoding": encoding})
|
||||
require.NoError(t, err)
|
||||
f := fRaw.(*Fs)
|
||||
linksMode(f)
|
||||
require.NoError(t, f.Mkdir(ctx, ""))
|
||||
return f
|
||||
}
|
||||
f := newLinksFs("dst", encoder.OS.String())
|
||||
s := newLinksFs("slash", "Slash")
|
||||
|
||||
// Stamp the parent of the destinations so a write to it shows up.
|
||||
before := fstest.Time("2011-12-25T12:59:59Z")
|
||||
require.NoError(t, os.Chtimes(outer, before, before))
|
||||
parentUnchanged := func() {
|
||||
t.Helper()
|
||||
fi, err := os.Lstat(outer)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, fi.ModTime().Equal(before), "the parent of the destination was modified")
|
||||
}
|
||||
|
||||
// A directory called "...rclonelink" is created under its own name
|
||||
// and its metadata goes there, not to the parent of the root which
|
||||
// trimming the suffix off its path would address.
|
||||
remote := ".." + fs.LinkSuffix
|
||||
metadata := fs.Metadata{"mtime": "2001-02-03T04:05:06Z"}
|
||||
_, err := f.MkdirMetadata(ctx, remote, metadata)
|
||||
require.NoError(t, err)
|
||||
parentUnchanged()
|
||||
|
||||
// A file called "...rclonelink" is a link called "..", which the
|
||||
// default encoding stores as fullwidth dots like any other name.
|
||||
require.NoError(t, putFile(ctx, f, remote, "target"))
|
||||
fi, err := os.Lstat(filepath.Join(f.root, ".."))
|
||||
require.NoError(t, err)
|
||||
assert.NotZero(t, fi.Mode()&os.ModeSymlink)
|
||||
parentUnchanged()
|
||||
|
||||
// Ordinary translated links still resolve to the file without the suffix.
|
||||
o, err := f.newObject("sub/link" + fs.LinkSuffix)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, o.translatedLink)
|
||||
assert.Equal(t, filepath.Join(f.root, "sub", "link"), o.path)
|
||||
|
||||
// A name which merely contains the suffix is a regular file.
|
||||
o, err = f.newObject("sub/link" + fs.LinkSuffix + ".txt")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, o.translatedLink)
|
||||
assert.Equal(t, filepath.Join(f.root, "sub", "link"+fs.LinkSuffix+".txt"), o.path)
|
||||
|
||||
// An encoding without Dot leaves ".." as a real ".." once the suffix
|
||||
// is gone, so the name is refused instead.
|
||||
require.ErrorIs(t, putFile(ctx, s, remote, "PWNED"), errLinkNameInvalid)
|
||||
_, err = s.MkdirMetadata(ctx, remote, metadata)
|
||||
require.NoError(t, err)
|
||||
parentUnchanged()
|
||||
|
||||
// As is any other name which doesn't leave a file name once the
|
||||
// suffix is removed and the encoding applied.
|
||||
for _, name := range []string{
|
||||
remote,
|
||||
"sub/.." + fs.LinkSuffix,
|
||||
"sub/." + fs.LinkSuffix,
|
||||
"sub/.." + fs.LinkSuffix,
|
||||
"sub/sub2/.." + fs.LinkSuffix,
|
||||
"sub/." + fs.LinkSuffix,
|
||||
"sub/" + fs.LinkSuffix,
|
||||
fs.LinkSuffix,
|
||||
} {
|
||||
_, err = s.newObject(name)
|
||||
assert.ErrorIs(t, err, errLinkNameInvalid, name)
|
||||
assert.True(t, fserrors.IsNoRetryError(err), name)
|
||||
}
|
||||
|
||||
// The root check still applies to the name of the link.
|
||||
_, err = s.newObject("../link" + fs.LinkSuffix)
|
||||
require.ErrorIs(t, err, errPathEscapes)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
// A backslash is a path separator on Windows, so an encoding
|
||||
// without BackSlash can hide ".." behind one.
|
||||
w := newLinksFs("win", "Slash,Dot")
|
||||
_, err = w.newObject(`sub\..` + fs.LinkSuffix)
|
||||
assert.ErrorIs(t, err, errLinkNameInvalid)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLinkSuffixListSkipsInvalidName checks that with --links a regular
|
||||
// file whose name is just the suffix is reported as an error and skipped
|
||||
// rather than failing the listing of its whole directory.
|
||||
func TestLinkSuffixListSkipsInvalidName(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
when := fstest.Time("2001-02-03T04:05:06Z")
|
||||
r.WriteFile("sub/"+fs.LinkSuffix, "not a link", when)
|
||||
r.WriteFile("sub/file.txt", "hello", when)
|
||||
|
||||
accounting.Stats(ctx).ResetErrors()
|
||||
entries, err := f.List(ctx, "sub")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
assert.Equal(t, "sub/file.txt", entries[0].Remote())
|
||||
assert.Equal(t, int64(1), accounting.Stats(ctx).GetErrors())
|
||||
accounting.Stats(ctx).ResetErrors()
|
||||
}
|
||||
|
||||
// TestLinkSuffixDirectory checks that in --links mode a directory whose
|
||||
// name ends in ".rclonelink" is an ordinary directory. Only files are
|
||||
// translated into links, so the suffix must stay in its path rather
|
||||
// than making it address a sibling.
|
||||
func TestLinkSuffixDirectory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
f := r.Flocal.(*Fs)
|
||||
linksMode(f)
|
||||
|
||||
dir := "sub" + fs.LinkSuffix
|
||||
want := filepath.Join(f.root, dir)
|
||||
mtime := fstest.Time("2001-02-03T04:05:06Z")
|
||||
|
||||
d, err := f.MkdirMetadata(ctx, dir, fs.Metadata{"mtime": mtime.Format(time.RFC3339Nano)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, d.(*Directory).path)
|
||||
fi, err := os.Lstat(want)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, fi.IsDir())
|
||||
assert.True(t, fi.ModTime().Equal(mtime), "metadata was not written to the directory")
|
||||
|
||||
entries, err := f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
got, ok := entries[0].(*Directory)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, dir, got.Remote())
|
||||
assert.Equal(t, want, got.path)
|
||||
assert.False(t, got.translatedLink)
|
||||
}
|
||||
|
||||
func TestHashWithTypeNone(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
@@ -683,6 +846,7 @@ func TestHashOnDelete(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMetadata(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
const filePath = "metafile.txt"
|
||||
@@ -959,6 +1123,7 @@ func TestFilter(t *testing.T) {
|
||||
}
|
||||
|
||||
func testFilterSymlink(t *testing.T, copyLinks bool) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
defer r.Finalise()
|
||||
@@ -1063,6 +1228,7 @@ func TestFilterSymlinkLinks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCopySymlink(t *testing.T) {
|
||||
skipIfNoSymlinks(t)
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
defer r.Finalise()
|
||||
|
||||
@@ -236,9 +236,9 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("couldn't parse URL %q: %w", opt.Endpoint, err)
|
||||
}
|
||||
u, err := rest.URLJoin(base, rest.URLPathEscape(root))
|
||||
u, err := rest.URLJoinRoot(base, root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("couldn't join URL %q and %q: %w", base.String(), root, err)
|
||||
return nil, err
|
||||
}
|
||||
client := fshttp.NewClient(ctx)
|
||||
|
||||
@@ -573,10 +573,12 @@ func (f *Fs) ListR(ctx context.Context, dir string, callback fs.ListRCallback) (
|
||||
fs.Errorf(nil, "Unable to parse URL %q: %v", f.endpointURL, err)
|
||||
return fs.ErrorDirNotFound
|
||||
}
|
||||
resumeURL, err := rest.URLJoin(u, rest.URLPathEscape(resumeStart))
|
||||
// A bad resume start must fail the listing rather than
|
||||
// return fs.ErrorDirNotFound which sync treats as an empty
|
||||
// directory
|
||||
resumeURL, err := rest.URLJoinRoot(u, resumeStart)
|
||||
if err != nil {
|
||||
fs.Errorf(nil, "Unable to join URL %q for resumeStart %s: %v", f.endpointURL, resumeStart, err)
|
||||
return fs.ErrorDirNotFound
|
||||
return fmt.Errorf("unable to join URL %q for resumeStart %q: %w", f.endpointURL, resumeStart, err)
|
||||
}
|
||||
URL = resumeURL.String()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package netstorage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestListResumeCannotChangeHost(t *testing.T) {
|
||||
// The resume start returned by a list request comes from the
|
||||
// server. It must not be able to move the signed continuation
|
||||
// request to another host.
|
||||
var requests int
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
}))
|
||||
defer other.Close()
|
||||
otherHost := strings.TrimPrefix(other.URL, "http://")
|
||||
|
||||
var listRequests int
|
||||
configured := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
action := r.Header.Get("X-Akamai-ACS-Action")
|
||||
switch {
|
||||
case strings.Contains(action, "action=stat"):
|
||||
_, _ = w.Write([]byte(`<stat directory="/123456/dir"><file type="dir" name="dir" mtime="0"/></stat>`))
|
||||
case strings.Contains(action, "action=list"):
|
||||
listRequests++
|
||||
_, _ = w.Write([]byte(`<list><file type="file" name="123456/dir/a.txt" size="1" mtime="0"/><resume start="//` + otherHost + `/123456/dir/b.txt"/></list>`))
|
||||
default:
|
||||
http.Error(w, "unexpected action "+action, http.StatusBadRequest)
|
||||
}
|
||||
}))
|
||||
defer configured.Close()
|
||||
|
||||
m := configmap.Simple{
|
||||
"type": "netstorage",
|
||||
"protocol": "http",
|
||||
"host": strings.TrimPrefix(configured.URL, "http://") + "/123456/",
|
||||
"account": "account",
|
||||
"secret": obscure.MustObscure("secret"),
|
||||
}
|
||||
f, err := NewFs(context.Background(), "TestNetStorage", "dir", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The listing must fail loudly rather than with
|
||||
// fs.ErrorDirNotFound which sync treats as an empty directory
|
||||
err = f.(*Fs).ListR(context.Background(), "", func(entries fs.DirEntries) error { return nil })
|
||||
assert.ErrorContains(t, err, "must not change the scheme, host or user")
|
||||
assert.NotErrorIs(t, err, fs.ErrorDirNotFound)
|
||||
assert.Equal(t, 1, listRequests, "list request sent to the configured host")
|
||||
assert.Equal(t, 0, requests, "request sent to the other host")
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
const (
|
||||
dirMimeType = "inode/directory"
|
||||
timeFormatIn = time.RFC3339
|
||||
timeFormatOut = "2006-01-02T15:04:05.999Z" // mS for OneDrive Personal, otherwise only S
|
||||
timeFormatOut = "2006-01-02T15:04:05.999Z" // keeps mS if present, though OneDrive only stores S
|
||||
)
|
||||
|
||||
// system metadata keys which this backend owns
|
||||
@@ -32,17 +32,17 @@ var systemMetadataInfo = map[string]fs.MetadataHelp{
|
||||
ReadOnly: true,
|
||||
},
|
||||
"mtime": {
|
||||
Help: "Time of last modification with S accuracy (mS for OneDrive Personal).",
|
||||
Help: "Time of last modification with S accuracy.",
|
||||
Type: "RFC 3339",
|
||||
Example: "2006-01-02T15:04:05Z",
|
||||
},
|
||||
"btime": {
|
||||
Help: "Time of file birth (creation) with S accuracy (mS for OneDrive Personal).",
|
||||
Help: "Time of file birth (creation) with S accuracy.",
|
||||
Type: "RFC 3339",
|
||||
Example: "2006-01-02T15:04:05Z",
|
||||
},
|
||||
"utime": {
|
||||
Help: "Time of upload with S accuracy (mS for OneDrive Personal).",
|
||||
Help: "Time of upload with S accuracy.",
|
||||
Type: "RFC 3339",
|
||||
Example: "2006-01-02T15:04:05Z",
|
||||
ReadOnly: true,
|
||||
@@ -113,7 +113,7 @@ var systemMetadataInfo = map[string]fs.MetadataHelp{
|
||||
ReadOnly: true,
|
||||
},
|
||||
"shared-time": {
|
||||
Help: "Time when the item was shared, with S accuracy (mS for OneDrive Personal).",
|
||||
Help: "Time when the item was shared, with S accuracy.",
|
||||
Type: "RFC 3339",
|
||||
Example: "2006-01-02T15:04:05Z",
|
||||
ReadOnly: true,
|
||||
|
||||
@@ -275,16 +275,13 @@ cases, rclone will fall back to normal copy (which will be slightly slower).`,
|
||||
Default: false,
|
||||
Help: `Remove all versions on modifying operations.
|
||||
|
||||
Onedrive for business creates versions when rclone uploads new files
|
||||
Onedrive creates versions when rclone uploads new files
|
||||
overwriting an existing one and when it sets the modification time.
|
||||
|
||||
These versions take up space out of the quota.
|
||||
|
||||
This flag checks for versions after file upload and setting
|
||||
modification time and removes all but the last version.
|
||||
|
||||
**NB** Onedrive personal can't currently delete versions so don't use
|
||||
this flag there.
|
||||
`,
|
||||
Advanced: true,
|
||||
}, {
|
||||
@@ -294,8 +291,7 @@ this flag there.
|
||||
Normally files will get sent to the recycle bin on deletion. Setting
|
||||
this flag causes them to be permanently deleted. Use with care.
|
||||
|
||||
OneDrive personal accounts do not support the permanentDelete API,
|
||||
it only applies to OneDrive for Business and SharePoint document libraries.
|
||||
This works with OneDrive for Business, SharePoint document libraries, and OneDrive personal accounts, including free accounts.
|
||||
`,
|
||||
Advanced: true,
|
||||
Default: false,
|
||||
@@ -324,14 +320,18 @@ it only applies to OneDrive for Business and SharePoint document libraries.
|
||||
Help: "Creates a read-write link to the item.",
|
||||
}, {
|
||||
Value: "embed",
|
||||
Help: "Creates an embeddable link to the item.",
|
||||
Help: "Creates an embeddable link to the item.\nOnly available in OneDrive personal.",
|
||||
}},
|
||||
}, {
|
||||
Name: "link_password",
|
||||
Default: "",
|
||||
Help: `Set the password for links created by the link command.
|
||||
|
||||
At the time of writing this only works with OneDrive personal paid accounts.
|
||||
At the time of writing this works with OneDrive for Business and
|
||||
OneDrive personal paid accounts.
|
||||
|
||||
OneDrive personal free accounts can't set a password or an expiry time
|
||||
(with --expire) on links.
|
||||
`,
|
||||
Advanced: true,
|
||||
Sensitive: true,
|
||||
|
||||
@@ -116,11 +116,14 @@ func useBYOKCopyObject(fs *Fs, request *objectstorage.CopyObjectRequest) {
|
||||
}
|
||||
if fs.opt.SSECustomerAlgorithm != "" {
|
||||
request.OpcSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
|
||||
request.OpcSourceSseCustomerAlgorithm = common.String(fs.opt.SSECustomerAlgorithm)
|
||||
}
|
||||
if fs.opt.SSECustomerKey != "" {
|
||||
request.OpcSseCustomerKey = common.String(fs.opt.SSECustomerKey)
|
||||
request.OpcSourceSseCustomerKey = common.String(fs.opt.SSECustomerKey)
|
||||
}
|
||||
if fs.opt.SSECustomerKeySha256 != "" {
|
||||
request.OpcSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
|
||||
request.OpcSourceSseCustomerKeySha256 = common.String(fs.opt.SSECustomerKeySha256)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build !plan9 && !solaris && !js
|
||||
|
||||
package oracleobjectstorage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/oracle/oci-go-sdk/v65/objectstorage"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUseBYOKCopyObject(t *testing.T) {
|
||||
f := &Fs{opt: Options{
|
||||
SSECustomerAlgorithm: "AES256",
|
||||
SSECustomerKey: "customer-key",
|
||||
SSECustomerKeySha256: "customer-key-sha256",
|
||||
}}
|
||||
req := &objectstorage.CopyObjectRequest{}
|
||||
|
||||
useBYOKCopyObject(f, req)
|
||||
|
||||
assert.Equal(t, &f.opt.SSECustomerAlgorithm, req.OpcSourceSseCustomerAlgorithm)
|
||||
assert.Equal(t, &f.opt.SSECustomerKey, req.OpcSourceSseCustomerKey)
|
||||
assert.Equal(t, &f.opt.SSECustomerKeySha256, req.OpcSourceSseCustomerKeySha256)
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
package oracleobjectstorage
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
@@ -396,6 +397,9 @@ func isZeroLength(streamReader io.Reader) bool {
|
||||
return v.Len() == 0
|
||||
case *strings.Reader:
|
||||
return v.Len() == 0
|
||||
case *bufio.Reader:
|
||||
_, err := v.Peek(1)
|
||||
return err == io.EOF
|
||||
case *os.File:
|
||||
fi, err := v.Stat()
|
||||
if err != nil {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package oracleobjectstorage
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -553,7 +554,7 @@ func (f *Fs) Put(ctx context.Context, in io.Reader, src fs.ObjectInfo, options .
|
||||
|
||||
// PutStream uploads to the remote path with the modTime given of indeterminate size
|
||||
func (f *Fs) PutStream(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) (fs.Object, error) {
|
||||
return f.Put(ctx, in, src, options...)
|
||||
return f.Put(ctx, bufio.NewReader(in), src, options...)
|
||||
}
|
||||
|
||||
// Mkdir creates the bucket if it doesn't exist
|
||||
|
||||
@@ -3,11 +3,16 @@
|
||||
package oracleobjectstorage
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
@@ -15,6 +20,7 @@ import (
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/fstest/fstests"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/rclone/rclone/lib/readers"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -31,6 +37,51 @@ func TestIntegration(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestIsZeroLength(t *testing.T) {
|
||||
newFile := func(contents string) *os.File {
|
||||
file, err := os.CreateTemp(t.TempDir(), "stream")
|
||||
require.NoError(t, err)
|
||||
_, err = file.WriteString(contents)
|
||||
require.NoError(t, err)
|
||||
_, err = file.Seek(0, io.SeekStart)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = file.Close() })
|
||||
return file
|
||||
}
|
||||
closedFile := newFile("")
|
||||
require.NoError(t, closedFile.Close())
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
in io.Reader
|
||||
want bool
|
||||
wantContents string
|
||||
}{
|
||||
{name: "EmptyBuffer", in: bytes.NewBuffer(nil), want: true},
|
||||
{name: "NonEmptyBuffer", in: bytes.NewBufferString("contents"), want: false},
|
||||
{name: "EmptyBytesReader", in: bytes.NewReader(nil), want: true},
|
||||
{name: "NonEmptyBytesReader", in: bytes.NewReader([]byte("contents")), want: false},
|
||||
{name: "EmptyStringsReader", in: strings.NewReader(""), want: true},
|
||||
{name: "NonEmptyStringsReader", in: strings.NewReader("contents"), want: false},
|
||||
{name: "EmptyBufferedStream", in: bufio.NewReader(io.TeeReader(bytes.NewReader(nil), io.Discard)), want: true},
|
||||
{name: "NonEmptyBufferedStream", in: bufio.NewReader(io.TeeReader(bytes.NewBufferString("contents"), io.Discard)), want: false, wantContents: "contents"},
|
||||
{name: "BufferedStreamError", in: bufio.NewReader(readers.ErrorReader{Err: errors.New("stream error")}), want: false},
|
||||
{name: "EmptyFile", in: newFile(""), want: true},
|
||||
{name: "NonEmptyFile", in: newFile("contents"), want: false},
|
||||
{name: "ClosedFile", in: closedFile, want: false},
|
||||
{name: "OpaqueEmptyStream", in: io.TeeReader(bytes.NewReader(nil), io.Discard), want: false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
assert.Equal(t, test.want, isZeroLength(test.in))
|
||||
if test.wantContents != "" {
|
||||
contents, err := io.ReadAll(test.in)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.wantContents, string(contents))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func gz(t *testing.T, s string) string {
|
||||
var buf bytes.Buffer
|
||||
zw := gzip.NewWriter(&buf)
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -56,6 +57,10 @@ var (
|
||||
ClientSecret: obscure.MustReveal(rcloneEncryptedClientSecret),
|
||||
RedirectURL: oauthutil.RedirectLocalhostURL,
|
||||
}
|
||||
|
||||
// hostnameRe matches a lower case API hostname within pCloud's
|
||||
// domain, eg api.pcloud.com or eapi.pcloud.com
|
||||
hostnameRe = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+pcloud\.com$`)
|
||||
)
|
||||
|
||||
// Update the TokenURL with the actual hostname
|
||||
@@ -63,6 +68,19 @@ func updateTokenURL(oauthConfig *oauthutil.Config, hostname string) {
|
||||
oauthConfig.TokenURL = "https://" + hostname + "/oauth2_token"
|
||||
}
|
||||
|
||||
// callbackHostname checks and returns the API hostname pCloud sent back in the
|
||||
// OAuth callback, lower cased, or defaultHostname if it sent none.
|
||||
func callbackHostname(hostname string) (string, error) {
|
||||
if hostname == "" {
|
||||
return defaultHostname, nil
|
||||
}
|
||||
hostname = strings.ToLower(hostname)
|
||||
if !hostnameRe.MatchString(hostname) {
|
||||
return "", fmt.Errorf("invalid hostname %q in oauth response", hostname)
|
||||
}
|
||||
return hostname, nil
|
||||
}
|
||||
|
||||
// Register with Fs
|
||||
func init() {
|
||||
updateTokenURL(oauthConfig, defaultHostname)
|
||||
@@ -81,9 +99,9 @@ func init() {
|
||||
if auth == nil || auth.Form == nil {
|
||||
return errors.New("form not found in response")
|
||||
}
|
||||
hostname := auth.Form.Get("hostname")
|
||||
if hostname == "" {
|
||||
hostname = defaultHostname
|
||||
hostname, err := callbackHostname(auth.Form.Get("hostname"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Save the hostname in the config
|
||||
m.Set("hostname", hostname)
|
||||
@@ -95,7 +113,6 @@ func init() {
|
||||
return oauthutil.ConfigOut("", &oauthutil.Options{
|
||||
OAuth2Config: oauthConfig,
|
||||
CheckAuth: checkAuth,
|
||||
StateBlankOK: true, // pCloud seems to drop the state parameter now - see #4210
|
||||
})
|
||||
},
|
||||
Options: append(oauthutil.SharedOptions, []fs.Option{{
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package pcloud
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// TestCallbackHostname checks that only hosts within pCloud's domain
|
||||
// are accepted.
|
||||
func TestCallbackHostname(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
in string
|
||||
want string // "" means an error is expected
|
||||
}{
|
||||
{"", defaultHostname},
|
||||
{"api.pcloud.com", "api.pcloud.com"},
|
||||
{"eapi.pcloud.com", "eapi.pcloud.com"},
|
||||
{"EAPI.pCloud.COM", "eapi.pcloud.com"},
|
||||
{"new-region.api.pcloud.com", "new-region.api.pcloud.com"},
|
||||
{"pcloud.com", ""},
|
||||
{".pcloud.com", ""},
|
||||
{"-.pcloud.com", ""},
|
||||
{"a-.pcloud.com", ""},
|
||||
{"a..pcloud.com", ""},
|
||||
{"api.pcloud.com.", ""},
|
||||
{"api.pclоud.com", ""}, // Cyrillic о
|
||||
{"127.0.0.1:18443", ""},
|
||||
{"evil.example.com", ""},
|
||||
{"api.pcloud.com.evil.example.com", ""},
|
||||
{"api.pcloud.com:443", ""},
|
||||
{"api.pcloud.com/path", ""},
|
||||
{"user@evil.example.com#.pcloud.com", ""},
|
||||
{"evil.example.com?.pcloud.com", ""},
|
||||
} {
|
||||
t.Run("["+test.in+"]", func(t *testing.T) {
|
||||
got, err := callbackHostname(test.in)
|
||||
if test.want == "" {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
assert.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@ func (f *Fs) put(
|
||||
// exist yet
|
||||
params.Set("make_parents", "true")
|
||||
|
||||
return node, f.pacer.Call(func() (bool, error) {
|
||||
return node, f.pacer.CallNoRetry(func() (bool, error) {
|
||||
resp, err := f.srv.CallJSON(
|
||||
ctx,
|
||||
&rest.Opts{
|
||||
|
||||
@@ -993,6 +993,13 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
}()
|
||||
}
|
||||
|
||||
// The upload server truncates the file name at the first ";" so
|
||||
// upload under a temporary name and rename it afterwards.
|
||||
uploadLeaf := leaf
|
||||
if strings.Contains(leaf, ";") {
|
||||
uploadLeaf = "rclone-upload-" + random.String(16)
|
||||
}
|
||||
|
||||
opts = rest.Opts{
|
||||
Method: "POST",
|
||||
RootURL: info.URL,
|
||||
@@ -1000,8 +1007,8 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
MultipartParams: url.Values{
|
||||
"token": {info.Token},
|
||||
},
|
||||
MultipartContentName: "file", // ..name of the parameter which is the attached file
|
||||
MultipartFileName: leaf, // ..name of the file for the attached file
|
||||
MultipartContentName: "file", // ..name of the parameter which is the attached file
|
||||
MultipartFileName: uploadLeaf, // ..name of the file for the attached file
|
||||
ContentLength: &size,
|
||||
}
|
||||
var result api.Response
|
||||
@@ -1016,6 +1023,29 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
return fmt.Errorf("upload file: %w", err)
|
||||
}
|
||||
|
||||
if uploadLeaf != leaf {
|
||||
var newID string
|
||||
var found bool
|
||||
_, found, err = o.fs.listAll(ctx, directoryID, false, true, func(item *api.Item) bool {
|
||||
if item.Name == uploadLeaf {
|
||||
newID = item.ID
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("upload find temporary file: %w", err)
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("upload find temporary file %q: %w", uploadLeaf, fs.ErrorObjectNotFound)
|
||||
}
|
||||
err = o.fs.renameLeaf(ctx, true, newID, leaf)
|
||||
if err != nil {
|
||||
_ = o.fs.remove(ctx, newID)
|
||||
return fmt.Errorf("upload rename temporary file: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// on successful upload, remove old file if it exists
|
||||
uploaded = true
|
||||
if o.hasMetaData {
|
||||
|
||||
@@ -19,3 +19,7 @@ quirks:
|
||||
force_path_style: true
|
||||
list_url_encode: false
|
||||
use_already_exists: false
|
||||
# Ceph RGW (and reverse proxies such as Cloudflare in front of it) can
|
||||
# mutate Accept-Encoding and break SigV4 when that header is signed.
|
||||
# See: https://github.com/rclone/rclone/issues/8206
|
||||
sign_accept_encoding: false
|
||||
@@ -24,3 +24,8 @@ endpoint:
|
||||
us-iad-10.linodeobjects.com: Washington, DC, US (us-iad-10)
|
||||
acl: {}
|
||||
bucket_acl: true
|
||||
quirks:
|
||||
# Linode Object Storage is Ceph-backed; signing Accept-Encoding causes
|
||||
# SignatureDoesNotMatch with rclone 1.68+. Match the Ceph quirk.
|
||||
# See: https://github.com/rclone/rclone/issues/8206
|
||||
sign_accept_encoding: false
|
||||
+41
-36
@@ -1357,10 +1357,10 @@ func getClient(ctx context.Context, opt *Options) *http.Client {
|
||||
}
|
||||
|
||||
// s3RedirectSecretHeaders are the request headers carrying origin-bound
|
||||
// secrets that must not be forwarded when a redirect crosses a host or
|
||||
// downgrades the scheme. Go strips Authorization on a hostname change but not
|
||||
// on a scheme downgrade, and has no knowledge that the SSE-C headers hold raw
|
||||
// encryption keys, so we strip them all ourselves.
|
||||
// secrets that must not be forwarded when a redirect leaves the original
|
||||
// host. Go strips Authorization on a hostname change but keeps it for a
|
||||
// subdomain or a different port, and has no knowledge that the SSE-C
|
||||
// headers hold raw encryption keys, so we strip them all ourselves.
|
||||
var s3RedirectSecretHeaders = []string{
|
||||
"X-Amz-Security-Token", // AWS STS session token
|
||||
"X-Amz-S3session-Token", // S3 Express (directory bucket) session token
|
||||
@@ -1375,36 +1375,10 @@ var s3RedirectSecretHeaders = []string{
|
||||
"Referer", // may be a presigned request
|
||||
}
|
||||
|
||||
func s3CheckRedirect(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
// Never follow a redirect that downgrades the transport from HTTPS to
|
||||
// HTTP. An S3 endpoint has no legitimate reason to do this, and replaying
|
||||
// the request over plaintext would expose whatever credential it carries.
|
||||
if via[len(via)-1].URL.Scheme == "https" && req.URL.Scheme == "http" {
|
||||
return fmt.Errorf("refusing to follow insecure redirect from HTTPS to HTTP: %s", req.URL.Redacted())
|
||||
}
|
||||
if s3RedirectCrossesHost(req, via) {
|
||||
for _, header := range s3RedirectSecretHeaders {
|
||||
req.Header.Del(header)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func s3RedirectCrossesHost(req *http.Request, via []*http.Request) bool {
|
||||
if len(via) == 0 {
|
||||
return false
|
||||
}
|
||||
scheme, host := via[0].URL.Scheme, via[0].URL.Host
|
||||
for _, redirect := range via[1:] {
|
||||
if redirect.URL.Host != host || redirect.URL.Scheme != scheme {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return host != req.URL.Host || scheme != req.URL.Scheme
|
||||
}
|
||||
// s3CheckRedirect is the http.Client CheckRedirect policy for S3. It
|
||||
// refuses HTTPS to HTTP downgrades and strips s3RedirectSecretHeaders
|
||||
// once a redirect has left the original host.
|
||||
var s3CheckRedirect = rest.StripHeadersOnCrossHostRedirectFn(s3RedirectSecretHeaders...)
|
||||
|
||||
// Fixup the request if needed.
|
||||
//
|
||||
@@ -2317,7 +2291,31 @@ func versionLess(a, b *types.ObjectVersion) bool {
|
||||
// types.ObjectVersion with Size = isDeleteMarker to tell them apart
|
||||
//
|
||||
// We then merge them back into the Versions in the correct order
|
||||
func mergeDeleteMarkers(oldVersions []types.ObjectVersion, deleteMarkers []types.DeleteMarkerEntry) (newVersions []types.ObjectVersion) {
|
||||
func mergeDeleteMarkers(oldVersions []types.ObjectVersion, deleteMarkers []types.DeleteMarkerEntry, urlEncoded bool) (newVersions []types.ObjectVersion) {
|
||||
encodedKeys := make(map[string]string)
|
||||
if urlEncoded {
|
||||
// URL encoding can change key order, so compare decoded keys and restore the encoded keys for the caller.
|
||||
oldVersions = append([]types.ObjectVersion(nil), oldVersions...)
|
||||
deleteMarkers = append([]types.DeleteMarkerEntry(nil), deleteMarkers...)
|
||||
decodeKey := func(key **string) {
|
||||
if *key == nil {
|
||||
return
|
||||
}
|
||||
encodedKey := **key
|
||||
decodedKey, err := url.QueryUnescape(encodedKey)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
encodedKeys[decodedKey] = encodedKey
|
||||
*key = &decodedKey
|
||||
}
|
||||
for i := range oldVersions {
|
||||
decodeKey(&oldVersions[i].Key)
|
||||
}
|
||||
for i := range deleteMarkers {
|
||||
decodeKey(&deleteMarkers[i].Key)
|
||||
}
|
||||
}
|
||||
newVersions = make([]types.ObjectVersion, 0, len(oldVersions)+len(deleteMarkers))
|
||||
for _, deleteMarker := range deleteMarkers {
|
||||
var obj types.ObjectVersion
|
||||
@@ -2332,6 +2330,11 @@ func mergeDeleteMarkers(oldVersions []types.ObjectVersion, deleteMarkers []types
|
||||
}
|
||||
// Merge any remaining versions
|
||||
newVersions = append(newVersions, oldVersions...)
|
||||
for i := range newVersions {
|
||||
if encodedKey, ok := encodedKeys[deref(newVersions[i].Key)]; ok {
|
||||
newVersions[i].Key = &encodedKey
|
||||
}
|
||||
}
|
||||
return newVersions
|
||||
}
|
||||
|
||||
@@ -2371,7 +2374,7 @@ func (ls *versionsList) List(ctx context.Context) (resp *s3.ListObjectsV2Output,
|
||||
|
||||
// Merge in delete Markers as types.ObjectVersion if we need them
|
||||
if ls.hidden || ls.usingVersionAt {
|
||||
respVersions.Versions = mergeDeleteMarkers(respVersions.Versions, respVersions.DeleteMarkers)
|
||||
respVersions.Versions = mergeDeleteMarkers(respVersions.Versions, respVersions.DeleteMarkers, ls.req.EncodingType == types.EncodingTypeUrl)
|
||||
}
|
||||
|
||||
// Convert the Versions and the DeleteMarkers into an array of types.Object
|
||||
@@ -2398,6 +2401,8 @@ func (ls *versionsList) List(ctx context.Context) (resp *s3.ListObjectsV2Output,
|
||||
var obj types.Object
|
||||
//structs.SetFrom(obj, objVersion)
|
||||
setFrom_typesObject_typesObjectVersion(&obj, &objVersion)
|
||||
// StorageClass has a different type in ObjectVersion so isn't copied by setFrom
|
||||
obj.StorageClass = types.ObjectStorageClass(objVersion.StorageClass)
|
||||
// Adjust the file names
|
||||
if !ls.usingVersionAt && (!deref(objVersion.IsLatest) || objVersion.Size == isDeleteMarker) {
|
||||
if obj.Key != nil && objVersion.LastModified != nil {
|
||||
|
||||
@@ -7,6 +7,9 @@ import (
|
||||
"crypto/md5"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -302,11 +305,64 @@ func TestMergeDeleteMarkers(t *testing.T) {
|
||||
},
|
||||
},
|
||||
} {
|
||||
got := mergeDeleteMarkers(test.versions, test.markers)
|
||||
got := mergeDeleteMarkers(test.versions, test.markers, false)
|
||||
assert.Equal(t, test.want, got, fmt.Sprintf("%d: %+v", n, test))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeDeleteMarkersWithURLEncodedKeys(t *testing.T) {
|
||||
plainKey := "images/reservations/photo.png"
|
||||
encodedKey := "images/%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82-01.jpg"
|
||||
t1 := fstest.Time("2022-01-21T12:00:00+01:00")
|
||||
t2 := fstest.Time("2022-01-21T12:00:01+01:00")
|
||||
versions := []types.ObjectVersion{
|
||||
{Key: &plainKey, LastModified: &t2},
|
||||
{Key: &encodedKey, LastModified: &t1},
|
||||
}
|
||||
markers := []types.DeleteMarkerEntry{
|
||||
{Key: &encodedKey, LastModified: &t2},
|
||||
}
|
||||
|
||||
got := mergeDeleteMarkers(versions, markers, true)
|
||||
want := []types.ObjectVersion{
|
||||
{Key: &plainKey, LastModified: &t2},
|
||||
{Key: &encodedKey, LastModified: &t2, Size: isDeleteMarker},
|
||||
{Key: &encodedKey, LastModified: &t1},
|
||||
}
|
||||
assert.Equal(t, want, got)
|
||||
}
|
||||
|
||||
func TestVersionsListStorageClass(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, `<ListVersionsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
|
||||
<Name>bucket</Name>
|
||||
<IsTruncated>false</IsTruncated>
|
||||
<Version>
|
||||
<Key>archived.bin</Key>
|
||||
<VersionId>v1</VersionId>
|
||||
<IsLatest>true</IsLatest>
|
||||
<LastModified>2026-09-26T12:00:00.000Z</LastModified>
|
||||
<ETag>"d41d8cd98f00b204e9800998ecf8427e"</ETag>
|
||||
<Size>0</Size>
|
||||
<StorageClass>DEEP_ARCHIVE</StorageClass>
|
||||
</Version>
|
||||
</ListVersionsResult>`)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
f := &Fs{c: s3.New(s3.Options{
|
||||
Region: "us-east-1",
|
||||
BaseEndpoint: aws.String(srv.URL),
|
||||
UsePathStyle: true,
|
||||
Credentials: aws.AnonymousCredentials{},
|
||||
})}
|
||||
ls := f.newVersionsList(&s3.ListObjectsV2Input{Bucket: aws.String("bucket")}, false, time.Time{})
|
||||
resp, _, err := ls.List(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Len(t, resp.Contents, 1)
|
||||
assert.Equal(t, types.ObjectStorageClassDeepArchive, resp.Contents[0].StorageClass)
|
||||
}
|
||||
|
||||
func TestRemoveAWSChunked(t *testing.T) {
|
||||
ps := func(s string) *string {
|
||||
return &s
|
||||
|
||||
@@ -228,54 +228,6 @@ func TestS3CheckRedirectRejectsSchemeDowngrade(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectCrossesHost(t *testing.T) {
|
||||
mustReq := func(method, url string) *http.Request {
|
||||
req, err := http.NewRequest(method, url, nil)
|
||||
require.NoError(t, err)
|
||||
return req
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
via []string
|
||||
req string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "SameHost",
|
||||
via: []string{"https://bucket.example.com/"},
|
||||
req: "https://bucket.example.com/redirected",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "DifferentHost",
|
||||
via: []string{"https://bucket.example.com/"},
|
||||
req: "https://evil.example.com/redirected",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "SchemeDowngradeSameHost",
|
||||
via: []string{"https://bucket.example.com/"},
|
||||
req: "http://bucket.example.com/redirected",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "SchemeDowngradeMidChain",
|
||||
via: []string{"https://bucket.example.com/", "http://bucket.example.com/middle"},
|
||||
req: "http://bucket.example.com/final",
|
||||
want: true,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
via := make([]*http.Request, len(test.via))
|
||||
for i, url := range test.via {
|
||||
via[i] = mustReq(http.MethodGet, url)
|
||||
}
|
||||
got := s3RedirectCrossesHost(mustReq(http.MethodGet, test.req), via)
|
||||
assert.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientStopsAfterTenRedirects(t *testing.T) {
|
||||
_, _, client := SetupS3Test(t)
|
||||
|
||||
|
||||
+15
-21
@@ -88,28 +88,22 @@ func (o *Object) Open(ctx context.Context, options ...fs.OpenOption) (io.ReadClo
|
||||
// But for unknown-sized objects (indicated by src.Size() == -1), Upload should either
|
||||
// return an error or update the object properly (rather than e.g. calling panic).
|
||||
func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, options ...fs.OpenOption) error {
|
||||
// The upload sometimes return a temporary 500 error
|
||||
// We cannot use the pacer to retry uploading the file as the upload link is single use only
|
||||
for retry := 0; retry <= 3; retry++ {
|
||||
uploadLink, err := o.fs.getUploadLink(ctx, o.libraryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
|
||||
if err == ErrorInternalDuringUpload {
|
||||
// This is a temporary error, try again with a new upload link
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set the properties from the upload back to the object
|
||||
o.size = uploaded.Size
|
||||
|
||||
return nil
|
||||
uploadLink, err := o.fs.getUploadLink(ctx, o.libraryID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrorInternalDuringUpload
|
||||
|
||||
// The upload can't be retried here as the input stream can't be re-read and
|
||||
// the upload link is single use, so upload returns a retry
|
||||
// error for the caller to retry with a fresh stream.
|
||||
uploaded, err := o.fs.upload(ctx, in, uploadLink, o.pathInLibrary)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set the properties from the upload back to the object
|
||||
o.size = uploaded.Size
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Remove this object
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/rclone/rclone/backend/seafile/api"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/fserrors"
|
||||
"github.com/rclone/rclone/lib/readers"
|
||||
"github.com/rclone/rclone/lib/rest"
|
||||
)
|
||||
@@ -721,8 +722,8 @@ func (f *Fs) upload(ctx context.Context, in io.Reader, uploadLink, filePath stri
|
||||
return nil, fs.ErrorPermissionDenied
|
||||
}
|
||||
if resp.StatusCode == 500 {
|
||||
// This is a temporary error - we will get a new upload link before retrying
|
||||
return nil, ErrorInternalDuringUpload
|
||||
// This is a temporary error - the caller will get a new upload link when it retries
|
||||
return nil, fserrors.RetryError(ErrorInternalDuringUpload)
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("failed to upload file: %w", err)
|
||||
|
||||
@@ -2791,6 +2791,8 @@ func (o *Object) Update(ctx context.Context, in io.Reader, src fs.ObjectInfo, op
|
||||
}
|
||||
_, err = file.ReadFrom(&sizeReader{Reader: in, size: src.Size()})
|
||||
if err != nil {
|
||||
// Close the handle otherwise the server keeps the removed file's space allocated
|
||||
_ = file.Close()
|
||||
o.fs.putSftpConnection(&c, err)
|
||||
remove()
|
||||
return fmt.Errorf("Update ReadFrom failed: %w", err)
|
||||
|
||||
@@ -380,9 +380,11 @@ func (f *Fs) DirMove(ctx context.Context, src fs.Fs, srcRemote, dstRemote string
|
||||
//Need to check if destination exists
|
||||
fullPath := f.buildFullPath(dstRemote)
|
||||
var response api.ListDirResponse
|
||||
res, _ := f.callAPI(ctx, "GET", fmt.Sprintf("/%s/fs/attr?path=%s", f.drive, fullPath), &response)
|
||||
|
||||
if res.StatusCode != http.StatusNotFound {
|
||||
res, err := f.callAPI(ctx, "GET", fmt.Sprintf("/%s/fs/attr?path=%s", f.drive, fullPath), &response)
|
||||
if res == nil || res.StatusCode != http.StatusNotFound {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check destination directory: %w", err)
|
||||
}
|
||||
return fs.ErrorDirExists
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -49,8 +49,7 @@ func init() {
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "user",
|
||||
Help: "SMB username.",
|
||||
Default: currentUser,
|
||||
Help: "SMB username.\n\nLeave blank to use the current user name.",
|
||||
Sensitive: true,
|
||||
}, {
|
||||
Name: "port",
|
||||
@@ -191,6 +190,9 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if opt.User == "" {
|
||||
opt.User = currentUser
|
||||
}
|
||||
|
||||
// if root is empty or ends with / (must be a directory)
|
||||
isRootDir := isPathDir(root)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configmap"
|
||||
"github.com/rclone/rclone/fs/object"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -129,3 +130,33 @@ func TestIsPathDir(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFsUser(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, test := range []struct {
|
||||
user string
|
||||
want string
|
||||
}{
|
||||
{user: "", want: currentUser},
|
||||
{user: currentUser, want: currentUser},
|
||||
{user: "someone", want: "someone"},
|
||||
} {
|
||||
m := configmap.Simple{"host": "localhost", "user": test.user}
|
||||
f, err := NewFs(ctx, "TestSMB", "", m)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, f.(*Fs).opt.User, "user=%q", test.user)
|
||||
}
|
||||
|
||||
// No user in the config at all
|
||||
f, err := NewFs(ctx, "TestSMB", "", configmap.Simple{"host": "localhost"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, currentUser, f.(*Fs).opt.User)
|
||||
}
|
||||
|
||||
// The default is blank so that a user name which happens to match the
|
||||
// current user is still written to the config file.
|
||||
func TestUserDefault(t *testing.T) {
|
||||
ri, err := fs.Find("smb")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", ri.Options.Get("user").Default)
|
||||
}
|
||||
@@ -135,6 +135,13 @@ The input format is comma separated list of key,value pairs. Standard
|
||||
For example, to set a Cookie use 'Cookie,name=value', or '"Cookie","name=value"'.
|
||||
|
||||
You can set multiple headers, e.g. '"Cookie","name=value","Authorization","xxx"'.
|
||||
|
||||
The headers are only sent to the host in the configured URL. If the
|
||||
server redirects to another host (including a subdomain or a different
|
||||
port) the headers are not sent to it, or to any further hop in that
|
||||
redirect chain. The exception is the directory listing and file
|
||||
download requests when auth_redirect is set, as that keeps all
|
||||
credentials across redirects.
|
||||
`,
|
||||
Default: fs.CommaSepList{},
|
||||
Advanced: true,
|
||||
@@ -235,6 +242,8 @@ type Fs struct {
|
||||
canChunk bool // set if nextcloud and nextcloud_chunk_size is set
|
||||
canRecalcHash bool // set if the server can recalculate checksums with PATCH (nextcloud)
|
||||
authSingleflight *singleflight.Group
|
||||
// redirect policy which keeps opt.Headers on the configured host
|
||||
checkRedirect func(req *http.Request, via []*http.Request) error
|
||||
}
|
||||
|
||||
// Object describes a webdav object
|
||||
@@ -345,6 +354,41 @@ func itemIsDir(item *api.Response) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// sabreNotFound is the exception SabreDAV based servers report for a
|
||||
// path which doesn't exist
|
||||
var sabreNotFound = []byte(`Sabre\DAV\Exception\NotFound`)
|
||||
|
||||
// callPropfind does the PROPFIND in opts and decodes the response into result
|
||||
//
|
||||
// ownCloud 10.16 starts a 207 Multi-Status response before it finds
|
||||
// that the path doesn't exist, then appends a Sabre NotFound error to
|
||||
// it which makes it invalid XML. This is returned as the 404 *api.Error
|
||||
// which servers normally give for a path which doesn't exist.
|
||||
func (f *Fs) callPropfind(ctx context.Context, opts *rest.Opts, result *api.Multistatus) (resp *http.Response, err error) {
|
||||
resp, err = f.srv.Call(ctx, opts)
|
||||
if err != nil {
|
||||
return resp, err
|
||||
}
|
||||
// Keep the start of the body to look for the error in
|
||||
start := make([]byte, 4096)
|
||||
n, _ := io.ReadFull(resp.Body, start)
|
||||
start = start[:n]
|
||||
body := resp.Body
|
||||
resp.Body = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{io.MultiReader(bytes.NewReader(start), body), body}
|
||||
err = rest.DecodeXML(resp, result)
|
||||
if err != nil && bytes.Contains(start, sabreNotFound) {
|
||||
return resp, &api.Error{
|
||||
Exception: string(sabreNotFound),
|
||||
Status: http.StatusText(http.StatusNotFound),
|
||||
StatusCode: http.StatusNotFound,
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// readMetaDataForPath reads the metadata from the path
|
||||
func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Prop, err error) {
|
||||
// FIXME how do we read back additional properties?
|
||||
@@ -354,7 +398,7 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Pr
|
||||
ExtraHeaders: map[string]string{
|
||||
"Depth": "0",
|
||||
},
|
||||
CheckRedirect: rest.PreserveMethodRedirectFn,
|
||||
CheckRedirect: f.preserveMethodRedirect,
|
||||
}
|
||||
if f.hasOCMD5 || f.hasOCSHA1 {
|
||||
opts.Body = bytes.NewBuffer(owncloudProps)
|
||||
@@ -365,7 +409,11 @@ func (f *Fs) readMetaDataForPath(ctx context.Context, path string) (info *api.Pr
|
||||
var result api.Multistatus
|
||||
var resp *http.Response
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
resp, err = f.srv.CallXML(ctx, &opts, nil, &result)
|
||||
var attempt api.Multistatus
|
||||
resp, err = f.callPropfind(ctx, &opts, &attempt)
|
||||
if err == nil {
|
||||
result = attempt
|
||||
}
|
||||
return f.shouldRetry(ctx, resp, err)
|
||||
})
|
||||
if apiErr, ok := err.(*api.Error); ok {
|
||||
@@ -516,8 +564,17 @@ func NewFs(ctx context.Context, name, root string, m configmap.Mapper) (fs.Fs, e
|
||||
rt: ntlmssp.Negotiator{RoundTripper: t},
|
||||
}
|
||||
}
|
||||
// Refuse redirects that downgrade HTTPS to plaintext HTTP.
|
||||
client.CheckRedirect = rest.RefuseHTTPSDowngradeRedirectFn
|
||||
// Refuse redirects that downgrade HTTPS to plaintext HTTP and
|
||||
// don't send the configured headers to another host.
|
||||
//
|
||||
// The auth_redirect option bypasses this for the requests it applies
|
||||
// to as it is an explicit opt-in to keep credentials across redirects.
|
||||
headerNames := make([]string, 0, len(opt.Headers)/2)
|
||||
for i := 0; i < len(opt.Headers); i += 2 {
|
||||
headerNames = append(headerNames, opt.Headers[i])
|
||||
}
|
||||
f.checkRedirect = rest.StripHeadersOnCrossHostRedirectFn(headerNames...)
|
||||
client.CheckRedirect = f.checkRedirect
|
||||
f.srv = rest.NewClient(client).SetRoot(u.String())
|
||||
|
||||
f.features = (&fs.Features{
|
||||
@@ -596,6 +653,16 @@ func (f *Fs) fetchBearerToken(cmd fs.SpaceSepList) (string, error) {
|
||||
return stdoutString, nil
|
||||
}
|
||||
|
||||
// preserveMethodRedirect is an http.Client.CheckRedirect function
|
||||
// which applies f.checkRedirect and then preserves the original HTTP
|
||||
// method like rest.PreserveMethodRedirectFn.
|
||||
func (f *Fs) preserveMethodRedirect(req *http.Request, via []*http.Request) error {
|
||||
if err := f.checkRedirect(req, via); err != nil {
|
||||
return err
|
||||
}
|
||||
return rest.PreserveMethodRedirectFn(req, via)
|
||||
}
|
||||
|
||||
// Adds the configured headers to the request if any
|
||||
func (f *Fs) addHeaders(headers fs.CommaSepList) {
|
||||
for i := 0; i < len(headers); i += 2 {
|
||||
@@ -815,7 +882,11 @@ func (f *Fs) listAll(ctx context.Context, dir string, directoriesOnly bool, file
|
||||
var result api.Multistatus
|
||||
var resp *http.Response
|
||||
err = f.pacer.Call(func() (bool, error) {
|
||||
resp, err = f.srv.CallXML(ctx, &opts, nil, &result)
|
||||
var attempt api.Multistatus
|
||||
resp, err = f.callPropfind(ctx, &opts, &attempt)
|
||||
if err == nil {
|
||||
result = attempt
|
||||
}
|
||||
return f.shouldRetry(ctx, resp, err)
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -3,9 +3,12 @@ package webdav_test
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/backend/webdav"
|
||||
@@ -120,6 +123,114 @@ func TestListAllAuthRedirect(t *testing.T) {
|
||||
assert.NotEmpty(t, targetAuth, "Authorization header should be preserved across redirect")
|
||||
}
|
||||
|
||||
// fileInfoResponse is a PROPFIND response describing a single file.
|
||||
const fileInfoResponse = `<d:multistatus xmlns:d="DAV:">
|
||||
<d:response>
|
||||
<d:href>/file.txt</d:href>
|
||||
<d:propstat>
|
||||
<d:prop>
|
||||
<d:getcontentlength>10</d:getcontentlength>
|
||||
<d:resourcetype/>
|
||||
</d:prop>
|
||||
<d:status>HTTP/1.1 200 OK</d:status>
|
||||
</d:propstat>
|
||||
</d:response>
|
||||
</d:multistatus>`
|
||||
|
||||
// redirectTestHeaders are the headers option for the redirect tests.
|
||||
// The one starting with "*" is sent without canonicalising.
|
||||
var redirectTestHeaders = []string{"X-Potato", "sausage", "*x-marrow", "pea"}
|
||||
|
||||
// redirectHeaders makes a webdav remote with redirectTestHeaders
|
||||
// pointing at a server which redirects every request to a second
|
||||
// server on hostname, or back to itself if hostname is empty, and
|
||||
// exercises each of the backend's redirect policies against it: the
|
||||
// PROPFIND used to look up an object, the GET used to read it and the
|
||||
// PROPFIND used to list a directory. It returns the headers the
|
||||
// redirect target saw on each of those requests.
|
||||
func redirectHeaders(t *testing.T, hostname string) []http.Header {
|
||||
var target string
|
||||
var mu sync.Mutex
|
||||
var seen []http.Header
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(r.URL.Path, "/moved/") {
|
||||
http.Redirect(w, r, target+"/moved"+r.URL.Path, http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
seen = append(seen, r.Header.Clone())
|
||||
mu.Unlock()
|
||||
switch r.Method {
|
||||
case "PROPFIND":
|
||||
w.WriteHeader(http.StatusMultiStatus)
|
||||
_, err := fmt.Fprint(w, fileInfoResponse)
|
||||
assert.NoError(t, err)
|
||||
case http.MethodGet:
|
||||
_, err := fmt.Fprint(w, "hello")
|
||||
assert.NoError(t, err)
|
||||
default:
|
||||
http.Error(w, "unexpected method", http.StatusMethodNotAllowed)
|
||||
}
|
||||
})
|
||||
ts := httptest.NewServer(handler)
|
||||
defer ts.Close()
|
||||
if hostname == "" {
|
||||
target = ts.URL
|
||||
} else {
|
||||
// Serve the final response from a second server on a different host
|
||||
other := httptest.NewServer(handler)
|
||||
defer other.Close()
|
||||
target = strings.Replace(other.URL, "127.0.0.1", hostname, 1)
|
||||
}
|
||||
|
||||
configfile.Install()
|
||||
m := configmap.Simple{
|
||||
"type": "webdav",
|
||||
"url": ts.URL,
|
||||
"headers": strings.Join(redirectTestHeaders, ","),
|
||||
}
|
||||
ctx := context.Background()
|
||||
f, err := webdav.NewFs(ctx, remoteName, "", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
// PROPFIND with Depth 0 uses rest.PreserveMethodRedirectFn
|
||||
o, err := f.NewObject(ctx, "file.txt")
|
||||
require.NoError(t, err)
|
||||
// GET uses the client's default redirect policy
|
||||
fd, err := o.Open(ctx)
|
||||
require.NoError(t, err)
|
||||
data, err := io.ReadAll(fd)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, fd.Close())
|
||||
assert.Equal(t, "hello", string(data))
|
||||
// PROPFIND with Depth 1 uses the client's default redirect policy
|
||||
_, err = f.List(ctx, "")
|
||||
require.NoError(t, err)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
require.Len(t, seen, 3, "expected the redirect target to see all three requests")
|
||||
return seen
|
||||
}
|
||||
|
||||
func TestRedirectKeepsHeadersOnSameHost(t *testing.T) {
|
||||
for _, got := range redirectHeaders(t, "") {
|
||||
for i := 0; i < len(redirectTestHeaders); i += 2 {
|
||||
assert.Equal(t, redirectTestHeaders[i+1], got.Get(strings.TrimPrefix(redirectTestHeaders[i], "*")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectStripsHeadersOnHostChange(t *testing.T) {
|
||||
// Redirect to a different host name and port. net/http strips
|
||||
// Authorization on its own here so this checks the custom headers.
|
||||
for _, got := range redirectHeaders(t, "localhost") {
|
||||
for i := 0; i < len(redirectTestHeaders); i += 2 {
|
||||
assert.Empty(t, got.Values(strings.TrimPrefix(redirectTestHeaders[i], "*")), "header %q leaked to redirect target", redirectTestHeaders[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestReservedCharactersInPathAreEscaped verifies that reserved characters
|
||||
// like semicolons and equals signs in file paths are percent-encoded in
|
||||
// HTTP requests to the WebDAV server (RFC 3986 compliance).
|
||||
@@ -151,3 +262,119 @@ func TestReservedCharactersInPathAreEscaped(t *testing.T) {
|
||||
assert.Contains(t, capturedPath, "my%3Btest", "semicolons in path should be percent-encoded")
|
||||
assert.NotContains(t, capturedPath, "my;test", "raw semicolons should not appear in path")
|
||||
}
|
||||
|
||||
// TestListAllRetryDoesNotConcatenate verifies that when a listing PROPFIND
|
||||
// fails after having partially decoded and is retried, the final listing is
|
||||
// exactly the retried response, with no entries carried over from the
|
||||
// failed attempt.
|
||||
func TestListAllRetryDoesNotConcatenate(t *testing.T) {
|
||||
entryXML := func(i int) string {
|
||||
name := fmt.Sprintf("file-%03d.bin", i)
|
||||
return "<d:response><d:href>/" + name + "</d:href><d:propstat><d:prop>" +
|
||||
"<d:displayname>" + name + "</d:displayname><d:getcontentlength>1024</d:getcontentlength>" +
|
||||
"</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>\n"
|
||||
}
|
||||
head := `<?xml version="1.0" encoding="utf-8"?><d:multistatus xmlns:d="DAV:">`
|
||||
self := head + `<d:response><d:href>/</d:href><d:propstat><d:prop><d:resourcetype><d:collection xmlns:d="DAV:"/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>`
|
||||
writeEntries := func(w http.ResponseWriter, from, to int) {
|
||||
_, err := fmt.Fprint(w, head)
|
||||
require.NoError(t, err)
|
||||
for i := from; i <= to; i++ {
|
||||
_, err := fmt.Fprint(w, entryXML(i))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
var listCalls atomic.Int64
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "PROPFIND", r.Method)
|
||||
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||
if r.Header.Get("Depth") == "0" {
|
||||
w.WriteHeader(207)
|
||||
_, err := fmt.Fprint(w, self)
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
if listCalls.Add(1) == 1 {
|
||||
// return file-000..file-010 but kill the response before it
|
||||
// completes, so the client has parsed those entries when it
|
||||
// hits an unexpected EOF
|
||||
w.Header().Set("Content-Length", "1000000")
|
||||
w.WriteHeader(207)
|
||||
writeEntries(w, 0, 10)
|
||||
return
|
||||
}
|
||||
// return the disjoint file-011..file-030 as a complete listing
|
||||
w.WriteHeader(207)
|
||||
writeEntries(w, 11, 30)
|
||||
_, err := fmt.Fprint(w, "</d:multistatus>")
|
||||
require.NoError(t, err)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
configfile.Install()
|
||||
m := configmap.Simple{
|
||||
"type": "webdav",
|
||||
"url": ts.URL,
|
||||
}
|
||||
f, err := webdav.NewFs(context.Background(), remoteName, "", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
entries, err := f.List(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
var remotes []string
|
||||
for _, e := range entries {
|
||||
remotes = append(remotes, e.Remote())
|
||||
}
|
||||
var want []string
|
||||
for i := 11; i <= 30; i++ {
|
||||
want = append(want, fmt.Sprintf("file-%03d.bin", i))
|
||||
}
|
||||
assert.ElementsMatch(t, want, remotes)
|
||||
}
|
||||
|
||||
// TestNotFoundInMultistatus checks that a missing path is detected when the
|
||||
// server reports it by appending a Sabre NotFound error to a 207 response it
|
||||
// has already started, as ownCloud 10.16 does, rather than by returning 404.
|
||||
func TestNotFoundInMultistatus(t *testing.T) {
|
||||
head := `<?xml version="1.0"?>` + "\n" + `<d:multistatus xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns" xmlns:oc="http://owncloud.org/ns"`
|
||||
root := head + `><d:response><d:href>/</d:href><d:propstat><d:prop><d:resourcetype><d:collection/></d:resourcetype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response></d:multistatus>`
|
||||
notFound := head + `<?xml version="1.0" encoding="utf-8"?>
|
||||
<d:error xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns">
|
||||
<s:exception>Sabre\DAV\Exception\NotFound</s:exception>
|
||||
<s:message>File with name missing could not be located</s:message>
|
||||
</d:error>
|
||||
`
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, "PROPFIND", r.Method)
|
||||
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
|
||||
w.WriteHeader(207)
|
||||
body := notFound
|
||||
if r.URL.Path == "/" {
|
||||
body = root
|
||||
}
|
||||
_, err := fmt.Fprint(w, body)
|
||||
require.NoError(t, err)
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
configfile.Install()
|
||||
m := configmap.Simple{
|
||||
"type": "webdav",
|
||||
"url": ts.URL,
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
// A root which doesn't exist yet
|
||||
_, err := webdav.NewFs(ctx, remoteName, "missing", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
f, err := webdav.NewFs(ctx, remoteName, "", m)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = f.NewObject(ctx, "missing")
|
||||
assert.Equal(t, fs.ErrorObjectNotFound, err)
|
||||
|
||||
_, err = f.List(ctx, "missing")
|
||||
assert.Equal(t, fs.ErrorDirNotFound, err)
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -134,6 +136,47 @@ func testArchiveRemote(t *testing.T, fromLocal bool, subDir string, extension st
|
||||
fstest.CheckListingWithPrecision(t, src, items, nil, fs.ModTimeNotSupported)
|
||||
}
|
||||
|
||||
// test archiving to stdout when no destination is given
|
||||
func TestArchiveStdout(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r := fstest.NewRun(t)
|
||||
|
||||
f1 := r.WriteObject(ctx, "file1.txt", "content 1", t1)
|
||||
f2 := r.WriteObject(ctx, "dir1/sub1.txt", "sub content 1", t1)
|
||||
fstest.CheckItems(t, r.Fremote, f1, f2)
|
||||
|
||||
// redirect stdout into a file on the local fs
|
||||
archiveName := "stdout.zip"
|
||||
require.NoError(t, r.Flocal.Mkdir(ctx, ""))
|
||||
out, err := os.Create(filepath.Join(r.LocalName, archiveName))
|
||||
require.NoError(t, err)
|
||||
oldStdout := os.Stdout
|
||||
os.Stdout = out
|
||||
err = create.ArchiveCreate(ctx, nil, "", r.Fremote, "zip", "")
|
||||
os.Stdout = oldStdout
|
||||
require.NoError(t, out.Close())
|
||||
require.NoError(t, err)
|
||||
|
||||
// check the archive written to stdout is readable
|
||||
expected := map[string]bool{
|
||||
"file1.txt": true,
|
||||
"dir1/": true,
|
||||
"dir1/sub1.txt": true,
|
||||
}
|
||||
listFile := func(ctx context.Context, f archives.FileInfo) error {
|
||||
name := f.NameInArchive
|
||||
if f.IsDir() && !strings.HasSuffix(name, "/") {
|
||||
name += "/"
|
||||
}
|
||||
assert.True(t, expected[name], name)
|
||||
delete(expected, name)
|
||||
return nil
|
||||
}
|
||||
err = list.ArchiveList(ctx, r.Flocal, archiveName, listFile)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 0, len(expected), expected)
|
||||
}
|
||||
|
||||
func testArchive(t *testing.T) {
|
||||
var extensions = []string{
|
||||
"zip",
|
||||
|
||||
@@ -118,7 +118,6 @@ will make an archive with the contents:
|
||||
cmd.CheckArgs(1, 2, command, args)
|
||||
}
|
||||
cmd.Run(false, false, command, func() error {
|
||||
fmt.Printf("dst=%v, dstFile=%q, src=%v, format=%q, prefix=%q\n", dst, dstFile, src, format, prefix)
|
||||
if prefix != "" {
|
||||
return ArchiveCreate(context.Background(), dst, dstFile, src, format, prefix)
|
||||
} else if fullPath {
|
||||
@@ -301,10 +300,12 @@ func ArchiveCreate(ctx context.Context, dst fs.Fs, dstFile string, src fs.Fs, fo
|
||||
var compArchive archives.CompressedArchive
|
||||
var totalLength int64
|
||||
|
||||
// check id dst is valid
|
||||
err = CheckValidDestination(ctx, dst, dstFile)
|
||||
if err != nil {
|
||||
return err
|
||||
// check if dst is valid, nil dst means write to stdout
|
||||
if dst != nil {
|
||||
err = CheckValidDestination(ctx, dst, dstFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ci := fs.GetConfig(ctx)
|
||||
|
||||
@@ -69,7 +69,7 @@ var initDate = time.Date(2000, time.January, 1, 0, 0, 0, 0, bisync.TZ)
|
||||
// go run ./fstest/test_all -remotes local,TestCrypt:,TestDrive:,TestOneDrive:,TestOneDriveBusiness:,TestDropbox:,TestCryptDrive:,TestOpenDrive:,TestChunker:,:memory:,TestCryptNoEncryption:,TestCombine:DirA,TestFTPRclone:,TestWebdavRclone:,TestS3Rclone:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestNextcloud:,TestChunkerNometaLocal:,TestChunkerChunk3bLocal:,TestChunkerLocal:,TestChunkerChunk3bNometaLocal:,TestStorj: -run '^TestBisync.*$' -timeout 3h -verbose -maxtries 5
|
||||
// go test -timeout 3h -run '^TestBisync.*$' github.com/rclone/rclone/cmd/bisync -remote TestDrive:Bisync -v
|
||||
// go test -timeout 3h -run '^TestBisyncRemoteRemote/basic$' github.com/rclone/rclone/cmd/bisync -remote TestDropbox:Bisync -v
|
||||
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3MinioEdge:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSeafileV6:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
|
||||
// TestFTPProftpd:,TestFTPPureftpd:,TestFTPRclone:,TestFTPVsftpd:,TestHdfs:,TestS3Minio:,TestS3Rclone:,TestSeafile:,TestSeafileEncrypted:,TestSeafileV6:,TestSFTPOpenssh:,TestSFTPRclone:,TestSFTPRcloneSSH:,TestSia:,TestSwiftAIO:,TestWebdavNextcloud:,TestWebdavOwncloud:,TestWebdavRclone:
|
||||
|
||||
// logReplacements make modern test logs comparable with golden dir.
|
||||
// It is a string slice of even length with this structure:
|
||||
|
||||
@@ -26785,654 +26785,6 @@
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3Minio:", "-remote2", "TestS3Minio:", "-case", "test_volatile", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_all_changed LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_all_changed", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_all_changed RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_all_changed", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_all_changed RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_all_changed", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_backupdir LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_backupdir", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_backupdir RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_backupdir", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_backupdir RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_backupdir", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_basic LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_basic", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_basic RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_basic", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_basic RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_basic", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_changes LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_changes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_changes RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_changes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_changes RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_changes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_access", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access_filters LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access_filters RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_access_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_access_filters RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_access_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_filename LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_filename", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_filename RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_filename", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_filename RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_filename", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_sync LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_check_sync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_sync RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_check_sync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_check_sync RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_check_sync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_compare_all LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_compare_all", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_compare_all RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_compare_all", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_compare_all RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_compare_all", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_createemptysrcdirs LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_createemptysrcdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_createemptysrcdirs RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_createemptysrcdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_createemptysrcdirs RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_createemptysrcdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_dry_run LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_dry_run", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_dry_run RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_dry_run", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_dry_run RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_dry_run", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_equal LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_equal", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_equal RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_equal", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_equal RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_equal", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ext_paths LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_ext_paths", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ext_paths RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_ext_paths", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ext_paths RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_ext_paths", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_extended_filenames LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_extended_filenames", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_extended_filenames RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_extended_filenames", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_extended_filenames RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_extended_filenames", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filters LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filters RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filters RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_filters", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filtersfile_checks LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_filtersfile_checks", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filtersfile_checks RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_filtersfile_checks", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_filtersfile_checks RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_filtersfile_checks", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_ignorelistingchecksum RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_ignorelistingchecksum", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path1 LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path1", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path1 RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_max_delete_path1", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path1 RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path1", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path2_force LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path2_force", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path2_force RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_max_delete_path2_force", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_max_delete_path2_force RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_max_delete_path2_force", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_nomodtime LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_nomodtime", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_nomodtime RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_nomodtime", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_nomodtime RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_nomodtime", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_normalization LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_normalization", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_normalization RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_normalization", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_normalization RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_normalization", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rclone_args LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_rclone_args", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rclone_args RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_rclone_args", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rclone_args RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_rclone_args", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resolve LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resolve", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resolve RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resolve", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resolve RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resolve", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resync", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync_modes LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_resync_modes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync_modes RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_resync_modes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_resync_modes RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_resync_modes", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rmdirs LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_rmdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rmdirs RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_rmdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_rmdirs RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_rmdirs", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_volatile LocalRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "local", "-remote2", "TestS3MinioEdge:", "-case", "test_volatile", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_volatile RemoteLocal",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "local", "-case", "test_volatile", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3MinioEdge: test_volatile RemoteRemote",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "test",
|
||||
"program": "./cmd/bisync",
|
||||
"args": ["-remote", "TestS3MinioEdge:", "-remote2", "TestS3MinioEdge:", "-case", "test_volatile", "-no-cleanup"]
|
||||
},
|
||||
{
|
||||
"name": "Test TestS3Wasabi: test_all_changed LocalRemote",
|
||||
"type": "go",
|
||||
|
||||
+23
-2
@@ -379,6 +379,27 @@ func StartStats() func() {
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
rcServer *rcserver.Server
|
||||
metricsServer *rcserver.MetricsServer
|
||||
)
|
||||
|
||||
// StopRemoteControl shuts down the remote control and metrics servers started by initConfig.
|
||||
func StopRemoteControl() {
|
||||
if rcServer != nil {
|
||||
if err := rcServer.Shutdown(); err != nil {
|
||||
fs.Errorf(nil, "Failed to stop remote control: %v", err)
|
||||
}
|
||||
rcServer = nil
|
||||
}
|
||||
if metricsServer != nil {
|
||||
if err := metricsServer.Shutdown(); err != nil {
|
||||
fs.Errorf(nil, "Failed to stop metrics server: %v", err)
|
||||
}
|
||||
metricsServer = nil
|
||||
}
|
||||
}
|
||||
|
||||
// initConfig is run by cobra after initialising the flags
|
||||
func initConfig() {
|
||||
// Set the global options from the flags
|
||||
@@ -422,14 +443,14 @@ func initConfig() {
|
||||
}
|
||||
|
||||
// Start the remote control server if configured
|
||||
_, err = rcserver.Start(ctx, &rc.Opt)
|
||||
rcServer, err = rcserver.Start(ctx, &rc.Opt)
|
||||
if err != nil {
|
||||
fs.Fatalf(nil, "Failed to start remote control: %v", err)
|
||||
}
|
||||
|
||||
// Start the metrics server if configured and not running the "rc" command
|
||||
if len(os.Args) >= 2 && os.Args[1] != "rc" {
|
||||
_, err = rcserver.MetricsStart(ctx, &rc.Opt)
|
||||
metricsServer, err = rcserver.MetricsStart(ctx, &rc.Opt)
|
||||
if err != nil {
|
||||
fs.Fatalf(nil, "Failed to start metrics server: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/fs/rc"
|
||||
"github.com/rclone/rclone/fs/rc/rcserver"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func freeAddr(t *testing.T) string {
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
addr := l.Addr().String()
|
||||
require.NoError(t, l.Close())
|
||||
return addr
|
||||
}
|
||||
|
||||
func TestStopRemoteControl(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
rcAddr, metricsAddr := freeAddr(t), freeAddr(t)
|
||||
opt := rc.Opt
|
||||
opt.Enabled = true
|
||||
opt.HTTP.ListenAddr = []string{rcAddr}
|
||||
opt.MetricsHTTP.ListenAddr = []string{metricsAddr}
|
||||
|
||||
var err error
|
||||
rcServer, err = rcserver.Start(ctx, &opt)
|
||||
require.NoError(t, err)
|
||||
metricsServer, err = rcserver.MetricsStart(ctx, &opt)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, rcServer)
|
||||
require.NotNil(t, metricsServer)
|
||||
|
||||
for _, addr := range []string{rcAddr, metricsAddr} {
|
||||
_, err := net.Listen("tcp", addr)
|
||||
require.Error(t, err, "%s should be in use while the servers run", addr)
|
||||
}
|
||||
|
||||
StopRemoteControl()
|
||||
assert.Nil(t, rcServer)
|
||||
assert.Nil(t, metricsServer)
|
||||
|
||||
for _, addr := range []string{rcAddr, metricsAddr} {
|
||||
l, err := net.Listen("tcp", addr)
|
||||
require.NoError(t, err, "%s should be free after StopRemoteControl", addr)
|
||||
require.NoError(t, l.Close())
|
||||
}
|
||||
}
|
||||
@@ -536,27 +536,56 @@ func (fsys *FS) Fsyncdir(path string, datasync bool, fh uint64) (errc int) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// #9908: simulate macFUSE behaviour (discard setxattr calls) - otherwise Finder cannot copy files onto the mount
|
||||
func shouldIgnoreAppleXattr(opt *mountlib.Options) bool {
|
||||
if !opt.NoAppleXattr {
|
||||
return false
|
||||
}
|
||||
if runtime.GOOS != "darwin" {
|
||||
return false
|
||||
}
|
||||
// only flip the behaviour on FSKit
|
||||
for _, o := range opt.ExtraOptions {
|
||||
if strings.TrimSpace(o) == "backend=fskit" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Setxattr sets extended attributes.
|
||||
func (fsys *FS) Setxattr(path string, name string, value []byte, flags int) (errc int) {
|
||||
defer log.Trace(path, "name=%q, value=%q, flags=%d", name, value, flags)("errc=%d", &errc)
|
||||
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
|
||||
return 0
|
||||
}
|
||||
return -fuse.ENOSYS
|
||||
}
|
||||
|
||||
// Getxattr gets extended attributes.
|
||||
func (fsys *FS) Getxattr(path string, name string) (errc int, value []byte) {
|
||||
defer log.Trace(path, "name=%q", name)("errc=%d, value=%q", &errc, &value)
|
||||
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
|
||||
return -fuse.ENOATTR, nil
|
||||
}
|
||||
return -fuse.ENOSYS, nil
|
||||
}
|
||||
|
||||
// Removexattr removes extended attributes.
|
||||
func (fsys *FS) Removexattr(path string, name string) (errc int) {
|
||||
defer log.Trace(path, "name=%q", name)("errc=%d", &errc)
|
||||
if shouldIgnoreAppleXattr(fsys.opt) && strings.HasPrefix(name, "com.apple.") {
|
||||
return 0
|
||||
}
|
||||
return -fuse.ENOSYS
|
||||
}
|
||||
|
||||
// Listxattr lists extended attributes.
|
||||
func (fsys *FS) Listxattr(path string, fill func(name string) bool) (errc int) {
|
||||
defer log.Trace(path, "fill=%p", fill)("errc=%d", &errc)
|
||||
if shouldIgnoreAppleXattr(fsys.opt) {
|
||||
return 0
|
||||
}
|
||||
return -fuse.ENOSYS
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ Note that |ls| and |lsl| recurse by default - use |--max-depth 1| to stop the re
|
||||
The other list commands |lsd|,|lsf|,|lsjson| do not recurse by default -
|
||||
use |-R| to make them recurse.
|
||||
|
||||
On the bucket-based remotes (e.g. s3, gcs, b2) a directory is a key prefix
|
||||
rather than an object, so a listing without |-R| shows each prefix as one
|
||||
directory entry and not the objects stored under it.
|
||||
|
||||
List commands prefer a recursive method that uses more memory but fewer
|
||||
transactions by default. Use |--disable ListR| to suppress the behavior.
|
||||
See [|--fast-list|](/docs/#fast-list) for more details.
|
||||
|
||||
@@ -299,6 +299,10 @@ func NewMountCommand(commandName string, hidden bool, mount MountFn) *cobra.Comm
|
||||
|
||||
if Opt.Daemon {
|
||||
config.PassConfigKeyForDaemonization = true
|
||||
if !fs.IsDaemon() {
|
||||
// The daemon child starts these servers on the same addresses
|
||||
cmd.StopRemoteControl()
|
||||
}
|
||||
}
|
||||
|
||||
if os.Getenv("PATH") == "" && runtime.GOOS != "windows" {
|
||||
|
||||
@@ -133,18 +133,28 @@ func GetVersion(ctx context.Context, beta bool, version string) (newVersion, sit
|
||||
if err != nil {
|
||||
return "", siteURL, fmt.Errorf("failed to get list of releases: %w", err)
|
||||
}
|
||||
reSubver := fmt.Sprintf(`href="\./%s\.\d+/"`, regexp.QuoteMeta(newVersion))
|
||||
allSubvers := regexp.MustCompile(reSubver).FindAllString(string(html), -1)
|
||||
if allSubvers == nil {
|
||||
return "", siteURL, errors.New("could not find the minor release")
|
||||
newVersion, err = latestMicroRelease(html, newVersion)
|
||||
if err != nil {
|
||||
return "", siteURL, err
|
||||
}
|
||||
// Use the fact that releases in the index are sorted by date
|
||||
lastSubver := allSubvers[len(allSubvers)-1]
|
||||
newVersion = lastSubver[8 : len(lastSubver)-2]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// latestMicroRelease returns the latest micro release of the
|
||||
// major.minor release version linked to from the HTML index of
|
||||
// releases.
|
||||
func latestMicroRelease(html []byte, version string) (string, error) {
|
||||
// The links may or may not start with ./ depending on what made the index
|
||||
reSubver := fmt.Sprintf(`href="(?:\./)?(%s\.\d+)/"`, regexp.QuoteMeta(version))
|
||||
allSubvers := regexp.MustCompile(reSubver).FindAllSubmatch(html, -1)
|
||||
if allSubvers == nil {
|
||||
return "", errors.New("could not find the minor release")
|
||||
}
|
||||
// Use the fact that releases in the index are sorted by date
|
||||
return string(allSubvers[len(allSubvers)-1][1]), nil
|
||||
}
|
||||
|
||||
// InstallUpdate performs rclone self-update
|
||||
func InstallUpdate(ctx context.Context, opt *Options) error {
|
||||
// Find the latest release number
|
||||
|
||||
@@ -45,6 +45,50 @@ func TestGetVersion(t *testing.T) {
|
||||
assert.Equal(t, "v1.52.3", resultVer)
|
||||
}
|
||||
|
||||
func TestLatestMicroRelease(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
html string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "caddy",
|
||||
html: `<a href="./v1.51.0/">v1.51.0/</a>
|
||||
<a href="./v1.52.0/">v1.52.0/</a>
|
||||
<a href="./v1.52.3/">v1.52.3/</a>
|
||||
<a href="./v1.53.0/">v1.53.0/</a>
|
||||
<a href="./v1.52-DEV/">v1.52-DEV/</a>
|
||||
<a href="./v1.52.3/rclone-v1.52.3-linux-amd64.zip">rclone</a>`,
|
||||
want: "v1.52.3",
|
||||
},
|
||||
{
|
||||
name: "no prefix",
|
||||
html: `<a href="v1.51.0/">v1.51.0/</a>
|
||||
<a href="v1.52.0/">v1.52.0/</a>
|
||||
<a href="v1.52.3/">v1.52.3/</a>
|
||||
<a href="v1.53.0/">v1.53.0/</a>`,
|
||||
want: "v1.52.3",
|
||||
},
|
||||
{
|
||||
name: "other prefix",
|
||||
html: `<a href="../v1.52.0/">v1.52.0/</a>
|
||||
<a href="https://example.com/v1.52.1/">v1.52.1/</a>
|
||||
<a href="v1.52.2/index.html">v1.52.2/</a>
|
||||
<a href="v1x52.3/">v1x52.3/</a>`,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := latestMicroRelease([]byte(test.html), "v1.52")
|
||||
if test.want == "" {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallOnLinux(t *testing.T) {
|
||||
testy.SkipUnreliable(t)
|
||||
if runtime.GOOS != "linux" {
|
||||
@@ -56,6 +100,12 @@ func TestInstallOnLinux(t *testing.T) {
|
||||
testDir := t.TempDir()
|
||||
path := filepath.Join(testDir, "rclone")
|
||||
|
||||
// Pin the running version so the checks below do not depend on
|
||||
// whether this build happens to be the latest beta.
|
||||
oldVersion := fs.Version
|
||||
fs.Version = "v1.0.0"
|
||||
t.Cleanup(func() { fs.Version = oldVersion })
|
||||
|
||||
regexVer := regexp.MustCompile(`v[0-9]\S+`)
|
||||
|
||||
betaVer, _, err := GetVersion(ctx, true, "")
|
||||
@@ -71,7 +121,7 @@ func TestInstallOnLinux(t *testing.T) {
|
||||
_ = os.Chmod(path, 0644)
|
||||
}()
|
||||
err = (InstallUpdate(ctx, &Options{Beta: true, Output: path}))
|
||||
assert.Error(t, err)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "run self-update as root")
|
||||
|
||||
// Must keep non-standard permissions
|
||||
|
||||
@@ -86,7 +86,8 @@ func verifyHashsumDownloaded(ctx context.Context, sumsBuf []byte, archive string
|
||||
return fmt.Errorf("invalid hashsum signature: %w", err)
|
||||
}
|
||||
|
||||
wantHash, err := findFileHash(sumsBuf, archive)
|
||||
// Only read hashes from the the signed text
|
||||
wantHash, err := findFileHash(block.Bytes, archive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -39,4 +40,22 @@ func TestVerify(t *testing.T) {
|
||||
err = verifyHashsumDownloaded(ctx, sumsBuf, "archive.zipX", hash)
|
||||
assert.ErrorContains(t, err, "unable to find hash")
|
||||
})
|
||||
t.Run("UnsignedPrefix", func(t *testing.T) {
|
||||
hash[0] ^= 1 // forge an unsigned hash line before the signed block
|
||||
prefixed := append([]byte(hex.EncodeToString(hash)+" archive.zip\n"), sumsBuf...)
|
||||
err = verifyHashsumDownloaded(ctx, prefixed, "archive.zip", hash)
|
||||
assert.ErrorContains(t, err, "archive hash mismatch")
|
||||
hash[0] ^= 1 // undo the change
|
||||
})
|
||||
t.Run("UnsignedInArmor", func(t *testing.T) {
|
||||
// Dash escaping the signed line doesn't change the signed text but hides
|
||||
// it from a raw scan, and lines after the armor checksum are ignored.
|
||||
badHash := hex.EncodeToString([]byte{0x01})
|
||||
armored := strings.Replace(string(sumsBuf), "b20b", "- b20b", 1)
|
||||
armored = strings.Replace(armored, "=1GTr\n", "=1GTr\n"+badHash+" archive.zip\n", 1)
|
||||
err = verifyHashsumDownloaded(ctx, []byte(armored), "archive.zip", []byte{0x01})
|
||||
assert.ErrorContains(t, err, "archive hash mismatch")
|
||||
err = verifyHashsumDownloaded(ctx, []byte(armored), "archive.zip", hash)
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
@@ -153,7 +153,7 @@ func (lrw *loggingResponseWriter) logRequest(code int, err any) {
|
||||
err = ""
|
||||
}
|
||||
|
||||
fs.LogLevelPrintf(level, lrw.request.URL, "%s %s %d %s %s",
|
||||
fs.LogLevelPrintf(level, lrw.request.URL.Path, "%s %s %d %s %s",
|
||||
lrw.request.RemoteAddr, lrw.request.Method, code,
|
||||
lrw.request.Header.Get("SOAPACTION"), err)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package dlna
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/cmd/bisync/bilib"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -46,3 +49,13 @@ func TestAdjustXML(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggingUnescapedPath(t *testing.T) {
|
||||
handler := logging(http.NotFoundHandler())
|
||||
req := httptest.NewRequest("GET", "/r/%D0%91%D0%B0%D1%80%D0%B4%D1%8B/file%20name.mp3", nil)
|
||||
logged := bilib.CaptureOutput(func() {
|
||||
handler.ServeHTTP(httptest.NewRecorder(), req)
|
||||
})
|
||||
|
||||
assert.Contains(t, string(logged), "ERROR : /r/Барды/file name.mp3: ")
|
||||
}
|
||||
@@ -6,14 +6,17 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -398,6 +401,50 @@ func (a *APIClient) request(path string, in, out any, wantErr bool) {
|
||||
time.Sleep(tempDelay)
|
||||
}
|
||||
|
||||
// writeMountedFile writes data to a file on a FUSE mount served by this
|
||||
// process.
|
||||
//
|
||||
// It avoids os.WriteFile as files opened with os.OpenFile are handed
|
||||
// to the Go runtime poller and the kernel then asks the FUSE server
|
||||
// to poll them from epoll_ctl and epoll_wait. The server lives in
|
||||
// this process and a thread waiting inside epoll cannot be preempted,
|
||||
// so a garbage collection starting while a poll is outstanding stops
|
||||
// the world for good. The poll is never answered, the process cannot
|
||||
// be killed even with SIGKILL and the mount is left behind.
|
||||
// See: https://github.com/golang/go/issues/21014
|
||||
//
|
||||
// os.NewFile only returns a pollable file for a descriptor which is
|
||||
// already in non-blocking mode, so a descriptor straight from open(2)
|
||||
// stays out of the poller.
|
||||
func writeMountedFile(path string, data []byte, perm uint32) (err error) {
|
||||
fd, err := syscall.Open(path, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_TRUNC, perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f := os.NewFile(uintptr(fd), path)
|
||||
defer fs.CheckClose(f, &err)
|
||||
// Deadlines work on polled files only
|
||||
if err := f.SetDeadline(time.Time{}); !errors.Is(err, os.ErrNoDeadline) {
|
||||
return fmt.Errorf("%s is being polled by the runtime which risks deadlocking the test: %w", path, err)
|
||||
}
|
||||
_, err = f.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
// checkUnmounted fails the test and tears the mount down if mountpoint
|
||||
// is still mounted.
|
||||
func checkUnmounted(t *testing.T, mountpoint string) {
|
||||
// CheckMountReady and fusermount are both Linux only
|
||||
if !mountlib.CanCheckMountReady || mountlib.CheckMountReady(mountpoint) != nil {
|
||||
return
|
||||
}
|
||||
assert.Fail(t, fmt.Sprintf("mountpoint %s was left mounted", mountpoint))
|
||||
// Lazy unmount as the mount may still be busy
|
||||
if out, err := exec.Command("fusermount", "-uz", mountpoint).CombinedOutput(); err != nil {
|
||||
t.Logf("Failed to unmount %s: %v: %s", mountpoint, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func testMountAPI(t *testing.T, sockAddr string) {
|
||||
// Disable tests under macOS and linux in the CI since they are locking up
|
||||
if runtime.GOOS == "darwin" || runtime.GOOS == "linux" {
|
||||
@@ -412,6 +459,7 @@ func testMountAPI(t *testing.T, sockAddr string) {
|
||||
testDir, testFs := initialise(ctx, t)
|
||||
err := config.SetCacheDir(testDir)
|
||||
require.NoError(t, err)
|
||||
mount1 := filepath.Join(testDir, "vol1")
|
||||
defer func() {
|
||||
_ = config.SetCacheDir(oldCacheDir)
|
||||
if !t.Failed() {
|
||||
@@ -419,6 +467,7 @@ func testMountAPI(t *testing.T, sockAddr string) {
|
||||
_ = os.RemoveAll(testDir)
|
||||
}
|
||||
}()
|
||||
defer checkUnmounted(t, mount1)
|
||||
|
||||
// Prepare API client
|
||||
var cli *APIClient
|
||||
@@ -457,7 +506,6 @@ func testMountAPI(t *testing.T, sockAddr string) {
|
||||
// Run test sequence
|
||||
path1 := filepath.Join(testDir, "path1")
|
||||
require.NoError(t, file.MkdirAll(path1, 0755))
|
||||
mount1 := filepath.Join(testDir, "vol1")
|
||||
res := ""
|
||||
|
||||
cli.request("Activate", "{}", &res, false)
|
||||
@@ -485,7 +533,7 @@ func testMountAPI(t *testing.T, sockAddr string) {
|
||||
assert.Contains(t, res, "volume is in use")
|
||||
|
||||
text := []byte("banana")
|
||||
err = os.WriteFile(filepath.Join(mount1, "txt"), text, 0644)
|
||||
err = writeMountedFile(filepath.Join(mount1, "txt"), text, 0644)
|
||||
assert.NoError(t, err)
|
||||
time.Sleep(tempDelay)
|
||||
|
||||
|
||||
@@ -140,6 +140,9 @@ func (vol *Volume) restoreState(ctx context.Context, drv *Driver) error {
|
||||
volOpt := vol.Options
|
||||
volOpt["fs"] = vol.Fs
|
||||
volOpt["type"] = vol.Type
|
||||
// applyOptions consumes "path" into vol.Path rather than leaving it in
|
||||
// vol.Options, so it must be fed back explicitly like fs and type.
|
||||
volOpt["path"] = vol.Path
|
||||
if err := vol.applyOptions(volOpt); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package docker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
)
|
||||
|
||||
// persistedCopy returns vol as it comes back from the plugin state file:
|
||||
// only the exported fields survive being marshalled and reloaded.
|
||||
func persistedCopy(t *testing.T, vol *Volume) *Volume {
|
||||
t.Helper()
|
||||
vol.prepareState()
|
||||
data, err := json.Marshal(vol)
|
||||
require.NoError(t, err)
|
||||
restored := &Volume{}
|
||||
require.NoError(t, json.Unmarshal(data, restored))
|
||||
return restored
|
||||
}
|
||||
|
||||
// TestRestoreStatePath checks that the on-remote path of a volume survives
|
||||
// being reloaded from the plugin state file, for each of the option
|
||||
// combinations that can carry one.
|
||||
func TestRestoreStatePath(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
volOpt VolOpts
|
||||
fsString string
|
||||
}{{
|
||||
name: "type and path",
|
||||
volOpt: VolOpts{"type": "local", "path": "/tmp/path"},
|
||||
fsString: ":local:/tmp/path",
|
||||
}, {
|
||||
name: "remote only",
|
||||
volOpt: VolOpts{"remote": "/tmp/remote"},
|
||||
fsString: ":local:/tmp/remote",
|
||||
}, {
|
||||
// an explicit path overrides the path of the connection string,
|
||||
// and must keep doing so after a restart
|
||||
name: "remote and path",
|
||||
volOpt: VolOpts{"remote": "/tmp/remote", "path": "/tmp/path"},
|
||||
fsString: ":local:/tmp/path",
|
||||
}, {
|
||||
name: "type only",
|
||||
volOpt: VolOpts{"type": "local"},
|
||||
fsString: ":local:",
|
||||
}} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
drv := &Driver{
|
||||
root: t.TempDir(),
|
||||
volumes: map[string]*Volume{},
|
||||
dummy: true,
|
||||
}
|
||||
vol, err := newVolume(ctx, "vol1", test.volOpt, drv)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.fsString, vol.fsString)
|
||||
|
||||
restored := persistedCopy(t, vol)
|
||||
require.NoError(t, restored.restoreState(ctx, drv))
|
||||
assert.Equal(t, test.fsString, restored.fsString)
|
||||
assert.Equal(t, vol.Path, restored.Path)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDriverRestoreStatePath checks the same through the real state file: a
|
||||
// volume persisted by a previous plugin instance is reloaded with its path.
|
||||
func TestDriverRestoreStatePath(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDir := t.TempDir()
|
||||
|
||||
state := fmt.Sprintf(`[{"name":"vol1","mountpoint":%q,"created":%q,"fs":"","type":"local","path":"/tmp/path","options":{},"mounts":[]}]`,
|
||||
filepath.Join(testDir, "vol1"), time.Now().Format(time.RFC3339))
|
||||
statePath := filepath.Join(testDir, stateFile)
|
||||
require.NoError(t, os.WriteFile(statePath, []byte(state), 0600))
|
||||
|
||||
drv := &Driver{
|
||||
root: testDir,
|
||||
statePath: statePath,
|
||||
volumes: map[string]*Volume{},
|
||||
dummy: true,
|
||||
}
|
||||
require.NoError(t, drv.restoreState(ctx))
|
||||
|
||||
vol, err := drv.getVolume("vol1")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ":local:/tmp/path", vol.fsString)
|
||||
assert.Equal(t, "/tmp/path", vol.Path)
|
||||
}
|
||||
+50
-13
@@ -16,6 +16,7 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/rclone/cmd"
|
||||
@@ -189,7 +190,7 @@ func init() {
|
||||
var passivePortsRe = regexp.MustCompile(`^\s*\d+\s*-\s*\d+\s*$`)
|
||||
|
||||
// Make a new FTP to serve the remote
|
||||
func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Options, proxyOpt *proxy.Options) (*driver, error) {
|
||||
func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Options, proxyOpt *proxy.Options) (_ *driver, err error) {
|
||||
host, port, err := net.SplitHostPort(opt.ListenAddr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse host:port from %q", opt.ListenAddr)
|
||||
@@ -358,13 +359,27 @@ func (d *driver) CheckPasswd(sctx *ftp.Context, user, pass string) (ok bool, err
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// getVFS returns the VFS for this connection.
|
||||
// getVFS returns the VFS for this connection, held so it can't be
|
||||
// shut down while it is in use. The caller must call Shutdown on it
|
||||
// when it has finished with it.
|
||||
//
|
||||
// In proxy mode, getVFS calls proxy.Call on each FTP command which refreshes
|
||||
// the proxy cache timer (like http/webdav). Therefore, connection-level pinning
|
||||
// is not used; only individual transfers exceeding the cache expiry window
|
||||
// could be affected.
|
||||
// In proxy mode, getVFS calls proxy.Call on each FTP command which
|
||||
// refreshes the proxy cache timer (like http/webdav). The proxy shuts
|
||||
// the VFS down when that timer expires, which a single transfer can
|
||||
// outlast, so the timer alone isn't enough to keep the VFS alive.
|
||||
func (d *driver) getVFS(sctx *ftp.Context) (VFS *vfs.VFS, err error) {
|
||||
VFS, err = d.findVFS(sctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !VFS.Hold() {
|
||||
return nil, errors.New("VFS has been shut down")
|
||||
}
|
||||
return VFS, nil
|
||||
}
|
||||
|
||||
// findVFS returns the VFS for this connection without holding it.
|
||||
func (d *driver) findVFS(sctx *ftp.Context) (VFS *vfs.VFS, err error) {
|
||||
if !d.provider.IsProxy() {
|
||||
// If no proxy always use the same VFS
|
||||
return d.provider.VFS(), nil
|
||||
@@ -392,6 +407,7 @@ func (d *driver) Stat(sctx *ftp.Context, path string) (fi iofs.FileInfo, err err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
n, err := VFS.Stat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -406,6 +422,7 @@ func (d *driver) ChangeDir(sctx *ftp.Context, path string) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
n, err := VFS.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -423,6 +440,7 @@ func (d *driver) ListDir(sctx *ftp.Context, path string, callback func(iofs.File
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
node, err := VFS.Stat(path)
|
||||
if err == vfs.ENOENT {
|
||||
return errors.New("directory not found")
|
||||
@@ -461,6 +479,7 @@ func (d *driver) DeleteDir(sctx *ftp.Context, path string) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
node, err := VFS.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -482,6 +501,7 @@ func (d *driver) DeleteFile(sctx *ftp.Context, path string) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
node, err := VFS.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -503,6 +523,7 @@ func (d *driver) Rename(sctx *ftp.Context, oldName, newName string) (err error)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
return VFS.Rename(oldName, newName)
|
||||
}
|
||||
|
||||
@@ -513,12 +534,8 @@ func (d *driver) MakeDir(sctx *ftp.Context, path string) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir, leaf, err := VFS.StatParent(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = dir.Mkdir(leaf)
|
||||
return err
|
||||
defer VFS.Shutdown()
|
||||
return VFS.Mkdir(path, 0777)
|
||||
}
|
||||
|
||||
// GetFile download a file
|
||||
@@ -528,6 +545,12 @@ func (d *driver) GetFile(sctx *ftp.Context, path string, offset int64) (size int
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
// The returned file takes over the hold on the VFS
|
||||
defer func() {
|
||||
if err != nil {
|
||||
VFS.Shutdown()
|
||||
}
|
||||
}()
|
||||
node, err := VFS.Stat(path)
|
||||
if err == vfs.ENOENT {
|
||||
fs.Infof(path, "File not found")
|
||||
@@ -552,7 +575,20 @@ func (d *driver) GetFile(sctx *ftp.Context, path string, offset int64) (size int
|
||||
tr := accounting.GlobalStats().NewTransferRemoteSize(path, node.Size(), d.f, nil)
|
||||
defer tr.Done(d.ctx, nil)
|
||||
|
||||
return node.Size(), handle, nil
|
||||
return node.Size(), &heldFile{ReadCloser: handle, VFS: VFS}, nil
|
||||
}
|
||||
|
||||
// heldFile is an open file which holds its VFS until it is closed.
|
||||
type heldFile struct {
|
||||
io.ReadCloser
|
||||
VFS *vfs.VFS
|
||||
release sync.Once
|
||||
}
|
||||
|
||||
// Close closes the file and releases the hold on the VFS.
|
||||
func (f *heldFile) Close() error {
|
||||
defer f.release.Do(f.VFS.Shutdown)
|
||||
return f.ReadCloser.Close()
|
||||
}
|
||||
|
||||
// PutFile upload a file
|
||||
@@ -564,6 +600,7 @@ func (d *driver) PutFile(sctx *ftp.Context, path string, data io.Reader, offset
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
fi, err := VFS.Stat(path)
|
||||
if err == nil {
|
||||
isExist = true
|
||||
|
||||
@@ -9,8 +9,14 @@ package ftp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
ftpclient "github.com/jlaffaye/ftp"
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
"github.com/rclone/rclone/cmd/serve/proxy"
|
||||
"github.com/rclone/rclone/cmd/serve/servetest"
|
||||
@@ -19,6 +25,8 @@ import (
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/rclone/rclone/fs/rc"
|
||||
"github.com/rclone/rclone/lib/israce"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/rclone/rclone/vfs"
|
||||
"github.com/rclone/rclone/vfs/vfscommon"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -122,6 +130,32 @@ func TestNewServerPerServerAuthProxy(t *testing.T) {
|
||||
assert.Nil(t, d.provider.VFS(), "expected no fixed VFS when auth proxy is in use")
|
||||
}
|
||||
|
||||
// TestMakeDirRoot checks that "MKD /" makes the directory being
|
||||
// served. The ftp backend never sends this so TestFTP doesn't cover it.
|
||||
func TestMakeDirRoot(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "root")
|
||||
f, err := fs.NewFs(context.Background(), root)
|
||||
require.NoError(t, err)
|
||||
|
||||
opt := Opt
|
||||
opt.ListenAddr = testHOST + ":" + testPORT
|
||||
opt.PassivePorts = testPASSIVEPORTRANGE
|
||||
|
||||
d, err := newServer(context.Background(), f, &opt, &vfscommon.Opt, &proxy.Opt)
|
||||
require.NoError(t, err)
|
||||
defer d.provider.Shutdown()
|
||||
|
||||
require.NoError(t, d.MakeDir(nil, "/"))
|
||||
fi, err := os.Stat(root)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, fi.IsDir())
|
||||
|
||||
require.NoError(t, d.MakeDir(nil, "/dir"))
|
||||
fi, err = os.Stat(filepath.Join(root, "dir"))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, fi.IsDir())
|
||||
}
|
||||
|
||||
func TestRc(t *testing.T) {
|
||||
if israce.Enabled {
|
||||
t.Skip("Skipping under race detector as underlying library is racy")
|
||||
@@ -131,3 +165,112 @@ func TestRc(t *testing.T) {
|
||||
"vfs_cache_mode": "off",
|
||||
})
|
||||
}
|
||||
|
||||
// TestNewServerError checks that a server initialisation failure is
|
||||
// returned as an error and does not leak the VFS it created.
|
||||
func TestNewServerError(t *testing.T) {
|
||||
f, err := fs.NewFs(context.Background(), t.TempDir())
|
||||
require.NoError(t, err)
|
||||
|
||||
opt := Opt
|
||||
opt.ListenAddr = testHOST + ":" + testPORT
|
||||
opt.PassivePorts = "not-a-port-range"
|
||||
|
||||
before := vfs.ActiveCount()
|
||||
d, err := newServer(context.Background(), f, &opt, &vfscommon.Opt, &proxy.Opt)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, d)
|
||||
assert.Equal(t, before, vfs.ActiveCount(), "VFS leaked after failed server creation")
|
||||
}
|
||||
|
||||
// TestAuthProxyTransferOutlivesCache checks transfers in progress
|
||||
// carry on working when the auth proxy drops their VFS from its cache,
|
||||
// as it does when a transfer takes longer than the cache expiry time.
|
||||
func TestAuthProxyTransferOutlivesCache(t *testing.T) {
|
||||
const addr = "127.0.0.1:" + testPORT
|
||||
root := t.TempDir()
|
||||
contents := random.String(32 * 1024 * 1024)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "download.bin"), []byte(contents), 0666))
|
||||
|
||||
prog, err := filepath.Abs("../servetest/proxy_code.go")
|
||||
require.NoError(t, err)
|
||||
opt := Opt
|
||||
opt.ListenAddr = addr
|
||||
opt.PassivePorts = testPASSIVEPORTRANGE
|
||||
proxyOpt := proxy.Opt
|
||||
proxyOpt.AuthProxy = "go run " + prog + " " + root
|
||||
d, err := newServer(context.Background(), nil, &opt, &vfscommon.Opt, &proxyOpt)
|
||||
require.NoError(t, err)
|
||||
quit := make(chan struct{})
|
||||
go func() {
|
||||
assert.NoError(t, d.Serve())
|
||||
close(quit)
|
||||
}()
|
||||
defer func() {
|
||||
assert.NoError(t, d.Shutdown())
|
||||
<-quit
|
||||
}()
|
||||
|
||||
var c *ftpclient.ServerConn
|
||||
require.Eventually(t, func() bool {
|
||||
c, err = ftpclient.Dial(addr)
|
||||
return err == nil
|
||||
}, 10*time.Second, 10*time.Millisecond)
|
||||
defer func() { _ = c.Quit() }()
|
||||
require.NoError(t, c.Login(testUSER, testPASS))
|
||||
|
||||
// Only the IP of the address is used, which is the same as the client's
|
||||
_, vfsKey, err := d.provider.Proxy().Call(testUSER, testPASS, false, addr)
|
||||
require.NoError(t, err)
|
||||
|
||||
// expire waits for a transfer to be using the VFS, then drops
|
||||
// everything from the proxy's cache as if it had expired.
|
||||
expire := func(t *testing.T) {
|
||||
var VFS *vfs.VFS
|
||||
require.Eventually(t, func() bool {
|
||||
VFS = d.provider.Proxy().Get(vfsKey)
|
||||
return VFS != nil && VFS.Stats()["inUse"] == int32(2)
|
||||
}, 10*time.Second, 10*time.Millisecond, "transfer isn't holding the VFS")
|
||||
d.provider.Proxy().Shutdown()
|
||||
assert.Equal(t, int32(1), VFS.Stats()["inUse"], "VFS not held by the transfer alone")
|
||||
}
|
||||
|
||||
t.Run("Download", func(t *testing.T) {
|
||||
resp, err := c.Retr("download.bin")
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Close() }()
|
||||
start := make([]byte, 1024)
|
||||
_, err = io.ReadFull(resp, start)
|
||||
require.NoError(t, err)
|
||||
expire(t)
|
||||
rest, err := io.ReadAll(resp)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, resp.Close())
|
||||
assert.True(t, contents == string(start)+string(rest), "download corrupted")
|
||||
})
|
||||
|
||||
t.Run("Upload", func(t *testing.T) {
|
||||
pr, pw := io.Pipe()
|
||||
var storErr error
|
||||
var wg sync.WaitGroup
|
||||
wg.Go(func() {
|
||||
storErr = c.Stor("upload.bin", pr)
|
||||
})
|
||||
// Finish the upload before the connection is used again
|
||||
defer func() {
|
||||
_ = pw.Close()
|
||||
wg.Wait()
|
||||
}()
|
||||
_, err := io.WriteString(pw, contents[:1024*1024])
|
||||
require.NoError(t, err)
|
||||
expire(t)
|
||||
_, err = io.WriteString(pw, contents[1024*1024:])
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, pw.Close())
|
||||
wg.Wait()
|
||||
require.NoError(t, storErr)
|
||||
got, err := os.ReadFile(filepath.Join(root, "upload.bin"))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, contents == string(got), "upload corrupted")
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -170,8 +171,8 @@ func (s *HTTP) auth(r *http.Request, user, pass string) (value any, err error) {
|
||||
return VFS, err
|
||||
}
|
||||
|
||||
func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Options, proxyOpt *proxy.Options) (s *HTTP, err error) {
|
||||
s = &HTTP{
|
||||
func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Options, proxyOpt *proxy.Options) (_ *HTTP, err error) {
|
||||
s := &HTTP{
|
||||
f: f,
|
||||
ctx: ctx,
|
||||
opt: *opt,
|
||||
@@ -198,6 +199,7 @@ func newServer(ctx context.Context, f fs.Fs, opt *Options, vfsOpt *vfscommon.Opt
|
||||
|
||||
router := s.server.Router()
|
||||
router.Use(
|
||||
s.provider.HoldVFS,
|
||||
middleware.Compress(5),
|
||||
middleware.SetHeader("Accept-Ranges", "bytes"),
|
||||
middleware.SetHeader("Server", "rclone/"+fs.Version),
|
||||
@@ -295,7 +297,7 @@ func (s *HTTP) serveDir(w http.ResponseWriter, r *http.Request, dirRemote string
|
||||
if dirRemote == "" {
|
||||
zipName = "root"
|
||||
}
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=\""+zipName+".zip\"")
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": zipName + ".zip"}))
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
err := vfs.CreateZip(ctx, dir, w)
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/rclone/rclone/fs/filter"
|
||||
"github.com/rclone/rclone/fs/rc"
|
||||
libhttp "github.com/rclone/rclone/lib/http"
|
||||
"github.com/rclone/rclone/lib/random"
|
||||
"github.com/rclone/rclone/vfs/vfscommon"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -542,3 +543,57 @@ func TestRc(t *testing.T) {
|
||||
"vfs_cache_mode": "off",
|
||||
})
|
||||
}
|
||||
|
||||
// TestNewServerError checks that a server initialisation failure is
|
||||
// returned as an error rather than panicking in the cleanup.
|
||||
func TestNewServerError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f, err := fs.NewFs(ctx, "testdata/files")
|
||||
require.NoError(t, err)
|
||||
|
||||
opts := Options{
|
||||
HTTP: libhttp.DefaultCfg(),
|
||||
}
|
||||
opts.HTTP.ListenAddr = []string{"localhost:-1"}
|
||||
|
||||
s, err := newServer(ctx, f, &opts, &vfscommon.Opt, &proxy.Opt)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, s)
|
||||
}
|
||||
|
||||
// TestAuthProxyDownloadOutlivesCache checks a download in progress
|
||||
// carries on working when the auth proxy drops its VFS from its cache,
|
||||
// as it does when a download takes longer than the cache expiry time.
|
||||
func TestAuthProxyDownloadOutlivesCache(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
contents := random.String(32 * 1024 * 1024)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(root, "download.bin"), []byte(contents), 0666))
|
||||
|
||||
prog, err := filepath.Abs("../servetest/proxy_code.go")
|
||||
require.NoError(t, err)
|
||||
// FIXME this is untidy setting a global variable!
|
||||
proxy.Opt.AuthProxy = "go run " + prog + " " + root
|
||||
defer func() {
|
||||
proxy.Opt.AuthProxy = ""
|
||||
}()
|
||||
s, testURL := start(context.Background(), t, nil)
|
||||
defer func() { assert.NoError(t, s.Shutdown()) }()
|
||||
|
||||
req, err := http.NewRequest("GET", testURL+"download.bin", nil)
|
||||
require.NoError(t, err)
|
||||
req.SetBasicAuth(testUser, testPass)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
start := make([]byte, 1024)
|
||||
_, err = io.ReadFull(resp.Body, start)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Drop everything from the proxy's cache as if it had expired
|
||||
s.provider.Proxy().Shutdown()
|
||||
|
||||
rest, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, contents == string(start)+string(rest), "download corrupted")
|
||||
}
|
||||
@@ -3,9 +3,15 @@
|
||||
package nfs
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/memory"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/operations"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/vfs"
|
||||
"github.com/rclone/rclone/vfs/vfscommon"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -39,3 +45,56 @@ func TestChmodDanglingSymlink(t *testing.T) {
|
||||
assert.ErrorIs(t, bfs.Chmod("missing", 0777), vfs.ENOENT)
|
||||
assert.ErrorIs(t, bfs.Chown("missing", 1000, 1000), vfs.ENOENT)
|
||||
}
|
||||
|
||||
// go-nfs joins the file name from the client onto the directory path
|
||||
// with Join without checking it for ".." elements or a "/", so such a
|
||||
// name must not reach outside the directory served.
|
||||
//
|
||||
// The memory backend is used because it resolves ".." by joining paths,
|
||||
// unlike the local backend which refuses paths outside its root.
|
||||
func TestPathTraversal(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
modTime := fstest.Time("2001-02-03T04:05:06.499999999Z")
|
||||
|
||||
// outside is the parent of the directory served and holds an object
|
||||
// which must stay unreachable through the server.
|
||||
outside, err := fs.NewFs(ctx, ":memory:nfs-traversal-test")
|
||||
require.NoError(t, err)
|
||||
_, err = operations.Rcat(ctx, outside, "outside-secret.txt", io.NopCloser(strings.NewReader("SECRET")), modTime, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
f, err := fs.NewFs(ctx, ":memory:nfs-traversal-test/served-root")
|
||||
require.NoError(t, err)
|
||||
_, err = operations.Rcat(ctx, f, "inside.txt", io.NopCloser(strings.NewReader("INSIDE")), modTime, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
opt := vfscommon.Opt
|
||||
opt.Links = true
|
||||
opt.CacheMode = vfscommon.CacheModeWrites
|
||||
v := vfs.New(ctx, f, &opt)
|
||||
defer v.Shutdown()
|
||||
bfs := &FS{vfs: v}
|
||||
|
||||
// The MkdirAll calls come first so that, should one succeed, the
|
||||
// later calls are routed through the directory node it made.
|
||||
assert.Error(t, bfs.MkdirAll(bfs.Join("", "../new-dir"), 0777))
|
||||
assert.Error(t, bfs.MkdirAll(bfs.Join("", ".."), 0777))
|
||||
|
||||
_, err = bfs.Create(bfs.Join("", "../outside-write.txt"))
|
||||
assert.Error(t, err)
|
||||
_, err = bfs.OpenFile(bfs.Join("", "../outside-secret.txt"), os.O_WRONLY|os.O_TRUNC, 0666)
|
||||
assert.Error(t, err)
|
||||
_, err = bfs.Open(bfs.Join("", "../outside-secret.txt"))
|
||||
assert.Error(t, err)
|
||||
assert.Error(t, bfs.Symlink("target", bfs.Join("", "../outside-link")))
|
||||
assert.Error(t, bfs.Rename("inside.txt", bfs.Join("", "../outside-move.txt")))
|
||||
assert.Error(t, bfs.Rename(bfs.Join("", "../outside-secret.txt"), "stolen.txt"))
|
||||
assert.Error(t, bfs.Remove(bfs.Join("", "../outside-secret.txt")))
|
||||
|
||||
// Nothing was created, modified, moved or removed, either outside
|
||||
// the served root or inside it.
|
||||
fstest.CheckListingWithPrecision(t, outside, []fstest.Item{
|
||||
fstest.NewItem("outside-secret.txt", "SECRET", modTime),
|
||||
fstest.NewItem("served-root/inside.txt", "INSIDE", modTime),
|
||||
}, []string{"served-root"}, fs.GetModifyWindow(ctx, outside))
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"os/exec"
|
||||
"strings"
|
||||
@@ -27,6 +28,7 @@ import (
|
||||
libhttp "github.com/rclone/rclone/lib/http"
|
||||
"github.com/rclone/rclone/vfs"
|
||||
"github.com/rclone/rclone/vfs/vfscommon"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
// Help contains text describing how to use the proxy
|
||||
@@ -179,7 +181,8 @@ type Proxy struct {
|
||||
ctx context.Context // for global config
|
||||
Opt Options
|
||||
vfsOpt vfscommon.Options
|
||||
accessKeyMu sync.Mutex // serialises replacing a cached access key entry
|
||||
accessKeyMu sync.Mutex // serialises replacing a cached access key entry
|
||||
calls singleflight.Group // shares the calls made by logins which arrive together
|
||||
}
|
||||
|
||||
// cacheEntry is what is stored in the vfsCache
|
||||
@@ -232,6 +235,13 @@ func New(ctx context.Context, opt *Options, vfsOpt *vfscommon.Options) *Proxy {
|
||||
entry.vfs.Shutdown()
|
||||
}
|
||||
})
|
||||
// Shutting down a VFS stops it writing, so keep one which still
|
||||
// has data to write, e.g. files in the VFS cache waiting to be
|
||||
// uploaded after the transfer which wrote them has finished.
|
||||
p.vfsCache.SetCanExpire(func(value any) bool {
|
||||
entry, ok := value.(cacheEntry)
|
||||
return !ok || entry.vfs == nil || !entry.vfs.Busy()
|
||||
})
|
||||
return p
|
||||
}
|
||||
|
||||
@@ -449,7 +459,13 @@ func (p *Proxy) Call(user, auth string, isPublicKey bool, remoteAddr string) (VF
|
||||
if isPublicKey {
|
||||
kind = authPublicKey
|
||||
}
|
||||
value, err = p.call(user, auth, kind, clientIP)
|
||||
// Logins with the same credentials which arrive together
|
||||
// share one call, as each call which made its own cache
|
||||
// entry would take a reference to the VFS but only the
|
||||
// last entry made would be kept to give its reference back.
|
||||
value, err, _ = p.calls.Do(cacheKey, func() (any, error) {
|
||||
return p.call(user, auth, kind, clientIP)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
@@ -577,6 +593,26 @@ func (p *Provider) Get(ctx context.Context) (*vfs.VFS, error) {
|
||||
return VFS, nil
|
||||
}
|
||||
|
||||
// HoldVFS is HTTP middleware which holds the VFS for the request until
|
||||
// the request has been served.
|
||||
//
|
||||
// An auth proxy shuts down a VFS when it expires from its cache, which
|
||||
// a long upload or download can outlast as only the start of a request
|
||||
// counts as a use of the VFS.
|
||||
func (p *Provider) HoldVFS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Requests which don't need auth, eg CORS preflight, have no VFS
|
||||
if VFS, err := p.Get(r.Context()); err == nil {
|
||||
if !VFS.Hold() {
|
||||
http.Error(w, "VFS has been shut down", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer VFS.Shutdown()
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// VFS returns the fixed VFS, or nil if using an auth proxy.
|
||||
func (p *Provider) VFS() *vfs.VFS {
|
||||
if p == nil {
|
||||
|
||||
@@ -17,6 +17,16 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Note each run in a file if asked to
|
||||
if runLog := os.Getenv("RCLONE_TEST_PROXY_RUN_LOG"); runLog != "" {
|
||||
f, err := os.OpenFile(runLog, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
_, _ = f.WriteString(in["user"] + "\n")
|
||||
_ = f.Close()
|
||||
}
|
||||
|
||||
// Write the output
|
||||
var out = map[string]string{}
|
||||
for k, v := range in {
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -475,3 +477,61 @@ func TestCallAccessKey(t *testing.T) {
|
||||
_, _, err = p.CallAccessKey("AKID", remoteAddr, false)
|
||||
require.ErrorContains(t, err, "revoked")
|
||||
}
|
||||
|
||||
// TestBusyVFSNotExpired checks a VFS which still has data to write
|
||||
// isn't expired from the cache, and so shut down, until it is written.
|
||||
func TestBusyVFSNotExpired(t *testing.T) {
|
||||
opt := Opt
|
||||
opt.AuthProxy = "go run ../servetest/proxy_code.go " + t.TempDir()
|
||||
p := New(context.Background(), &opt, &vfscommon.Opt)
|
||||
defer p.Shutdown()
|
||||
p.vfsCache.SetExpireDuration(time.Millisecond).SetExpireInterval(10 * time.Millisecond)
|
||||
|
||||
VFS, _, err := p.Call("user", "pass", false, "192.0.2.1:1024")
|
||||
require.NoError(t, err)
|
||||
fh, err := VFS.Create("file.txt")
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Never(t, func() bool {
|
||||
return p.vfsCache.Entries() == 0
|
||||
}, 250*time.Millisecond, 10*time.Millisecond, "VFS expired with a file open for write")
|
||||
assert.Equal(t, int32(1), VFS.Stats()["inUse"], "VFS shut down with a file open for write")
|
||||
|
||||
require.NoError(t, fh.Close())
|
||||
assert.Eventually(t, func() bool {
|
||||
return p.vfsCache.Entries() == 0
|
||||
}, 10*time.Second, 10*time.Millisecond, "VFS not expired once it had nothing to write")
|
||||
assert.Equal(t, int32(0), VFS.Stats()["inUse"], "VFS not shut down once it had nothing to write")
|
||||
}
|
||||
|
||||
// TestSimultaneousLogins checks logins with the same credentials which
|
||||
// arrive together share one run of the proxy and one reference to the
|
||||
// VFS, so the VFS is shut down when it expires from the cache.
|
||||
func TestSimultaneousLogins(t *testing.T) {
|
||||
runLog := filepath.Join(t.TempDir(), "runs")
|
||||
t.Setenv("RCLONE_TEST_PROXY_RUN_LOG", runLog)
|
||||
opt := Opt
|
||||
opt.AuthProxy = "go run proxy_code.go"
|
||||
p := New(context.Background(), &opt, &vfscommon.Opt)
|
||||
defer p.Shutdown()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
VFSes := make([]*vfs.VFS, 4)
|
||||
for i := range VFSes {
|
||||
wg.Go(func() {
|
||||
var err error
|
||||
VFSes[i], _, err = p.Call("user", "pass", false, "192.0.2.1:1024")
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
runs, err := os.ReadFile(runLog)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "user\n", string(runs), "proxy run more than once")
|
||||
for _, VFS := range VFSes {
|
||||
require.Same(t, VFSes[0], VFS)
|
||||
}
|
||||
assert.Equal(t, 1, p.vfsCache.Entries())
|
||||
assert.Equal(t, int32(1), VFSes[0].Stats()["inUse"], "VFS referenced more than once")
|
||||
}
|
||||
+57
-13
@@ -13,6 +13,7 @@ import (
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -208,11 +209,13 @@ with a path of ` + "`/<username>/`" + `.
|
||||
stdout: os.Stdout,
|
||||
}
|
||||
|
||||
httpSrv := &http2.Server{}
|
||||
opts := &http2.ServeConnOpts{
|
||||
// http.Server can't serve a single net.Conn so the
|
||||
// deprecated http2.Server is still needed here.
|
||||
httpSrv := &http2.Server{} //nolint:staticcheck // see above
|
||||
opts := &http2.ServeConnOpts{ //nolint:staticcheck // see above
|
||||
Handler: s.server.Router(),
|
||||
}
|
||||
httpSrv.ServeConn(conn, opts)
|
||||
httpSrv.ServeConn(conn, opts) //nolint:staticcheck // see above
|
||||
return nil
|
||||
}
|
||||
fs.Logf(s.f, "Serving restic REST API on %s", s.server.URLs())
|
||||
@@ -283,19 +286,28 @@ func checkPrivate(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// uploadLock serializes uploads to one remote.
|
||||
type uploadLock struct {
|
||||
uploadingMu sync.Mutex
|
||||
refs int // protected by server.uploadLocksMu
|
||||
}
|
||||
|
||||
// server contains everything to run the server
|
||||
type server struct {
|
||||
server *libhttp.Server
|
||||
f fs.Fs
|
||||
cache *cache
|
||||
opt Options
|
||||
server *libhttp.Server
|
||||
f fs.Fs
|
||||
cache *cache
|
||||
opt Options
|
||||
uploadLocksMu sync.Mutex
|
||||
uploadLocks map[string]*uploadLock
|
||||
}
|
||||
|
||||
func newServer(ctx context.Context, f fs.Fs, opt *Options) (s *server, err error) {
|
||||
s = &server{
|
||||
f: f,
|
||||
cache: newCache(opt.CacheObjects),
|
||||
opt: *opt,
|
||||
f: f,
|
||||
cache: newCache(opt.CacheObjects),
|
||||
opt: *opt,
|
||||
uploadLocks: make(map[string]*uploadLock),
|
||||
}
|
||||
// Don't bind any HTTP listeners if running with --stdio
|
||||
if opt.Stdio {
|
||||
@@ -313,6 +325,30 @@ func newServer(ctx context.Context, f fs.Fs, opt *Options) (s *server, err error
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// lockUpload locks uploads to remote and returns its unlock function.
|
||||
func (s *server) lockUpload(remote string) func() {
|
||||
s.uploadLocksMu.Lock()
|
||||
lock := s.uploadLocks[remote]
|
||||
if lock == nil {
|
||||
lock = new(uploadLock)
|
||||
s.uploadLocks[remote] = lock
|
||||
}
|
||||
lock.refs++
|
||||
s.uploadLocksMu.Unlock()
|
||||
|
||||
lock.uploadingMu.Lock()
|
||||
return func() {
|
||||
lock.uploadingMu.Unlock()
|
||||
|
||||
s.uploadLocksMu.Lock()
|
||||
lock.refs--
|
||||
if lock.refs == 0 {
|
||||
delete(s.uploadLocks, remote)
|
||||
}
|
||||
s.uploadLocksMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// Serve restic until the server is shutdown
|
||||
func (s *server) Serve() error {
|
||||
s.server.Serve()
|
||||
@@ -377,7 +413,8 @@ func (s *server) Bind(router chi.Router) {
|
||||
}
|
||||
}
|
||||
|
||||
var matchData = regexp.MustCompile("(?:^|/)data/([^/]{2,})$")
|
||||
// Restic pack names are lowercase hexadecimal storage IDs.
|
||||
var matchData = regexp.MustCompile("(?:^|/)data/([0-9a-f]{2,})$")
|
||||
|
||||
// newObject returns an object with the remote given either from the
|
||||
// cache or directly
|
||||
@@ -422,12 +459,19 @@ func (s *server) postObject(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if s.opt.AppendOnly {
|
||||
// make sure the file does not exist yet
|
||||
unlock := s.lockUpload(remote)
|
||||
defer unlock()
|
||||
|
||||
// Only a definitive not-found result permits creating the object.
|
||||
_, err := s.newObject(r.Context(), remote)
|
||||
if err == nil {
|
||||
fs.Errorf(remote, "Post request: file already exists, refusing to overwrite in append-only mode")
|
||||
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, fs.ErrorObjectNotFound) {
|
||||
fs.Errorf(remote, "Post request: failed to check whether file exists: %v", err)
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,17 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/rclone/rclone/cmd"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/configfile"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -135,3 +139,60 @@ func TestResticHandler(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendOnlyFailsClosedOnLookupError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
configfile.Install()
|
||||
|
||||
underlying := cmd.NewFsSrc([]string{t.TempDir()})
|
||||
f := &newObjectErrorFs{
|
||||
Fs: underlying,
|
||||
err: errors.New("lookup failed"),
|
||||
}
|
||||
opt := newOpt()
|
||||
opt.AppendOnly = true
|
||||
s, err := newServer(ctx, f, &opt)
|
||||
require.NoError(t, err)
|
||||
|
||||
req := newRequest(t, "POST", "/config", strings.NewReader("replacement"))
|
||||
checkRequest(t, s.server.Router().ServeHTTP, req, []wantFunc{wantCode(http.StatusInternalServerError)})
|
||||
|
||||
_, err = underlying.NewObject(ctx, "config")
|
||||
assert.ErrorIs(t, err, fs.ErrorObjectNotFound)
|
||||
}
|
||||
|
||||
func TestAppendOnlyConcurrentUploads(t *testing.T) {
|
||||
configfile.Install()
|
||||
opt := newOpt()
|
||||
opt.AppendOnly = true
|
||||
f := cmd.NewFsSrc([]string{t.TempDir()})
|
||||
s, err := newServer(context.Background(), f, &opt)
|
||||
require.NoError(t, err)
|
||||
handler := s.server.Router().ServeHTTP
|
||||
|
||||
const uploads = 10
|
||||
start := make(chan struct{})
|
||||
results := make(chan int, uploads)
|
||||
for range uploads {
|
||||
go func() {
|
||||
req := newRequest(t, "POST", "/config", strings.NewReader("config data"))
|
||||
recorder := httptest.NewRecorder()
|
||||
<-start
|
||||
handler(recorder, req)
|
||||
results <- recorder.Code
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
|
||||
succeeded := 0
|
||||
for range uploads {
|
||||
if code := <-results; code == http.StatusOK {
|
||||
succeeded++
|
||||
} else {
|
||||
assert.Equal(t, http.StatusForbidden, code)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, succeeded)
|
||||
checkRequest(t, handler, newRequest(t, "GET", "/config", nil),
|
||||
[]wantFunc{wantCode(http.StatusOK), wantBody("config data")})
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
_ "github.com/rclone/rclone/backend/all"
|
||||
@@ -106,6 +108,17 @@ func TestMakeRemote(t *testing.T) {
|
||||
{"/data/12", "data/12/12"},
|
||||
{"/data/123", "data/12/123"},
|
||||
{"/data/123/", "data/12/123"},
|
||||
{"/data/abcdef", "data/ab/abcdef"},
|
||||
{"/data/config", "data/config"},
|
||||
{"/data/data/", "data/data"},
|
||||
{"/data/index/", "data/index"},
|
||||
{"/data/keys/", "data/keys"},
|
||||
{"/data/locks/", "data/locks"},
|
||||
{"/data/snapshots/", "data/snapshots"},
|
||||
{"/data/data/abcdef", "data/data/ab/abcdef"},
|
||||
{"/repo/data/config", "repo/data/config"},
|
||||
{"/repo/data/keys/", "repo/data/keys"},
|
||||
{"/repo/data/data/abcdef", "repo/data/data/ab/abcdef"},
|
||||
{"/keys", "keys"},
|
||||
{"/keys/1", "keys/1"},
|
||||
{"/keys/12", "keys/12"},
|
||||
@@ -123,6 +136,46 @@ func TestMakeRemote(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResticDataRepository(t *testing.T) {
|
||||
for _, repo := range []string{"data", "repo/data"} {
|
||||
t.Run(repo, func(t *testing.T) {
|
||||
tempdir := t.TempDir()
|
||||
f := cmd.NewFsSrc([]string{tempdir})
|
||||
opt := newOpt()
|
||||
s, err := newServer(context.Background(), f, &opt)
|
||||
require.NoError(t, err)
|
||||
handler := s.server.Router().ServeHTTP
|
||||
checkRequest(t, handler, newRequest(t, "POST", "/"+repo+"/?create=true", nil),
|
||||
[]wantFunc{wantCode(http.StatusOK)})
|
||||
|
||||
const id = "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789"
|
||||
for _, object := range []struct {
|
||||
url, remote string
|
||||
}{
|
||||
{"config", "config"},
|
||||
{"keys/" + id, "keys/" + id},
|
||||
{"data/" + id, "data/ab/" + id},
|
||||
} {
|
||||
url := "/" + repo + "/" + object.url
|
||||
checkRequest(t, handler, newRequest(t, "POST", url, strings.NewReader("test content")),
|
||||
[]wantFunc{wantCode(http.StatusOK)})
|
||||
checkRequest(t, handler, newRequest(t, "GET", url, nil),
|
||||
[]wantFunc{wantCode(http.StatusOK), wantBody("test content")})
|
||||
content, err := os.ReadFile(filepath.Join(tempdir, repo, object.remote))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "test content", string(content))
|
||||
}
|
||||
|
||||
for _, dir := range []string{"keys", "data"} {
|
||||
checkRequest(t, handler, newRequest(t, "GET", "/"+repo+"/"+dir+"/", nil),
|
||||
[]wantFunc{wantCode(http.StatusOK), func(t testing.TB, res *httptest.ResponseRecorder) {
|
||||
assert.JSONEq(t, `[{"name":"`+id+`","size":12}]`, res.Body.String())
|
||||
}})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type listErrorFs struct {
|
||||
fs.Fs
|
||||
}
|
||||
|
||||
+160
-85
@@ -6,13 +6,17 @@ import (
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"maps"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
lru "github.com/hashicorp/golang-lru/v2"
|
||||
"github.com/ncw/swift/v2"
|
||||
"github.com/rclone/gofakes3"
|
||||
"github.com/rclone/rclone/fs"
|
||||
@@ -38,12 +42,14 @@ const putObjectPrefix = tempObjectPrefix + "put_"
|
||||
// multipart uploads stream straight through to the underlying Fs via
|
||||
// PutStream, instead of being buffered in memory by gofakes3.
|
||||
type s3Backend struct {
|
||||
s *Server
|
||||
meta *sync.Map
|
||||
s *Server
|
||||
|
||||
// multipartUploads tracks in-flight streaming multipart uploads,
|
||||
// keyed by gofakes3.UploadID.
|
||||
multipartUploads sync.Map
|
||||
tenantsMu sync.Mutex
|
||||
tenants map[string]*tenant // per-user state by tenant ID
|
||||
|
||||
// warnMaxUploadsOnce logs a single NOTICE the first time a multipart
|
||||
// upload is refused by --multipart-max-uploads.
|
||||
warnMaxUploadsOnce sync.Once
|
||||
|
||||
// warnInMemoryOnce logs a single NOTICE the first time a multipart
|
||||
// upload falls back to being buffered in memory.
|
||||
@@ -53,15 +59,149 @@ type s3Backend struct {
|
||||
reaperStop sync.Once
|
||||
}
|
||||
|
||||
// tenant is the state kept between requests for one user of the server.
|
||||
//
|
||||
// Anything remembered about a user's objects or uploads must be reached
|
||||
// through their tenant, as different users may be serving different
|
||||
// backends.
|
||||
type tenant struct {
|
||||
b *s3Backend
|
||||
id string
|
||||
|
||||
// uploads tracks in-flight streaming multipart uploads,
|
||||
// keyed by gofakes3.UploadID.
|
||||
uploads sync.Map
|
||||
|
||||
// nUploads counts the in-flight uploads, limited by
|
||||
// --multipart-max-uploads.
|
||||
nUploads atomic.Int64
|
||||
|
||||
// budget limits the memory buffered by all the multipart uploads,
|
||||
// set by --multipart-streaming-buffer-total.
|
||||
budget *bufferBudget
|
||||
|
||||
// meta is the stored metadata of objects, by object path.
|
||||
meta *lru.Cache[string, objectMeta]
|
||||
}
|
||||
|
||||
// objectMeta is the metadata stored for an object, with the size and
|
||||
// modification time the object had when it was stored.
|
||||
type objectMeta struct {
|
||||
meta map[string]string
|
||||
size int64
|
||||
modTime time.Time
|
||||
}
|
||||
|
||||
// newMetadataStore makes a store for the metadata of up to maxObjects
|
||||
// objects, forgetting that of the least recently used after that. If
|
||||
// maxObjects <= 0 there is no limit.
|
||||
func newMetadataStore(maxObjects int) *lru.Cache[string, objectMeta] {
|
||||
if maxObjects <= 0 {
|
||||
maxObjects = math.MaxInt
|
||||
}
|
||||
meta, err := lru.New[string, objectMeta](maxObjects)
|
||||
if err != nil {
|
||||
panic(err) // only fails if maxObjects <= 0
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
// newBackend creates a new SimpleBucketBackend.
|
||||
func newBackend(s *Server) *s3Backend {
|
||||
return &s3Backend{
|
||||
s: s,
|
||||
meta: new(sync.Map),
|
||||
tenants: map[string]*tenant{},
|
||||
reaperQuit: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// tenant returns the state of the user making the request in ctx.
|
||||
func (b *s3Backend) tenant(ctx context.Context) *tenant {
|
||||
id := b.s.getTenant(ctx)
|
||||
b.tenantsMu.Lock()
|
||||
defer b.tenantsMu.Unlock()
|
||||
t, ok := b.tenants[id]
|
||||
if !ok {
|
||||
t = &tenant{
|
||||
b: b,
|
||||
id: id,
|
||||
budget: newBufferBudget(int64(b.s.opt.MultipartStreamingBufferTotal)),
|
||||
meta: newMetadataStore(b.s.opt.MetadataMaxObjects),
|
||||
}
|
||||
b.tenants[id] = t
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// allTenants returns the state of every user seen so far.
|
||||
func (b *s3Backend) allTenants() []*tenant {
|
||||
b.tenantsMu.Lock()
|
||||
defer b.tenantsMu.Unlock()
|
||||
return slices.Collect(maps.Values(b.tenants))
|
||||
}
|
||||
|
||||
// context returns a context for requests made on behalf of t.
|
||||
func (t *tenant) context() context.Context {
|
||||
return context.WithValue(context.Background(), ctxKeyAccessKeyID, t.id)
|
||||
}
|
||||
|
||||
// getMeta returns the stored metadata of node, the object at fp.
|
||||
//
|
||||
// Nothing is returned if the object has changed since the metadata was
|
||||
// stored, as it has been replaced by something other than this user.
|
||||
func (t *tenant) getMeta(ctx context.Context, fp string, node vfs.Node) (meta map[string]string, ok bool) {
|
||||
om, ok := t.meta.Get(fp)
|
||||
if !ok || om.size != node.Size() {
|
||||
return nil, false
|
||||
}
|
||||
window := fs.GetModifyWindow(ctx, node.VFS().Fs())
|
||||
if window != fs.ModTimeNotSupported {
|
||||
if dt := node.ModTime().Sub(om.modTime); dt < -window || dt > window {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return om.meta, true
|
||||
}
|
||||
|
||||
// storeMeta stores meta as the metadata of the object at fp in _vfs.
|
||||
//
|
||||
// If meta has a modification time in "X-Amz-Meta-Mtime" or "mtime" the
|
||||
// object's modification time is set to it, returning any error, and
|
||||
// both are set to it in meta.
|
||||
func (t *tenant) storeMeta(_vfs *vfs.VFS, fp string, meta map[string]string) (err error) {
|
||||
for _, key := range []string{"X-Amz-Meta-Mtime", "mtime"} {
|
||||
val, ok := meta[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ti, parseErr := swift.FloatStringToTime(val)
|
||||
if parseErr != nil {
|
||||
continue
|
||||
}
|
||||
meta["X-Amz-Meta-Mtime"] = val
|
||||
meta["mtime"] = val
|
||||
err = _vfs.Chtimes(fp, ti, ti)
|
||||
break
|
||||
}
|
||||
// Stat after setting the modification time as getMeta compares with it
|
||||
node, statErr := _vfs.Stat(fp)
|
||||
if statErr != nil {
|
||||
t.removeMeta(fp)
|
||||
return err
|
||||
}
|
||||
t.meta.Add(fp, objectMeta{
|
||||
meta: meta,
|
||||
size: node.Size(),
|
||||
modTime: node.ModTime(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// removeMeta forgets the metadata of the object at fp.
|
||||
func (t *tenant) removeMeta(fp string) {
|
||||
t.meta.Remove(fp)
|
||||
}
|
||||
|
||||
// ListBuckets always returns the default bucket.
|
||||
func (b *s3Backend) ListBuckets(ctx context.Context) ([]gofakes3.BucketInfo, error) {
|
||||
_vfs, err := b.s.getVFS(ctx)
|
||||
@@ -111,7 +251,7 @@ func (b *s3Backend) ListBucket(ctx context.Context, bucket string, prefix *gofak
|
||||
response := gofakes3.NewObjectList()
|
||||
path, remaining := prefixParser(prefix)
|
||||
|
||||
err = b.entryListR(_vfs, bucket, path, remaining, prefix.HasDelimiter, response)
|
||||
err = b.listPage(_vfs, bucket, path, remaining, prefix.HasDelimiter, page, response)
|
||||
if err == gofakes3.ErrNoSuchKey {
|
||||
// AWS just returns an empty list
|
||||
response = gofakes3.NewObjectList()
|
||||
@@ -119,7 +259,7 @@ func (b *s3Backend) ListBucket(ctx context.Context, bucket string, prefix *gofak
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return b.pager(response, page)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// formatHeaderTime makes an timestamp which is the same as that used by AWS.
|
||||
@@ -163,7 +303,7 @@ func (b *s3Backend) HeadObject(ctx context.Context, bucketName, objectName strin
|
||||
// to hashing the VFS cache when the backing object is not available yet.
|
||||
entry := node.DirEntry()
|
||||
size := node.Size()
|
||||
hash := getFileHashByte(node, b.s.etagHashType)
|
||||
hash := getFileHashByte(node, b.s.etagHash(_vfs))
|
||||
|
||||
mimeType := fs.MimeTypeFromName(objectName)
|
||||
if fobj, ok := entry.(fs.Object); ok {
|
||||
@@ -175,8 +315,7 @@ func (b *s3Backend) HeadObject(ctx context.Context, bucketName, objectName strin
|
||||
"Content-Type": mimeType,
|
||||
}
|
||||
|
||||
if val, ok := b.meta.Load(fp); ok {
|
||||
metaMap := val.(map[string]string)
|
||||
if metaMap, ok := b.tenant(ctx).getMeta(ctx, fp, node); ok {
|
||||
maps.Copy(meta, metaMap)
|
||||
}
|
||||
|
||||
@@ -220,7 +359,7 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
|
||||
file := node.(*vfs.File)
|
||||
|
||||
size := node.Size()
|
||||
hash := getFileHashByte(node, b.s.etagHashType)
|
||||
hash := getFileHashByte(node, b.s.etagHash(_vfs))
|
||||
|
||||
in, err := file.Open(os.O_RDONLY)
|
||||
if err != nil {
|
||||
@@ -256,8 +395,7 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
|
||||
"Content-Type": mimeType,
|
||||
}
|
||||
|
||||
if val, ok := b.meta.Load(fp); ok {
|
||||
metaMap := val.(map[string]string)
|
||||
if metaMap, ok := b.tenant(ctx).getMeta(ctx, fp, node); ok {
|
||||
maps.Copy(meta, metaMap)
|
||||
}
|
||||
|
||||
@@ -271,14 +409,6 @@ func (b *s3Backend) GetObject(ctx context.Context, bucketName, objectName string
|
||||
}, nil
|
||||
}
|
||||
|
||||
// storeModtime sets both "mtime" and "X-Amz-Meta-Mtime" to val in b.meta.
|
||||
// Call this whenever modtime is updated.
|
||||
func (b *s3Backend) storeModtime(fp string, meta map[string]string, val string) {
|
||||
meta["X-Amz-Meta-Mtime"] = val
|
||||
meta["mtime"] = val
|
||||
b.meta.Store(fp, meta)
|
||||
}
|
||||
|
||||
// TouchObject creates or updates meta on specified object.
|
||||
func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]string) (result gofakes3.PutObjectResult, err error) {
|
||||
_vfs, err := b.s.getVFS(ctx)
|
||||
@@ -302,27 +432,7 @@ func (b *s3Backend) TouchObject(ctx context.Context, fp string, meta map[string]
|
||||
return result, err
|
||||
}
|
||||
|
||||
b.meta.Store(fp, meta)
|
||||
|
||||
if val, ok := meta["X-Amz-Meta-Mtime"]; ok {
|
||||
ti, err := swift.FloatStringToTime(val)
|
||||
if err == nil {
|
||||
b.storeModtime(fp, meta, val)
|
||||
return result, _vfs.Chtimes(fp, ti, ti)
|
||||
}
|
||||
// ignore error since the file is successfully created
|
||||
}
|
||||
|
||||
if val, ok := meta["mtime"]; ok {
|
||||
ti, err := swift.FloatStringToTime(val)
|
||||
if err == nil {
|
||||
b.storeModtime(fp, meta, val)
|
||||
return result, _vfs.Chtimes(fp, ti, ti)
|
||||
}
|
||||
// ignore error since the file is successfully created
|
||||
}
|
||||
|
||||
return result, nil
|
||||
return result, b.tenant(ctx).storeMeta(_vfs, fp, meta)
|
||||
}
|
||||
|
||||
// PutObject creates or overwrites the object with the given name.
|
||||
@@ -423,27 +533,7 @@ func (b *s3Backend) PutObject(
|
||||
return result, err
|
||||
}
|
||||
|
||||
b.meta.Store(fp, meta)
|
||||
|
||||
if val, ok := meta["X-Amz-Meta-Mtime"]; ok {
|
||||
ti, err := swift.FloatStringToTime(val)
|
||||
if err == nil {
|
||||
b.storeModtime(fp, meta, val)
|
||||
return result, _vfs.Chtimes(fp, ti, ti)
|
||||
}
|
||||
// ignore error since the file is successfully created
|
||||
}
|
||||
|
||||
if val, ok := meta["mtime"]; ok {
|
||||
ti, err := swift.FloatStringToTime(val)
|
||||
if err == nil {
|
||||
b.storeModtime(fp, meta, val)
|
||||
return result, _vfs.Chtimes(fp, ti, ti)
|
||||
}
|
||||
// ignore error since the file is successfully created
|
||||
}
|
||||
|
||||
return result, nil
|
||||
return result, b.tenant(ctx).storeMeta(_vfs, fp, meta)
|
||||
}
|
||||
|
||||
// DeleteMulti deletes multiple objects in a single request.
|
||||
@@ -491,6 +581,7 @@ func (b *s3Backend) deleteObject(ctx context.Context, bucketName, objectName str
|
||||
if err := _vfs.Remove(fp); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
b.tenant(ctx).removeMeta(fp)
|
||||
|
||||
// FIXME: unsafe operation
|
||||
rmdirRecursive(fp, _vfs)
|
||||
@@ -560,28 +651,12 @@ func (b *s3Backend) CopyObject(ctx context.Context, srcBucket, srcKey, dstBucket
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if srcBucket == dstBucket && srcKey == dstKey {
|
||||
b.meta.Store(fp, meta)
|
||||
|
||||
val, ok := meta["X-Amz-Meta-Mtime"]
|
||||
if !ok {
|
||||
if val, ok = meta["mtime"]; !ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
// update modtime
|
||||
ti, err := swift.FloatStringToTime(val)
|
||||
if err != nil {
|
||||
return result, nil
|
||||
}
|
||||
b.storeModtime(fp, meta, val)
|
||||
|
||||
return result, _vfs.Chtimes(fp, ti, ti)
|
||||
}
|
||||
|
||||
cStat, err := _vfs.Stat(fp)
|
||||
if err != nil {
|
||||
return
|
||||
if err != nil || !cStat.IsFile() {
|
||||
return result, gofakes3.KeyNotFound(srcKey)
|
||||
}
|
||||
if srcBucket == dstBucket && srcKey == dstKey {
|
||||
return result, b.tenant(ctx).storeMeta(_vfs, fp, meta)
|
||||
}
|
||||
|
||||
c, err := b.GetObject(ctx, srcBucket, srcKey, nil)
|
||||
|
||||
@@ -2,17 +2,23 @@ package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rclone/gofakes3"
|
||||
_ "github.com/rclone/rclone/backend/crypt"
|
||||
_ "github.com/rclone/rclone/backend/local"
|
||||
"github.com/rclone/rclone/cmd/serve/proxy"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/config/obscure"
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
"github.com/rclone/rclone/fstest"
|
||||
"github.com/rclone/rclone/vfs"
|
||||
"github.com/rclone/rclone/vfs/vfscommon"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -180,3 +186,124 @@ func TestBucketDirPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEtagHashAuto checks that --etag-hash auto uses the best hash of
|
||||
// the backend of each auth proxy user rather than of the remote the
|
||||
// server was started with, which may have none or not exist at all.
|
||||
func TestEtagHashAuto(t *testing.T) {
|
||||
fstest.Initialise()
|
||||
ctx := context.Background()
|
||||
opt := Opt
|
||||
opt.EtagHash = "auto"
|
||||
opt.HTTP.ListenAddr = []string{endpoint}
|
||||
proxyOpt := proxy.Opt
|
||||
proxyOpt.AuthProxy = "/path/to/auth/proxy"
|
||||
|
||||
fCrypt, err := fs.NewFs(ctx, ":crypt,remote='"+t.TempDir()+"',password="+obscure.MustObscure("password")+":")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, hash.None, fCrypt.Hashes().GetOne(), "crypt has no hashes")
|
||||
for _, f := range []fs.Fs{nil, fCrypt} {
|
||||
w, err := newServer(ctx, f, &opt, &vfscommon.Opt, &proxyOpt)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = w.Shutdown() })
|
||||
|
||||
fUser, err := fs.NewFs(ctx, t.TempDir())
|
||||
require.NoError(t, err)
|
||||
userVFS := vfs.New(ctx, fUser, &vfscommon.Opt)
|
||||
t.Cleanup(userVFS.Shutdown)
|
||||
ctx := context.WithValue(ctx, ctxKeyID, userVFS)
|
||||
require.NoError(t, w.backend.CreateBucket(ctx, "bucket"))
|
||||
_, err = w.backend.PutObject(ctx, "bucket", "object", nil, strings.NewReader("data"), 4)
|
||||
require.NoError(t, err)
|
||||
|
||||
obj, err := w.backend.HeadObject(ctx, "bucket", "object")
|
||||
require.NoError(t, err)
|
||||
want := md5.Sum([]byte("data"))
|
||||
assert.Equal(t, want[:], obj.Hash)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCopyObjectMissingSource checks that copying an object which
|
||||
// doesn't exist fails with NoSuchKey, including a copy onto itself to
|
||||
// replace its metadata.
|
||||
func TestCopyObjectMissingSource(t *testing.T) {
|
||||
b, _ := newTestBackend(t)
|
||||
ctx := context.Background()
|
||||
for _, dstKey := range []string{"missing.txt", "other.txt"} {
|
||||
_, err := b.CopyObject(ctx, "bucket", "missing.txt", "bucket", dstKey, map[string]string{"X-Amz-Meta-Colour": "red"})
|
||||
assert.True(t, gofakes3.HasErrorCode(err, gofakes3.ErrNoSuchKey), "copy to %q: %v", dstKey, err)
|
||||
}
|
||||
_, err := b.HeadObject(ctx, "bucket", "other.txt")
|
||||
assert.True(t, gofakes3.HasErrorCode(err, gofakes3.ErrNoSuchKey))
|
||||
}
|
||||
|
||||
// tenantCtx returns the context of a request authenticated by the auth
|
||||
// proxy as accessKeyID.
|
||||
func tenantCtx(accessKeyID string) context.Context {
|
||||
return context.WithValue(context.Background(), ctxKeyAccessKeyID, accessKeyID)
|
||||
}
|
||||
|
||||
// TestMetadataOtherTenant checks that with an auth proxy the metadata
|
||||
// one user (access key ID) stores for an object isn't returned for
|
||||
// another user's object at the same path.
|
||||
func TestMetadataOtherTenant(t *testing.T) {
|
||||
b, _ := newTestBackend(t)
|
||||
ctxA, ctxB := tenantCtx("tenantA"), tenantCtx("tenantB")
|
||||
const secretKey = "X-Amz-Meta-Secret"
|
||||
|
||||
put := func(ctx context.Context, meta map[string]string) {
|
||||
_, err := b.PutObject(ctx, "bucket", "meta.txt", meta, strings.NewReader("data"), 4)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
head := func(ctx context.Context) map[string]string {
|
||||
obj, err := b.HeadObject(ctx, "bucket", "meta.txt")
|
||||
require.NoError(t, err)
|
||||
return obj.Metadata
|
||||
}
|
||||
|
||||
put(ctxB, map[string]string{})
|
||||
put(ctxA, map[string]string{secretKey: "tenantA's"})
|
||||
|
||||
assert.Equal(t, "tenantA's", head(ctxA)[secretKey])
|
||||
assert.NotContains(t, head(ctxB), secretKey)
|
||||
|
||||
obj, err := b.GetObject(ctxB, "bucket", "meta.txt", nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, obj.Contents.Close())
|
||||
assert.NotContains(t, obj.Metadata, secretKey)
|
||||
}
|
||||
|
||||
// TestMetadataStale checks that the metadata stored for an object isn't
|
||||
// returned once the object has been changed by someone else: another
|
||||
// auth proxy user sharing the backend or a change to the backend itself.
|
||||
func TestMetadataStale(t *testing.T) {
|
||||
b, root := newTestBackend(t)
|
||||
ctxA, ctxB := tenantCtx("tenantA"), tenantCtx("tenantB")
|
||||
const key = "X-Amz-Meta-Colour"
|
||||
objPath := filepath.Join(root, "bucket", "meta.txt")
|
||||
|
||||
put := func(ctx context.Context, meta map[string]string, data string) {
|
||||
_, err := b.PutObject(ctx, "bucket", "meta.txt", meta, strings.NewReader(data), int64(len(data)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
colour := func(ctx context.Context) string {
|
||||
_vfs, err := b.s.getVFS(ctx)
|
||||
require.NoError(t, err)
|
||||
b.forgetPath(_vfs, "bucket/meta.txt")
|
||||
obj, err := b.HeadObject(ctx, "bucket", "meta.txt")
|
||||
require.NoError(t, err)
|
||||
return obj.Metadata[key]
|
||||
}
|
||||
|
||||
put(ctxA, map[string]string{key: "red"}, "data")
|
||||
assert.Equal(t, "red", colour(ctxA))
|
||||
|
||||
put(ctxB, map[string]string{}, "other data")
|
||||
assert.Equal(t, "", colour(ctxA), "metadata kept after another user replaced the object")
|
||||
|
||||
put(ctxA, map[string]string{key: "blue"}, "data")
|
||||
assert.Equal(t, "blue", colour(ctxA))
|
||||
later := time.Now().Add(time.Hour)
|
||||
require.NoError(t, os.Chtimes(objPath, later, later))
|
||||
assert.Equal(t, "", colour(ctxA), "metadata kept after the object was changed on the backend")
|
||||
}
|
||||
+168
-14
@@ -1,10 +1,14 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/rclone/gofakes3"
|
||||
"github.com/rclone/rclone/fs"
|
||||
"github.com/rclone/rclone/fs/hash"
|
||||
"github.com/rclone/rclone/vfs"
|
||||
)
|
||||
|
||||
@@ -13,17 +17,139 @@ import (
|
||||
// (rclone v1.75); leftovers from an older server are still hidden.
|
||||
const legacyMultipartUploadPrefix = ".rclone_multipart_upload_"
|
||||
|
||||
func (b *s3Backend) entryListR(_vfs *vfs.VFS, bucketName, fdPath, name string, addPrefix bool, response *gofakes3.ObjectList) error {
|
||||
fp, err := bucketDirPath(bucketName, fdPath)
|
||||
// errPageFull is returned by the listing walk once the page has been filled
|
||||
// and one further key has been seen, so the walk can unwind early. It never
|
||||
// escapes ListBucket.
|
||||
var errPageFull = errors.New("listing page full")
|
||||
|
||||
// lister walks a directory tree emitting one page of an S3 listing.
|
||||
//
|
||||
// The walk emits keys in flat S3 order and stops as soon as the page is full,
|
||||
// so the cost of a page is proportional to the keys it returns rather than to
|
||||
// the size of the subtree below the prefix.
|
||||
type lister struct {
|
||||
vfs *vfs.VFS
|
||||
hashType hash.Type // hash used for ETags
|
||||
bucket string
|
||||
marker string // keys at or before this one have already been returned
|
||||
hasMarker bool
|
||||
max int // number of keys wanted in this page
|
||||
response *gofakes3.ObjectList
|
||||
keys int // keys added to the page so far
|
||||
lastKey string // the last key added to the page
|
||||
dirsRead int // directories read, for debug logging
|
||||
}
|
||||
|
||||
// newLister makes a lister which fills response with at most one page of the
|
||||
// listing of bucket, as described by page.
|
||||
func newLister(b *s3Backend, _vfs *vfs.VFS, bucket string, page gofakes3.ListBucketPage, response *gofakes3.ObjectList) *lister {
|
||||
max := int(page.MaxKeys)
|
||||
if max <= 0 {
|
||||
// A missing or zero max-keys means the client didn't ask for a
|
||||
// particular page size, so use the S3 maximum.
|
||||
max = 1000
|
||||
}
|
||||
return &lister{
|
||||
vfs: _vfs,
|
||||
hashType: b.s.etagHash(_vfs),
|
||||
bucket: bucket,
|
||||
marker: page.Marker,
|
||||
hasMarker: page.HasMarker,
|
||||
max: max,
|
||||
response: response,
|
||||
}
|
||||
}
|
||||
|
||||
// truncate marks the page as truncated after the last key added to it, so
|
||||
// that the next page resumes from there, and returns errPageFull.
|
||||
func (l *lister) truncate() error {
|
||||
l.response.IsTruncated = true
|
||||
l.response.NextMarker = l.lastKey
|
||||
return errPageFull
|
||||
}
|
||||
|
||||
// sortKey returns the S3 key an entry contributes to the listing.
|
||||
//
|
||||
// Directories sort as if they carried their trailing slash, which is what
|
||||
// makes a depth first walk emit keys in the same order as the flat keyspace
|
||||
// of a real S3 bucket.
|
||||
func sortKey(entry vfs.Node) string {
|
||||
if entry.IsDir() {
|
||||
return entry.Name() + "/"
|
||||
}
|
||||
return entry.Name()
|
||||
}
|
||||
|
||||
// skipKey reports whether key has already been returned by an earlier page.
|
||||
func (l *lister) skipKey(key string) bool {
|
||||
return l.hasMarker && key <= l.marker
|
||||
}
|
||||
|
||||
// skipDir reports whether every key under the directory prefix p was returned
|
||||
// by an earlier page, so the subtree need not be read at all.
|
||||
//
|
||||
// A marker inside the subtree has p as a prefix and is never skipped: that
|
||||
// subtree is descended and filtered key by key.
|
||||
func (l *lister) skipDir(p string) bool {
|
||||
return l.hasMarker && l.marker > p && !strings.HasPrefix(l.marker, p)
|
||||
}
|
||||
|
||||
// addCommonPrefix adds a common prefix to the page, returning errPageFull if
|
||||
// the page is now complete.
|
||||
func (l *lister) addCommonPrefix(prefix string) error {
|
||||
if l.keys >= l.max {
|
||||
return l.truncate()
|
||||
}
|
||||
l.response.AddPrefix(prefix)
|
||||
l.keys++
|
||||
l.lastKey = prefix
|
||||
return nil
|
||||
}
|
||||
|
||||
// addObject adds an object to the page, returning errPageFull if the page is
|
||||
// now complete.
|
||||
func (l *lister) addObject(key string, entry vfs.Node) error {
|
||||
if l.keys >= l.max {
|
||||
return l.truncate()
|
||||
}
|
||||
l.response.Add(&gofakes3.Content{
|
||||
Key: key,
|
||||
LastModified: gofakes3.NewContentTime(entry.ModTime()),
|
||||
ETag: getFileHash(entry, l.hashType),
|
||||
Size: entry.Size(),
|
||||
StorageClass: gofakes3.StorageStandard,
|
||||
})
|
||||
l.keys++
|
||||
l.lastKey = key
|
||||
return nil
|
||||
}
|
||||
|
||||
// list walks the directory fdPath, adding the entries whose leaf name starts
|
||||
// with name to the page.
|
||||
//
|
||||
// If addPrefix is set, subdirectories are reported as common prefixes,
|
||||
// otherwise they are descended into.
|
||||
//
|
||||
// It returns errPageFull once the page is complete, and gofakes3.ErrNoSuchKey
|
||||
// if fdPath is not a directory.
|
||||
func (l *lister) list(fdPath, name string, addPrefix bool) error {
|
||||
fp, err := bucketDirPath(l.bucket, fdPath)
|
||||
if err != nil {
|
||||
// A listing prefix that can't be represented as a path matches nothing.
|
||||
return gofakes3.ErrNoSuchKey
|
||||
}
|
||||
|
||||
dirEntries, err := getDirEntries(fp, _vfs)
|
||||
dirEntries, err := getDirEntries(fp, l.vfs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.dirsRead++
|
||||
|
||||
// Emit the entries in the order their keys have in a flat keyspace,
|
||||
// which is not the plain name order getDirEntries returns.
|
||||
slices.SortFunc(dirEntries, func(a, b vfs.Node) int {
|
||||
return strings.Compare(sortKey(a), sortKey(b))
|
||||
})
|
||||
|
||||
for _, entry := range dirEntries {
|
||||
object := entry.Name()
|
||||
@@ -41,25 +167,53 @@ func (b *s3Backend) entryListR(_vfs *vfs.VFS, bucketName, fdPath, name string, a
|
||||
}
|
||||
|
||||
if entry.IsDir() {
|
||||
prefixWithTrailingSlash := objectPath + "/"
|
||||
if addPrefix {
|
||||
prefixWithTrailingSlash := objectPath + "/"
|
||||
response.AddPrefix(prefixWithTrailingSlash)
|
||||
if l.skipKey(prefixWithTrailingSlash) {
|
||||
continue
|
||||
}
|
||||
if err := l.addCommonPrefix(prefixWithTrailingSlash); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
err := b.entryListR(_vfs, bucketName, path.Join(fdPath, object), "", false, response)
|
||||
if err != nil {
|
||||
if l.skipDir(prefixWithTrailingSlash) {
|
||||
continue
|
||||
}
|
||||
err := l.list(objectPath, "", false)
|
||||
if errors.Is(err, gofakes3.ErrNoSuchKey) {
|
||||
// The directory went away while we were listing it, so
|
||||
// there is nothing below it to report.
|
||||
continue
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
item := &gofakes3.Content{
|
||||
Key: objectPath,
|
||||
LastModified: gofakes3.NewContentTime(entry.ModTime()),
|
||||
ETag: getFileHash(entry, b.s.etagHashType),
|
||||
Size: entry.Size(),
|
||||
StorageClass: gofakes3.StorageStandard,
|
||||
if l.skipKey(objectPath) {
|
||||
continue
|
||||
}
|
||||
if err := l.addObject(objectPath, entry); err != nil {
|
||||
return err
|
||||
}
|
||||
response.Add(item)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// listPage fills response with one page of the listing of the directory
|
||||
// fdPath in bucket, as described by page.
|
||||
//
|
||||
// Only entries whose leaf name starts with name are listed. If addPrefix is
|
||||
// set, subdirectories are reported as common prefixes, otherwise the whole
|
||||
// subtree below fdPath is listed.
|
||||
//
|
||||
// It returns gofakes3.ErrNoSuchKey if fdPath is not a directory.
|
||||
func (b *s3Backend) listPage(_vfs *vfs.VFS, bucket, fdPath, name string, addPrefix bool, page gofakes3.ListBucketPage, response *gofakes3.ObjectList) error {
|
||||
l := newLister(b, _vfs, bucket, page, response)
|
||||
err := l.list(fdPath, name, addPrefix)
|
||||
if err != nil && !errors.Is(err, errPageFull) {
|
||||
return err
|
||||
}
|
||||
fs.Debugf("serve s3", "Listed %d keys from %d directories (truncated=%v)", l.keys, l.dirsRead, response.IsTruncated)
|
||||
return nil
|
||||
}
|
||||
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user