garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /disk/src/gpt.rs

raw

//! The GUID Partition Table (UEFI 2.10, chapter 5): a protective MBR in
//! the first sector, the table's header in the second with its entries
//! after it, and a copy of both at the disk's end. Every disk Pinnacle
//! installs on gets one; a disk that has one is read as its partitions.
//!
//! Sectors here are the disk's logical ones ([`Table::sector`]), 512 bytes
//! on nearly every disk and 4096 on some; partitions Pinnacle makes start
//! and end on whole MiB, so its 4 KiB blocks never straddle one.

use crate::{Medium, crc32, u32_at, u64_at};
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;

/// A GUID in the byte order it has on disk (the first three fields little
/// endian, the rest as written).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Guid(pub [u8; 16]);

impl Guid {
    /// From its usual text, `12345678-9abc-def0-1234-56789abcdef0`.
    pub const fn parse(text: &str) -> Guid {
        let t = text.as_bytes();
        assert!(t.len() == 36, "a GUID is 36 characters");
        const fn hex(c: u8) -> u8 {
            match c {
                b'0'..=b'9' => c - b'0',
                b'a'..=b'f' => c - b'a' + 10,
                b'A'..=b'F' => c - b'A' + 10,
                _ => panic!("not a hex digit"),
            }
        }
        // The text's byte pairs, in the order written, skipping dashes.
        let mut plain = [0u8; 16];
        let (mut i, mut n) = (0, 0);
        while i < 36 {
            if t[i] == b'-' {
                i += 1;
                continue;
            }
            plain[n] = hex(t[i]) << 4 | hex(t[i + 1]);
            n += 1;
            i += 2;
        }
        let mut b = plain;
        // The first three fields are little endian on disk.
        b[0] = plain[3];
        b[1] = plain[2];
        b[2] = plain[1];
        b[3] = plain[0];
        b[4] = plain[5];
        b[5] = plain[4];
        b[6] = plain[7];
        b[7] = plain[6];
        Guid(b)
    }

    /// Its usual text, lower case.
    pub fn text(&self) -> String {
        let b = &self.0;
        let order = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15];
        let mut s = String::with_capacity(36);
        for (n, &i) in order.iter().enumerate() {
            if matches!(n, 4 | 6 | 8 | 10) {
                s.push('-');
            }
            s.push(char::from_digit(u32::from(b[i] >> 4), 16).unwrap());
            s.push(char::from_digit(u32::from(b[i] & 15), 16).unwrap());
        }
        s
    }

    /// A version 4 (random) GUID from 16 random bytes.
    pub fn random(mut bytes: [u8; 16]) -> Guid {
        // Version 4 in the third field's high nibble (byte 7 on disk), the
        // variant in the fourth's top bits.
        bytes[7] = (bytes[7] & 0x0f) | 0x40;
        bytes[8] = (bytes[8] & 0x3f) | 0x80;
        Guid(bytes)
    }

    pub fn is_zero(&self) -> bool {
        self.0 == [0; 16]
    }
}

/// The EFI system partition, FAT, which a UEFI firmware starts from.
pub const EFI_SYSTEM: Guid = Guid::parse("c12a7328-f81f-11d2-ba4b-00a0c93ec93b");
/// Pinnacle's system: its file system, labelled `system`.
pub const PINNACLE_SYSTEM: Guid = Guid::parse("6f7e2a1c-3b9d-4e51-9a2f-50494e4e5359");
/// The person's data: a vault (`pfs::vault`), blank until the first start
/// makes it one.
pub const PINNACLE_DATA: Guid = Guid::parse("6f7e2a1c-3b9d-4e51-9a2f-50494e4e4441");

/// One partition: its kind, its own identity, its first and last sector
/// (both in it) and its name.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Partition {
    pub kind: Guid,
    pub id: Guid,
    pub first: u64,
    pub last: u64,
    pub name: String,
}

impl Partition {
    /// Where it starts, and how long it is, in bytes.
    pub fn range(&self, sector: u64) -> (u64, u64) {
        (self.first * sector, (self.last + 1 - self.first) * sector)
    }
}

/// A disk's partition table.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Table {
    /// The disk's logical sector size in bytes.
    pub sector: u64,
    pub disk: Guid,
    pub partitions: Vec<Partition>,
}

const SIGNATURE: &[u8; 8] = b"EFI PART";
const REVISION: u32 = 0x0001_0000;
const HEADER_SIZE: usize = 92;
const ENTRY_SIZE: usize = 128;
/// Entries the table has room for: the usual 128, 16 KiB of them.
const ENTRIES: usize = 128;
const ENTRIES_BYTES: usize = ENTRY_SIZE * ENTRIES;

/// Reads the partition table of a disk of `sector`-byte sectors: the
/// primary, or the copy at the end when the primary is damaged. None when
/// the disk has none (no signature, or neither copy's checksums hold).
pub fn read(disk: &mut impl Medium, sector: u64) -> Option<Table> {
    let last = disk.size() / sector - 1;
    read_at(disk, sector, 1).or_else(|| read_at(disk, sector, last))
}

