Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion drivers/115/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ func (d *Pan115) rapidUpload(fileSize int64, fileName, dirID, preID, fileID stri
form.Set("sig", d.client.GenerateSignature(fileID, target))

signKey, signVal := "", ""
decryptRetryCount := 0
for retry := true; retry; {
t := driver115.NowMilli()

Expand Down Expand Up @@ -228,11 +229,16 @@ func (d *Pan115) rapidUpload(fileSize int64, fileName, dirID, preID, fileID stri
return nil, err
}
data := resp.RawBody()
defer data.Close()
if bodyBytes, err = io.ReadAll(data); err != nil {
_ = data.Close()
return nil, err
}
_ = data.Close()
if decrypted, err = ecdhCipher.Decrypt(bodyBytes); err != nil {
decryptRetryCount++
if decryptRetryCount < 3 {
continue
}
return nil, err
}
if err = driver115.CheckErr(json.Unmarshal(decrypted, &result), &result, resp); err != nil {
Expand Down
16 changes: 16 additions & 0 deletions drivers/local/copy_namedpipes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//go:build !windows && !plan9 && !netbsd && !aix && !illumos && !solaris && !js

package local

import (
"os"
"path/filepath"
"syscall"
)

func copyNamedPipe(dstPath string, mode os.FileMode, dirMode os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(dstPath), dirMode); err != nil {
return err
}
return syscall.Mkfifo(dstPath, uint32(mode))
}
9 changes: 9 additions & 0 deletions drivers/local/copy_namedpipes_x.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//go:build windows || plan9 || netbsd || aix || illumos || solaris || js

package local

import "os"

func copyNamedPipe(_ string, _, _ os.FileMode) error {
return nil
}
12 changes: 12 additions & 0 deletions drivers/local/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,18 @@ func (d *Local) Remove(ctx context.Context, obj model.Obj) error {
dstPath = filepath.Join(d.RecycleBinPath, obj.GetName()+"_"+time.Now().Format("20060102150405"))
}
err = os.Rename(obj.GetPath(), dstPath)
if isCrossDeviceError(err) {
err = d.copyForMove(obj.GetPath(), dstPath)
if err != nil {
_ = os.RemoveAll(dstPath)
} else {
if obj.IsDir() {
err = os.RemoveAll(obj.GetPath())
} else {
err = os.Remove(obj.GetPath())
}
}
}
}
if err != nil {
return err
Expand Down
109 changes: 109 additions & 0 deletions drivers/local/remove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"os"
"path/filepath"
"runtime"
"testing"
"time"

"github.com/AlliotTech/openalist/internal/model"
)
Expand Down Expand Up @@ -35,3 +37,110 @@ func TestThumbCachePathDisabled(t *testing.T) {
t.Fatalf("thumbCachePath = %q, want empty", got)
}
}

func TestCopyForMovePreservesRelativeSymlink(t *testing.T) {
root := t.TempDir()
srcPath := filepath.Join(root, "source")
dstPath := filepath.Join(root, "recycle", "source")
if err := os.Mkdir(srcPath, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(srcPath, "data"), []byte("data"), 0o666); err != nil {
t.Fatal(err)
}
if err := os.Symlink("data", filepath.Join(srcPath, "link")); err != nil {
t.Skipf("symlinks are unavailable: %v", err)
}

driver := &Local{mkdirPerm: 0o755}
if err := driver.copyForMove(srcPath, dstPath); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(srcPath); err != nil {
t.Fatal(err)
}

content, err := os.ReadFile(filepath.Join(dstPath, "link"))
if err != nil {
t.Fatal(err)
}
if string(content) != "data" {
t.Fatalf("expected data through moved relative symlink, got %q", content)
}
}

