Files
rclone/backend/protondrive/nodes.go
StereotypicalCatandClaude Opus 5.5 c0bdbcde6b
build / windows (push) Skipped
build / other_os (push) Skipped
build / mac_amd64 (push) Skipped
build / mac_arm64 (push) Skipped
build / linux (push) Skipped
build / go1.26 (push) Skipped
build / linux_386 (push) Skipped
build / lint (push) Skipped
build / android-all (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/386 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/amd64 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v6 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm/v7 (push) Skipped
Build & Push Docker Images / Build Docker Image for linux/arm64 (push) Skipped
Build & Push Docker Images / Merge & Push Final Docker Image (push) Waiting for needed jobs
protondrive: rewrite the backend as a native Go client of the Proton Drive API
Replace Proton-API-Bridge and go-proton-api with a client in
backend/protondrive written against Proton's current Drive API, following
the behaviour of Proton's official Drive SDK:

- volume-based and v2 routes only
- upload block verification, signed manifests and extended attributes
- current content encryption (v4 node keys, v6 PKESK, SEIPDv2)
- browser (session fork) sign-in, with username and password still
  supported
- the volume's change events, used to keep the metadata cache current and
  for ChangeNotify, polled at most every 30 s
- an in-memory fake Proton server (protontest) so the tests run without
  an account

Uses ProtonMail/gopenpgp/v3 and ProtonMail/go-srp directly; no cgo.

Written with heavy AI assistance (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:22:46 +01:00

1455 lines
49 KiB
Go

package protondrive
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/ProtonMail/gopenpgp/v3/constants"
"github.com/ProtonMail/gopenpgp/v3/crypto"
"github.com/rclone/rclone/backend/protondrive/api"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/pacer"
"github.com/rclone/rclone/lib/rest"
"golang.org/x/sync/errgroup"
)
var (
// errNotFound is returned when a node doesn't exist.
errNotFound = errors.New("not found")
// errExists is returned when a folder already has a node with the
// name, which may be one that listings leave out.
errExists = errors.New("already exists")
)
const (
// metadataBatchSize is the most node IDs one metadata request names.
metadataBatchSize = 100
// maxFolderDepth is the most ancestors fetched for a node: 2048
// levels of one-letter names fill Linux's 4096-byte PATH_MAX, so no
// usable path is deeper, and Proton refuses deep nesting itself
// (code 200301).
maxFolderDepth = 2048
// metadataConcurrency is the most metadata requests in flight for
// one listing.
metadataConcurrency = 15
// blocksInFlight is the most blocks uploading, and the most blocks
// downloading, at once per client.
blocksInFlight = 10
// defaultRetryAfter is how long to wait after HTTP 429 without a
// usable Retry-After header.
defaultRetryAfter = 10 * time.Second
// maxRetryAfter is the longest Retry-After honoured.
maxRetryAfter = 60 * time.Second
// readBackAttempts is how many times a node just changed is read
// while the server doesn't show the change yet. With the first wait
// readBackDelay, doubled each time up to readBackMaxDelay, they span
// about 7 s.
readBackAttempts = 8
readBackDelay = 100 * time.Millisecond
readBackMaxDelay = 2 * time.Second
// nameSignedSince and hashKeySignedSince are the Unix times from
// which names and hash keys are signed: as in the SDK, a missing
// signature on an older one is not an error. The creation time is
// the server's, so a server can exempt a node by back-dating it.
nameSignedSince = 1609459200 // 2021-01-01
hashKeySignedSince = 1627776000 // 2021-08-01
// protonDocMediaType and protonSheetMediaType are the media types
// of Proton Docs and Sheets, which have no content to read.
protonDocMediaType = "application/vnd.proton.doc"
protonSheetMediaType = "application/vnd.proton.sheet"
)
// clientOptions configure a client.
type clientOptions struct {
UploadConcurrency int // blocks in flight per uploading file
ReplaceExistingDraft bool // replace another client's draft of a file being uploaded
EnableCaching bool // cache nodes and listings in memory
IgnoreSignatureErrors bool // log content signature failures instead of failing
DraftClientUID string // identifies this remote's drafts
EventsInterval time.Duration // shortest time between polls for events; 0 disables polling
}
// client reads and writes the main volume of a Proton Drive account.
type client struct {
s *session
opt clientOptions
acct *account
addr *address // address of the main share, which signs what the client writes
volumeID string
shareID string
shareKeys *nodeKeys
root *node
apiPacer *fs.Pacer
storagePacer *fs.Pacer
uploadTokens *pacer.TokenDispenser
downloadTokens *pacer.TokenDispenser
cache *nodeCache
events *eventPoller // polls for changes made by other clients; nil until bootstrapped
learnt blockSizeCache // block sizes of files which don't record them
// verifierHook, if set, may change each block's verifier token
// before it is sent; for tests.
verifierHook func(token []byte)
maxFileBlocks int // the most blocks a file may list: maxFileBlocks, unless a test lowers it
maxFolderDepth int // the most ancestors fetched for a node: maxFolderDepth, unless a test lowers it
readBackDelay time.Duration // first wait before reading a changed node again: readBackDelay, unless a test lowers it
mu sync.Mutex
folderKeys map[string]*nodeKeys // by folder ID; kept whatever the cache, as node keys never change
reported map[string]bool // problems already logged, by kind and node ID
skipped int // nodes left out of listings because they can't be read
docsNoticed bool // whether leaving out Docs and Sheets was logged
}
// node is a decrypted file or folder. Nodes from a client are shared
// and must not be modified.
type node struct {
ID string
ParentID string // empty for the root
Name string
MIMEType string // files only
IsFolder bool
State int // api.LinkStateActive etc
CreateTime time.Time
ServerModTime time.Time
EncryptedSize int64 // of the active revision; files only
RevisionID string // active revision; files only
X *xattrs // extended attributes; nil if they can't be decrypted
keys *nodeKeys
hashKey []byte // folders only; nil if it can't be decrypted
hashKeyErr error // why hashKey may not be the folder's; nil if its signature verified or isn't required
nameSigned bool // whether the name's signature verified
keyVerifyKR *crypto.KeyRing // verifies the node's key and content key signatures
link *api.LinkDetails // the encrypted metadata
}
// size returns the size of the file's content: the plaintext size if
// original is set and the extended attributes have it, else the
// encrypted size.
func (n *node) size(original bool) int64 {
if size, ok := n.plaintextSize(); original && ok {
return size
}
return n.EncryptedSize
}
// plaintextSize returns the size of the file's content, and whether
// the extended attributes record it.
func (n *node) plaintextSize() (int64, bool) {
if n.X != nil && !n.X.NoSize && (n.X.SHA1 != "" || n.X.Size > 0 || len(n.X.BlockSizes) > 0) {
return n.X.Size, true
}
return 0, false
}
// modTime returns the modification time from the extended attributes,
// else the server's.
func (n *node) modTime() time.Time {
if n.X != nil && !n.X.ModTime.IsZero() {
return n.X.ModTime
}
return n.ServerModTime
}
// sha1 returns the lower-case hex SHA-1 of the file's content, or ""
// if it isn't known.
func (n *node) sha1() string {
if n.X == nil {
return ""
}
return strings.ToLower(n.X.SHA1)
}
// newDrivePacer returns a pacer for API or storage calls.
func newDrivePacer(ctx context.Context) *fs.Pacer {
return fs.NewPacer(ctx, pacer.NewDefault(pacer.MinSleep(10*time.Millisecond), pacer.MaxSleep(2*time.Second), pacer.DecayConstant(2)))
}
// newClient returns a client for the account of s, unlocking its keys
// with the session's key password. It creates the account's volume if
// it has none, as a new account doesn't.
func newClient(ctx context.Context, s *session, opt clientOptions) (*client, error) {
acct, err := loadAccount(ctx, s, []byte(s.current().KeyPassword))
if err != nil {
return nil, err
}
c := &client{
s: s,
opt: opt,
acct: acct,
apiPacer: newDrivePacer(ctx),
storagePacer: newDrivePacer(ctx),
uploadTokens: pacer.NewTokenDispenser(blocksInFlight),
downloadTokens: pacer.NewTokenDispenser(blocksInFlight),
cache: newNodeCache(opt.EnableCaching),
folderKeys: make(map[string]*nodeKeys),
reported: make(map[string]bool),
maxFileBlocks: maxFileBlocks,
maxFolderDepth: maxFolderDepth,
readBackDelay: readBackDelay,
}
if err := c.bootstrap(ctx); err != nil {
c.close()
return nil, err
}
c.events = newEventPoller(c, opt.EventsInterval)
if c.cache != nil {
c.cache.onFill = c.events.wake
}
return c, nil
}
// rootID returns the ID of the root folder.
func (c *client) rootID() string {
return c.root.ID
}
// apiCall makes an API call as session.call does, paced and retried.
func (c *client) apiCall(ctx context.Context, opts *rest.Opts, request, response any) error {
return c.pacedCall(ctx, c.apiPacer, func() (*http.Response, error) {
return c.s.call(ctx, opts, request, response)
})
}
// pacedCall calls fn with pacer p, retrying it as shouldRetry says.
func (c *client) pacedCall(ctx context.Context, p *fs.Pacer, fn func() (*http.Response, error)) error {
return p.Call(c.paced(ctx, fn))
}
// paced returns fn as a pacer.Paced which reports whether to retry as
// shouldRetry says, having waited out any Retry-After itself.
func (c *client) paced(ctx context.Context, fn func() (*http.Response, error)) pacer.Paced {
return func() (bool, error) {
resp, callErr := fn()
retry, err := c.shouldRetry(ctx, resp, callErr)
if wait, ok := pacer.IsRetryAfter(err); ok && retry {
// The Retry-After is waited out here, for this call alone.
// Given to the pacer it would only start when the retry
// does, sending the retry at once, and then hold every
// call of the client for the whole wait without regard
// to their contexts. A Retry-After of zero leaves the
// pacer at its minimum sleep.
select {
case <-time.After(wait):
case <-ctx.Done():
return false, ctx.Err()
}
return true, pacer.RetryAfterError(callErr, 0)
}
return retry, err
}
}
// shouldRetry returns whether the call which returned resp and err
// should be retried, and the error to retry or return.
func (c *client) shouldRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
if fserrors.ContextError(ctx, &err) {
return false, err
}
if err == nil {
return false, nil
}
status := 0
var apiErr *api.Error
if resp != nil {
status = resp.StatusCode
} else if errors.As(err, &apiErr) {
status = apiErr.Status
}
switch {
case status == http.StatusTooManyRequests:
return true, pacer.RetryAfterError(err, retryAfter(resp))
case status == http.StatusRequestTimeout || status >= 500:
return true, err
case errors.As(err, &apiErr) && apiErr.Code == api.CodeFeatureBlocked:
// Proton's code for a feature disabled, rate-limited or
// blocked: it may pass.
if resp != nil && resp.Header.Get("Retry-After") != "" {
return true, pacer.RetryAfterError(err, retryAfter(resp))
}
return true, err
case errors.As(err, &apiErr) && apiErr.Status >= 400 && apiErr.Status < 500:
return false, err
case errors.Is(err, errSessionExpired), errors.Is(err, errCaptcha), errors.Is(err, errNotSignedIn):
return false, err
}
return fserrors.ShouldRetry(err), err
}
// retryAfter returns the wait the Retry-After header of resp asks for,
// in seconds or as a date, at most maxRetryAfter. A missing, unusable
// or past value gives defaultRetryAfter.
func retryAfter(resp *http.Response) time.Duration {
if resp == nil {
return defaultRetryAfter
}
value := resp.Header.Get("Retry-After")
if isAllDigits(value) {
seconds, err := strconv.ParseUint(value, 10, 64)
switch {
case err != nil || seconds > uint64(maxRetryAfter/time.Second):
// err is only ever a value too large for a uint64.
return maxRetryAfter
case seconds == 0:
return defaultRetryAfter
}
return time.Duration(seconds) * time.Second
}
if t, err := http.ParseTime(value); err == nil && time.Until(t) > 0 {
return min(time.Until(t), maxRetryAfter)
}
return defaultRetryAfter
}
// isAllDigits reports whether s is a non-empty run of ASCII digits.
func isAllDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
// apiErrorCode returns the Proton code of err, or 0 if it has none.
func apiErrorCode(err error) int {
var apiErr *api.Error
if errors.As(err, &apiErr) {
return apiErr.Code
}
return 0
}
// bootstrap loads the main volume, share and root folder, creating
// them if the account has none.
func (c *client) bootstrap(ctx context.Context) error {
opts := &rest.Opts{Method: "GET", Path: "/drive/v2/shares/my-files"}
var my api.MyFilesResponse
err := c.apiCall(ctx, opts, nil, &my)
if apiErrorCode(err) == api.CodeNotExists {
fs.Logf(nil, "protondrive: the account has no drive yet: creating it")
if err = c.createVolume(ctx); err != nil {
return err
}
err = c.apiCall(ctx, opts, nil, &my)
}
if err != nil {
return fmt.Errorf("get drive: %w", err)
}
addr := c.acct.byID(my.Share.AddressID)
if addr == nil {
return fmt.Errorf("get drive: the keys of address %s of the drive are not available", my.Share.AddressID)
}
creatorKR, err := c.acct.publicKeys(ctx, c.apiCall, my.Share.CreatorEmail)
if err != nil {
return fmt.Errorf("get drive: %w", err)
}
shareKeys, verifyErr, err := decryptNodeKeys(addr.keyRing, creatorKR, my.Share.Key, my.Share.Passphrase, my.Share.PassphraseSignature, c.s.serverTime())
if err != nil {
return fmt.Errorf("get drive: decrypt share key: %w", err)
}
c.shareKeys = shareKeys
// Everything below is trusted because the share and root are the
// user's own: another user's keys would come from the server.
switch {
case !c.acct.owns(my.Share.CreatorEmail):
shareKeys.unverified = fmt.Errorf("the drive's share was created by %q, which is not one of your addresses", my.Share.CreatorEmail)
case verifyErr != nil:
shareKeys.unverified = fmt.Errorf("the drive's share key isn't signed by its creator: %w", verifyErr)
}
if shareKeys.unverified != nil {
fs.Errorf(nil, "protondrive: share %s: %v: reading and writing need ignore_signature_errors", my.Share.ShareID, shareKeys.unverified)
}
root, unreadable, err := c.decryptNode(ctx, &my.Link, shareKeys)
if err == nil && unreadable == nil && !root.IsFolder {
unreadable = errors.New("not a folder")
}
if err == nil && unreadable != nil {
err = unreadable
}
if err != nil {
return fmt.Errorf("get drive: root folder: %w", err)
}
if root.keys.unverified == nil && !c.acct.owns(my.Link.Link.SignatureEmail) {
root.keys.unverified = fmt.Errorf("the drive's root folder is signed by %q, which is not one of your addresses", my.Link.Link.SignatureEmail)
fs.Errorf(nil, "protondrive: %v: reading and writing need ignore_signature_errors", root.keys.unverified)
}
c.addr = addr
c.volumeID = my.Volume.VolumeID
c.shareID = my.Share.ShareID
c.root = root
c.rememberKeys(root)
return nil
}
// createVolume creates the account's volume with its main share and
// root folder for the primary address, as the SDK's createVolume does.
// Another client creating it first is not an error.
func (c *client) createVolume(ctx context.Context) error {
addr := c.acct.primary()
signKR, err := addr.signingKeyRing()
if err != nil {
return fmt.Errorf("create drive: %w", err)
}
now := c.s.serverTime()
shareKey, sharePassphrase, sharePassphraseSig, shareKeys, err := generateNodeKeys(signKR, signKR, false, now)
if err != nil {
return fmt.Errorf("create drive: share key: %w", err)
}
defer shareKeys.keyRing.ClearPrivateParams()
rootKey, rootPassphrase, rootPassphraseSig, rootKeys, err := generateNodeKeys(shareKeys.keyRing, signKR, false, now)
if err != nil {
return fmt.Errorf("create drive: root folder key: %w", err)
}
defer rootKeys.keyRing.ClearPrivateParams()
rootName, err := encryptName("root", nil, shareKeys.keyRing, signKR, now)
if err != nil {
return fmt.Errorf("create drive: %w", err)
}
hashKey, _, err := generateHashKey(rootKeys.keyRing, now)
if err != nil {
return fmt.Errorf("create drive: %w", err)
}
err = c.apiCall(ctx, &rest.Opts{Method: "POST", Path: "/drive/volumes"}, &api.CreateVolumeRequest{
AddressID: addr.ID,
AddressKeyID: addr.primaryKeyID,
ShareKey: shareKey,
SharePassphrase: sharePassphrase,
SharePassphraseSignature: sharePassphraseSig,
FolderName: rootName,
FolderKey: rootKey,
FolderPassphrase: rootPassphrase,
FolderPassphraseSignature: rootPassphraseSig,
FolderHashKey: hashKey,
}, nil)
if apiErrorCode(err) == api.CodeAlreadyExists {
fs.Debugf(nil, "protondrive: the drive was created by another client")
return nil
}
if err != nil {
return fmt.Errorf("create drive: %w", err)
}
return nil
}
// verifyKeys returns the public keys of email, or fallback for an
// anonymous signature, where email is empty.
func (c *client) verifyKeys(ctx context.Context, email string, fallback *crypto.KeyRing) (*crypto.KeyRing, error) {
if email == "" {
return fallback, nil
}
return c.acct.publicKeys(ctx, c.apiCall, email)
}
// isNotSigned reports whether verifyErr is a missing signature.
func isNotSigned(verifyErr error) bool {
var sigErr crypto.SignatureVerificationError
return errors.Is(verifyErr, errSignatureMissing) || (errors.As(verifyErr, &sigErr) && sigErr.Status == constants.SIGNATURE_NOT_SIGNED)
}
// annotate returns err prefixed with what, or nil if err is nil.
func annotate(what string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s: %w", what, err)
}
// decryptNode decrypts the metadata d of a node whose parent's keys
// are parent, choosing the keys which verify each signature as the
// SDK's decryptNode does.
//
// The node's key is unverified if its passphrase signature fails, or
// if parent's key is unverified: whoever made that key can decrypt
// this one's passphrase, and, for an anonymous node, sign it.
//
// It returns unreadable, and no node, if the node has no ID, its name
// or key can't be decrypted, its name isn't valid, its type is unknown
// or its encrypted size is negative. err is
// set only if the verification keys can't be had. Failed signature
// checks, and extended attributes or hash key which can't be
// decrypted, are logged once per node.
func (c *client) decryptNode(ctx context.Context, d *api.LinkDetails, parent *nodeKeys) (n *node, unreadable, err error) {
l := &d.Link
if l.LinkID == "" {
return nil, errors.New("node has no ID"), nil
}
parentKR := parent.keyRing
now := c.s.serverTime()
// An anonymous node is signed with its parent's key, which a root
// has not.
var parentVerifyKR *crypto.KeyRing
if l.ParentLinkID != "" {
parentVerifyKR = parentKR
}
keyVerifyKR, err := c.verifyKeys(ctx, l.SignatureEmail, parentVerifyKR)
if err != nil {
return nil, nil, err
}
nameVerifyKR := keyVerifyKR
if l.NameSignatureEmail != l.SignatureEmail {
if nameVerifyKR, err = c.verifyKeys(ctx, l.NameSignatureEmail, parentVerifyKR); err != nil {
return nil, nil, err
}
}
name, nameVerifyErr, err := decryptName(l.Name, parentKR, nameVerifyKR, now)
if err != nil {
return nil, err, nil
}
if l.ParentLinkID != "" {
if err := validateName(name); err != nil {
return nil, fmt.Errorf("invalid name %q: %w", truncateName(name), err), nil
}
}
nameSigned := nameVerifyErr == nil
if isNotSigned(nameVerifyErr) && l.CreateTime < nameSignedSince {
nameVerifyErr = nil
}
keys, keyVerifyErr, err := decryptNodeKeys(parentKR, keyVerifyKR, l.NodeKey, l.NodePassphrase, l.NodePassphraseSignature, now)
if err != nil {
return nil, fmt.Errorf("%q: %w", truncateName(name), err), nil
}
switch {
case parent.unverified != nil:
keys.unverified = parent.unverified
case keyVerifyErr != nil:
keys.unverified = fmt.Errorf("the key of %q isn't signed by its owner: %w", truncateName(name), keyVerifyErr)
}
n = &node{
ID: l.LinkID,
ParentID: l.ParentLinkID,
Name: name,
State: l.State,
CreateTime: time.Unix(l.CreateTime, 0),
ServerModTime: time.Unix(l.ModifyTime, 0),
keys: keys,
keyVerifyKR: keyVerifyKR,
nameSigned: nameSigned,
link: d,
}
verifyErrs := []error{annotate("name", nameVerifyErr), annotate("node key", keyVerifyErr)}
var decryptErrs []error
// Signatures other than the name's and the key's are by the
// signature email alone.
var signerKR *crypto.KeyRing
if l.SignatureEmail != "" {
signerKR = keyVerifyKR
}
var xattrsVerifyErr error
switch {
case l.Type == api.LinkTypeFolder && d.Folder != nil:
n.IsFolder = true
hashKey, hashKeyVerifyErr, err := decryptHashKey(d.Folder.NodeHashKey, keys.keyRing, signerKR, now)
if isNotSigned(hashKeyVerifyErr) && l.CreateTime < hashKeySignedSince {
hashKeyVerifyErr = nil
}
n.hashKey = hashKey
if hashKeyVerifyErr != nil {
n.hashKeyErr = fmt.Errorf("the hash key of %q isn't signed by its owner: %w", truncateName(name), hashKeyVerifyErr)
}
decryptErrs = append(decryptErrs, annotate("hash key", err))
verifyErrs = append(verifyErrs, annotate("hash key", hashKeyVerifyErr))
xattrsVerifyKR := signerKR
if xattrsVerifyKR == nil {
xattrsVerifyKR = keys.keyRing
}
n.X, xattrsVerifyErr, err = decryptXAttrs(d.Folder.XAttr, keys.keyRing, xattrsVerifyKR, now)
decryptErrs = append(decryptErrs, annotate("extended attributes", err))
case l.Type == api.LinkTypeFile && d.File != nil:
n.MIMEType = d.File.MediaType
if rev := d.File.ActiveRevision; rev != nil {
if rev.EncryptedSize < 0 {
return nil, fmt.Errorf("%q: negative encrypted size %d", truncateName(name), rev.EncryptedSize), nil
}
n.RevisionID = rev.RevisionID
n.EncryptedSize = rev.EncryptedSize
revVerifyKR, err := c.verifyKeys(ctx, rev.SignatureEmail, keys.keyRing)
if err != nil {
return nil, nil, err
}
n.X, xattrsVerifyErr, err = decryptXAttrs(rev.XAttr, keys.keyRing, revVerifyKR, now)
decryptErrs = append(decryptErrs, annotate("extended attributes", err))
}
default:
return nil, fmt.Errorf("%q: unknown node type %d", truncateName(name), l.Type), nil
}
if xattrsVerifyErr != nil && !c.opt.IgnoreSignatureErrors {
// Anyone with the node's public key can write attributes.
// Block sizes are checked as blocks are read; nothing checks
// the rest.
n.X = n.X.blockSizesOnly()
verifyErrs = append(verifyErrs, annotate("extended attributes, so their modification time, size and SHA-1 are not used", xattrsVerifyErr))
} else {
verifyErrs = append(verifyErrs, annotate("extended attributes", xattrsVerifyErr))
}
if err := errors.Join(decryptErrs...); err != nil {
c.reportOnce("decrypt", n.ID, func() {
fs.Errorf(nil, "protondrive: %q (ID %s): can't decrypt: %v", n.Name, n.ID, err)
})
}
if err := errors.Join(verifyErrs...); err != nil {
c.reportOnce("verify", n.ID, func() {
fs.Errorf(nil, "protondrive: %q (ID %s): signature check failed: %v", n.Name, n.ID, err)
})
}
return n, nil, nil
}
// truncateName returns name shortened for a log line.
func truncateName(name string) string {
const maxLen = 64
if len(name) <= maxLen {
return name
}
cut := maxLen
for cut > 0 && !utf8.RuneStart(name[cut]) {
cut--
}
return name[:cut] + "..."
}
// reportOnce calls log unless a problem of kind with node id has
// already been reported.
func (c *client) reportOnce(kind, id string, log func()) {
key := kind + ":" + id
c.mu.Lock()
seen := c.reported[key]
c.reported[key] = true
c.mu.Unlock()
if !seen {
log()
}
}
// rememberKeys keeps the key of folder n for decrypting its children.
func (c *client) rememberKeys(n *node) {
if !n.IsFolder {
return
}
c.mu.Lock()
defer c.mu.Unlock()
c.folderKeys[n.ID] = n.keys
}
// folderKeysOf returns the node keys of folder id.
func (c *client) folderKeysOf(ctx context.Context, id string) (*nodeKeys, error) {
return c.folderKeysIn(ctx, id, nil)
}
// folderKeysIn is folderKeysOf for the parent of the nodes below,
// nearest first, which are being fetched.
func (c *client) folderKeysIn(ctx context.Context, id string, below []string) (*nodeKeys, error) {
c.mu.Lock()
keys := c.folderKeys[id]
c.mu.Unlock()
if keys != nil {
return keys, nil
}
n, err := c.getNodeIn(ctx, id, below)
if err != nil {
return nil, err
}
if !n.IsFolder {
return nil, fmt.Errorf("node %s is not a folder", id)
}
return n.keys, nil
}
// fetchLinks returns the metadata of the nodes ids, at most
// metadataBatchSize of them. Unknown IDs are left out.
func (c *client) fetchLinks(ctx context.Context, ids []string) ([]api.LinkDetails, error) {
var resp api.LinksResponse
opts := &rest.Opts{Method: "POST", Path: "/drive/v2/volumes/" + url.PathEscape(c.volumeID) + "/links"}
if err := c.apiCall(ctx, opts, &api.LinksRequest{LinkIDs: ids}, &resp); err != nil {
return nil, err
}
return resp.Links, nil
}
// getNode returns the node id, of any state, wrapping errNotFound if
// it doesn't exist.
func (c *client) getNode(ctx context.Context, id string) (*node, error) {
return c.getNodeIn(ctx, id, nil)
}
// getNodeIn is getNode for the parent of the nodes below, nearest
// first, which are being fetched.
func (c *client) getNodeIn(ctx context.Context, id string, below []string) (*node, error) {
if id == c.root.ID {
return c.root, nil
}
if n := c.cache.get(id); n != nil {
return n, nil
}
return c.fetchNodeIn(ctx, id, below)
}
// fetchNode reads node id, of any state, from the server whatever the
// cache holds, and caches it. It wraps errNotFound if it doesn't exist.
func (c *client) fetchNode(ctx context.Context, id string) (*node, error) {
return c.fetchNodeIn(ctx, id, nil)
}
// fetchNodeIn is fetchNode for the parent of the nodes below, nearest
// first, which are being fetched, as the parents of a node not yet in
// the cache are fetched up to one that is. A server reporting a cycle
// or a chain deeper than maxFolderDepth gets an error.
func (c *client) fetchNodeIn(ctx context.Context, id string, below []string) (*node, error) {
switch {
case slices.Contains(below, id):
return nil, fmt.Errorf("get node %s: %w: the server reports it as its own ancestor", id, errIntegrity)
case len(below) >= c.maxFolderDepth:
return nil, fmt.Errorf("get node %s: %w: folders nested more than %d deep", id, errIntegrity, c.maxFolderDepth)
}
links, err := c.fetchLinks(ctx, []string{id})
if err != nil {
return nil, fmt.Errorf("get node %s: %w", id, err)
}
i := slices.IndexFunc(links, func(d api.LinkDetails) bool { return d.Link.LinkID == id })
if i < 0 {
return nil, fmt.Errorf("get node %s: %w", id, errNotFound)
}
d := links[i]
if d.Link.ParentLinkID == "" {
return nil, fmt.Errorf("get node %s: not in the drive", id)
}
parent, err := c.folderKeysIn(ctx, d.Link.ParentLinkID, append(below[:len(below):len(below)], id))
if err != nil {
if len(below) > 0 {
// Wrapped once, by the node asked for: at every level
// of a chain a server can make 2048 deep, it would
// grow without bound.
return nil, err
}
return nil, fmt.Errorf("get node %s: %w", id, err)
}
n, unreadable, err := c.decryptNode(ctx, &d, parent)
if err == nil {
err = unreadable
}
if err != nil {
return nil, fmt.Errorf("get node %s: %w", id, err)
}
c.rememberKeys(n)
c.cache.put(n)
return n, nil
}
// readBack reads node id, just changed, from the server as fetchNode
// does, reading it again while shows reports the read doesn't show the
// change yet: Proton's servers can take a moment to. It returns the
// last read once shows reports true, after readBackAttempts reads, or
// when ctx is done.
func (c *client) readBack(ctx context.Context, id string, shows func(n *node, err error) bool) (*node, error) {
delay := c.readBackDelay
for attempt := 1; ; attempt++ {
n, err := c.fetchNode(ctx, id)
if shows(n, err) || attempt >= readBackAttempts {
return n, err
}
fs.Debugf(nil, "protondrive: node %s doesn't show its change yet: reading it again in %v", id, delay)
select {
case <-time.After(delay):
case <-ctx.Done():
return n, err
}
delay = min(2*delay, readBackMaxDelay)
}
}
// found reports whether a read of a node which returned err found it.
func found(_ *node, err error) bool {
return !errors.Is(err, errNotFound)
}
// activeNode reads node id from the server whatever the cache holds,
// and returns it if it is active. Otherwise it forgets the node and
// the listing of its parent and returns errNotFound.
func (c *client) activeNode(ctx context.Context, id string) (*node, error) {
if id == c.root.ID {
return c.root, nil
}
n, err := c.fetchNode(ctx, id)
if err != nil {
return nil, err
}
if n.State != api.LinkStateActive {
c.forget(id, n.ParentID)
return nil, fmt.Errorf("get node %s: %w", id, errNotFound)
}
return n, nil
}
// hasChildren reports whether the server lists any child of folder id,
// whatever its type and whether or not it can be read. It asks the
// server, not the cache.
func (c *client) hasChildren(ctx context.Context, id string) (bool, error) {
var page api.ChildrenResponse
opts := &rest.Opts{Method: "GET", Path: c.volumePath("/drive/v2/volumes", "folders", id, "children")}
if err := c.apiCall(ctx, opts, nil, &page); err != nil {
return false, fmt.Errorf("list %s: %w", id, err)
}
return len(page.LinkIDs) > 0 || page.More, nil
}
// listChildren calls fn with batches of the active children of folder
// parentID, one call at a time, until all are listed or fn returns an
// error.
//
// Children which can't be read are left out and logged; Proton Docs
// and Sheets are left out with one notice per client.
func (c *client) listChildren(ctx context.Context, parentID string, fn func([]*node) error) error {
if nodes, ok := c.cache.children(parentID); ok {
if len(nodes) == 0 {
return nil
}
return fn(nodes)
}
parent, err := c.folderKeysOf(ctx, parentID)
if err != nil {
return fmt.Errorf("list %s: %w", parentID, err)
}
// Taken before the first page, so a change made while the folder
// is read keeps what was read out of the cache.
token := c.cache.startFetch(parentID)
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(metadataConcurrency)
var (
mu sync.Mutex // serialises calls of fn
all []*node
)
fetch := func(ids []string) {
g.Go(func() error {
nodes, err := c.decryptChildren(gCtx, parentID, parent, ids)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
if err := gCtx.Err(); err != nil {
return err
}
all = append(all, nodes...)
if len(nodes) == 0 {
return nil
}
return fn(nodes)
})
}
opts := &rest.Opts{
Method: "GET",
Path: "/drive/v2/volumes/" + url.PathEscape(c.volumeID) + "/folders/" + url.PathEscape(parentID) + "/children",
}
seen := make(map[string]bool)
anchors := make(map[string]bool)
var pending []string
for {
var page api.ChildrenResponse
if err = c.apiCall(gCtx, opts, nil, &page); err != nil {
break
}
for _, id := range page.LinkIDs {
// The folder may change between pages.
if !seen[id] {
seen[id] = true
pending = append(pending, id)
}
}
for len(pending) >= metadataBatchSize {
fetch(slices.Clone(pending[:metadataBatchSize]))
pending = pending[metadataBatchSize:]
}
if !page.More || page.AnchorID == "" {
break
}
if anchors[page.AnchorID] {
err = fmt.Errorf("the server repeated the page after anchor %s", page.AnchorID)
break
}
anchors[page.AnchorID] = true
opts.Parameters = url.Values{"AnchorID": {page.AnchorID}}
}
if err == nil && len(pending) > 0 {
fetch(pending)
}
// A failed batch cancels gCtx, so its error is the cause of any
// paging error.
if waitErr := g.Wait(); waitErr != nil {
err = waitErr
}
c.cache.endFetch(parentID, token, all, err == nil)
if err != nil {
return fmt.Errorf("list %s: %w", parentID, err)
}
return nil
}
// decryptChildren fetches and decrypts the children ids of folder
// parentID, whose keys are parent, leaving out those which are not
// listed.
func (c *client) decryptChildren(ctx context.Context, parentID string, parent *nodeKeys, ids []string) ([]*node, error) {
links, err := c.fetchLinks(ctx, ids)
if err != nil {
return nil, err
}
nodes := make([]*node, 0, len(links))
for _, d := range links {
if !c.listable(&d, parentID) {
continue
}
n, unreadable, err := c.decryptNode(ctx, &d, parent)
if err != nil {
return nil, err
}
if unreadable != nil {
c.reportOnce("unreadable", d.Link.LinkID, func() {
c.mu.Lock()
c.skipped++
c.mu.Unlock()
fs.Errorf(nil, "protondrive: leaving node %s out of listing: %v", d.Link.LinkID, unreadable)
})
continue
}
c.rememberKeys(n)
nodes = append(nodes, n)
}
return nodes, nil
}
// listable reports whether d belongs in the listing of folder
// parentID: an active folder or file in it with content to read.
func (c *client) listable(d *api.LinkDetails, parentID string) bool {
l := &d.Link
// The node may have been moved or trashed since its ID was listed.
if l.ParentLinkID != parentID || l.State != api.LinkStateActive {
return false
}
if l.Type == api.LinkTypeFile && (d.File == nil || d.File.ActiveRevision == nil) {
return false
}
if d.File != nil && (d.File.MediaType == protonDocMediaType || d.File.MediaType == protonSheetMediaType) {
c.mu.Lock()
noticed := c.docsNoticed
c.docsNoticed = true
c.mu.Unlock()
if !noticed {
fs.Logf(nil, "protondrive: leaving Proton Docs and Sheets out of listings, as rclone can't read them")
}
return false
}
return true
}
// findChild returns the child of folder parentID named name, compared
// exactly, or errNotFound.
func (c *client) findChild(ctx context.Context, parentID, name string) (*node, error) {
nodes, ok := c.cache.children(parentID)
if !ok {
err := c.listChildren(ctx, parentID, func(batch []*node) error {
nodes = append(nodes, batch...)
return nil
})
if err != nil {
return nil, err
}
}
for _, n := range nodes {
if n.Name == name {
return n, nil
}
}
return nil, errNotFound
}
// mutationError returns err of the change what, wrapping errExists for
// API code 2500 and errNotFound for 2501.
func mutationError(what string, err error) error {
switch apiErrorCode(err) {
case api.CodeAlreadyExists:
return fmt.Errorf("%s: %w: %w", what, errExists, err)
case api.CodeNotExists:
return fmt.Errorf("%s: %w: %w", what, errNotFound, err)
}
return fmt.Errorf("%s: %w", what, err)
}
// targetFolder returns folder id to put or name a node in, which must
// have a readable hash key, and a verified key and hash key unless
// IgnoreSignatureErrors is set.
func (c *client) targetFolder(ctx context.Context, id string) (*node, error) {
n, err := c.getNode(ctx, id)
if errors.Is(err, errNotFound) && c.cache == nil {
// Without the cache a folder just made is read from the
// server, which may not show it yet. With it, the folder was
// cached when made, so a miss means it is gone.
n, err = c.readBack(ctx, id, found)
}
switch {
case err != nil:
return nil, err
case !n.IsFolder:
return nil, fmt.Errorf("node %s is not a folder", id)
case n.hashKey == nil:
return nil, fmt.Errorf("folder %s has no readable hash key", id)
case n.keys.unverified != nil && !c.opt.IgnoreSignatureErrors:
// Names and keys written into it would be encrypted to a key
// the server may have made.
return nil, fmt.Errorf("folder %q: %w: its key isn't verified, so whoever made it could read what is written into it: %v: set ignore_signature_errors to write anyway", n.Name, errIntegrity, n.keys.unverified)
case n.keys.unverified != nil:
c.reportUnverified("writing into", n, "whoever made its key can read what is written")
}
switch {
case n.hashKeyErr != nil && !c.opt.IgnoreSignatureErrors:
// Whoever made the hash key could test guesses at the names
// written into the folder against their lookup hashes.
return nil, fmt.Errorf("folder %q: %w: its hash key isn't verified, so whoever made it could test guesses at the names written into it: %v: set ignore_signature_errors to write anyway", n.Name, errIntegrity, n.hashKeyErr)
case n.hashKeyErr != nil:
c.reportOnce("unverified hash key writing into", n.ID, func() {
fs.Errorf(nil, "protondrive: writing into %q (ID %s) although its hash key isn't verified, so whoever made it can test guesses at the names written: %v", n.Name, n.ID, n.hashKeyErr)
})
}
return n, nil
}
// reportUnverified logs, once per op and node, that op goes ahead on
// node n although its key is unverified, as IgnoreSignatureErrors
// allows, with the consequence if not empty.
func (c *client) reportUnverified(op string, n *node, consequence string) {
c.reportOnce("unverified "+op, n.ID, func() {
msg := fmt.Sprintf("protondrive: %s %q (ID %s) although its key isn't verified", op, n.Name, n.ID)
if consequence != "" {
msg += ", so " + consequence
}
fs.Errorf(nil, "%s: %v", msg, n.keys.unverified)
})
}
// forget drops node id and the listings of parentIDs from the cache.
func (c *client) forget(id string, parentIDs ...string) {
c.cache.invalidate(id)
for _, parentID := range parentIDs {
c.cache.invalidateChildren(parentID)
}
}
// volumePath returns the API path of the main volume with the
// segments after it, escaped.
func (c *client) volumePath(prefix string, segments ...string) string {
p := prefix + "/" + url.PathEscape(c.volumeID)
for _, s := range segments {
p += "/" + url.PathEscape(s)
}
return p
}
// createFolder creates folder name in folder parentID, with modTime in
// its extended attributes unless it is zero, and returns it. It returns
// errExists if parentID has a node named name.
func (c *client) createFolder(ctx context.Context, parentID, name string, modTime time.Time) (*node, error) {
what := fmt.Sprintf("create folder %q", name)
if err := validateName(name); err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
parent, err := c.targetFolder(ctx, parentID)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
signKR, err := c.addr.signingKeyRing()
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
now := c.s.serverTime()
nodeKey, passphrase, passphraseSig, keys, err := generateNodeKeys(parent.keys.keyRing, signKR, false, now)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
created := false
defer func() {
if !created {
keys.keyRing.ClearPrivateParams()
}
}()
encName, err := encryptName(name, nil, parent.keys.keyRing, signKR, now)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
encHashKey, hashKey, err := generateHashKey(keys.keyRing, now)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
x := &xattrs{}
var encXAttrs string
if !modTime.IsZero() {
x.ModTime = modTime.UTC()
if encXAttrs, err = encryptXAttrs(x, keys.keyRing, signKR, now); err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
}
req := &api.CreateFolderRequest{
ParentLinkID: parentID,
NodeKey: nodeKey,
NodeHashKey: encHashKey,
NodePassphrase: passphrase,
NodePassphraseSignature: passphraseSig,
SignatureEmail: c.addr.Email,
Name: encName,
Hash: nameHash(name, parent.hashKey),
XAttr: encXAttrs,
}
var resp api.CreateFolderResponse
err = c.apiCall(ctx, &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/folders"}, req, &resp)
if err != nil {
// A failed call may still have created the folder.
c.cache.invalidateChildren(parentID)
return nil, mutationError(what, err)
}
created = true
// Whoever holds the parent's key can decrypt the new one.
keys.unverified = parent.keys.unverified
t := now
if t.IsZero() {
t = time.Now()
}
n := &node{
ID: resp.Folder.ID,
ParentID: parentID,
Name: name,
IsFolder: true,
State: api.LinkStateActive,
CreateTime: t,
ServerModTime: t,
X: x,
keys: keys,
hashKey: hashKey,
keyVerifyKR: c.addr.keyRing,
link: &api.LinkDetails{
Link: api.Link{
LinkID: resp.Folder.ID,
Type: api.LinkTypeFolder,
ParentLinkID: parentID,
State: api.LinkStateActive,
CreateTime: t.Unix(),
ModifyTime: t.Unix(),
Name: encName,
NameHash: req.Hash,
NodeKey: nodeKey,
NodePassphrase: passphrase,
NodePassphraseSignature: passphraseSig,
SignatureEmail: c.addr.Email,
NameSignatureEmail: c.addr.Email,
},
Folder: &api.Folder{NodeHashKey: encHashKey, XAttr: encXAttrs},
},
}
c.rememberKeys(n)
c.cache.add(n)
return n, nil
}
// rename renames n within its folder. It returns errExists if the
// folder has a node named newName, and an error if n was renamed or
// moved since it was read.
func (c *client) rename(ctx context.Context, n *node, newName string) error {
what := fmt.Sprintf("rename %q to %q", n.Name, newName)
if n.ParentID == "" {
return fmt.Errorf("%s: the root can't be renamed", what)
}
if err := validateName(newName); err != nil {
return fmt.Errorf("%s: %w", what, err)
}
if err := c.checkVerified("renaming", n); err != nil {
return fmt.Errorf("%s: %w", what, err)
}
parent, err := c.targetFolder(ctx, n.ParentID)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
signKR, err := c.addr.signingKeyRing()
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
sk, err := renameSessionKey(n, parent.keys.keyRing)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
encName, err := encryptName(newName, sk, parent.keys.keyRing, signKR, c.s.serverTime())
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
req := &api.RenameRequest{
Name: encName,
Hash: nameHash(newName, parent.hashKey),
NameSignatureEmail: c.addr.Email,
OriginalHash: n.link.Link.NameHash,
}
err = c.apiCall(ctx, &rest.Opts{Method: "PUT", Path: c.volumePath("/drive/v2/volumes", "links", n.ID, "rename")}, req, nil)
// A failure may mean the cached node is out of date.
c.forget(n.ID, n.ParentID)
if err != nil {
return mutationError(what, err)
}
return nil
}
// renameSessionKey returns the session key for n's new name, from the
// name encrypted to parentKR: as in the SDK the session key of the old
// name, unless its signature didn't verify, when it is nil for a new
// one, as whoever made it may know it.
func renameSessionKey(n *node, parentKR *crypto.KeyRing) (*crypto.SessionKey, error) {
if !n.nameSigned {
return nil, nil
}
return nameSessionKey(n.link.Link.Name, parentKR)
}
// checkVerified returns an error wrapping errIntegrity if n's key is
// unverified, for op, an operation which would vouch for n. If
// IgnoreSignatureErrors is set it logs that instead.
func (c *client) checkVerified(op string, n *node) error {
switch {
case n.keys.unverified == nil:
return nil
case c.opt.IgnoreSignatureErrors:
c.reportUnverified(op, n, "it is trusted from now on")
return nil
}
return fmt.Errorf("%w: %v: set ignore_signature_errors to change it anyway", errIntegrity, n.keys.unverified)
}
// newParentCrypto is a node's name and passphrase encrypted to a new
// parent, for a move or copy.
type newParentCrypto struct {
name string
hash string
passphrase string
// passphraseSig and its signer are set only for a node whose key
// is anonymous, which the SDK has the mover sign: the passphrase
// is unchanged, so another node keeps its signature.
passphraseSig string
passphraseSigEmail string
}
// encryptForNewParent returns the name newName and the passphrase of n
// encrypted to folder newParent and signed by the client's address,
// reusing their session keys as the SDK's encryptNodeWithNewParent
// does (the name's only if renameSessionKey allows), for op, a move or
// copy.
func (c *client) encryptForNewParent(ctx context.Context, op string, n *node, newParent *node, newName string) (*newParentCrypto, error) {
// An anonymous node's passphrase is signed anew as the client's.
if err := c.checkVerified(op, n); err != nil {
return nil, err
}
oldParent, err := c.folderKeysOf(ctx, n.ParentID)
if err != nil {
return nil, err
}
oldParentKR := oldParent.keyRing
signKR, err := c.addr.signingKeyRing()
if err != nil {
return nil, err
}
now := c.s.serverTime()
sk, err := renameSessionKey(n, oldParentKR)
if err != nil {
return nil, err
}
out := &newParentCrypto{hash: nameHash(newName, newParent.hashKey)}
if out.name, err = encryptName(newName, sk, newParent.keys.keyRing, signKR, now); err != nil {
return nil, err
}
passphraseSig := ""
// The passphrase keeps its session key, as in the SDK.
out.passphrase, passphraseSig, err = encryptPassphrase(n.keys, newParent.keys.keyRing, signKR, now)
if err != nil {
return nil, err
}
if n.link.Link.SignatureEmail == "" {
out.passphraseSig, out.passphraseSigEmail = passphraseSig, c.addr.Email
}
return out, nil
}
// move moves n into folder newParentID as newName. It returns
// errExists if newParentID has a node named newName, and an error if n
// was renamed or moved since it was read.
func (c *client) move(ctx context.Context, n *node, newParentID, newName string) error {
what := fmt.Sprintf("move %q to %q in %s", n.Name, newName, newParentID)
if n.ParentID == "" {
return fmt.Errorf("%s: the root can't be moved", what)
}
if err := validateName(newName); err != nil {
return fmt.Errorf("%s: %w", what, err)
}
newParent, err := c.targetFolder(ctx, newParentID)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
enc, err := c.encryptForNewParent(ctx, "moving", n, newParent, newName)
if err != nil {
return fmt.Errorf("%s: %w", what, err)
}
req := &api.MoveRequest{
ParentLinkID: newParentID,
NodePassphrase: enc.passphrase,
NodePassphraseSignature: enc.passphraseSig,
SignatureEmail: enc.passphraseSigEmail,
Name: enc.name,
NameSignatureEmail: c.addr.Email,
Hash: enc.hash,
OriginalHash: n.link.Link.NameHash,
}
err = c.apiCall(ctx, &rest.Opts{Method: "PUT", Path: c.volumePath("/drive/v2/volumes", "links", n.ID, "move")}, req, nil)
// A failure may mean the cached node is out of date.
c.forget(n.ID, n.ParentID, newParentID)
if err != nil {
return mutationError(what, err)
}
return nil
}
// copyNode copies n, and a folder's contents, into folder newParentID
// as newName and returns the copy. It returns errExists if newParentID
// has a node named newName.
//
// As in the SDK only the name and passphrase are encrypted anew; the
// server copies the rest.
func (c *client) copyNode(ctx context.Context, n *node, newParentID, newName string) (*node, error) {
what := fmt.Sprintf("copy %q to %q in %s", n.Name, newName, newParentID)
if n.ParentID == "" {
return nil, fmt.Errorf("%s: the root can't be copied", what)
}
if err := validateName(newName); err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
newParent, err := c.targetFolder(ctx, newParentID)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
enc, err := c.encryptForNewParent(ctx, "copying", n, newParent, newName)
if err != nil {
return nil, fmt.Errorf("%s: %w", what, err)
}
req := &api.CopyRequest{
Name: enc.name,
NodePassphrase: enc.passphrase,
Hash: enc.hash,
TargetVolumeID: c.volumeID,
TargetParentLinkID: newParentID,
NameSignatureEmail: c.addr.Email,
NodePassphraseSignature: enc.passphraseSig,
SignatureEmail: enc.passphraseSigEmail,
}
var resp api.CopyResponse
err = c.apiCall(ctx, &rest.Opts{Method: "POST", Path: c.volumePath("/drive/volumes", "links", n.ID, "copy")}, req, &resp)
if err != nil {
// A failed call may still have made the copy.
c.cache.invalidateChildren(newParentID)
return nil, mutationError(what, err)
}
cp, err := c.readBack(ctx, resp.LinkID, found)
if err != nil {
c.cache.invalidateChildren(newParentID)
return nil, fmt.Errorf("%s: %w", what, err)
}
c.cache.add(cp)
return cp, nil
}
// trash moves the nodes ids to the trash, metadataBatchSize per
// request. The failures of single nodes are joined in the returned
// error, each wrapping errNotFound if the node doesn't exist.
func (c *client) trash(ctx context.Context, ids ...string) error {
opts := &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/trash_multiple"}
var errs []error
for batch := range slices.Chunk(ids, metadataBatchSize) {
var resp api.MultiLinkResponse
err := c.apiCall(ctx, opts, &api.LinksRequest{LinkIDs: batch}, &resp)
for _, id := range batch {
c.cache.invalidate(id)
}
if err != nil {
errs = append(errs, fmt.Errorf("trash: %w", err))
break
}
// As in the SDK, a node without a response was trashed.
for _, r := range resp.Responses {
if r.Response.Code/1000 == 1 && r.Response.Error == "" {
continue
}
errs = append(errs, mutationError("trash "+r.LinkID, &api.Error{Code: r.Response.Code, Message: r.Response.Error}))
}
}
return errors.Join(errs...)
}
// emptyTrash permanently deletes the nodes in the trash.
func (c *client) emptyTrash(ctx context.Context) error {
err := c.apiCall(ctx, &rest.Opts{Method: "DELETE", Path: c.volumePath("/drive/volumes") + "/trash"}, nil, nil)
// Nodes in the trash, and below folders in it, may be cached.
c.cache.clear()
if err != nil {
return fmt.Errorf("empty trash: %w", err)
}
return nil
}
// about returns the space used by the account and its total space.
func (c *client) about(ctx context.Context) (used, total int64, err error) {
var resp api.UserResponse
if err := c.apiCall(ctx, &rest.Opts{Method: "GET", Path: "/core/v4/users"}, nil, &resp); err != nil {
return 0, 0, fmt.Errorf("get quota: %w", err)
}
return resp.User.UsedSpace, resp.User.MaxSpace, nil
}
// close forgets the cache and clears the private key material of the
// client, which must not be used afterwards.
func (c *client) close() {
if c.events != nil {
c.events.close()
}
c.cache.clear()
c.mu.Lock()
for id, keys := range c.folderKeys {
keys.keyRing.ClearPrivateParams()
delete(c.folderKeys, id)
}
c.mu.Unlock()
if c.shareKeys != nil {
c.shareKeys.keyRing.ClearPrivateParams()
}
c.acct.close()
}