Skip to main content

fxfs_make_blob_image/
lib.rs

1// Copyright 2023 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#![recursion_limit = "256"]
6
7use anyhow::{Context, Error, anyhow};
8use delivery_blob::Type1Blob;
9pub use delivery_blob::compression::CompressionAlgorithm;
10use delivery_blob::compression::{ChunkedArchive, ChunkedArchiveOptions};
11use fuchsia_async as fasync;
12use fuchsia_merkle::{Hash, MerkleRootBuilder};
13use futures::{SinkExt as _, StreamExt as _, TryStreamExt as _, try_join};
14use fxfs::blob_metadata::{
15    BlobFormat, BlobMetadata, BlobMetadataLeafHashCollector, FxfsBlobMetadataExt,
16};
17use fxfs::errors::FxfsError;
18use fxfs::filesystem::{FxFilesystemBuilder, OpenFxFilesystem};
19use fxfs::object_handle::WriteBytes;
20use fxfs::object_store::directory::Directory;
21use fxfs::object_store::journal::RESERVED_SPACE;
22use fxfs::object_store::journal::super_block::SuperBlockInstance;
23use fxfs::object_store::transaction::{LockKey, lock_keys};
24use fxfs::object_store::volume::root_volume;
25use fxfs::object_store::{
26    DataObjectHandle, DirectWriter, HandleOptions, NewChildStoreOptions, ObjectStore, StoreOptions,
27};
28use rayon::ThreadPoolBuilder;
29use rayon::prelude::*;
30use serde::{Deserialize, Serialize};
31use sparse::unsparse;
32use std::fs;
33use std::io::{BufWriter, Read, Write};
34use std::path::PathBuf;
35use storage_device::DeviceHolder;
36use storage_device::file_backed_device::FileBackedDevice;
37use storage_units::BlockSize;
38
39pub const BLOB_VOLUME_NAME: &str = "blob";
40
41const BLOCK_SIZE: BlockSize = BlockSize::SIZE_4KIB;
42
43#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
44struct BlobsJsonOutputEntry {
45    source_path: String,
46    merkle: String,
47    bytes: usize,
48    size: u64,
49    file_size: usize,
50    compressed_file_size: u64,
51    merkle_tree_size: usize,
52    // For consistency with the legacy blobfs tooling, we still use the name `blobfs`.
53    used_space_in_blobfs: u64,
54}
55
56type BlobsJsonOutput = Vec<BlobsJsonOutputEntry>;
57
58/// Generates an Fxfs image containing a blob volume with the blobs specified in `manifest_path`.
59/// Creates the block image at `output_image_path` and writes a blobs.json file to
60/// `json_output_path`.
61/// If `target_size` bytes is set, the raw image will be set to exactly this size (and an error is
62/// returned if the contents exceed that size).  If unset (or 0), the image will be truncated to
63/// twice the size of its contents, which is a heuristic that gives us roughly enough space for
64/// normal usage of the image.
65/// If `sparse_output_image_path` is set, an image will also be emitted in the Android sparse
66/// format, which is suitable for flashing via fastboot.  The sparse image's logical size and
67/// contents are identical to the raw image, but its actual size will likely be smaller.
68pub async fn make_blob_image(
69    output_image_path: &str,
70    sparse_output_image_path: Option<&str>,
71    blobs: Vec<(Hash, PathBuf)>,
72    json_output_path: &str,
73    target_size: Option<u64>,
74    compression_algorithm: Option<CompressionAlgorithm>,
75) -> Result<(), Error> {
76    let output_image = std::fs::OpenOptions::new()
77        .read(true)
78        .write(true)
79        .create(true)
80        .truncate(true)
81        .open(output_image_path)?;
82
83    let mut target_size = target_size.unwrap_or_default();
84
85    if target_size > 0 && target_size < BLOCK_SIZE {
86        return Err(anyhow!("Size {} is too small", target_size));
87    }
88    if !BLOCK_SIZE.is_aligned(target_size) {
89        return Err(anyhow!("Invalid size {} is not block-aligned", target_size));
90    }
91    let block_count = if target_size != 0 {
92        // Truncate the image to the target size now.
93        output_image.set_len(target_size).context("Failed to resize image")?;
94        target_size / BLOCK_SIZE
95    } else {
96        // Arbitrarily use 4GiB for the initial block device size, but don't truncate the file yet,
97        // so it becomes exactly as large as needed to contain the contents.  We'll truncate it down
98        // to 2x contents later.
99        // 4G just needs to be large enough to fit pretty much any image.
100        const FOUR_GIGS: u64 = 4 * 1024 * 1024 * 1024;
101        FOUR_GIGS / BLOCK_SIZE
102    };
103
104    let device = DeviceHolder::new(FileBackedDevice::new_with_block_count(
105        output_image,
106        BLOCK_SIZE.get() as u32,
107        block_count,
108    ));
109    let fxblob = FxBlobBuilder::new(device).await?;
110    let blobs_json = install_blobs(&fxblob, blobs, compression_algorithm).await.map_err(|e| {
111        if target_size != 0 && FxfsError::NoSpace.matches(&e) {
112            e.context(format!(
113                "Configured image size {} is too small to fit the base system image.",
114                target_size
115            ))
116        } else {
117            e
118        }
119    })?;
120    let actual_size = fxblob.finalize().await?.1;
121
122    if target_size == 0 {
123        // Apply a default heuristic of 2x the actual image size.  This is necessary to use the
124        // Fxfs image, since if it's completely full it can't be modified.
125        target_size = (actual_size + RESERVED_SPACE) * 2;
126    }
127
128    if let Some(sparse_path) = sparse_output_image_path {
129        create_sparse_image(sparse_path, output_image_path, actual_size, target_size, BLOCK_SIZE)
130            .context("Failed to create sparse image")?;
131    }
132
133    if target_size != actual_size {
134        debug_assert!(target_size > actual_size);
135        let output_image =
136            std::fs::OpenOptions::new().read(true).write(true).open(output_image_path)?;
137        output_image.set_len(target_size).context("Failed to resize image")?;
138    }
139
140    let mut json_output = BufWriter::new(
141        std::fs::File::create(json_output_path).context("Failed to create JSON output file")?,
142    );
143    serde_json::to_writer_pretty(&mut json_output, &blobs_json)
144        .context("Failed to serialize to JSON output")?;
145
146    Ok(())
147}
148
149fn create_sparse_image(
150    sparse_output_image_path: &str,
151    image_path: &str,
152    actual_size: u64,
153    target_size: u64,
154    block_size: BlockSize,
155) -> Result<(), Error> {
156    let image = std::fs::OpenOptions::new()
157        .read(true)
158        .open(image_path)
159        .with_context(|| format!("Failed to open {:?}", image_path))?;
160    let mut output = std::fs::OpenOptions::new()
161        .read(true)
162        .write(true)
163        .create(true)
164        .truncate(true)
165        .open(sparse_output_image_path)
166        .with_context(|| format!("Failed to create {:?}", sparse_output_image_path))?;
167    sparse::builder::SparseImageBuilder::new()
168        .set_block_size(block_size.get() as u32)
169        .add_source(sparse::builder::DataSource::Reader {
170            reader: Box::new(image),
171            size: actual_size,
172        })
173        .add_source(sparse::builder::DataSource::Skip(target_size - actual_size))
174        .build(&mut output)
175        .map_err(anyhow::Error::from)
176}
177
178/// Builder used to construct a new Fxblob instance ready for flashing to a device.
179pub struct FxBlobBuilder {
180    blob_directory: Directory<ObjectStore>,
181    filesystem: OpenFxFilesystem,
182}
183
184impl FxBlobBuilder {
185    /// Creates a new [`FxBlobBuilder`] backed by the given `device`.
186    pub async fn new(device: DeviceHolder) -> Result<Self, Error> {
187        let filesystem = FxFilesystemBuilder::new()
188            .format(true)
189            .trim_config(None)
190            .image_builder_mode(Some(SuperBlockInstance::A))
191            .open(device)
192            .await
193            .context("Failed to format filesystem")?;
194        filesystem.enable_allocations();
195        let root_volume = root_volume(filesystem.clone()).await?;
196        let vol = root_volume
197            .new_volume(BLOB_VOLUME_NAME, NewChildStoreOptions::default())
198            .await
199            .context("Failed to create volume")?;
200        let blob_directory = Directory::open(&vol, vol.root_directory_object_id())
201            .await
202            .context("Unable to open root blob directory")?;
203        Ok(Self { blob_directory, filesystem })
204    }
205
206    /// Finalizes building the FxBlob instance this builder represents. The filesystem will not be
207    /// usable unless this is called. Returns the filesystem's DeviceHolder and the last offset in
208    /// bytes which was used on the device.
209    pub async fn finalize(self) -> Result<(DeviceHolder, u64), Error> {
210        self.filesystem.close().await?;
211        let actual_size = self.filesystem.allocator().maximum_offset();
212        Ok((self.filesystem.take_device().await, actual_size))
213    }
214
215    /// Installs the given `blob` into the filesystem, returning a handle to the new object.
216    pub async fn install_blob(
217        &self,
218        blob: &BlobToInstall,
219    ) -> Result<DataObjectHandle<ObjectStore>, Error> {
220        let handle;
221        let keys = lock_keys![LockKey::object(
222            self.blob_directory.store().store_object_id(),
223            self.blob_directory.object_id(),
224        )];
225        let mut transaction = self
226            .blob_directory
227            .store()
228            .new_transaction(keys, Default::default())
229            .await
230            .context("new transaction")?;
231        handle = self
232            .blob_directory
233            .create_child_file_with_options(
234                &mut transaction,
235                &blob.hash.to_string(),
236                // Checksums are redundant for blobs, which are already content-verified.
237                HandleOptions { skip_checksums: true, ..Default::default() },
238            )
239            .await
240            .context("create child file")?;
241        transaction.commit().await.context("transaction commit")?;
242
243        // Write the blob data directly into the object handle.
244        {
245            let mut writer = DirectWriter::new(&handle, Default::default()).await;
246            match &blob.data {
247                BlobData::Uncompressed(data) => {
248                    writer.write_bytes(data).await.context("write blob contents")?;
249                }
250                BlobData::CompressedZstd(archive) | BlobData::CompressedLz4(archive) => {
251                    for chunk in archive.chunks() {
252                        writer
253                            .write_bytes(&chunk.compressed_data)
254                            .await
255                            .context("write blob contents")?;
256                    }
257                }
258            }
259            writer.complete().await.context("flush blob contents")?;
260        }
261
262        // Write the metadata to the object handle.
263        blob.metadata.write_to(&handle).await.context("write blob metadata")?;
264
265        Ok(handle)
266    }
267
268    /// Helper function to quickly create a blob to install from in-memory data. Mainly for testing.
269    pub fn generate_blob(
270        &self,
271        data: Vec<u8>,
272        compression_algorithm: Option<CompressionAlgorithm>,
273    ) -> Result<BlobToInstall, Error> {
274        BlobToInstall::new(data, self.filesystem.block_size(), compression_algorithm)
275    }
276}
277
278enum BlobData {
279    Uncompressed(Vec<u8>),
280    CompressedZstd(ChunkedArchive),
281    CompressedLz4(ChunkedArchive),
282}
283
284fn compressed_offsets(chunked_archive: &ChunkedArchive) -> Vec<u64> {
285    let mut offsets = Vec::with_capacity(chunked_archive.chunks().len());
286    let mut offset: u64 = 0;
287    for chunk in chunked_archive.chunks() {
288        offsets.push(offset);
289        offset += chunk.compressed_data.len() as u64;
290    }
291    offsets
292}
293
294/// Represents a blob ready to be installed into an FxBlob instance.
295pub struct BlobToInstall {
296    /// The validated Merkle root of this blob.
297    hash: Hash,
298    /// On-disk representation of the blob data (either compressed or uncompressed).
299    data: BlobData,
300    /// Uncompressed size of the blob's data.
301    uncompressed_size: usize,
302    /// Holds the merkle leaves and compressed offsets.
303    metadata: BlobMetadata,
304    /// Path, if any, corresponding to the on-disk location of the source for this blob. Only set
305    /// if created via [`Self::new_from_file`].
306    source: Option<PathBuf>,
307}
308
309impl BlobToInstall {
310    /// Create a new blob ready for installation with [`FxBlobBuilder::install_blob`].
311    pub fn new(
312        data: Vec<u8>,
313        fs_block_size: BlockSize,
314        compression_algorithm: Option<CompressionAlgorithm>,
315    ) -> Result<Self, Error> {
316        let (hash, hashes) =
317            MerkleRootBuilder::new(BlobMetadataLeafHashCollector::new()).complete(&data);
318
319        let uncompressed_size = data.len();
320        let data = if let Some(compression_algorithm) = compression_algorithm {
321            maybe_compress(data, fs_block_size, compression_algorithm)
322        } else {
323            BlobData::Uncompressed(data)
324        };
325        let metadata = match &data {
326            BlobData::Uncompressed(_) => {
327                BlobMetadata { merkle_leaves: hashes, format: BlobFormat::Uncompressed }
328            }
329            BlobData::CompressedZstd(chunked_archive) => BlobMetadata {
330                merkle_leaves: hashes,
331                format: BlobFormat::ChunkedZstd {
332                    uncompressed_size: uncompressed_size as u64,
333                    chunk_size: chunked_archive.chunk_size() as u64,
334                    compressed_offsets: compressed_offsets(&chunked_archive),
335                },
336            },
337            BlobData::CompressedLz4(chunked_archive) => BlobMetadata {
338                merkle_leaves: hashes,
339                format: BlobFormat::ChunkedLz4 {
340                    uncompressed_size: uncompressed_size as u64,
341                    chunk_size: chunked_archive.chunk_size() as u64,
342                    compressed_offsets: compressed_offsets(&chunked_archive),
343                },
344            },
345        };
346        Ok(BlobToInstall { hash, data, uncompressed_size, metadata, source: None })
347    }
348
349    /// Create a new blob ready for installation with [`FxBlobBuilder::install_blob`] from an
350    /// existing file on disk.
351    pub fn new_from_file(
352        path: PathBuf,
353        fs_block_size: BlockSize,
354        compression_algorithm: Option<CompressionAlgorithm>,
355    ) -> Result<Self, Error> {
356        let mut data = Vec::new();
357        std::fs::File::open(&path)
358            .with_context(|| format!("Unable to open `{:?}'", path))?
359            .read_to_end(&mut data)
360            .with_context(|| format!("Unable to read contents of `{:?}'", path))?;
361        let blob = Self::new(data, fs_block_size, compression_algorithm)?;
362        Ok(Self { source: Some(path), ..blob })
363    }
364
365    pub fn hash(&self) -> Hash {
366        self.hash.clone()
367    }
368}
369
370async fn install_blobs(
371    fxblob: &FxBlobBuilder,
372    blobs: Vec<(Hash, PathBuf)>,
373    compression_algorithm: Option<CompressionAlgorithm>,
374) -> Result<BlobsJsonOutput, Error> {
375    let num_blobs = blobs.len();
376    let fs_block_size = fxblob.filesystem.block_size();
377    // We don't need any backpressure as the channel guarantees at least one slot per sender.
378    let (tx, rx) = futures::channel::mpsc::channel::<BlobToInstall>(0);
379    // Generate each blob in parallel using a thread pool.
380    let num_threads: usize = std::thread::available_parallelism().unwrap().into();
381    let thread_pool = ThreadPoolBuilder::new().num_threads(num_threads).build().unwrap();
382    let generate = fasync::unblock(move || {
383        thread_pool.install(|| {
384            blobs.par_iter().try_for_each(|(hash, path)| {
385                let blob = BlobToInstall::new_from_file(
386                    path.clone(),
387                    fs_block_size,
388                    compression_algorithm,
389                )?;
390                if &blob.hash != hash {
391                    let calculated_hash = &blob.hash;
392                    let path = path.display();
393                    return Err(anyhow!(
394                        "Hash mismatch for {path}: calculated={calculated_hash}, expected={hash}"
395                    ));
396                }
397                futures::executor::block_on(tx.clone().send(blob))
398                    .context("send blob to install task")
399            })
400        })?;
401        Ok(())
402    });
403    // We can buffer up to this many blobs after processing.
404    const MAX_INSTALL_CONCURRENCY: usize = 10;
405    let install = rx
406        .map(|blob| install_blob_with_json_output(fxblob, blob))
407        .buffer_unordered(MAX_INSTALL_CONCURRENCY)
408        .try_collect::<BlobsJsonOutput>();
409    let (installed_blobs, _) = try_join!(install, generate)?;
410    assert_eq!(installed_blobs.len(), num_blobs);
411    Ok(installed_blobs)
412}
413
414async fn install_blob_with_json_output(
415    fxblob: &FxBlobBuilder,
416    blob: BlobToInstall,
417) -> Result<BlobsJsonOutputEntry, Error> {
418    let handle = fxblob.install_blob(&blob).await?;
419    let properties = handle.get_properties().await.context("get properties")?;
420    let source_path = blob
421        .source
422        .expect("missing source path")
423        .to_str()
424        .context("blob path to utf8")?
425        .to_string();
426    Ok(BlobsJsonOutputEntry {
427        source_path,
428        merkle: blob.hash.to_string(),
429        bytes: blob.uncompressed_size,
430        size: properties.allocated_size,
431        file_size: blob.uncompressed_size,
432        compressed_file_size: properties.data_attribute_size,
433        merkle_tree_size: blob.metadata.serialized_size().context("blob metadata size")?,
434        used_space_in_blobfs: properties.allocated_size,
435    })
436}
437
438fn maybe_compress(
439    buf: Vec<u8>,
440    filesystem_block_size: BlockSize,
441    compression_algorithm: CompressionAlgorithm,
442) -> BlobData {
443    if buf.len() as u64 <= filesystem_block_size {
444        return BlobData::Uncompressed(buf); // No savings, return original data.
445    }
446    let chunked_archive_options = match compression_algorithm {
447        CompressionAlgorithm::Zstd => {
448            // TODO(https://fxbug.dev/450626615) Use chunked-compression V3.
449            Type1Blob::CHUNKED_ARCHIVE_OPTIONS
450        }
451        CompressionAlgorithm::Lz4 => ChunkedArchiveOptions::V3 { compression_algorithm },
452    };
453    let archive =
454        ChunkedArchive::new(&buf, chunked_archive_options).expect("failed to compress data");
455    if filesystem_block_size.align_up(archive.compressed_data_size() as u64).unwrap()
456        >= buf.len() as u64
457    {
458        BlobData::Uncompressed(buf) // Compression expanded the file, return original data.
459    } else {
460        match compression_algorithm {
461            CompressionAlgorithm::Zstd => BlobData::CompressedZstd(archive),
462            CompressionAlgorithm::Lz4 => BlobData::CompressedLz4(archive),
463        }
464    }
465}
466
467/// Extract blobs from the Fxfs image in the product bundle to the output directory.
468pub async fn extract_blobs(image: PathBuf, out_dir: PathBuf) -> anyhow::Result<()> {
469    if out_dir.exists() {
470        fs::remove_dir_all(&out_dir).context("Failed to remove output directory")?;
471    }
472    fs::create_dir_all(&out_dir)?;
473
474    // TODO (https://fxbug.dev/483735826):
475    // Update the fxfs crate so that you can hand it a sparse image and
476    // it will be able to parse that and iterate over the contents
477    let mut source = fs::File::open(&image)?;
478    let mut non_sparse_image = tempfile::NamedTempFile::new_in(&out_dir)?;
479    unsparse(&mut source, non_sparse_image.as_file_mut()).map_err(anyhow::Error::from)?;
480
481    let device = DeviceHolder::new(FileBackedDevice::new(
482        non_sparse_image.reopen()?,
483        BLOCK_SIZE.get() as u32,
484    ));
485    let fs = FxFilesystemBuilder::new().read_only(true).open(device).await?;
486    let vol =
487        root_volume(fs.clone()).await?.volume(BLOB_VOLUME_NAME, StoreOptions::default()).await?;
488    let root_dir = Directory::open(&vol, vol.root_directory_object_id()).await?;
489    let layer_set = root_dir.store().tree().layer_set();
490    let mut merger = layer_set.merger();
491    let mut iter = root_dir.iter(&mut merger).await?;
492    let blob_extraction_futures = futures::stream::FuturesUnordered::new();
493
494    while let Some((name, object_id, descriptor)) = iter.get() {
495        if *descriptor == fxfs::object_store::ObjectDescriptor::File {
496            let handle = fxfs::object_store::ObjectStore::open_object(
497                root_dir.owner(),
498                object_id,
499                fxfs::object_store::HandleOptions::default(),
500                None,
501            )
502            .await?;
503
504            let mut components = std::path::Path::new(name).components();
505            if !matches!(components.next(), Some(std::path::Component::Normal(..))) {
506                return Err(anyhow!("Invalid blob name: {}", name));
507            }
508            if components.next().is_some() {
509                return Err(anyhow!("Invalid blob name: {}", name));
510            }
511            let out_path = out_dir.join(name);
512            let mut file = std::fs::File::create(&out_path)?;
513            let read_buf = handle.contents(usize::MAX).await?;
514
515            let metadata = BlobMetadata::read_from(&handle).await?;
516            blob_extraction_futures.push(fasync::unblock(move || -> Result<(), Error> {
517                match metadata.format {
518                    BlobFormat::ChunkedZstd {
519                        uncompressed_size,
520                        compressed_offsets,
521                        chunk_size,
522                    } => decompress_blob(
523                        &read_buf,
524                        uncompressed_size,
525                        compressed_offsets,
526                        chunk_size,
527                        CompressionAlgorithm::Zstd,
528                        &mut file,
529                    ),
530                    BlobFormat::ChunkedLz4 {
531                        uncompressed_size,
532                        compressed_offsets,
533                        chunk_size,
534                    } => decompress_blob(
535                        &read_buf,
536                        uncompressed_size,
537                        compressed_offsets,
538                        chunk_size,
539                        CompressionAlgorithm::Lz4,
540                        &mut file,
541                    ),
542                    BlobFormat::Uncompressed => {
543                        file.write_all(&read_buf)?;
544                        Ok(())
545                    }
546                }
547            }));
548        }
549        iter.advance().await?;
550    }
551    blob_extraction_futures.try_collect::<()>().await?;
552    Ok(())
553}
554
555fn decompress_blob(
556    blob_data: &[u8],
557    uncompressed_size: u64,
558    compressed_offsets: Vec<u64>,
559    chunk_size: u64,
560    compression_algorithm: CompressionAlgorithm,
561    out: &mut std::fs::File,
562) -> Result<(), Error> {
563    let mut decompressor = compression_algorithm.decompressor();
564    let mut buf = vec![0; chunk_size as usize];
565    let mut total_decompressed_size = 0;
566    for i in 0..compressed_offsets.len() {
567        let start_offset = compressed_offsets[i] as usize;
568        let end_offset = if i + 1 == compressed_offsets.len() {
569            blob_data.len()
570        } else {
571            compressed_offsets[i + 1] as usize
572        };
573        let decompressed_size =
574            decompressor.decompress_into(&blob_data[start_offset..end_offset], &mut buf, i)?;
575        total_decompressed_size += decompressed_size;
576        out.write_all(&buf[..decompressed_size])?;
577    }
578    if total_decompressed_size != uncompressed_size as usize {
579        Err(anyhow!(
580            "Decompressed size does not match expected size {} {}",
581            total_decompressed_size,
582            uncompressed_size
583        ))
584    } else {
585        Ok(())
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use super::{BlobsJsonOutput, BlobsJsonOutputEntry, extract_blobs, make_blob_image};
592    use assert_matches::assert_matches;
593    use delivery_blob::compression::CompressionAlgorithm;
594    use fxfs::blob_metadata::FxfsBlobMetadataExt;
595    use fxfs::filesystem::FxFilesystem;
596    use fxfs::object_store::StoreOptions;
597    use fxfs::object_store::directory::Directory;
598    use fxfs::object_store::volume::root_volume;
599    use sparse::reader::SparseReader;
600    use std::fs::File;
601    use std::io::{Seek as _, SeekFrom, Write};
602    use std::path::Path;
603    use std::str::from_utf8;
604    use storage_device::DeviceHolder;
605    use storage_device::file_backed_device::FileBackedDevice;
606    use tempfile::TempDir;
607
608    #[fuchsia::test(threads = 10)]
609    async fn test_extract_blobs_zstd() {
610        let tmp = TempDir::new().unwrap();
611        let dir = tmp.path();
612
613        let input_blob_path = dir.join("input.txt");
614        let image_path = dir.join("fxfs1.blk");
615        let sparse_path = dir.join("fxfs1.sparse.blk");
616        let out_dir = dir.join("extracted_out");
617
618        let data = "C".repeat(128 * 1024);
619        std::fs::write(&input_blob_path, &data).unwrap();
620
621        let merkle_hash = fuchsia_merkle::root_from_slice(data.as_bytes());
622
623        make_blob_image(
624            image_path.to_str().unwrap(),
625            Some(sparse_path.to_str().unwrap()),
626            vec![(merkle_hash, input_blob_path.clone())],
627            dir.join("blobs1.json").to_str().unwrap(),
628            None,
629            Some(CompressionAlgorithm::Zstd),
630        )
631        .await
632        .expect("make_blob_image failed");
633
634        extract_blobs(sparse_path, out_dir.clone())
635            .await
636            .expect("Extraction failed inside extract_blobs");
637
638        let mut extracted_files = std::fs::read_dir(&out_dir).expect("out_dir should exist");
639        let first_entry = extracted_files
640            .next()
641            .expect("No files were extracted!")
642            .expect("Failed to read directory entry");
643
644        let extracted_blob_path = first_entry.path();
645        let final_len = std::fs::metadata(&extracted_blob_path).unwrap().len();
646
647        assert_eq!(
648            final_len,
649            data.len() as u64,
650            "Decompressed data size does not match original size",
651        );
652    }
653
654    #[fuchsia::test(threads = 10)]
655    async fn test_extract_blobs_lz4() {
656        let tmp = TempDir::new().unwrap();
657        let dir = tmp.path();
658
659        let input_blob_path = dir.join("input.txt");
660        let image_path = dir.join("fxfs1.blk");
661        let sparse_path = dir.join("fxfs1.sparse.blk");
662        let out_dir = dir.join("extracted_out");
663
664        let data = "C".repeat(128 * 1024);
665        std::fs::write(&input_blob_path, &data).unwrap();
666
667        let merkle_hash = fuchsia_merkle::root_from_slice(data.as_bytes());
668
669        make_blob_image(
670            image_path.to_str().unwrap(),
671            Some(sparse_path.to_str().unwrap()),
672            vec![(merkle_hash, input_blob_path.clone())],
673            dir.join("blobs1.json").to_str().unwrap(),
674            None,
675            Some(CompressionAlgorithm::Lz4),
676        )
677        .await
678        .expect("make_blob_image failed");
679
680        extract_blobs(sparse_path, out_dir.clone())
681            .await
682            .expect("Extraction failed inside extract_blobs");
683
684        let mut extracted_files = std::fs::read_dir(&out_dir).expect("out_dir should exist");
685        let first_entry = extracted_files
686            .next()
687            .expect("No files were extracted!")
688            .expect("Failed to read directory entry");
689
690        let extracted_blob_path = first_entry.path();
691        let final_len = std::fs::metadata(&extracted_blob_path).unwrap().len();
692
693        assert_eq!(
694            final_len,
695            data.len() as u64,
696            "Decompressed data size does not match original size",
697        );
698    }
699
700    #[fuchsia::test(threads = 10)]
701    async fn test_make_blob_image() {
702        let tmp = TempDir::new().unwrap();
703        let dir = tmp.path();
704        let blobs_in = {
705            let write_data = |path, data: &str| {
706                let mut file = File::create(&path).unwrap();
707                write!(file, "{}", data).unwrap();
708                let root = fuchsia_merkle::root_from_slice(data);
709                (root, path)
710            };
711            vec![
712                write_data(dir.join("stuff1.txt"), "Goodbye, stranger!"),
713                write_data(dir.join("stuff2.txt"), "It's been nice!"),
714                write_data(dir.join("stuff3.txt"), from_utf8(&['a' as u8; 65_537]).unwrap()),
715            ]
716        };
717
718        let dir = tmp.path();
719        let output_path = dir.join("fxfs.blk");
720        let sparse_path = dir.join("fxfs.sparse.blk");
721        let blobs_json_path = dir.join("blobs.json");
722        make_blob_image(
723            output_path.as_os_str().to_str().unwrap(),
724            Some(sparse_path.as_os_str().to_str().unwrap()),
725            blobs_in,
726            blobs_json_path.as_os_str().to_str().unwrap(),
727            /*target_size=*/ None,
728            Some(CompressionAlgorithm::Zstd),
729        )
730        .await
731        .expect("make_blob_image failed");
732
733        // Check that the blob manifest contains the entries we expect.
734        let mut blobs_json = std::fs::OpenOptions::new()
735            .read(true)
736            .open(blobs_json_path)
737            .expect("Failed to open blob manifest");
738        let mut blobs: BlobsJsonOutput =
739            serde_json::from_reader(&mut blobs_json).expect("Failed to serialize to JSON output");
740
741        assert_eq!(blobs.len(), 3);
742        blobs.sort_by_key(|entry| entry.source_path.clone());
743
744        assert_eq!(Path::new(blobs[0].source_path.as_str()), dir.join("stuff1.txt"));
745        assert_matches!(
746            &blobs[0],
747            BlobsJsonOutputEntry {
748                merkle,
749                bytes: 18,
750                size: 4096,
751                file_size: 18,
752                merkle_tree_size: 0,
753                used_space_in_blobfs: 4096,
754                ..
755            } if merkle == "9a24fe2fb8da617f39d303750bbe23f4e03a8b5f4d52bc90b2e5e9e44daddb3a"
756        );
757        assert_eq!(Path::new(blobs[1].source_path.as_str()), dir.join("stuff2.txt"));
758        assert_matches!(
759            &blobs[1],
760            BlobsJsonOutputEntry {
761                merkle,
762                bytes: 15,
763                size: 4096,
764                file_size: 15,
765                merkle_tree_size: 0,
766                used_space_in_blobfs: 4096,
767                ..
768            } if merkle == "deebe5d5a0a42a51a293b511d0368e6f2b4da522ee0f05c6ae728c77d904f916"
769        );
770        assert_eq!(Path::new(blobs[2].source_path.as_str()), dir.join("stuff3.txt"));
771        assert_matches!(
772            &blobs[2],
773            BlobsJsonOutputEntry {
774                merkle,
775                bytes: 65537,
776                // This is technically sensitive to compression, but a string of 'a' should
777                // always compress down to a single block.
778                size: 8192,
779                file_size: 65537,
780                merkle_tree_size: 308,
781                used_space_in_blobfs: 8192,
782                ..
783            } if merkle == "1194c76d2d3b61f29df97a85ede7b2fd2b293b452f53072356e3c5c939c8131d"
784        );
785
786        let unsparsed_image = {
787            let sparse_image = std::fs::OpenOptions::new().read(true).open(sparse_path).unwrap();
788            let mut reader = SparseReader::new(sparse_image).expect("Failed to parse sparse image");
789
790            let unsparsed_image_path = dir.join("fxfs.unsparsed.blk");
791            let mut unsparsed_image = std::fs::OpenOptions::new()
792                .read(true)
793                .write(true)
794                .create(true)
795                .open(unsparsed_image_path)
796                .unwrap();
797
798            std::io::copy(&mut reader, &mut unsparsed_image).expect("Failed to unsparse");
799            unsparsed_image.seek(SeekFrom::Start(0)).unwrap();
800            unsparsed_image
801        };
802
803        let orig_image = std::fs::OpenOptions::new()
804            .read(true)
805            .open(output_path.clone())
806            .expect("Failed to open image");
807
808        assert_eq!(unsparsed_image.metadata().unwrap().len(), orig_image.metadata().unwrap().len());
809
810        // Verify the images created are valid Fxfs images and contains the blobs we expect.
811        for image in [orig_image, unsparsed_image] {
812            let device = DeviceHolder::new(FileBackedDevice::new(image, 4096));
813            let filesystem = FxFilesystem::open(device).await.unwrap();
814            let root_volume = root_volume(filesystem.clone()).await.expect("Opening root volume");
815            let vol =
816                root_volume.volume("blob", StoreOptions::default()).await.expect("Opening volume");
817            let directory = Directory::open(&vol, vol.root_directory_object_id())
818                .await
819                .expect("Opening root dir");
820            let entries = {
821                let layer_set = directory.store().tree().layer_set();
822                let mut merger = layer_set.merger();
823                let mut iter = directory.iter(&mut merger).await.expect("iter failed");
824                let mut entries = vec![];
825                while let Some((name, _, _)) = iter.get() {
826                    entries.push(name.to_string());
827                    iter.advance().await.expect("advance failed");
828                }
829                entries
830            };
831            assert_eq!(
832                &entries[..],
833                &[
834                    "1194c76d2d3b61f29df97a85ede7b2fd2b293b452f53072356e3c5c939c8131d",
835                    "9a24fe2fb8da617f39d303750bbe23f4e03a8b5f4d52bc90b2e5e9e44daddb3a",
836                    "deebe5d5a0a42a51a293b511d0368e6f2b4da522ee0f05c6ae728c77d904f916",
837                ]
838            );
839        }
840    }
841
842    #[fuchsia::test(threads = 10)]
843    async fn test_make_uncompressed_blob_image() {
844        let tmp = TempDir::new().unwrap();
845        let dir = tmp.path();
846        let path = dir.join("large_blob.txt");
847        let mut file = File::create(&path).unwrap();
848        let data = vec![0xabu8; 32 * 1024 * 1024];
849        file.write_all(&data).unwrap();
850        let root = fuchsia_merkle::root_from_slice(&data);
851        let blobs_in = vec![(root, path)];
852
853        let compressed_path = dir.join("fxfs-compressed.blk");
854        let blobs_json_path = dir.join("blobs.json");
855        make_blob_image(
856            compressed_path.as_os_str().to_str().unwrap(),
857            None,
858            blobs_in.clone(),
859            blobs_json_path.as_os_str().to_str().unwrap(),
860            /*target_size=*/ None,
861            Some(CompressionAlgorithm::Zstd),
862        )
863        .await
864        .expect("make_blob_image failed");
865
866        let uncompressed_path = dir.join("fxfs-uncompressed.blk");
867        make_blob_image(
868            uncompressed_path.as_os_str().to_str().unwrap(),
869            None,
870            blobs_in,
871            blobs_json_path.as_os_str().to_str().unwrap(),
872            /*target_size=*/ None,
873            /*compression_algorithm=*/ None,
874        )
875        .await
876        .expect("make_blob_image failed");
877
878        assert!(
879            std::fs::metadata(compressed_path).unwrap().len()
880                < std::fs::metadata(uncompressed_path).unwrap().len()
881        )
882    }
883
884    #[fuchsia::test(threads = 10)]
885    async fn test_make_blob_image_with_target_size() {
886        const TARGET_SIZE: u64 = 200 * 1024 * 1024;
887        let tmp = TempDir::new().unwrap();
888        let dir = tmp.path();
889        let path = dir.join("large_blob.txt");
890        let mut file = File::create(&path).unwrap();
891        let data = vec![0xabu8; 8 * 1024 * 1024];
892        file.write_all(&data).unwrap();
893        let root = fuchsia_merkle::root_from_slice(&data);
894        let blobs_in = vec![(root, path)];
895
896        let image_path = dir.join("fxfs.blk");
897        let sparse_image_path = dir.join("fxfs.sparse.blk");
898        let blobs_json_path = dir.join("blobs.json");
899        make_blob_image(
900            image_path.as_os_str().to_str().unwrap(),
901            Some(sparse_image_path.as_os_str().to_str().unwrap()),
902            blobs_in.clone(),
903            blobs_json_path.as_os_str().to_str().unwrap(),
904            /*target_size=*/ Some(200 * 1024 * 1024),
905            Some(CompressionAlgorithm::Zstd),
906        )
907        .await
908        .expect("make_blob_image failed");
909
910        // The fxfs image is small but gets padded with zeros up to the target size. The zeros
911        // should be replaced with a don't care chunk in the sparse format making it much smaller.
912        let image_size = std::fs::metadata(image_path).unwrap().len();
913        let sparse_image_size = std::fs::metadata(sparse_image_path).unwrap().len();
914        assert_eq!(image_size, TARGET_SIZE);
915        assert!(sparse_image_size < TARGET_SIZE, "Sparse image size: {sparse_image_size}");
916    }
917
918    #[fuchsia::test(threads = 10)]
919    async fn test_extract_blobs_path_traversal() {
920        use super::{
921            BLOB_VOLUME_NAME, BLOCK_SIZE, BlobFormat, BlobMetadata, DirectWriter,
922            FxFilesystemBuilder, HandleOptions, LockKey, NewChildStoreOptions, SuperBlockInstance,
923            create_sparse_image,
924        };
925        use fxfs::object_handle::WriteBytes;
926        use fxfs::object_store::transaction::lock_keys;
927
928        let tmp = TempDir::new().unwrap();
929        let dir = tmp.path();
930        let image_size = 10 * 1024 * 1024;
931
932        let image_path = dir.join("malicious.blk");
933
934        // Create a minimal Fxfs image with a malicious filename.
935        let output_image = std::fs::OpenOptions::new()
936            .read(true)
937            .write(true)
938            .create(true)
939            .truncate(true)
940            .open(&image_path)
941            .unwrap();
942        output_image.set_len(image_size).unwrap();
943
944        let device =
945            DeviceHolder::new(FileBackedDevice::new(output_image, BLOCK_SIZE.get() as u32));
946        let fs = FxFilesystemBuilder::new()
947            .format(true)
948            .trim_config(None)
949            .image_builder_mode(Some(SuperBlockInstance::A))
950            .open(device)
951            .await
952            .unwrap();
953        fs.enable_allocations();
954        let root_volume = root_volume(fs.clone()).await.unwrap();
955        let vol = root_volume
956            .new_volume(BLOB_VOLUME_NAME, NewChildStoreOptions::default())
957            .await
958            .unwrap();
959        let blob_directory = Directory::open(&vol, vol.root_directory_object_id()).await.unwrap();
960
961        // Create a file with a malicious name.
962        let malicious_name = "../prevent_escaped_write.txt";
963        let keys = lock_keys![LockKey::object(
964            blob_directory.store().store_object_id(),
965            blob_directory.object_id(),
966        )];
967        let mut transaction =
968            blob_directory.store().new_transaction(keys, Default::default()).await.unwrap();
969        let handle = blob_directory
970            .create_child_file_with_options(
971                &mut transaction,
972                malicious_name,
973                HandleOptions { skip_checksums: true, ..Default::default() },
974            )
975            .await
976            .unwrap();
977        transaction.commit().await.unwrap();
978
979        // Write some placeholder data.
980        {
981            let mut writer = DirectWriter::new(&handle, Default::default()).await;
982            writer.write_bytes(b"malicious data").await.unwrap();
983            writer.complete().await.unwrap();
984        }
985        // Write uncompressed metadata (simplest).
986        let metadata = BlobMetadata { merkle_leaves: vec![], format: BlobFormat::Uncompressed };
987        metadata.write_to(&handle).await.unwrap();
988
989        fs.close().await.unwrap();
990
991        let sparse_path = dir.join("malicious.sparse.blk");
992        create_sparse_image(
993            sparse_path.to_str().unwrap(),
994            image_path.to_str().unwrap(),
995            image_size,
996            image_size,
997            BLOCK_SIZE,
998        )
999        .unwrap();
1000
1001        // Now try to extract it. It should fail.
1002        let extract_dir = dir.join("normal_out");
1003        std::fs::create_dir(&extract_dir).unwrap();
1004
1005        let err = extract_blobs(sparse_path, extract_dir.clone()).await.unwrap_err();
1006        assert_eq!(err.to_string(), "Invalid blob name: ../prevent_escaped_write.txt");
1007
1008        // Ensure the file was NOT created outside the output directory.
1009        let escaped_path = dir.join("prevent_escaped_write.txt");
1010        assert!(!escaped_path.exists());
1011    }
1012}