use std::io::{Read, Seek, SeekFrom, Write};
use crate::bytes::{get_u16, get_u32, get_u32_be, put_arr, put_u32, put_u32_be};
use crate::crc32c::crc32c;
use crate::feature::Incompat;
use crate::geometry::sparse_super_has_copy;
use crate::io::{offset_of, read_exact_at};
use crate::journal;
use crate::ondisk::{SuperBlock, superblock_checksum};
use crate::read::{OpenOptions, ReadError, Reader};
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct IdentityChange {
pub uuid: Option<[u8; 16]>,
pub volume_name: Option<[u8; 16]>,
pub set_checksum_seed: bool,
}
impl IdentityChange {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.uuid.is_none() && self.volume_name.is_none() && !self.set_checksum_seed
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct IdentityReport {
pub superblocks: u32,
pub journal_superblock: bool,
pub checksum_seed_set: bool,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum IdentityError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
Read(#[from] ReadError),
#[error(
"changing the UUID would invalidate every metadata checksum: this filesystem has \
metadata_csum without metadata_csum_seed, so its checksums are seeded from the \
UUID itself — set the checksum seed to keep them valid"
)]
UuidWouldInvalidateChecksums,
#[error(
"setting the checksum seed needs a filesystem with metadata_csum and without \
metadata_csum_seed; this one is {found}"
)]
#[non_exhaustive]
ChecksumSeedPointless {
found: &'static str,
},
#[error(
"group {group}'s backup superblock lies past the end of a {blocks}-block image: \
the superblock describes a larger filesystem than this file holds"
)]
#[non_exhaustive]
BackupPastEnd {
group: u32,
blocks: u64,
},
#[error(
"group {group} should hold a backup superblock at block {block} and does not: \
re-identifying would leave the copies disagreeing about the filesystem"
)]
#[non_exhaustive]
BackupNotASuperblock {
group: u32,
block: u64,
},
#[error(
"the superblock in group {group} has checksum {found:#010x} but its contents \
compute to {computed:#010x}: the image is damaged, and re-identifying it would \
write a correct checksum over a wrong superblock"
)]
#[non_exhaustive]
SuperblockChecksumMismatch {
group: u32,
found: u32,
computed: u32,
},
#[error(
"the journal superblock's checksum is {found:#010x} but its contents compute to \
{computed:#010x}: the log is damaged, and re-identifying it would write a correct \
checksum over a wrong journal superblock"
)]
#[non_exhaustive]
JournalChecksumMismatch {
found: u32,
computed: u32,
},
#[error(
"the journal declares checksums of type {checksum_type} rather than crc32c, so its \
superblock checksum cannot be brought back into agreement with a new UUID"
)]
#[non_exhaustive]
JournalChecksumUnsupported {
checksum_type: u8,
},
}
pub fn rewrite_identity<F: Read + Write + Seek>(
image: &mut F,
change: &IdentityChange,
) -> Result<IdentityReport, IdentityError> {
rewrite_identity_at(image, change, 0)
}
pub fn rewrite_identity_at<F: Read + Write + Seek>(
image: &mut F,
change: &IdentityChange,
base: u64,
) -> Result<IdentityReport, IdentityError> {
let plan = plan_rewrite(image, change, base)?;
for (offset, bytes) in &plan.writes {
image.seek(SeekFrom::Start(base + *offset))?;
image.write_all(bytes)?;
}
image.flush()?;
Ok(plan.report)
}
struct Rewrite {
writes: Vec<(u64, Vec<u8>)>,
report: IdentityReport,
}
fn plan_rewrite<F: Read + Write + Seek>(
image: &mut F,
change: &IdentityChange,
base: u64,
) -> Result<Rewrite, IdentityError> {
let mut reader = Reader::open_with(&mut *image, &OpenOptions::new().base(base))?;
let feature = reader.feature();
let sb = reader.superblock().clone();
let group_count = reader.group_count();
let block_size = u64::from(feature.block_size);
let journal_block = if change.uuid.is_some() {
reader.journal_superblock_block()?
} else {
None
};
drop(reader);
let checksummed = feature.has_metadata_csum();
let seeded = feature.has_csum_seed();
let seed_to_set = decide_checksum_seed(change, &sb, checksummed, seeded)?;
let source_blocks = image.seek(SeekFrom::End(0))?.saturating_sub(base) / block_size;
let mut copies = vec![(0u32, 1024u64)];
for group in 1..group_count {
let block = match offset_of(
u64::from(sb.first_data_block),
u64::from(group),
u64::from(sb.blocks_per_group),
) {
Some(block) if block < source_blocks => block,
_ => {
return Err(IdentityError::BackupPastEnd {
group,
blocks: source_blocks,
});
}
};
if feature.is_sparse_super() && !sparse_super_has_copy(group) {
continue;
}
let offset = offset_of(0, block, block_size).ok_or(IdentityError::BackupPastEnd {
group,
blocks: source_blocks,
})?;
copies.push((group, offset));
}
let superblocks = u32::try_from(copies.len()).unwrap_or(u32::MAX);
let mut writes = Vec::with_capacity(copies.len() + 1);
for (group, offset) in copies {
let mut bytes = read_exact_at(image, base + offset, SuperBlock::SIZE)?;
if get_u16(&bytes, SuperBlock::MAGIC_OFFSET) != crate::ondisk::SUPERBLOCK_MAGIC {
return Err(IdentityError::BackupNotASuperblock {
group,
block: offset / block_size,
});
}
if checksummed {
verify_checksum(&bytes, group)?;
}
patch(&mut bytes, change, seed_to_set, checksummed);
writes.push((offset, bytes));
}
let journal_written = match (journal_block, change.uuid) {
(Some(block), Some(uuid)) => {
let offset = offset_of(0, block, block_size).ok_or(IdentityError::BackupPastEnd {
group: 0,
blocks: source_blocks,
})?;
let mut bytes = read_exact_at(image, base + offset, journal::SUPERBLOCK_SIZE)?;
patch_journal(&mut bytes, uuid)?;
writes.push((offset, bytes));
true
}
_ => false,
};
Ok(Rewrite {
writes,
report: IdentityReport {
superblocks,
journal_superblock: journal_written,
checksum_seed_set: seed_to_set.is_some(),
},
})
}
fn decide_checksum_seed(
change: &IdentityChange,
sb: &SuperBlock,
checksummed: bool,
seeded: bool,
) -> Result<Option<u32>, IdentityError> {
let seedable = checksummed && !seeded;
if change.set_checksum_seed {
if !seedable {
return Err(IdentityError::ChecksumSeedPointless {
found: match (checksummed, seeded) {
(false, _) => "without metadata_csum, so nothing is seeded",
(true, true) => "already carrying metadata_csum_seed",
(true, false) => unreachable!("seedable is checked above"),
},
});
}
return Ok(Some(crc32c(!0, &sb.uuid)));
}
if change.uuid.is_some() && seedable {
return Err(IdentityError::UuidWouldInvalidateChecksums);
}
Ok(None)
}
fn patch(bytes: &mut [u8], change: &IdentityChange, seed: Option<u32>, checksummed: bool) {
if let Some(uuid) = change.uuid {
put_arr(bytes, SuperBlock::UUID_OFFSET, &uuid);
}
if let Some(label) = change.volume_name {
put_arr(bytes, SuperBlock::VOLUME_NAME_OFFSET, &label);
}
if let Some(seed) = seed {
put_u32(bytes, SuperBlock::CHECKSUM_SEED_OFFSET, seed);
let incompat =
get_u32(bytes, SuperBlock::FEATURE_INCOMPAT_OFFSET) | Incompat::CSUM_SEED.bits();
put_u32(bytes, SuperBlock::FEATURE_INCOMPAT_OFFSET, incompat);
}
if checksummed {
put_u32(
bytes,
SuperBlock::CHECKSUM_OFFSET,
superblock_checksum(bytes),
);
}
}
fn patch_journal(bytes: &mut [u8], uuid: [u8; 16]) -> Result<(), IdentityError> {
let checksummed = journal::superblock_is_checksummed(bytes);
if checksummed {
let kind = bytes[journal::offset::CHECKSUM_TYPE];
if kind != journal::CRC32C_CHKSUM {
return Err(IdentityError::JournalChecksumUnsupported {
checksum_type: kind,
});
}
let found = get_u32_be(bytes, journal::offset::CHECKSUM);
let computed = journal::superblock_checksum(bytes);
if found != computed {
return Err(IdentityError::JournalChecksumMismatch { found, computed });
}
}
put_arr(bytes, journal::offset::UUID, &uuid);
if checksummed {
put_u32_be(
bytes,
journal::offset::CHECKSUM,
journal::superblock_checksum(bytes),
);
}
Ok(())
}
fn verify_checksum(bytes: &[u8], group: u32) -> Result<(), IdentityError> {
let found = get_u32(bytes, SuperBlock::CHECKSUM_OFFSET);
let computed = superblock_checksum(bytes);
if found != computed {
return Err(IdentityError::SuperblockChecksumMismatch {
group,
found,
computed,
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::feature::Profile;
use crate::materialize::{FormatOptions, format};
use crate::source::{Metadata, TreeBuilder};
use crate::time::Timestamp;
use std::io::Cursor;
const MIB: u64 = 1024 * 1024;
fn options(profile: Profile) -> FormatOptions {
FormatOptions::new([0x11; 16], Timestamp::from_secs(1_700_000_000), [0u8; 16])
.profile(profile)
}
fn image(profile: Profile) -> Vec<u8> {
let time = Timestamp::from_secs(1_700_000_000);
let source = TreeBuilder::new().file(
b"/a".to_vec(),
b"contents\n".to_vec(),
Metadata::new(0o644, time),
);
format(source, 8 * MIB, options(profile))
.expect("format")
.into_bytes()
}
fn put_u32(bytes: &mut [u8], field: usize, value: u32) {
bytes[1024 + field..1024 + field + 4].copy_from_slice(&value.to_le_bytes());
}
#[test]
fn a_superblock_claiming_more_groups_than_the_image_holds_is_refused() {
let mut bytes = image(Profile::Ext2);
put_u32(&mut bytes, 0x04, u32::MAX);
put_u32(&mut bytes, 0x20, 8);
let mut change = IdentityChange::new();
change.uuid = Some([0x5a; 16]);
let err = rewrite_identity(&mut Cursor::new(&mut bytes), &change)
.expect_err("a geometry the file cannot hold is refused");
assert!(
matches!(err, IdentityError::BackupPastEnd { .. }),
"expected BackupPastEnd, got {err:?}"
);
}
#[test]
fn a_group_size_that_puts_the_first_backup_past_the_image_is_refused_at_that_group() {
let mut bytes = image(Profile::Ext2);
put_u32(&mut bytes, 0x04, u32::MAX);
put_u32(&mut bytes, 0x20, 8 * 4096);
let mut change = IdentityChange::new();
change.uuid = Some([0x5a; 16]);
let err = rewrite_identity(&mut Cursor::new(&mut bytes), &change)
.expect_err("an unreachable backup is refused");
assert!(
matches!(err, IdentityError::BackupPastEnd { group: 1, .. }),
"expected BackupPastEnd at group 1, got {err:?}"
);
}
#[test]
fn an_untouched_image_still_rewrites_every_copy() {
let mut bytes = image(Profile::Ext2);
let mut change = IdentityChange::new();
change.uuid = Some([0x5a; 16]);
let report = rewrite_identity(&mut Cursor::new(&mut bytes), &change).expect("rewrite");
assert!(report.superblocks >= 1);
let reader = Reader::open(Cursor::new(bytes.as_slice())).expect("open");
assert_eq!(reader.superblock().uuid, [0x5a; 16]);
}
}