func TestCopyForMoveHandlesReadOnlyDirectory(t *testing.T) {
root := t.TempDir()
srcPath := filepath.Join(root, "source")
dstPath := filepath.Join(root, "recycle", "source")
if err := os.Mkdir(srcPath, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(srcPath, "data"), []byte("data"), 0o666); err != nil {
t.Fatal(err)
}
if err := os.Chmod(srcPath, 0o555); err != nil {
t.Fatal(err)
}
defer os.Chmod(srcPath, 0o755)
defer os.Chmod(dstPath, 0o755) // copied dir is 0555 too, or TempDir cleanup cannot remove it

driver := &Local{mkdirPerm: 0o755}
if err := driver.copyForMove(srcPath, dstPath); err != nil {
t.Fatal(err)
}

content, err := os.ReadFile(filepath.Join(dstPath, "data"))
if err != nil {
t.Fatal(err)
}
if string(content) != "data" {
t.Fatalf("expected copied file content, got %q", content)
}
info, err := os.Stat(dstPath)
if err != nil {
t.Fatal(err)
}
if runtime.GOOS != "windows" && info.Mode().Perm() != 0o555 {
t.Fatalf("expected destination mode 0555, got %o", info.Mode().Perm())
}
}

func TestCopyForMovePreservesModTime(t *testing.T) {
root := t.TempDir()
srcPath := filepath.Join(root, "source")
dstPath := filepath.Join(root, "recycle", "source")
filePath := filepath.Join(srcPath, "data")
if err := os.Mkdir(srcPath, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filePath, []byte("data"), 0o666); err != nil {
t.Fatal(err)
}
fileTime := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
dirTime := time.Date(2021, 6, 7, 8, 9, 10, 0, time.UTC)
if err := os.Chtimes(filePath, fileTime, fileTime); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(srcPath, dirTime, dirTime); err != nil {
t.Fatal(err)
}

driver := &Local{mkdirPerm: 0o755}
if err := driver.copyForMove(srcPath, dstPath); err != nil {
t.Fatal(err)
}

for path, want := range map[string]time.Time{
filepath.Join(dstPath, "data"): fileTime,
dstPath: dirTime,
} {
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if !info.ModTime().Equal(want) {
t.Fatalf("expected %s mod time %v, got %v", path, want, info.ModTime())
}
}
}
65 changes: 65 additions & 0 deletions drivers/local/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package local
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
Expand All @@ -17,6 +18,7 @@ import (
"github.com/AlliotTech/openalist/internal/model"
"github.com/AlliotTech/openalist/pkg/utils"
"github.com/disintegration/imaging"
log "github.com/sirupsen/logrus"
ffmpeg "github.com/u2takey/ffmpeg-go"
)

Expand Down Expand Up @@ -204,3 +206,66 @@ func (d *Local) removeThumbCache(fullPath string) {
_ = os.Remove(thumbPath)
}
}

func (d *Local) copyForMove(srcPath, dstPath string) error {
info, err := os.Lstat(srcPath)
if err != nil {
return err
}
if info.Mode()&os.ModeDevice != 0 {
return errors.New("cannot copy a device")
}
if info.Mode()&os.ModeSymlink != 0 {
return d.copySymlinkForMove(srcPath, dstPath)
}
if info.Mode()&os.ModeNamedPipe != 0 {
if err = copyNamedPipe(dstPath, info.Mode(), os.FileMode(d.mkdirPerm)); err != nil {
return err
}
// Some platforms skip named pipes, so keep the source when nothing was created.
_, err = os.Lstat(dstPath)
return err
}
if !info.IsDir() {
if err = utils.CopyFile(srcPath, dstPath); err != nil {
return err
}
preserveModTime(dstPath, info)
return nil
}

if err = os.MkdirAll(dstPath, os.FileMode(d.mkdirPerm)); err != nil {
return err
}
files, err := readDir(srcPath)
if err != nil {
return err
}
for _, file := range files {
if err = d.copyForMove(filepath.Join(srcPath, file.Name()), filepath.Join(dstPath, file.Name())); err != nil {
return err
}
}
if err = os.Chmod(dstPath, info.Mode()); err != nil {
return err
}
preserveModTime(dstPath, info)
return nil
}

func preserveModTime(dstPath string, info os.FileInfo) {
if err := os.Chtimes(dstPath, info.ModTime(), info.ModTime()); err != nil {
log.Errorf("[local] failed to change time of %s: %s", dstPath, err)
}
}

func (d *Local) copySymlinkForMove(srcPath, dstPath string) error {
linkOrig, err := os.Readlink(srcPath)
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Dir(dstPath), os.FileMode(d.mkdirPerm)); err != nil {
return err
}
return os.Symlink(linkOrig, dstPath)
}
7 changes: 7 additions & 0 deletions drivers/local/util_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@
package local

import (
"errors"
"io/fs"
"strings"

"golang.org/x/sys/unix"
)

