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
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>
787 lines
24 KiB
Go
787 lines
24 KiB
Go
package protondrive
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"slices"
|
|
"strconv"
|
|
"sync"
|
|
|
|
"github.com/ProtonMail/gopenpgp/v3/crypto"
|
|
"github.com/rclone/rclone/backend/protondrive/api"
|
|
"github.com/rclone/rclone/fs"
|
|
"github.com/rclone/rclone/lib/pool"
|
|
"github.com/rclone/rclone/lib/rest"
|
|
)
|
|
|
|
var (
|
|
// errIntegrity is returned when a file's content doesn't match
|
|
// what its uploader signed or claimed.
|
|
errIntegrity = errors.New("integrity check failed")
|
|
|
|
// errBlockHash is returned when a block doesn't match its hash
|
|
// however many times it is downloaded.
|
|
errBlockHash = errors.New("block hash mismatch")
|
|
|
|
// errDownloadClosed is returned by Read after Close.
|
|
errDownloadClosed = errors.New("download closed")
|
|
)
|
|
|
|
// signatureHint ends an error for a signature which fails, telling the
|
|
// user how to read the file anyway.
|
|
const signatureHint = "set ignore_signature_errors to read the file anyway"
|
|
|
|
const (
|
|
// defaultBlockSize is the plaintext size of every block but the
|
|
// last of a file the client uploads.
|
|
defaultBlockSize = 4 << 20
|
|
|
|
// blocksPerPage is the most blocks one revision request lists.
|
|
blocksPerPage = 20
|
|
|
|
// maxBlockSize is the largest block accepted, encrypted or
|
|
// decrypted.
|
|
maxBlockSize = 8 << 20
|
|
|
|
// blockAttempts is how many times a block whose hash doesn't match
|
|
// is downloaded.
|
|
blockAttempts = 3
|
|
|
|
// downloadAhead is the most blocks of one download fetched or
|
|
// waiting to be read, besides the one being read.
|
|
downloadAhead = 4
|
|
|
|
// minUnclaimedBlockSize bounds the blocks of a file which doesn't
|
|
// record its block sizes: there are at most its encrypted size over
|
|
// this, plus one.
|
|
minUnclaimedBlockSize = 1 << 20
|
|
|
|
// maxFileBlocks is the most blocks a file may list: 2 TiB in
|
|
// 4 MiB blocks, beyond any one file the largest Proton plan, of a
|
|
// few TB in all, could hold. A full read holds the metadata of
|
|
// every block until the manifest is checked, so this bounds how
|
|
// many whatever the server claims: about 250-350 MiB at the cap
|
|
// with realistic tokens and URLs. Their length isn't bounded.
|
|
maxFileBlocks = 1 << 19
|
|
|
|
// contentKeyFallbackUntil is the Unix time until which a content
|
|
// key packet may be signed by any of the account's address keys,
|
|
// as in the SDK.
|
|
contentKeyFallbackUntil = 1672531200 // 2023-01-01
|
|
)
|
|
|
|
// open returns a reader of limit bytes of the content of file n from
|
|
// offset, or to the end if limit < 0.
|
|
//
|
|
// A read from offset 0 to the end lists every block and checks the
|
|
// manifest signature before releasing any byte: if it fails, the first
|
|
// Read returns errIntegrity, unless IgnoreSignatureErrors is set, when
|
|
// it is logged. A ranged read checks each block against its listed
|
|
// hash but can't check the manifest. A node key or content key
|
|
// signature which fails is errIntegrity from open, on the same terms.
|
|
// The reader must be closed.
|
|
func (c *client) open(ctx context.Context, n *node, offset, limit int64) (io.ReadCloser, error) {
|
|
return c.openRead(ctx, n, offset, limit, offset == 0 && limit < 0)
|
|
}
|
|
|
|
// openWhole is open for limit bytes from offset 0 of a range which
|
|
// covers the whole file, checked as a full read is.
|
|
func (c *client) openWhole(ctx context.Context, n *node, limit int64) (io.ReadCloser, error) {
|
|
return c.openRead(ctx, n, 0, limit, true)
|
|
}
|
|
|
|
// openRead is open, listing every block and checking the manifest
|
|
// before releasing any byte if full is set, which needs offset 0.
|
|
func (c *client) openRead(ctx context.Context, n *node, offset, limit int64, full bool) (io.ReadCloser, error) {
|
|
if n.IsFolder || n.link == nil || n.link.File == nil || n.RevisionID == "" {
|
|
return nil, fmt.Errorf("open %q: not a file with content", n.Name)
|
|
}
|
|
if offset < 0 {
|
|
return nil, fmt.Errorf("open %q: negative offset %d", n.Name, offset)
|
|
}
|
|
sk, err := c.contentKey(n, "reading")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open %q: %w", n.Name, err)
|
|
}
|
|
var sizes []int64
|
|
if n.X != nil {
|
|
sizes = n.X.BlockSizes
|
|
}
|
|
full = full && offset == 0
|
|
if len(sizes) > c.maxFileBlocks {
|
|
return nil, fmt.Errorf("open %q: %w: %d blocks recorded, more than %d blocks", n.Name, errIntegrity, len(sizes), c.maxFileBlocks)
|
|
}
|
|
if sizes != nil {
|
|
var total int64
|
|
for i, size := range sizes {
|
|
// Bounding each size bounds the total too.
|
|
if size > maxBlockSize {
|
|
return nil, fmt.Errorf("open %q: %w: block %d recorded as %d bytes", n.Name, errIntegrity, i+1, size)
|
|
}
|
|
total += size
|
|
}
|
|
switch {
|
|
case full:
|
|
// A full read always lists the blocks, to reach the
|
|
// manifest.
|
|
case offset >= total:
|
|
limit = 0
|
|
case limit >= 0:
|
|
limit = min(limit, total-offset)
|
|
}
|
|
}
|
|
if limit == 0 {
|
|
return io.NopCloser(bytes.NewReader(nil)), nil
|
|
}
|
|
// Without recorded block sizes only the sizes learnt by earlier
|
|
// reads tell which block holds offset, as old clients didn't all
|
|
// write 4 MiB blocks, so the read starts at the last block they
|
|
// reach and discards the bytes before offset.
|
|
first, skip, last := 1, offset, -1
|
|
var startHash []byte
|
|
switch {
|
|
case sizes != nil:
|
|
first, skip = blockAt(sizes, offset)
|
|
if limit > 0 && !full {
|
|
last, _ = blockAt(sizes, offset+limit-1)
|
|
}
|
|
case !full:
|
|
first, skip, last, startHash = c.learnt.locate(n.RevisionID, offset, limit)
|
|
}
|
|
maxBlocks := len(sizes)
|
|
if sizes == nil {
|
|
maxBlocks = int(min(n.EncryptedSize/minUnclaimedBlockSize+1, 1<<30))
|
|
}
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
r := &blockReader{
|
|
c: c,
|
|
n: n,
|
|
sk: sk,
|
|
ctx: ctx,
|
|
cancel: cancel,
|
|
slots: make(chan chan blockResult, downloadAhead),
|
|
sizes: sizes,
|
|
startHash: startHash,
|
|
skip: skip,
|
|
remaining: limit,
|
|
}
|
|
r.wg.Add(1)
|
|
go r.list(first, last, maxBlocks, full)
|
|
return r, nil
|
|
}
|
|
|
|
// blockAt returns the index, from 1, of the block holding plaintext
|
|
// offset pos of a file with block sizes sizes, and the offset of pos in
|
|
// it.
|
|
func blockAt(sizes []int64, pos int64) (index int, offset int64) {
|
|
for i, size := range sizes {
|
|
if pos < size {
|
|
return i + 1, pos
|
|
}
|
|
pos -= size
|
|
}
|
|
return len(sizes) + 1, pos
|
|
}
|
|
|
|
// contentKey returns the content session key of file n for op,
|
|
// "reading" or "updating", checking its signature as the SDK's
|
|
// decryptContentKeyPacket does, except that a missing signature fails
|
|
// too: anyone with the node's public key can make a content key packet.
|
|
//
|
|
// An unverified node key or content key is errIntegrity unless
|
|
// IgnoreSignatureErrors is set, when it is logged once per node and op:
|
|
// whoever made the key could read what is written with it and make up
|
|
// the content read.
|
|
func (c *client) contentKey(n *node, op string) (*crypto.SessionKey, error) {
|
|
hint := signatureHint
|
|
if op != "reading" {
|
|
hint = "set ignore_signature_errors to update the file anyway"
|
|
}
|
|
if n.keys.unverified != nil {
|
|
if !c.opt.IgnoreSignatureErrors {
|
|
return nil, fmt.Errorf("node key: %w: %w: %s", errIntegrity, n.keys.unverified, hint)
|
|
}
|
|
c.reportUnverified(op, n, "")
|
|
}
|
|
f := n.link.File
|
|
now := c.s.serverTime()
|
|
sk, verifyErr, err := decryptContentKey(f.ContentKeyPacket, f.ContentKeyPacketSignature, n.keys.keyRing, n.keyVerifyKR, now)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if verifyErr != nil && !isNotSigned(verifyErr) && n.CreateTime.Unix() <= contentKeyFallbackUntil {
|
|
// Old clients signed with an address key, and a rename or
|
|
// move could change the node's signer without signing the
|
|
// content key packet again.
|
|
krs := make([]*crypto.KeyRing, 0, len(c.acct.addresses))
|
|
for _, addr := range c.acct.addresses {
|
|
krs = append(krs, addr.keyRing)
|
|
}
|
|
if allKR, err := joinKeyRings(krs...); err == nil && verifyDetached(sk.Key, f.ContentKeyPacketSignature, allKR, now) == nil {
|
|
fs.Debugf(nil, "protondrive: %q (ID %s): content key signed by another address of the account", n.Name, n.ID)
|
|
verifyErr = nil
|
|
}
|
|
}
|
|
if verifyErr != nil {
|
|
verifyErr = fmt.Errorf("content key: %w: %w", errIntegrity, verifyErr)
|
|
if !c.opt.IgnoreSignatureErrors {
|
|
return nil, fmt.Errorf("%w: %s", verifyErr, hint)
|
|
}
|
|
c.reportOnce("content key "+op, n.ID, func() {
|
|
fs.Errorf(nil, "protondrive: %s %q (ID %s): %v", op, n.Name, n.ID, verifyErr)
|
|
})
|
|
}
|
|
return sk, nil
|
|
}
|
|
|
|
// revisionBlocks returns the active revision of file n with at most
|
|
// pageSize of its blocks from block index from.
|
|
func (c *client) revisionBlocks(ctx context.Context, n *node, from, pageSize int) (*api.Revision, error) {
|
|
opts := &rest.Opts{
|
|
Method: "GET",
|
|
Path: c.volumePath("/drive/v2/volumes", "files", n.ID, "revisions", n.RevisionID),
|
|
Parameters: url.Values{
|
|
"FromBlockIndex": {strconv.Itoa(from)},
|
|
"PageSize": {strconv.Itoa(pageSize)},
|
|
},
|
|
}
|
|
var resp api.RevisionResponse
|
|
if err := c.apiCall(ctx, opts, nil, &resp); err != nil {
|
|
return nil, fmt.Errorf("list blocks: %w", err)
|
|
}
|
|
return &resp.Revision, nil
|
|
}
|
|
|
|
// blockURL returns block index of file n with a new download URL.
|
|
func (c *client) blockURL(ctx context.Context, n *node, index int) (api.Block, error) {
|
|
rev, err := c.revisionBlocks(ctx, n, index, 1)
|
|
if err != nil {
|
|
return api.Block{}, err
|
|
}
|
|
if len(rev.Blocks) == 0 || rev.Blocks[0].Index != index {
|
|
return api.Block{}, fmt.Errorf("list blocks: block %d is missing", index)
|
|
}
|
|
return rev.Blocks[0], nil
|
|
}
|
|
|
|
// downloadBlock returns the encrypted block at bareURL, which token
|
|
// unlocks, and its SHA-256. The block must be closed.
|
|
func (c *client) downloadBlock(ctx context.Context, bareURL, token string) (enc *pool.RW, sum []byte, err error) {
|
|
c.downloadTokens.Get()
|
|
defer c.downloadTokens.Put()
|
|
opts := &rest.Opts{
|
|
Method: "GET",
|
|
RootURL: bareURL,
|
|
// 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": token},
|
|
}
|
|
err = c.pacedCall(ctx, c.storagePacer, func() (*http.Response, error) {
|
|
if enc != nil {
|
|
_ = enc.Close()
|
|
}
|
|
enc = pool.NewRW(pool.Global())
|
|
resp, err := c.s.srv.Call(ctx, opts)
|
|
if err != nil {
|
|
return resp, err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.ContentLength > maxBlockSize {
|
|
return nil, fmt.Errorf("block is larger than %d bytes", maxBlockSize)
|
|
}
|
|
h := sha256.New()
|
|
size, err := enc.ReadFrom(io.TeeReader(io.LimitReader(resp.Body, maxBlockSize+1), h))
|
|
if err != nil {
|
|
return resp, err
|
|
}
|
|
if size > maxBlockSize {
|
|
return nil, fmt.Errorf("block is larger than %d bytes", maxBlockSize)
|
|
}
|
|
sum = h.Sum(nil)
|
|
return resp, nil
|
|
})
|
|
if err != nil {
|
|
if enc != nil {
|
|
_ = enc.Close()
|
|
}
|
|
return nil, nil, err
|
|
}
|
|
return enc, sum, nil
|
|
}
|
|
|
|
// blockResult is the outcome of a block of a download, or its end.
|
|
type blockResult struct {
|
|
index int
|
|
hash []byte // the block's SHA-256
|
|
plain *pool.RW // the decrypted block; nil on error or at the end
|
|
err error
|
|
end bool // no more blocks follow; err is the verdict on the file
|
|
}
|
|
|
|
// blockReader reads a range of a file, fetching blocks ahead of the
|
|
// reader in the background.
|
|
type blockReader struct {
|
|
c *client
|
|
n *node
|
|
sk *crypto.SessionKey
|
|
ctx context.Context
|
|
cancel context.CancelFunc
|
|
slots chan chan blockResult // results to read, in order
|
|
wg sync.WaitGroup // the lister and the fetches
|
|
sizes []int64 // claimed plaintext block sizes; nil if not recorded
|
|
// startHash is the hash the first block had when its size was
|
|
// learnt, if it was.
|
|
startHash []byte
|
|
|
|
mu sync.Mutex // held by Read and Close
|
|
cur *pool.RW // block being read
|
|
skip int64 // bytes to discard before the range, from the first block on
|
|
remaining int64 // bytes left to read; negative for all
|
|
err error // returned by every Read once set
|
|
closed bool
|
|
}
|
|
|
|
// list lists the blocks first to last (to the end if last < 0) and
|
|
// fetches them, then sends the end of the download. If verify is set,
|
|
// the list having started at the first block, it lists every block and
|
|
// checks the manifest before fetching any.
|
|
//
|
|
// A list of more than maxBlocks blocks is an error.
|
|
func (r *blockReader) list(first, last, maxBlocks int, verify bool) {
|
|
defer r.wg.Done()
|
|
end := make(chan blockResult, 1)
|
|
end <- blockResult{end: true, err: r.listBlocks(first, last, maxBlocks, verify)}
|
|
select {
|
|
case r.slots <- end:
|
|
case <-r.ctx.Done():
|
|
}
|
|
}
|
|
|
|
// listedBlock is a block of the list with its decoded hash.
|
|
type listedBlock struct {
|
|
block api.Block
|
|
hash []byte
|
|
}
|
|
|
|
// listBlocks does the work of list, returning the verdict on the file.
|
|
func (r *blockReader) listBlocks(first, last, maxBlocks int, verify bool) error {
|
|
var (
|
|
hashes [][]byte
|
|
listed []listedBlock // blocks waiting for the manifest check, if verify
|
|
manifest string
|
|
signer string
|
|
index = first
|
|
firstPage = true
|
|
)
|
|
for {
|
|
pageSize := blocksPerPage
|
|
if last > 0 {
|
|
pageSize = min(pageSize, last-index+1)
|
|
}
|
|
rev, err := r.c.revisionBlocks(r.ctx, r.n, index, pageSize)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if firstPage && verify {
|
|
manifest, signer = rev.ManifestSignature, rev.SignatureEmail
|
|
// As in the SDK, the manifest starts with the thumbnails.
|
|
for _, th := range rev.Thumbnails {
|
|
hash, err := decodeBlockHash(th.Hash)
|
|
if err != nil {
|
|
return fmt.Errorf("thumbnail: %w", err)
|
|
}
|
|
hashes = append(hashes, hash)
|
|
}
|
|
}
|
|
firstPage = false
|
|
if len(rev.Blocks) == 0 {
|
|
break
|
|
}
|
|
for _, b := range rev.Blocks {
|
|
switch {
|
|
case index > r.c.maxFileBlocks:
|
|
return fmt.Errorf("%w: more than %d blocks listed, more than any file can have", errIntegrity, r.c.maxFileBlocks)
|
|
case b.Index != index:
|
|
return fmt.Errorf("%w: block %d listed where block %d belongs", errIntegrity, b.Index, index)
|
|
case index > maxBlocks && r.sizes != nil:
|
|
return fmt.Errorf("%w: more blocks listed than the %d the file records", errIntegrity, maxBlocks)
|
|
case index > maxBlocks:
|
|
return fmt.Errorf("%w: more blocks listed than the file's encrypted size of %d allows", errIntegrity, r.n.EncryptedSize)
|
|
}
|
|
hash, err := decodeBlockHash(b.Hash)
|
|
if err != nil {
|
|
return fmt.Errorf("block %d: %w", index, err)
|
|
}
|
|
if index == first && r.startHash != nil && !bytes.Equal(hash, r.startHash) {
|
|
// The sizes placing the range came from another block
|
|
// list of the same revision.
|
|
return fmt.Errorf("%w: block %d listed with another hash than when it was read before", errIntegrity, index)
|
|
}
|
|
if verify {
|
|
// Nothing is released before the manifest vouches for
|
|
// every block's hash and place.
|
|
hashes = append(hashes, hash)
|
|
listed = append(listed, listedBlock{block: b, hash: hash})
|
|
} else if !r.fetch(b, hash) {
|
|
return r.ctx.Err()
|
|
}
|
|
if index == last {
|
|
return nil
|
|
}
|
|
index++
|
|
}
|
|
}
|
|
if r.sizes != nil && index <= len(r.sizes) {
|
|
return fmt.Errorf("%w: %d blocks listed of the %d the file records", errIntegrity, index-1, len(r.sizes))
|
|
}
|
|
if !verify {
|
|
return nil
|
|
}
|
|
if err := r.verifyManifest(hashes, manifest, signer); err != nil {
|
|
return err
|
|
}
|
|
for _, lb := range listed {
|
|
if !r.fetch(lb.block, lb.hash) {
|
|
return r.ctx.Err()
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// decodeBlockHash returns the base64 SHA-256 hash.
|
|
func decodeBlockHash(b64 string) ([]byte, error) {
|
|
hash, err := base64.StdEncoding.DecodeString(b64)
|
|
if err == nil && len(hash) != sha256.Size {
|
|
err = fmt.Errorf("%d bytes long", len(hash))
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("bad hash: %w", err)
|
|
}
|
|
return hash, nil
|
|
}
|
|
|
|
// verifyManifest checks the manifest signature of the file's block
|
|
// hashes against the keys of signer, or the node key if it is empty.
|
|
func (r *blockReader) verifyManifest(hashes [][]byte, manifest, signer string) error {
|
|
verifyKR, err := r.c.verifyKeys(r.ctx, signer, r.n.keys.keyRing)
|
|
if err != nil {
|
|
return fmt.Errorf("verify manifest: %w", err)
|
|
}
|
|
err = verifyManifest(hashes, manifest, verifyKR, r.c.s.serverTime())
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
err = fmt.Errorf("%w: %w", errIntegrity, err)
|
|
if !r.c.opt.IgnoreSignatureErrors {
|
|
return fmt.Errorf("%w: %s", err, signatureHint)
|
|
}
|
|
fs.Errorf(nil, "protondrive: %q (ID %s): %v", r.n.Name, r.n.ID, err)
|
|
return nil
|
|
}
|
|
|
|
// fetch queues block b, whose SHA-256 is hash, for the reader and
|
|
// fetches it in the background. It returns false if the download is
|
|
// cancelled first.
|
|
func (r *blockReader) fetch(b api.Block, hash []byte) bool {
|
|
slot := make(chan blockResult, 1)
|
|
select {
|
|
case r.slots <- slot:
|
|
case <-r.ctx.Done():
|
|
return false
|
|
}
|
|
r.wg.Add(1)
|
|
go func() {
|
|
defer r.wg.Done()
|
|
slot <- r.fetchBlock(b, hash)
|
|
}()
|
|
return true
|
|
}
|
|
|
|
// fetchBlock downloads and decrypts block b, whose SHA-256 is hash,
|
|
// requesting a new URL after a 404 (once) or a hash mismatch.
|
|
func (r *blockReader) fetchBlock(b api.Block, hash []byte) blockResult {
|
|
index := b.Index
|
|
refetched := false
|
|
for attempt := 1; ; {
|
|
plain, err := r.fetchOnce(b, hash)
|
|
var apiErr *api.Error
|
|
switch {
|
|
case err == nil:
|
|
return blockResult{index: index, hash: hash, plain: plain}
|
|
case r.ctx.Err() != nil:
|
|
return blockResult{index: index, err: r.ctx.Err()}
|
|
case errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound && !refetched:
|
|
// The URL may have expired.
|
|
refetched = true
|
|
case errors.Is(err, errBlockHash) && attempt < blockAttempts:
|
|
// The bytes may have been damaged on the way.
|
|
attempt++
|
|
default:
|
|
return blockResult{index: index, err: fmt.Errorf("block %d: %w", index, err)}
|
|
}
|
|
fs.Debugf(nil, "protondrive: %q (ID %s): block %d: %v: retrying with a new URL", r.n.Name, r.n.ID, index, err)
|
|
// hash stays the listed one, which the manifest covers.
|
|
if b, err = r.c.blockURL(r.ctx, r.n, index); err != nil {
|
|
return blockResult{index: index, err: fmt.Errorf("block %d: %w", index, err)}
|
|
}
|
|
if relisted, err := decodeBlockHash(b.Hash); err != nil || !bytes.Equal(relisted, hash) {
|
|
return blockResult{index: index, err: fmt.Errorf("block %d: %w: listed again with another hash", index, errIntegrity)}
|
|
}
|
|
}
|
|
}
|
|
|
|
// fetchOnce downloads block b and checks it against hash and its
|
|
// claimed size, returning it decrypted.
|
|
func (r *blockReader) fetchOnce(b api.Block, hash []byte) (*pool.RW, error) {
|
|
enc, sum, err := r.c.downloadBlock(r.ctx, b.BareURL, b.Token)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer func() { _ = enc.Close() }()
|
|
if !bytes.Equal(sum, hash) {
|
|
return nil, errBlockHash
|
|
}
|
|
dec, err := blockDecrypter(enc, r.sk)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
plain := pool.NewRW(pool.Global())
|
|
size, err := plain.ReadFrom(io.LimitReader(dec, maxBlockSize+1))
|
|
switch {
|
|
case err != nil:
|
|
err = fmt.Errorf("decrypt block: %w", err)
|
|
case size > maxBlockSize:
|
|
err = fmt.Errorf("block decrypts to more than %d bytes", maxBlockSize)
|
|
case r.sizes != nil && size != r.sizes[b.Index-1]:
|
|
err = fmt.Errorf("%w: block is %d bytes, the file records %d", errIntegrity, size, r.sizes[b.Index-1])
|
|
}
|
|
if err != nil {
|
|
_ = plain.Close()
|
|
return nil, err
|
|
}
|
|
return plain, nil
|
|
}
|
|
|
|
// Read reads the range of the file.
|
|
func (r *blockReader) Read(p []byte) (int, error) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
if len(p) == 0 {
|
|
return 0, nil
|
|
}
|
|
for {
|
|
switch {
|
|
case r.closed:
|
|
return 0, errDownloadClosed
|
|
case r.err != nil:
|
|
return 0, r.err
|
|
case r.remaining == 0:
|
|
return 0, io.EOF
|
|
}
|
|
if r.cur == nil {
|
|
if err := r.next(); err != nil {
|
|
r.err = err
|
|
r.cancel()
|
|
}
|
|
continue
|
|
}
|
|
if r.remaining > 0 && int64(len(p)) > r.remaining {
|
|
p = p[:r.remaining]
|
|
}
|
|
n, err := r.cur.Read(p)
|
|
if n > 0 {
|
|
if r.remaining > 0 {
|
|
r.remaining -= int64(n)
|
|
}
|
|
return n, nil
|
|
}
|
|
if err != nil && err != io.EOF {
|
|
r.err = err
|
|
continue
|
|
}
|
|
_ = r.cur.Close()
|
|
r.cur = nil
|
|
}
|
|
}
|
|
|
|
// next makes the next block holding bytes of the range current,
|
|
// returning io.EOF at the end.
|
|
func (r *blockReader) next() error {
|
|
for {
|
|
var slot chan blockResult
|
|
select {
|
|
case slot = <-r.slots:
|
|
case <-r.ctx.Done():
|
|
return r.ctx.Err()
|
|
}
|
|
res := <-slot
|
|
switch {
|
|
case res.err != nil && r.ctx.Err() != nil:
|
|
return r.ctx.Err()
|
|
case res.err != nil:
|
|
return res.err
|
|
case res.end:
|
|
return io.EOF
|
|
}
|
|
if r.sizes == nil {
|
|
if err := r.c.learnt.learn(r.n.RevisionID, res.index, res.hash, res.plain.Size()); err != nil {
|
|
_ = res.plain.Close()
|
|
return err
|
|
}
|
|
}
|
|
if size := res.plain.Size(); r.skip > 0 && r.skip >= size {
|
|
r.skip -= size
|
|
_ = res.plain.Close()
|
|
continue
|
|
}
|
|
if r.skip > 0 {
|
|
if _, err := res.plain.Seek(r.skip, io.SeekStart); err != nil {
|
|
_ = res.plain.Close()
|
|
return err
|
|
}
|
|
r.skip = 0
|
|
}
|
|
r.cur = res.plain
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Close stops the download and frees its buffers. It may be called
|
|
// more than once.
|
|
func (r *blockReader) Close() error {
|
|
r.cancel()
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
if r.closed {
|
|
return nil
|
|
}
|
|
r.closed = true
|
|
r.wg.Wait()
|
|
if r.cur != nil {
|
|
_ = r.cur.Close()
|
|
r.cur = nil
|
|
}
|
|
// Every queued slot has its result now.
|
|
for {
|
|
select {
|
|
case slot := <-r.slots:
|
|
if res := <-slot; res.plain != nil {
|
|
_ = res.plain.Close()
|
|
}
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// check interfaces
|
|
var _ io.ReadCloser = (*blockReader)(nil)
|
|
|
|
const (
|
|
// learntRevisions and learntBlocks bound the block sizes a client
|
|
// learns: of at most this many revisions, and this many blocks in
|
|
// all, about 2.5 MiB.
|
|
learntRevisions = 16
|
|
learntBlocks = 1 << 16
|
|
)
|
|
|
|
// learntBlock is the plaintext size of a block read, with its hash.
|
|
type learntBlock struct {
|
|
hash [sha256.Size]byte
|
|
size int64
|
|
}
|
|
|
|
// blockSizeCache holds the plaintext sizes of the blocks, from the
|
|
// first on, read of revisions which don't record their block sizes, so
|
|
// a later ranged read, as each chunk of a multi-thread copy is, can
|
|
// start at the block holding its offset. The zero value is empty.
|
|
type blockSizeCache struct {
|
|
mu sync.Mutex
|
|
revs map[string][]learntBlock // by revision ID
|
|
order []string // revision IDs, oldest first
|
|
blocks int // learnt in all
|
|
}
|
|
|
|
// locate returns where a read of limit bytes (to the end if negative)
|
|
// from offset of revision id starts, as for blockReader: the first
|
|
// block, the bytes of it to skip, the last block or -1 if not known,
|
|
// and the hash the first block had when its size was learnt, or nil if
|
|
// it wasn't.
|
|
func (b *blockSizeCache) locate(id string, offset, limit int64) (first int, skip int64, last int, startHash []byte) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
blocks := b.revs[id]
|
|
first, skip, last = len(blocks)+1, offset, -1
|
|
for i, lb := range blocks {
|
|
if skip < lb.size {
|
|
first = i + 1
|
|
startHash = slices.Clone(lb.hash[:])
|
|
break
|
|
}
|
|
skip -= lb.size
|
|
}
|
|
if first > len(blocks) || limit <= 0 {
|
|
return first, skip, last, startHash
|
|
}
|
|
end := skip + limit - 1
|
|
for i := first - 1; i < len(blocks); i++ {
|
|
if end < blocks[i].size {
|
|
return first, skip, i + 1, startHash
|
|
}
|
|
end -= blocks[i].size
|
|
}
|
|
return first, skip, last, startHash
|
|
}
|
|
|
|
// learn records that block index of revision id, whose SHA-256 is hash,
|
|
// is size bytes. A block learnt before with another hash or size is
|
|
// errIntegrity: the server listed two blocks for one place.
|
|
func (b *blockSizeCache) learn(id string, index int, hash []byte, size int64) error {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
blocks, ok := b.revs[id]
|
|
if index <= len(blocks) {
|
|
if lb := blocks[index-1]; !bytes.Equal(lb.hash[:], hash) || lb.size != size {
|
|
return fmt.Errorf("%w: block %d listed with another hash than when it was read before", errIntegrity, index)
|
|
}
|
|
return nil
|
|
}
|
|
if index != len(blocks)+1 || len(hash) != sha256.Size {
|
|
return nil
|
|
}
|
|
if !ok {
|
|
if b.revs == nil {
|
|
b.revs = make(map[string][]learntBlock)
|
|
}
|
|
for len(b.order) >= learntRevisions {
|
|
b.forgetOldest()
|
|
}
|
|
b.order = append(b.order, id)
|
|
}
|
|
for b.blocks >= learntBlocks && len(b.order) > 1 && b.order[0] != id {
|
|
b.forgetOldest()
|
|
}
|
|
if b.blocks >= learntBlocks {
|
|
return nil
|
|
}
|
|
lb := learntBlock{size: size}
|
|
copy(lb.hash[:], hash)
|
|
b.revs[id] = append(blocks, lb)
|
|
b.blocks++
|
|
return nil
|
|
}
|
|
|
|
// forgetOldest drops the revision learnt first.
|
|
func (b *blockSizeCache) forgetOldest() {
|
|
b.blocks -= len(b.revs[b.order[0]])
|
|
delete(b.revs, b.order[0])
|
|
b.order = b.order[1:]
|
|
}
|