ouisync/blob/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
pub(crate) mod lock;

mod block_ids;
mod id;
mod position;

#[cfg(test)]
mod tests;

pub(crate) use self::{block_ids::BlockIds, id::BlobId};

use self::position::Position;
use crate::{
    branch::Branch,
    collections::{hash_map::Entry, HashMap},
    crypto::{
        cipher::{self, Nonce, SecretKey},
        sign::{Keypair, PublicKey},
        Hashable,
    },
    error::{Error, Result},
    protocol::{
        Block, BlockContent, BlockId, BlockNonce, Locator, RootNode, RootNodeFilter,
        SingleBlockPresence, BLOCK_SIZE,
    },
    store::{self, Changeset, ReadTransaction},
};
use std::{io::SeekFrom, iter, mem};
use thiserror::Error;

/// Size of the blob header in bytes.
// Using u64 instead of usize because HEADER_SIZE must be the same irrespective of whether we're on
// a 32bit or 64bit processor (if we want two such replicas to be able to sync).
pub const HEADER_SIZE: usize = mem::size_of::<u64>();

// Max number of blocks processed in a single batch (write transaction). Increasing this number
// decreases the number of flushes needed during writes but increases the coplexity of the
// individual flushes.
pub const BATCH_SIZE: usize = 2048; // 64 MiB

#[derive(Debug, Error)]
pub(crate) enum ReadWriteError {
    #[error("block not found in the cache")]
    CacheMiss,
    #[error("cache is full")]
    CacheFull,
}

pub(crate) struct Blob {
    branch: Branch,
    id: BlobId,
    cache: HashMap<u32, CachedBlock>,
    len_original: u64,
    len_modified: u64,
    position: Position,
}

impl Blob {
    /// Opens an existing blob.
    pub async fn open(tx: &mut ReadTransaction, branch: Branch, id: BlobId) -> Result<Self> {
        let root_node = tx
            .load_latest_approved_root_node(branch.id(), RootNodeFilter::Any)
            .await?;
        Self::open_at(tx, &root_node, branch, id).await
    }

    pub async fn open_at(
        tx: &mut ReadTransaction,
        root_node: &RootNode,
        branch: Branch,
        id: BlobId,
    ) -> Result<Self> {
        assert_eq!(root_node.proof.writer_id, *branch.id());

        let (_, buffer) =
            read_block(tx, root_node, &Locator::head(id), branch.keys().read()).await?;

        let len = buffer.read_u64(0);
        let cached_block = CachedBlock::from(buffer);
        let cache = iter::once((0, cached_block)).collect();
        let position = Position::ZERO;

        Ok(Self {
            branch,
            id,
            cache,
            len_original: len,
            len_modified: len,
            position,
        })
    }

    /// Creates a new blob.
    pub fn create(branch: Branch, id: BlobId) -> Self {
        let cached_block = CachedBlock::new().with_dirty(true);
        let cache = iter::once((0, cached_block)).collect();

        Self {
            branch,
            id,
            cache,
            len_original: 0,
            len_modified: 0,
            position: Position::ZERO,
        }
    }

    pub fn branch(&self) -> &Branch {
        &self.branch
    }

    /// Id of this blob.
    pub fn id(&self) -> &BlobId {
        &self.id
    }

    /// Length of this blob in bytes.
    pub fn len(&self) -> u64 {
        self.len_modified
    }

    // Returns the current seek position from the start of the blob.
    pub fn seek_position(&self) -> u64 {
        self.position.get()
    }

    pub fn block_count(&self) -> u32 {
        block_count(self.len())
    }

    /// Was this blob modified and not flushed yet?
    pub fn is_dirty(&self) -> bool {
        self.cache.values().any(|block| block.dirty) || self.len_modified != self.len_original
    }

    /// Seek to an offset in the blob.
    ///
    /// It is allowed to specify offset that is outside of the range of the blob but such offset
    /// will be clamped to be within the range.
    ///
    /// Returns the new seek position from the start of the blob.
    pub fn seek(&mut self, pos: SeekFrom) -> u64 {
        let position = match pos {
            SeekFrom::Start(n) => n.min(self.len()),
            SeekFrom::End(n) => {
                if n >= 0 {
                    self.len()
                } else {
                    self.len().saturating_sub((-n) as u64)
                }
            }
            SeekFrom::Current(n) => {
                if n >= 0 {
                    self.seek_position()
                        .saturating_add(n as u64)
                        .min(self.len())
                } else {
                    self.seek_position().saturating_sub((-n) as u64)
                }
            }
        };

        self.position.set(position);

        position
    }