func isHidden(f fs.FileInfo, _ string) bool {
return strings.HasPrefix(f.Name(), ".")
}

func isCrossDeviceError(err error) bool {
return errors.Is(err, unix.EXDEV)
}
7 changes: 7 additions & 0 deletions drivers/local/util_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
package local

import (
"errors"
"io/fs"
"path/filepath"
"syscall"

"golang.org/x/sys/windows"
)

func isHidden(f fs.FileInfo, fullPath string) bool {
Expand All @@ -20,3 +23,7 @@ func isHidden(f fs.FileInfo, fullPath string) bool {
}
return attrs&syscall.FILE_ATTRIBUTE_HIDDEN != 0
}

func isCrossDeviceError(err error) bool {
return errors.Is(err, windows.ERROR_NOT_SAME_DEVICE)
}
9 changes: 7 additions & 2 deletions drivers/onedrive/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ func (d *Onedrive) _refreshToken() error {
}

func (d *Onedrive) Request(url string, method string, callback base.ReqCallback, resp interface{}) ([]byte, error) {
return d.request(url, method, callback, resp, false)
}

func (d *Onedrive) request(url string, method string, callback base.ReqCallback, resp interface{}, retried bool) ([]byte, error) {
req := base.RestyClient.R()
req.SetHeader("Authorization", "Bearer "+d.AccessToken)
if callback != nil {
Expand All @@ -110,12 +114,13 @@ func (d *Onedrive) Request(url string, method string, callback base.ReqCallback,
return nil, err
}
if e.Error.Code != "" {
if e.Error.Code == "InvalidAuthenticationToken" {
if e.Error.Code == "InvalidAuthenticationToken" && !retried {
err = d.refreshToken()
if err != nil {
return nil, err
}
return d.Request(url, method, callback, resp)
// retry once with the refreshed token, never loop on a bad token
return d.request(url, method, callback, resp, true)
}
return nil, errors.New(e.Error.Message)
}
Expand Down
9 changes: 7 additions & 2 deletions drivers/onedrive_app/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ func (d *OnedriveAPP) _accessToken() error {
}

func (d *OnedriveAPP) Request(url string, method string, callback base.ReqCallback, resp interface{}) ([]byte, error) {
return d.request(url, method, callback, resp, false)
}

func (d *OnedriveAPP) request(url string, method string, callback base.ReqCallback, resp interface{}, retried bool) ([]byte, error) {
req := base.RestyClient.R()
req.SetHeader("Authorization", "Bearer "+d.AccessToken)
if callback != nil {
Expand All @@ -101,12 +105,13 @@ func (d *OnedriveAPP) Request(url string, method string, callback base.ReqCallba
return nil, err
}
if e.Error.Code != "" {
if e.Error.Code == "InvalidAuthenticationToken" {
if e.Error.Code == "InvalidAuthenticationToken" && !retried {
err = d.accessToken()
if err != nil {
return nil, err
}
return d.Request(url, method, callback, resp)
// retry once with the refreshed token, never loop on a bad token
return d.request(url, method, callback, resp, true)
}
return nil, errors.New(e.Error.Message)
}
Expand Down
14 changes: 14 additions & 0 deletions server/webdav/webdav.go
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,10 @@ func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus
w.Header().Set("Lock-Token", "<"+token+">")
}

// ld.Root is the storage path; the response's lockroot is the client's URL.
obj, err := fs.Get(ctx, ld.Root, &fs.GetArgs{NoLog: true})
ld.Root = lockRootHref(h.Prefix, user.BasePath, ld.Root, err == nil && obj.IsDir())

w.Header().Set("Content-Type", "application/xml; charset=utf-8")
if created {
// This is "w.WriteHeader(http.StatusCreated)" and not "return
Expand All @@ -591,6 +595,16 @@ func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus
return 0, nil
}

// lockRootHref maps the storage path a lock is kept under back to the URL path
// the client sees, like the hrefs PROPFIND writes.
func lockRootHref(prefix, basePath, root string, isDir bool) string {
href := path.Join(prefix, strings.TrimPrefix(root, basePath))
if href != "/" && isDir {
href += "/"
}
return (&url.URL{Path: href}).EscapedPath()
}

func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) {
// http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
// Lock-Token value is a Coded-URL. We strip its angle brackets.
Expand Down
Loading
Loading