fn read_at(disk: &mut impl Medium, sector: u64, lba: u64) -> Option<Table> {
    let mut header = vec![0u8; sector as usize];
    if !disk.read_at(lba * sector, &mut header) || &header[..8] != SIGNATURE {
        return None;
    }
    let size = u32_at(&header, 12) as usize;
    if !(HEADER_SIZE..=sector as usize).contains(&size) {
        return None;
    }
    let mut check = header[..size].to_vec();
    check[16..20].fill(0);
    if crc32(&check) != u32_at(&header, 16) || u64_at(&header, 24) != lba {
        return None;
    }
    let entries_at = u64_at(&header, 72);
    let count = u32_at(&header, 80) as usize;
    let entry_size = u32_at(&header, 84) as usize;
    if entry_size < ENTRY_SIZE || count > 1024 || entry_size > 1024 {
        return None;
    }
    let mut entries = vec![0u8; count * entry_size];
    if !disk.read_at(entries_at * sector, &mut entries) || crc32(&entries) != u32_at(&header, 88) {
        return None;
    }
    let mut disk_id = [0u8; 16];
    disk_id.copy_from_slice(&header[56..72]);
    let partitions = entries
        .chunks_exact(entry_size)
        .filter_map(|e| {
            let kind = Guid(e[..16].try_into().unwrap());
            if kind.is_zero() {
                return None;
            }
            let name: Vec<u16> = e[56..128]
                .as_chunks::<2>()
                .0
                .iter()
                .map(|&c| u16::from_le_bytes(c))
                .take_while(|&c| c != 0)
                .collect();
            let (first, last) = (u64_at(e, 32), u64_at(e, 40));
            (first <= last).then(|| Partition {
                kind,
                id: Guid(e[16..32].try_into().unwrap()),
                first,
                last,
                name: String::from_utf16_lossy(&name),
            })
        })
        .collect();
    Some(Table {
        sector,
        disk: Guid(disk_id),
        partitions,
    })
}

/// The sectors a table on a disk of `sectors` leaves for partitions: after
/// the MBR, the header and its entries, before the copy at the end.
pub fn usable(sector: u64, sectors: u64) -> (u64, u64) {
    let entry_sectors = (ENTRIES_BYTES as u64).div_ceil(sector);
    (2 + entry_sectors, sectors - 2 - entry_sectors)
}

/// The sector a partition that starts at or after `lba` starts at, on a
/// whole MiB.
pub fn align(sector: u64, lba: u64) -> u64 {
    let per_mib = (1 << 20) / sector;
    lba.next_multiple_of(per_mib)
}

/// Writes `table` to the disk: the protective MBR, the header and its
/// entries, and their copies at the end. False when a write failed or a
/// partition does not fit.
pub fn write(disk: &mut impl Medium, table: &Table) -> bool {
    let sector = table.sector;
    let sectors = disk.size() / sector;
    let (first_usable, last_usable) = usable(sector, sectors);
    if table.partitions.len() > ENTRIES
        || table
            .partitions
            .iter()
            .any(|p| p.first < first_usable || p.last > last_usable || p.first > p.last)
    {
        return false;
    }
    let mut entries = vec![0u8; ENTRIES_BYTES];
    for (p, e) in table
        .partitions
        .iter()
        .zip(entries.as_chunks_mut::<ENTRY_SIZE>().0)
    {
        e[..16].copy_from_slice(&p.kind.0);
        e[16..32].copy_from_slice(&p.id.0);
        e[32..40].copy_from_slice(&p.first.to_le_bytes());
        e[40..48].copy_from_slice(&p.last.to_le_bytes());
        for (i, c) in p.name.encode_utf16().take(36).enumerate() {
            e[56 + 2 * i..58 + 2 * i].copy_from_slice(&c.to_le_bytes());
        }
    }
    let entries_crc = crc32(&entries);
    let entry_sectors = (ENTRIES_BYTES as u64).div_ceil(sector);
    let last = sectors - 1;
    let header = |mine: u64, other: u64, entries_at: u64| {
        let mut h = vec![0u8; sector as usize];
        h[..8].copy_from_slice(SIGNATURE);
        h[8..12].copy_from_slice(&REVISION.to_le_bytes());
        h[12..16].copy_from_slice(&(HEADER_SIZE as u32).to_le_bytes());
        h[24..32].copy_from_slice(&mine.to_le_bytes());
        h[32..40].copy_from_slice(&other.to_le_bytes());
        h[40..48].copy_from_slice(&first_usable.to_le_bytes());
        h[48..56].copy_from_slice(&last_usable.to_le_bytes());
        h[56..72].copy_from_slice(&table.disk.0);
        h[72..80].copy_from_slice(&entries_at.to_le_bytes());
        h[80..84].copy_from_slice(&(ENTRIES as u32).to_le_bytes());
        h[84..88].copy_from_slice(&(ENTRY_SIZE as u32).to_le_bytes());
        h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
        let crc = crc32(&h[..HEADER_SIZE]);
        h[16..20].copy_from_slice(&crc.to_le_bytes());
        h
    };
    // The protective MBR: one partition of type 0xee over the whole disk
    // (as far as 32 bits reach), so tools that know only MBRs leave it be.
    let mut mbr = vec![0u8; sector as usize];
    let p = &mut mbr[446..462];
    p[1..4].copy_from_slice(&[0, 2, 0]);
    p[4] = 0xee;
    p[5..8].copy_from_slice(&[0xff, 0xff, 0xff]);
    p[8..12].copy_from_slice(&1u32.to_le_bytes());
    p[12..16].copy_from_slice(&(last.min(u64::from(u32::MAX)) as u32).to_le_bytes());
    mbr[510] = 0x55;
    mbr[511] = 0xaa;
    let backup_entries = last - entry_sectors;
    // The copy at the end first: a cut during the primary's write leaves a
    // whole table to read.
    disk.write_at(backup_entries * sector, &entries)
        && disk.write_at(last * sector, &header(last, 1, backup_entries))
        && disk.write_at(2 * sector, &entries)
        && disk.write_at(sector, &header(1, last, 2))
        && disk.write_at(0, &mbr)
}