package protondrive import ( "bytes" "context" "crypto/sha1" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "strings" "sync" "time" "github.com/ProtonMail/gopenpgp/v3/crypto" "github.com/rclone/rclone/backend/protondrive/api" "github.com/rclone/rclone/fs" "github.com/rclone/rclone/lib/pacer" "github.com/rclone/rclone/lib/pool" "github.com/rclone/rclone/lib/rest" "golang.org/x/sync/errgroup" ) // errUploadMismatch is returned when the bytes read from the source of // an upload don't match its declared size or SHA1. var errUploadMismatch = errors.New("source doesn't match its declared size or hash") // errUploadOutcomeUnknown is returned when the commit of an upload // failed and whether it took effect can't be found out. var errUploadOutcomeUnknown = errors.New("upload outcome unknown: it may have succeeded") // errUploadSuperseded is returned when an upload was committed but the // file read back has another revision, which is not this upload's. var errUploadSuperseded = errors.New("upload committed, but the file now has another revision") // errUploadUnconfirmed is returned when an upload was committed but the // server still didn't show it when the file was last read back. var errUploadUnconfirmed = errors.New("upload committed, but the server doesn't show it yet") const ( // defaultUploadConcurrency and maxUploadConcurrency bound the blocks // of one file being uploaded at once, as in the SDK. defaultUploadConcurrency = 4 maxUploadConcurrency = 5 // blockUploadAttempts is how many times uploading a block is tried. blockUploadAttempts = 3 // blockSealAttempts is how many times a block whose encryption // fails its check is encrypted, as in the SDK. blockSealAttempts = 2 // intendedSizePrecision is the precision of the size an upload // declares in advance, which must not tell the server the size. intendedSizePrecision = 100_000 // draftCleanupTimeout bounds deleting the draft of a failed upload. draftCleanupTimeout = 30 * time.Second ) // uploadRequest is a file to upload. type uploadRequest struct { ParentID string // folder to create the file in; unused if Existing is set Name string // name of the new file; unused if Existing is set Existing *node // file to give a new revision; nil for a new file In io.Reader Size int64 // bytes In holds; < 0 if unknown ModTime time.Time // zero if unknown MIMEType string SHA1 string // hex SHA-1 of the bytes In holds; "" if unknown } // draft is an uncommitted revision being uploaded. type draft struct { nodeID string revisionID string parentID string newFile bool // the node is a draft too, not just the revision baseRevisionID string // active revision the draft revision was created from; new revisions only nodeKR *crypto.KeyRing ownKeys bool // nodeKR was generated for the draft and is cleared with it sk *crypto.SessionKey // content key } // upload uploads r as a new file, or a new revision of r.Existing, as // the SDK's upload module does, and returns the file. // // A new file whose name is taken by a file is uploaded as a new // revision of it. A draft of the name left by this client (by // DraftClientUID) is deleted and the upload tried again; one left by // another client is errExists unless ReplaceExistingDraft is set. If // the bytes read differ from r.Size or r.SHA1 the upload fails with // errUploadMismatch. // // A failed upload deletes its draft only when nothing may have been // committed: before the commit, or when the server refused the commit // with a 4xx API error on its only attempt. Otherwise nothing is deleted // and a failed commit whose revision the file read back doesn't show is // errUploadOutcomeUnknown: the upload may have succeeded. A commit which // succeeded but whose file has another revision by the time it is read // back is errUploadSuperseded, and one the server still doesn't show // after a few reads is errUploadUnconfirmed. The returned node is always // the upload's own revision. func (c *client) upload(ctx context.Context, r uploadRequest) (*node, error) { what := fmt.Sprintf("upload %q", r.Name) if r.Existing != nil { what = fmt.Sprintf("upload %q", r.Existing.Name) } signKR, err := c.addr.signingKeyRing() if err != nil { return nil, fmt.Errorf("%s: %w", what, err) } d, err := c.createDraft(ctx, r, signKR) if err != nil { return nil, fmt.Errorf("%s: %w", what, err) } if d.ownKeys { defer d.nodeKR.ClearPrivateParams() } n, committed, err := c.uploadDraft(ctx, d, r, signKR) if err != nil { if !committed { c.deleteDraft(ctx, d) } return nil, fmt.Errorf("%s: %w", what, err) } return n, nil } // draftClientUID returns the ClientUID marking the client's drafts, or // nil if it has none. func (c *client) draftClientUID() *string { if c.opt.DraftClientUID == "" { return nil } uid := c.opt.DraftClientUID return &uid } // derivedDraftClientUID returns a draft client ID for the remote name // derived from the name and the account's volume, so it is the same on // every run. func (c *client) derivedDraftClientUID(name string) string { sum := sha256.Sum256([]byte("rclone draft client\x00" + c.volumeID + "\x00" + name)) return hex.EncodeToString(sum[:16]) } // uploadConcurrency returns the most blocks of one file to upload at // once. func (c *client) uploadConcurrency() int { if c.opt.UploadConcurrency <= 0 { return defaultUploadConcurrency } return min(c.opt.UploadConcurrency, maxUploadConcurrency) } // draftIntendedSize returns the IntendedUploadSize of a new file of // size bytes as the SDK's createDraft sends it: rounded down to // intendedSizePrecision, or nil if that is at most the precision or the // size is unknown. func draftIntendedSize(size int64) *int64 { rounded := size / intendedSizePrecision * intendedSizePrecision if size < 0 || rounded <= intendedSizePrecision { return nil } return &rounded } // revisionIntendedSize returns the IntendedUploadSize of a new revision // of size bytes as the SDK's createDraftRevision sends it // (reduceSizePrecision), or nil if the size is zero or unknown. func revisionIntendedSize(size int64) *int64 { var v int64 switch { case size <= 0: return nil case size < 4096: v = 4095 case size < intendedSizePrecision: v = intendedSizePrecision default: v = size / intendedSizePrecision * intendedSizePrecision } return &v } // createDraft creates the draft to upload r to: a draft file in // r.ParentID, or a draft revision of r.Existing or of the file which // has the name. func (c *client) createDraft(ctx context.Context, r uploadRequest, signKR *crypto.KeyRing) (*draft, error) { if r.Existing != nil { return c.createRevision(ctx, r.Existing, r.Size) } if err := validateName(r.Name); err != nil { return nil, err } parent, err := c.targetFolder(ctx, r.ParentID) if err != nil { return nil, err } now := c.s.serverTime() nodeKey, passphrase, passphraseSig, keys, err := generateNodeKeys(parent.keys.keyRing, signKR, true, now) if err != nil { return nil, err } created := false defer func() { if !created { keys.keyRing.ClearPrivateParams() } }() contentKeyPacket, contentKeyPacketSig, sk, err := generateContentKey(keys.keyRing, now) if err != nil { return nil, err } encName, err := encryptName(r.Name, nil, parent.keys.keyRing, signKR, now) if err != nil { return nil, err } mimeType := r.MIMEType if mimeType == "" { mimeType = "application/octet-stream" } req := &api.CreateFileRequest{ ParentLinkID: parent.ID, Name: encName, Hash: nameHash(r.Name, parent.hashKey), MIMEType: mimeType, ClientUID: c.draftClientUID(), IntendedUploadSize: draftIntendedSize(r.Size), NodeKey: nodeKey, NodePassphrase: passphrase, NodePassphraseSignature: passphraseSig, ContentKeyPacket: contentKeyPacket, ContentKeyPacketSignature: contentKeyPacketSig, SignatureAddress: c.addr.Email, } opts := &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/files"} for retried := false; ; retried = true { var resp api.CreateFileResponse err = c.apiCall(ctx, opts, req, &resp) if err == nil { created = true return &draft{ nodeID: resp.File.ID, revisionID: resp.File.RevisionID, parentID: parent.ID, newFile: true, nodeKR: keys.keyRing, ownKeys: true, sk: sk, }, nil } existing, err := c.resolveConflict(ctx, err, retried) if err != nil { return nil, err } if existing != nil { return c.createRevision(ctx, existing, r.Size) } } } // resolveConflict decides what to do after creating a draft failed // with err, as the SDK's handleConflictError does. It returns the file // to upload a new revision of if the name is taken by a file, or nil // and no error to try again once a draft in the way is deleted. // // A draft is deleted if it was left by this client or // ReplaceExistingDraft is set, unless retried is set: a draft which // comes back is another client's upload in progress. func (c *client) resolveConflict(ctx context.Context, err error, retried bool) (*node, error) { var apiErr *api.Error if !errors.As(err, &apiErr) || apiErr.Code != api.CodeAlreadyExists { return nil, fmt.Errorf("create draft: %w", err) } var conflict api.ConflictDetails if json.Unmarshal(apiErr.Details, &conflict) != nil || conflict.ConflictLinkID == "" { return nil, mutationError("create draft", err) } if conflict.ConflictRevisionID != "" || conflict.ConflictDraftRevisionID == "" { // Only a file, which has an active revision, can take a new // revision. A draft revision of it doesn't stop that. c.cache.invalidate(conflict.ConflictLinkID) n, getErr := c.getNode(ctx, conflict.ConflictLinkID) if getErr != nil { return nil, fmt.Errorf("create draft: %w", getErr) } if n.IsFolder || n.State != api.LinkStateActive || n.RevisionID == "" { return nil, mutationError("create draft", err) } return n, nil } own := c.opt.DraftClientUID != "" && conflict.ConflictDraftClientUID == c.opt.DraftClientUID switch { case retried: return nil, fmt.Errorf("create draft: a draft of the file came back after it was deleted: %w", mutationError("another client is uploading it", err)) case !own && !c.opt.ReplaceExistingDraft: return nil, fmt.Errorf("create draft: another client is uploading the file (set replace_existing_draft to replace its draft): %w", mutationError("draft exists", err)) } fs.Debugf(nil, "protondrive: deleting draft %s left by client %q", conflict.ConflictLinkID, conflict.ConflictDraftClientUID) if delErr := c.deleteDraftLink(ctx, conflict.ConflictLinkID); delErr != nil { return nil, fmt.Errorf("create draft: %w (deleting the draft in the way failed: %v)", mutationError("draft exists", err), delErr) } return nil, nil } // createRevision creates a draft revision of file n, which must be // unchanged since it was read. func (c *client) createRevision(ctx context.Context, n *node, size int64) (*draft, error) { if n.IsFolder || n.link == nil || n.link.File == nil || n.RevisionID == "" { return nil, fmt.Errorf("%q is not a file with content", n.Name) } sk, err := c.contentKey(n, "updating") if err != nil { return nil, err } req := &api.CreateRevisionRequest{ CurrentRevisionID: n.RevisionID, ClientUID: c.draftClientUID(), IntendedUploadSize: revisionIntendedSize(size), } var resp api.CreateRevisionResponse err = c.apiCall(ctx, &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes", "files", n.ID, "revisions")}, req, &resp) c.cache.invalidate(n.ID) if err != nil { return nil, mutationError("create revision", err) } return &draft{ nodeID: n.ID, revisionID: resp.Revision.ID, baseRevisionID: n.RevisionID, parentID: n.ParentID, nodeKR: n.keys.keyRing, sk: sk, }, nil } // uploadResult is what was read from the source of an upload and // uploaded. type uploadResult struct { size int64 sha1 string // hex hashes [][]byte // SHA-256 of each encrypted block, in order blockSizes []int64 // plaintext size of each block, in order } // check checks res against the size and SHA1 r declares, and its block // count against its size. func (res *uploadResult) check(r uploadRequest) error { switch { case r.Size >= 0 && res.size != r.Size: return fmt.Errorf("%w: read %d bytes, expected %d", errUploadMismatch, res.size, r.Size) case r.SHA1 != "" && !strings.EqualFold(r.SHA1, res.sha1): return fmt.Errorf("%w: read bytes with SHA1 %s, expected %s", errUploadMismatch, res.sha1, r.SHA1) case int64(len(res.hashes)) != (res.size+defaultBlockSize-1)/defaultBlockSize: return fmt.Errorf("%d blocks uploaded for %d bytes", len(res.hashes), res.size) } return nil } // uploadDraft uploads the content of r to draft d and commits it, // returning the committed file. committed reports whether the revision // may be committed, even if err is set, when the draft must not be // deleted: committed is false only when the commit wasn't sent or the // server refused it on its only attempt. What a read shows never proves // a commit didn't take effect: reads may lag. func (c *client) uploadDraft(ctx context.Context, d *draft, r uploadRequest, signKR *crypto.KeyRing) (n *node, committed bool, err error) { code, verifySK, err := c.verificationData(ctx, d) if err != nil { return nil, false, err } res, err := c.uploadBlocks(ctx, d, r, code, verifySK, signKR) if err != nil { return nil, false, err } if err := res.check(r); err != nil { return nil, false, err } now := c.s.serverTime() manifest, err := signManifest(res.hashes, signKR, now) if err != nil { return nil, false, err } x := &xattrs{Size: res.size, BlockSizes: res.blockSizes, SHA1: res.sha1} if !r.ModTime.IsZero() { x.ModTime = r.ModTime.UTC() } encXAttrs, err := encryptXAttrs(x, d.nodeKR, signKR, now) if err != nil { return nil, false, err } req := &api.CommitRevisionRequest{ ManifestSignature: manifest, SignatureAddress: c.addr.Email, XAttr: encXAttrs, ChecksumVerified: r.SHA1 != "", } opts := &rest.Opts{Method: "PUT", Path: c.volumePath("/drive/v2/volumes", "files", d.nodeID, "revisions", d.revisionID)} attempts := 0 commitErr := c.pacedCall(ctx, c.apiPacer, func() (*http.Response, error) { attempts++ return c.s.call(ctx, opts, req, nil) }) if commitErr != nil && attempts == 1 && refusedCommit(commitErr) { c.forget(d.nodeID, d.parentID) return nil, false, fmt.Errorf("commit: %w", commitErr) } // Whether a failed commit took effect is read even if ctx is done, // though only once then, as a commit which did is a success. readCtx, cancel := context.WithTimeout(ctx, draftCleanupTimeout) defer cancel() if commitErr != nil && ctx.Err() != nil { detached, cancelDetached := context.WithTimeout(context.WithoutCancel(ctx), draftCleanupTimeout) defer cancelDetached() n, err = c.fetchNode(detached, d.nodeID) } else { n, err = c.readBack(readCtx, d.nodeID, func(n *node, err error) bool { return !d.lagging(n, err) }) } ours := err == nil && n.State == api.LinkStateActive && n.RevisionID == d.revisionID if ours { c.cache.add(n) } else { c.forget(d.nodeID, d.parentID) } switch { case ours && commitErr != nil: // The response of a commit which succeeded may have been lost, // and its retry then failed. fs.Debugf(nil, "protondrive: %q (ID %s): commit failed but the revision is active: %v", n.Name, n.ID, commitErr) return n, true, nil case ours: return n, true, nil case commitErr == nil && (d.lagging(n, err) || ctx.Err() != nil): fs.Debugf(nil, "protondrive: node %s: revision %s committed, but the server doesn't show it yet", d.nodeID, d.revisionID) return nil, true, errUploadUnconfirmed case commitErr == nil && err != nil: return nil, true, fmt.Errorf("read the uploaded file: %w", err) case commitErr == nil: return nil, true, fmt.Errorf("%w (the file is in state %d with revision %q active, not %s)", errUploadSuperseded, n.State, n.RevisionID, d.revisionID) case err != nil: // Any draft left is replaced by the next upload of the name. return nil, true, fmt.Errorf("commit: %w: %w (reading the file failed: %v)", errUploadOutcomeUnknown, commitErr, err) } // A read may lag, or the file have changed since, so what it shows // doesn't prove the commit didn't take effect. return nil, true, fmt.Errorf("commit: %w: %w (the file doesn't show the revision)", errUploadOutcomeUnknown, commitErr) } // refusedCommit reports whether err, from a commit sent only once, is // the server refusing it, so that it didn't take effect: an API error // with a 4xx status other than 408 and a Proton code. func refusedCommit(err error) bool { var apiErr *api.Error return errors.As(err, &apiErr) && apiErr.Code != 0 && apiErr.Status >= 400 && apiErr.Status < 500 && apiErr.Status != http.StatusRequestTimeout } // lagging reports whether n and err, read after the commit of d, may // be from before the server shows the commit: the node isn't found, is // active without an active revision, or looks as it did before (a new // file still a draft, or the revision d started from still active). func (d *draft) lagging(n *node, err error) bool { switch { case errors.Is(err, errNotFound): return true case err != nil: return false case n.State == api.LinkStateActive && n.RevisionID == "": return true case d.newFile: return n.State == api.LinkStateDraft } return n.State == api.LinkStateActive && n.RevisionID == d.baseRevisionID } // verificationData returns the verification code of draft d and the // content key the server holds for it, which blocks are checked // against as in the SDK. func (c *client) verificationData(ctx context.Context, d *draft) (code []byte, sk *crypto.SessionKey, err error) { var resp api.VerificationResponse opts := &rest.Opts{Method: "GET", Path: c.volumePath("/drive/v2/volumes", "links", d.nodeID, "revisions", d.revisionID, "verification")} if err := c.apiCall(ctx, opts, nil, &resp); err != nil { return nil, nil, fmt.Errorf("get verification data: %w", err) } code, err = base64.StdEncoding.DecodeString(resp.VerificationCode) if err != nil { return nil, nil, fmt.Errorf("get verification data: %w", err) } sk, _, err = decryptContentKey(resp.ContentKeyPacket, "", d.nodeKR, nil, c.s.serverTime()) if err != nil { return nil, nil, fmt.Errorf("get verification data: %w", err) } return code, sk, nil } // encryptedBlock is a block of a draft, encrypted and checked, which // holds its share of the upload concurrency until freed. type encryptedBlock struct { index int enc *pool.RW encSignature string token []byte // verifier token release func() // gives back the share of the upload concurrency } // free frees the block's buffer and its share of the upload // concurrency. func (b *encryptedBlock) free() { _ = b.enc.Close() b.release() } // freeBlocks frees every block of blocks. func freeBlocks(blocks []*encryptedBlock) { for _, b := range blocks { b.free() } } // blockUpload is a block with the URL to upload it to. type blockUpload struct { block *encryptedBlock link api.UploadLink } // uploadBlocks reads, encrypts and uploads the content of r to draft // d: one goroutine reads and encrypts blocks, one requests their upload // URLs in batches, and uploadConcurrency workers upload them. Every // wait is bounded by ctx. func (c *client) uploadBlocks(ctx context.Context, d *draft, r uploadRequest, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (*uploadResult, error) { concurrency := c.uploadConcurrency() g, gCtx := errgroup.WithContext(ctx) ready := make(chan *encryptedBlock) uploads := make(chan blockUpload) res := &uploadResult{} g.Go(func() error { defer close(ready) return c.readBlocks(gCtx, d, r, code, verifySK, signKR, concurrency, res, ready) }) g.Go(func() error { defer close(uploads) return c.requestURLs(gCtx, d, ready, uploads) }) for range concurrency { g.Go(func() error { for { var u blockUpload var ok bool select { case u, ok = <-uploads: case <-gCtx.Done(): return gCtx.Err() } if !ok { return nil } err := c.uploadBlock(gCtx, d, u) u.block.free() if err != nil { return fmt.Errorf("block %d: %w", u.block.index, err) } } }) } if err := g.Wait(); err != nil { return nil, err } return res, nil } // readBlocks reads r.In block by block into pool buffers, encrypts and // checks each block and sends it to ready, recording what it read in // res. At most concurrency blocks of the upload, and blocksInFlight of // the client, are held at once. // // A source longer than r.Size fails with errUploadMismatch as soon as // that is seen. func (c *client) readBlocks(ctx context.Context, d *draft, r uploadRequest, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing, concurrency int, res *uploadResult, ready chan<- *encryptedBlock) error { slots := make(chan struct{}, concurrency) digest := sha1.New() in := io.TeeReader(r.In, digest) for index := 1; ; index++ { release, err := c.reserveBlock(ctx, slots) if err != nil { return err } plain := pool.NewRW(pool.Global()) n, err := plain.ReadFrom(io.LimitReader(in, defaultBlockSize)) res.size += n switch { case err != nil: err = fmt.Errorf("read source: %w", err) case r.Size >= 0 && res.size > r.Size: err = fmt.Errorf("%w: source is longer than %d bytes", errUploadMismatch, r.Size) } if err != nil || n == 0 { _ = plain.Close() release() if err != nil { return err } break } b, hash, err := c.sealBlock(d, plain, index, code, verifySK, signKR) _ = plain.Close() if err != nil { release() return fmt.Errorf("block %d: %w", index, err) } b.release = release res.hashes = append(res.hashes, hash) res.blockSizes = append(res.blockSizes, n) select { case ready <- b: case <-ctx.Done(): b.free() return ctx.Err() } if n < defaultBlockSize { break } } res.sha1 = hex.EncodeToString(digest.Sum(nil)) return nil } // reserveBlock takes a share of the upload's concurrency from slots and // of the client's from uploadTokens, returning the function which // gives both back. func (c *client) reserveBlock(ctx context.Context, slots chan struct{}) (release func(), err error) { select { case slots <- struct{}{}: case <-ctx.Done(): return nil, ctx.Err() } if err := acquireToken(ctx, c.uploadTokens); err != nil { <-slots return nil, err } return func() { c.uploadTokens.Put() <-slots }, nil } // acquireToken gets a token from td, or returns the error of ctx if it // is done first. TokenDispenser.Get can't be cancelled, so an abandoned // wait gives the token back when it gets it. func acquireToken(ctx context.Context, td *pacer.TokenDispenser) error { if err := ctx.Err(); err != nil { return err } got := make(chan struct{}) go func() { td.Get() select { case got <- struct{}{}: case <-ctx.Done(): td.Put() } }() select { case <-got: return nil case <-ctx.Done(): return ctx.Err() } } // sealBlock encrypts and signs the block in plain as block index of d, // checks it decrypts with the server's content key verifySK and makes // its verifier token from code. As in the SDK, a block whose check // fails, which may be a bit flip, is encrypted once more. func (c *client) sealBlock(d *draft, plain *pool.RW, index int, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (b *encryptedBlock, hash []byte, err error) { for attempt := 1; ; attempt++ { b, hash, err = c.sealBlockOnce(d, plain, index, code, verifySK, signKR) if err == nil || attempt == blockSealAttempts { return b, hash, err } fs.Debugf(nil, "protondrive: block %d: %v: encrypting it again", index, err) } } // sealBlockOnce makes one attempt of sealBlock. func (c *client) sealBlockOnce(d *draft, plain *pool.RW, index int, code []byte, verifySK *crypto.SessionKey, signKR *crypto.KeyRing) (*encryptedBlock, []byte, error) { if _, err := plain.Seek(0, io.SeekStart); err != nil { return nil, nil, err } enc := pool.NewRW(pool.Global()) h := sha256.New() encSignature, err := encryptBlockTo(io.MultiWriter(enc, h), plain, d.sk, d.nodeKR, signKR, c.s.serverTime()) if err == nil { err = checkBlock(enc, verifySK) } var token []byte if err == nil { token, err = blockToken(enc, code) } if err != nil { _ = enc.Close() return nil, nil, err } if c.verifierHook != nil { c.verifierHook(token) } return &encryptedBlock{index: index, enc: enc, encSignature: encSignature, token: token}, h.Sum(nil), nil } // checkBlock checks the encrypted block enc decrypts with sk. func checkBlock(enc *pool.RW, sk *crypto.SessionKey) error { if _, err := enc.Seek(0, io.SeekStart); err != nil { return err } dec, err := blockDecrypter(enc, sk) if err == nil { _, err = io.Copy(io.Discard, dec) } if err != nil { return fmt.Errorf("encrypted block doesn't decrypt with the file's content key: %w", err) } return nil } // blockToken returns the verifier token of the encrypted block enc. func blockToken(enc *pool.RW, code []byte) ([]byte, error) { if _, err := enc.Seek(0, io.SeekStart); err != nil { return nil, err } prefix := make([]byte, len(code)) n, err := io.ReadFull(enc, prefix) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { return nil, err } return verifierToken(code, prefix[:n]), nil } // requestURLs takes blocks from ready as they come, requests their // upload URLs in batches of those waiting and passes them to uploads. func (c *client) requestURLs(ctx context.Context, d *draft, ready <-chan *encryptedBlock, uploads chan<- blockUpload) error { for { var batch []*encryptedBlock select { case b, ok := <-ready: if !ok { return nil } batch = append(batch, b) case <-ctx.Done(): return ctx.Err() } done := false waiting: for !done { select { case b, ok := <-ready: if ok { batch = append(batch, b) } done = !ok default: break waiting } } links, err := c.blockURLs(ctx, d, batch) if err != nil { freeBlocks(batch) return err } for i, b := range batch { select { case uploads <- blockUpload{block: b, link: links[i]}: case <-ctx.Done(): freeBlocks(batch[i:]) return ctx.Err() } } if done { return nil } } } // blockURLs requests the upload URLs of blocks of draft d, in the // order of blocks. func (c *client) blockURLs(ctx context.Context, d *draft, blocks []*encryptedBlock) ([]api.UploadLink, error) { req := &api.BlockUploadRequest{ AddressID: c.addr.ID, VolumeID: c.volumeID, LinkID: d.nodeID, RevisionID: d.revisionID, BlockList: make([]api.BlockUploadInfo, 0, len(blocks)), ThumbnailList: []struct{}{}, } for _, b := range blocks { req.BlockList = append(req.BlockList, api.BlockUploadInfo{ Index: b.index, EncSignature: b.encSignature, Verifier: api.BlockVerifier{Token: base64.StdEncoding.EncodeToString(b.token)}, }) } var resp api.BlockUploadResponse if err := c.apiCall(ctx, &rest.Opts{Method: "POST", Path: "/drive/blocks"}, req, &resp); err != nil { return nil, fmt.Errorf("request upload URLs: %w", err) } byIndex := make(map[int]api.UploadLink, len(resp.UploadLinks)) for _, l := range resp.UploadLinks { byIndex[l.Index] = l } links := make([]api.UploadLink, len(blocks)) for i, b := range blocks { l, ok := byIndex[b.index] if !ok || l.BareURL == "" { return nil, fmt.Errorf("request upload URLs: no URL for block %d", b.index) } links[i] = l } return links, nil } // uploadBlock uploads block u to the storage host, trying up to // blockUploadAttempts times. A 404 means the URL expired, so a new one // is requested. func (c *client) uploadBlock(ctx context.Context, d *draft, u blockUpload) error { link := u.link for attempt := 1; ; attempt++ { retry, err := c.postBlock(ctx, link, u.block.enc) var apiErr *api.Error switch { case err == nil: return nil case ctx.Err() != nil: return ctx.Err() case attempt >= blockUploadAttempts: return err case errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound: fs.Debugf(nil, "protondrive: block %d: upload URL expired: requesting a new one", u.block.index) links, err := c.blockURLs(ctx, d, []*encryptedBlock{u.block}) if err != nil { return err } link = links[0] case !retry: return err default: fs.Debugf(nil, "protondrive: block %d: upload failed: %v: retrying", u.block.index, err) } } } // postBlock makes one attempt to upload the encrypted block enc to // link, paced by the storage pacer, and reports whether a failure may // be retried. func (c *client) postBlock(ctx context.Context, link api.UploadLink, enc *pool.RW) (retry bool, err error) { paced := c.paced(ctx, func() (*http.Response, error) { if _, err := enc.Seek(0, io.SeekStart); err != nil { return nil, err } body := newMultipartBlock(enc) defer body.finish() opts := &rest.Opts{ Method: "POST", RootURL: link.BareURL, Body: body, ContentType: body.contentType, ContentLength: &body.size, NoResponse: true, // The storage host gets the block's token, never the // session's credentials, which only session.call adds. ExtraHeaders: map[string]string{"pm-storage-token": link.Token}, } return c.s.srv.Call(ctx, opts) }) err = c.storagePacer.CallNoRetry(func() (bool, error) { var err error retry, err = paced() return retry, err }) return retry, err } // errAttemptOver is returned by reads of a multipartBlock whose upload // attempt is over. var errAttemptOver = errors.New("upload attempt is over") // multipartBlock is the multipart/form-data body of one attempt to // upload a block, as the SDK's uploadBlock sends it: the block in the // field Block. // // The HTTP transport may still read a request body after the request // returns, so the body stops reading the block once finished: the // block may then be read for a retry, or freed. type multipartBlock struct { contentType string size int64 mu sync.Mutex r io.Reader done bool } // newMultipartBlock returns the body uploading the block in enc from // its read position. func newMultipartBlock(enc *pool.RW) *multipartBlock { var buf bytes.Buffer mw := multipart.NewWriter(&buf) // Writes to a bytes.Buffer don't fail. _, _ = mw.CreateFormFile("Block", "blob") head := buf.String() buf.Reset() _ = mw.Close() tail := buf.String() pos, _ := enc.Seek(0, io.SeekCurrent) return &multipartBlock{ contentType: mw.FormDataContentType(), size: int64(len(head)+len(tail)) + enc.Size() - pos, r: io.MultiReader(strings.NewReader(head), enc, strings.NewReader(tail)), } } // Read reads the body, or fails once the body is finished. func (b *multipartBlock) Read(p []byte) (int, error) { b.mu.Lock() defer b.mu.Unlock() if b.done { return 0, errAttemptOver } return b.r.Read(p) } // finish stops the body reading the block, waiting for a read in // progress. func (b *multipartBlock) finish() { b.mu.Lock() b.done = true b.mu.Unlock() } // deleteDraft deletes draft d of a failed upload, even if ctx is done, // logging a failure: the draft stands in the way of the next upload of // the name until it is replaced. func (c *client) deleteDraft(ctx context.Context, d *draft) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), draftCleanupTimeout) defer cancel() var err error if d.newFile { err = c.deleteDraftLink(ctx, d.nodeID) } else { err = c.apiCall(ctx, &rest.Opts{Method: "DELETE", Path: c.volumePath("/drive/v2/volumes", "files", d.nodeID, "revisions", d.revisionID)}, nil, nil) } c.forget(d.nodeID, d.parentID) if err != nil { fs.Errorf(nil, "protondrive: failed to delete the draft of a failed upload (node %s, revision %s): %v", d.nodeID, d.revisionID, err) } } // deleteDraftLink permanently deletes the draft node id. func (c *client) deleteDraftLink(ctx context.Context, id string) error { var resp api.MultiLinkResponse opts := &rest.Opts{Method: "POST", Path: c.volumePath("/drive/v2/volumes") + "/delete_multiple"} if err := c.apiCall(ctx, opts, &api.LinksRequest{LinkIDs: []string{id}}, &resp); err != nil { return fmt.Errorf("delete draft: %w", err) } for _, r := range resp.Responses { if r.Response.Code/1000 != 1 || r.Response.Error != "" { return mutationError("delete draft "+r.LinkID, &api.Error{Code: r.Response.Code, Message: r.Response.Error}) } } return nil }