    /// Reads data from this blob into `buffer`, advancing the internal cursor. Returns the
    /// number of bytes actually read which might be less than `buffer.len()`.
    pub fn read(&mut self, buffer: &mut [u8]) -> Result<usize, ReadWriteError> {
        if self.position.get() >= self.len() {
            return Ok(0);
        }

        let block = match self.cache.get(&self.position.block) {
            Some(block) => block,
            None => {
                if self.check_cache_capacity() {
                    return Err(ReadWriteError::CacheMiss);
                } else {
                    return Err(ReadWriteError::CacheFull);
                }
            }
        };

        // minimum of:
        // - buffer length
        // - remaining size of the current block
        // - remaining size of the whole blob
        let read_len = buffer
            .len()
            .min(block.content.len() - self.position.offset)
            .min(self.len() as usize - self.position.get() as usize);

        block
            .content
            .read(self.position.offset, &mut buffer[..read_len]);

        self.position.advance(read_len);

        Ok(read_len)
    }

    #[cfg(test)]
    pub async fn read_all(&mut self, tx: &mut ReadTransaction, buffer: &mut [u8]) -> Result<usize> {
        let root_node = tx
            .load_latest_approved_root_node(self.branch.id(), RootNodeFilter::Any)
            .await?;
        self.read_all_at(tx, &root_node, buffer).await
    }

    pub async fn read_all_at(
        &mut self,
        tx: &mut ReadTransaction,
        root_node: &RootNode,
        buffer: &mut [u8],
    ) -> Result<usize> {
        assert_eq!(root_node.proof.writer_id, *self.branch.id());

        let mut offset = 0;

        loop {
            match self.read(&mut buffer[offset..]) {
                Ok(0) => break,
                Ok(len) => {
                    offset += len;
                }
                Err(ReadWriteError::CacheMiss) => self.warmup_at(tx, root_node).await?,
                Err(ReadWriteError::CacheFull) => {
                    tracing::error!("cache full");
                    return Err(Error::OperationNotSupported);
                }
            }
        }

        Ok(offset)
    }

    /// Read all data from this blob from the current seek position until the end and return then
    /// in a `Vec`.
    #[cfg(test)]
    pub async fn read_to_end(&mut self, tx: &mut ReadTransaction) -> Result<Vec<u8>> {
        let root_node = tx
            .load_latest_approved_root_node(self.branch.id(), RootNodeFilter::Any)
            .await?;
        self.read_to_end_at(tx, &root_node).await
    }

    /// Read all data from this blob at the given snapshot from the current seek position until the
    /// end and return then in a `Vec`.
    pub async fn read_to_end_at(
        &mut self,
        tx: &mut ReadTransaction,
        root_node: &RootNode,
    ) -> Result<Vec<u8>> {
        // Allocate the buffer `CHUNK_SIZE` bytes at a time to prevent blowing up the memory in
        // case the blob header was tampered with.
        const CHUNK_SIZE: usize = 1024 * 1024;

        let total = (self.len() - self.seek_position())
            .try_into()
            .unwrap_or(usize::MAX);

        let mut buffer = Vec::new();
        let mut offset = 0;

        while offset < total {
            buffer.resize(buffer.len() + CHUNK_SIZE.min(total - offset), 0);
            offset += self
                .read_all_at(tx, root_node, &mut buffer[offset..])
                .await?;
        }

        Ok(buffer)
    }

    pub fn write(&mut self, buffer: &[u8]) -> Result<usize, ReadWriteError> {
        if buffer.is_empty() {
            return Ok(0);
        }

        let block = match self.cache.get_mut(&self.position.block) {
            Some(block) => block,
            None => {
                if !self.check_cache_capacity() {
                    return Err(ReadWriteError::CacheFull);
                }

                if self.position.get() >= self.len_modified
                    || self.position.offset == 0 && buffer.len() >= BLOCK_SIZE
                {
                    self.cache.entry(self.position.block).or_default()
                } else {
                    return Err(ReadWriteError::CacheMiss);
                }
            }
        };

        let write_len = buffer.len().min(block.content.len() - self.position.offset);

        block
            .content
            .write(self.position.offset, &buffer[..write_len]);
        block.dirty = true;

        self.position.advance(write_len);
        self.len_modified = self.len_modified.max(self.position.get());

        Ok(write_len)
    }

    pub async fn write_all(
        &mut self,
        tx: &mut ReadTransaction,
        changeset: &mut Changeset,
        buffer: &[u8],
    ) -> Result<()> {
        let mut offset = 0;

        loop {
            match self.write(&buffer[offset..]) {
                Ok(0) => break,
                Ok(len) => {
                    offset += len;
                }
                Err(ReadWriteError::CacheMiss) => {
                    self.warmup(tx).await?;
                }
                Err(ReadWriteError::CacheFull) => {
                    self.flush(tx, changeset).await?;
                }
            }
        }

        Ok(())
    }

    /// Load the current block into the cache.
    pub async fn warmup(&mut self, tx: &mut ReadTransaction) -> Result<()> {
        let root_node = tx
            .load_latest_approved_root_node(self.branch.id(), RootNodeFilter::Any)
            .await?;
        self.warmup_at(tx, &root_node).await?;

        Ok(())
    }

    /// Load the current block at the given snapshot into the cache.
    pub async fn warmup_at(
        &mut self,
        tx: &mut ReadTransaction,
        root_node: &RootNode,
    ) -> Result<()> {
        match self.cache.entry(self.position.block) {
            Entry::Occupied(_) => (),
            Entry::Vacant(entry) => {
                let locator = Locator::head(self.id).nth(self.position.block);
                let (_, buffer) =
                    read_block(tx, root_node, &locator, self.branch.keys().read()).await?;
                entry.insert(CachedBlock::from(buffer));
            }
        }

        Ok(())
    }

    /// Truncate the blob to the given length.
    pub fn truncate(&mut self, len: u64) -> Result<()> {
        if len == self.len() {
            return Ok(());
        }

        if len > self.len() {
            // TODO: consider supporting this
            return Err(Error::OperationNotSupported);
        }

        if self.seek_position() > len {
            self.seek(SeekFrom::Start(len));
        }

        self.len_modified = len;

        Ok(())
    }

    /// Flushes this blob, ensuring that all intermediately buffered contents gets written to the
    /// store.
    pub(crate) async fn flush(
        &mut self,
        tx: &mut ReadTransaction,
        changeset: &mut Changeset,
    ) -> Result<()> {
        self.write_len(tx, changeset).await?;
        self.write_blocks(changeset);

        Ok(())
    }

    /// Remove this blob from the store.
    pub(crate) fn remove(self, changeset: &mut Changeset) {
        let locators = Locator::head(self.id)
            .sequence()
            .take(self.block_count() as usize);

        for locator in locators {
            let encoded = locator.encode(self.branch().keys().read());
            changeset.unlink_block(encoded, None);
        }
    }

    fn check_cache_capacity(&mut self) -> bool {
        if self.cache.len() < BATCH_SIZE {
            return true;
        }

        let number = self
            .cache
            .iter()
            .find(|(_, block)| !block.dirty)
            .map(|(number, _)| *number);

        if let Some(number) = number {
            self.cache.remove(&number);
            true
        } else {
            false
        }
    }

    // Write length, if changed
    async fn write_len(
        &mut self,
        tx: &mut ReadTransaction,
        changeset: &mut Changeset,
    ) -> Result<()> {
        if self.len_modified == self.len_original {
            return Ok(());
        }

        if let Some(block) = self.cache.get_mut(&0) {
            block.content.write_u64(0, self.len_modified);
            block.dirty = true;
        } else {
            let locator = Locator::head(self.id);
            let root_node = tx
                .load_latest_approved_root_node(self.branch.id(), RootNodeFilter::Any)
                .await?;
            let (_, mut content) =
                read_block(tx, &root_node, &locator, self.branch.keys().read()).await?;
            content.write_u64(0, self.len_modified);
            write_block(changeset, &locator, content, self.branch.keys().read());
        }

        self.len_original = self.len_modified;

        Ok(())
    }

    fn write_blocks(&mut self, changeset: &mut Changeset) {
        // Poor man's `drain_filter`.
        let cache = mem::take(&mut self.cache);
        let (dirty, clean): (HashMap<_, _>, _) =
            cache.into_iter().partition(|(_, block)| block.dirty);
        self.cache = clean;

        for (number, block) in dirty {
            let locator = Locator::head(self.id).nth(number);
            write_block(
                changeset,
                &locator,
                block.content,
                self.branch.keys().read(),
            );
        }
    }
}

// NOTE: Clone only creates a new instance of the same blob. It doesn't preserve dirtiness.
impl Clone for Blob {
    fn clone(&self) -> Self {
        Self {
            branch: self.branch.clone(),
            id: self.id,
            cache: HashMap::default(),
            len_original: self.len_original,
            len_modified: self.len_original,
            position: self.position,
        }
    }
}

#[derive(Default)]
struct CachedBlock {
    content: BlockContent,
    dirty: bool,
}

impl CachedBlock {
    fn new() -> Self {
        Self::default()
    }

    fn with_dirty(self, dirty: bool) -> Self {
        Self { dirty, ..self }
    }
}

impl From<BlockContent> for CachedBlock {
    fn from(content: BlockContent) -> Self {
        Self {
            content,
            dirty: false,
        }
    }
}

/// Creates a shallow copy (only the index nodes are copied, not blocks) of the specified blob into
/// the specified destination branch.
///
/// NOTE: This function is not atomic. However, it is idempotent, so in case it's interrupted, it
/// can be safely retried.
pub(crate) async fn fork(blob_id: BlobId, src_branch: &Branch, dst_branch: &Branch) -> Result<()> {
    // If the blob is already forked, do nothing but still return Ok to maintain idempotency.
    if src_branch.id() == dst_branch.id() {
        return Ok(());
    }

    let read_key = src_branch.keys().read();
    // Take the write key from the dst branch, not the src branch, to protect us against
    // accidentally forking into remote branch (remote branches don't have write access).
    let write_keys = dst_branch.keys().write().ok_or(Error::PermissionDenied)?;

    // FIXME: The src blob can change in the middle of the fork which could cause the dst blob to
    // become corrupted (part of it will be forked pre-change and part post-change). To prevent
    // that, we should restart the fork every time the src branch changes, or - better - run the
    // whole fork in a single transaction (but somehow avoid blocking other tasks).

    let end = {
        let mut tx = src_branch.store().begin_read().await?;
        let root_node = tx
            .load_latest_approved_root_node(src_branch.id(), RootNodeFilter::Any)
            .await?;
        load_block_count_hint(&mut tx, &root_node, blob_id, src_branch.keys().read()).await?
    };

    struct Batch {
        tx: crate::store::WriteTransaction,
        changeset: Changeset,
    }

    impl Batch {
        async fn apply(self, dst_branch_id: &PublicKey, write_keys: &Keypair) -> Result<()> {
            let Batch { mut tx, changeset } = self;
            changeset.apply(&mut tx, dst_branch_id, write_keys).await?;
            tx.commit().await?;
            Ok(())
        }
    }

    let mut batch = None;
    let locators = Locator::head(blob_id).sequence().take(end as usize);

    for locator in locators {
        let Batch { tx, changeset } = if let Some(batch) = &mut batch {
            batch
        } else {
            batch.insert(Batch {
                tx: src_branch.store().begin_write().await?,
                changeset: Changeset::new(),
            })
        };

        let encoded_locator = locator.encode(read_key);

        let (block_id, block_presence) =
            match tx.find_block(src_branch.id(), &encoded_locator).await {
                Ok(id) => id,
                Err(store::Error::LocatorNotFound) => {
                    // end of the blob
                    break;
                }
                Err(error) => return Err(error.into()),
            };

        changeset.link_block(encoded_locator, block_id, block_presence);

        // The `+ 1` is there to not hit on the first run.
        if (locator.number() + 1) as usize % BATCH_SIZE == 0 {
            if let Some(batch) = batch.take() {
                batch.apply(dst_branch.id(), write_keys).await?;
            }
        }

        tracing::trace!(
            num = locator.number(),
            block_id = ?block_id,
            ?block_presence,
            "fork block",
        );
    }

    if let Some(batch) = batch {
        batch.apply(dst_branch.id(), write_keys).await?;
    }

    Ok(())
}

fn block_count(len: u64) -> u32 {
    // https://stackoverflow.com/questions/2745074/fast-ceiling-of-an-integer-division-in-c-c
    (1 + (len + HEADER_SIZE as u64 - 1) / BLOCK_SIZE as u64)
        .try_into()
        .unwrap_or(u32::MAX)
}

async fn read_len(
    tx: &mut ReadTransaction,
    root_node: &RootNode,
    blob_id: BlobId,
    read_key: &cipher::SecretKey,
) -> Result<u64> {
    let (_, buffer) = read_block(tx, root_node, &Locator::head(blob_id), read_key).await?;
    Ok(buffer.read_u64(0))
}

// Returns the max number of blocks the specified blob has. This either returns the actual number
// or `u32::MAX` in case the first blob is not available and so the blob length can't be obtained.
async fn load_block_count_hint(
    tx: &mut ReadTransaction,
    root_node: &RootNode,
    blob_id: BlobId,
    read_key: &cipher::SecretKey,
) -> Result<u32> {
    match read_len(tx, root_node, blob_id, read_key).await {
        Ok(len) => Ok(block_count(len)),
        Err(Error::Store(store::Error::BlockNotFound)) => Ok(u32::MAX),
        Err(error) => Err(error),
    }
}

async fn read_block(
    tx: &mut ReadTransaction,
    root_node: &RootNode,
    locator: &Locator,
    read_key: &cipher::SecretKey,
) -> Result<(BlockId, BlockContent)> {
    let (id, _) = tx
        .find_block_at(root_node, &locator.encode(read_key))
        .await?;

    let mut content = BlockContent::new();
    let nonce = tx.read_block(&id, &mut content).await?;

    decrypt_block(read_key, &nonce, &mut content);

    Ok((id, content))
}

fn write_block(
    changeset: &mut Changeset,
    locator: &Locator,
    mut content: BlockContent,
    read_key: &cipher::SecretKey,
) -> BlockId {
    let nonce = make_block_nonce(locator, &content, read_key);
    encrypt_block(read_key, &nonce, &mut content);

    let block = Block::new(content, nonce);
    let block_id = block.id;

    changeset.link_block(
        locator.encode(read_key),
        block.id,
        SingleBlockPresence::Present,
    );
    changeset.write_block(block);

    tracing::trace!(?locator, ?block_id, "write block");

    block_id
}

fn decrypt_block(blob_key: &cipher::SecretKey, block_nonce: &BlockNonce, content: &mut [u8]) {
    let block_key = SecretKey::derive_from_key(blob_key.as_array(), block_nonce);
    block_key.decrypt_no_aead(&Nonce::default(), content);
}

fn encrypt_block(blob_key: &cipher::SecretKey, block_nonce: &BlockNonce, content: &mut [u8]) {
    let block_key = SecretKey::derive_from_key(blob_key.as_array(), block_nonce);
    block_key.encrypt_no_aead(&Nonce::default(), content);
}

/// Compute nonce for a block at the given locator and with the given plaintext content.
///
/// This function is deterministic so for a given block at a given locator it produces the same
/// nonce. This is not a nonce reuse because the only way two blocks can have the same nonce is if
/// they have the same content and are at the same locator which means they are in fact the same
/// block, just referenced from two different branches.
///
/// The reason nonces are computed this way instead of randomly is to guarantee two blocks with the
/// same content at the same locators but in different branches have the same nonce and thus the
/// same block_id even if they were created independently (as opposed to linking an existing block
/// from another branch). This in turn guarantees that two branches with identical content have the
/// same hash.
///
/// Note: `read_key` is used as an additional secret hashing material to prevent known plaintext
/// attacks.
fn make_block_nonce(
    locator: &Locator,
    plaintext_content: &[u8],
    read_key: &cipher::SecretKey,
) -> BlockNonce {
    (read_key.as_ref(), locator, plaintext_content)
        .hash()
        .into()
}