From d96a18e144f3ffcfb1b9072a50b25f6614c3a51a Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 01/19] json: add a pull parser Currently parse() is the only way to read JSON. It turns the whole text into a Value tree: every string is copied and every array and object is allocated before the caller gets to look at any of it. That's fine for the Varlink messages we exchange. But a UAPI.16 manifest can be gigabytes of records and a reader only wants a handful of fields out of each of them. Building a tree for every record just to throw it away again is a waste. Add Parser which reads a text value by value. peek() says what kind of value comes next and the method named after that kind reads it. An array is entered with array() and walked with element(). An object is entered with object() and walked with key(), which returns the key of the next member. skip() reads over a value of any kind, value() reads one into a Value, and end() checks that nothing but whitespace is left. A string without an escape is handed out as a slice of the text, so nothing is copied for it. The parser refuses what parse() refuses: bad syntax, nesting deeper than 128 levels and objects that have a key twice. Every object the parser is inside of gets a set of its keys. Keys without an escape are borrowed from the text for that, and checking a key is one lookup no matter how large the object is. When the parser leaves an object it empties the set and takes it again for the next object that is inside of as many objects. So a text needs as many sets as the most objects the parser is inside of at once, and not one for every object. The set of the outermost object is kept apart, so a text whose objects aren't nested needs nothing more. skip() is the exception. A reader of a manifest has to pass over a field it doesn't know whatever its value is, so skip() checks the grammar and nothing else: numbers aren't converted and arrays and objects can be nested to any depth. It doesn't recurse, and it keeps the keys of all objects of the value in one set, each with where its object starts, so a key twice is still refused at any depth. The parser keeps that set from one skip() to the next and empties it in between. A key twice is refused right behind the key, by key() and skip() alike, before its value is read. Currently parse() only notices it behind the value. A caller that streams would have read, and maybe acted on, the value of the duplicate by then. The error also has a kind of its own now, ParseErrorKind::DuplicateKey, so callers can tell it apart from a syntax error. Note that emptying a set that has keys takes time in proportion to its capacity, and an emptied set keeps its capacity. So a set that grew past the capacity it starts with is shrunk back when it is emptied. Otherwise every object that takes the set after a large one would pay for the capacity of the large one. One object with 200000 keys followed by 200000 small ones in the same array takes one to two seconds without that and 0.04 seconds with it. A string is searched for its end eight bytes at a time. std has nothing that looks for any of several bytes, and going byte by byte takes about four times as long on long strings. Everything else uses std. Numbers go through str::parse() once the JSON grammar has been checked by hand, since std's parsers would also take a plus sign, leading zeros, "inf" and "NaN". \u escapes go through char::to_digit() and char::decode_utf16(). -0 is read as a float. Currently parse() reads it as the integer 0 since an integer has no negative zero. But then a caller that only takes unsigned integers, like the reader of a manifest, can't tell it from 0. The Varlink service reads its messages with parse() as well, so it now refuses -0 for an integer parameter too. is_whitespace() is public. JSON's whitespace is space, tab, newline and carriage return, and that is also what systemd skips. Code that wants the same shouldn't use u8::is_ascii_whitespace() which takes form feed as well. Rebuild parse() on top of the parser so we only have one of them. On two million texts made by mutating a handful of seeds the old and the new parse() agree: both return the same value, or both fail with the same message at the same offset. Only -0 is read as a float now, and a key twice is reported earlier, right behind the key. Signed-off-by: Christian Brauner (Amutable) --- src/json/lib.rs | 1528 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 1343 insertions(+), 185 deletions(-) diff --git a/src/json/lib.rs b/src/json/lib.rs index 1121fae..1096e4d 100644 --- a/src/json/lib.rs +++ b/src/json/lib.rs @@ -2,14 +2,21 @@ //! A small, strict JSON implementation: a value type, an RFC 8259 parser and //! a compact serializer. //! +//! [`parse`] reads a text into a [`Value`], and a `Value` prints itself as +//! compact text. [`Parser`] reads a text value by value, for a caller that +//! has types of its own and does not want a `Value` in between. +//! //! Numbers keep their nature: anything written without a fraction or an //! exponent that fits into 128 bits stays an integer, so 64-bit sizes and -//! offsets survive a round trip exactly. Objects keep their insertion order -//! and refuse duplicate keys. +//! offsets survive a round trip exactly. -0 is a float, since an integer has +//! no negative zero. Objects keep their insertion order and refuse duplicate +//! keys. #![deny(unsafe_code)] #![warn(missing_docs)] +use std::borrow::Cow; +use std::collections::HashSet; use std::fmt; use std::str::FromStr; @@ -20,7 +27,7 @@ pub enum Value { Null, /// `true` or `false` Bool(bool), - /// A number without fraction or exponent. + /// A number without fraction or exponent, other than -0. Int(i128), /// Any other number. Float(f64), @@ -292,6 +299,18 @@ pub struct ParseError { pub offset: usize, /// What went wrong. pub message: &'static str, + /// Whether the text is not JSON or has a key twice in an object. + pub kind: ParseErrorKind, +} + +/// What kind of error a [`ParseError`] is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ParseErrorKind { + /// The text is not JSON. + Syntax, + /// An object has a key twice. RFC 8259 leaves open what such an object + /// means, and the parser refuses it. + DuplicateKey, } impl fmt::Display for ParseError { @@ -302,38 +321,369 @@ impl fmt::Display for ParseError { impl std::error::Error for ParseError {} -/// Nesting deeper than this is refused, to bound stack use. +/// Nesting deeper than this is refused, to bound stack use. A value that +/// [`Parser::skip`] passes over can be nested deeper. const MAX_DEPTH: usize = 128; -struct Parser<'a> { - bytes: &'a [u8], +/// The most arrays and objects a parser is inside of at once: the value at +/// the top and one at every level of nesting below it. +const MAX_OPEN: usize = MAX_DEPTH + 1; + +/// How many keys the set of an object has room for from the start, about +/// as many as an object of a manifest has. A set that grows hashes all its +/// keys again. +const OBJECT_KEYS: usize = 8; + +/// Eight bytes of a text in one integer, the first of them in its lowest +/// bits. A string is searched for its end a word at a time: std has no +/// search for any of several bytes, and looking at one byte after the +/// other takes four times as long on a long string. +#[derive(Clone, Copy)] +struct Word(u64); + +impl Word { + /// How many bytes a word holds. + const SIZE: usize = size_of::(); + /// The lowest bit of every byte, and the highest. + const LOW_BITS: u64 = u64::from_ne_bytes([0x01; Word::SIZE]); + const HIGH_BITS: u64 = u64::from_ne_bytes([0x80; Word::SIZE]); + + fn new(bytes: [u8; Word::SIZE]) -> Word { + Word(u64::from_le_bytes(bytes)) + } + + /// The high bit of every byte that is below `limit`, which is no more + /// than 0x80. Only the lowest bit set is to be relied on: a byte after + /// the first one below the limit can be marked wrongly. + const fn below(self, limit: u8) -> u64 { + self.0.wrapping_sub(Word::LOW_BITS * limit as u64) & !self.0 & Word::HIGH_BITS + } + + /// The high bit of every byte that is `byte`, to be relied on like + /// that of [`Word::below`]. + const fn equal(self, byte: u8) -> u64 { + Word(self.0 ^ (Word::LOW_BITS * byte as u64)).below(1) + } + + /// Where the first byte is that does not stand for itself in a + /// string, if the word has one. + fn first_special(self) -> Option { + let special = self.equal(QUOTE) | self.equal(ESCAPE) | self.below(FIRST_PRINTABLE); + (special != 0).then(|| (special.trailing_zeros() / u8::BITS) as usize) + } + + /// How many bytes at the start of `bytes` are what RFC 8259 calls + /// unescaped, bytes that stand for themselves in a string: all up to + /// the first quote, backslash or control character. + fn unescaped_len(bytes: &[u8]) -> usize { + let mut rest = bytes; + while let Some((word, behind)) = rest.split_first_chunk() { + if let Some(at) = Word::new(*word).first_special() { + return bytes.len() - rest.len() + at; + } + rest = behind; + } + let unescaped = |b: &&u8| **b != QUOTE && **b != ESCAPE && **b >= FIRST_PRINTABLE; + bytes.len() - rest.len() + rest.iter().take_while(unescaped).count() + } +} + +/// The first byte of a string and its last. +const QUOTE: u8 = b'"'; +/// The byte that starts an escape inside a string. +const ESCAPE: u8 = b'\\'; +/// The bytes below this one are control characters. A string has to +/// escape them. +const FIRST_PRINTABLE: u8 = 0x20; +/// What a `\u` escape starts with, and how many hex digits follow: one +/// UTF-16 unit. +const UNICODE_ESCAPE: &str = "\\u"; +const UNICODE_ESCAPE_DIGITS: usize = 4; +/// The control characters with an escape of a letter of their own, besides +/// newline, carriage return and tab. +const BACKSPACE: u8 = 0x08; +const FORM_FEED: u8 = 0x0c; +/// The base of those digits, and the bits of one of them. +const HEX: u32 = 16; +const HEX_DIGIT_BITS: u32 = 4; +/// The UTF-16 units that are the first half of a pair, the high +/// surrogates. A `\u` escape of one has to be followed by one of the low +/// surrogate that completes it. +const HIGH_SURROGATES: std::ops::Range = 0xD800..0xDC00; +/// The structural characters, as RFC 8259 names them: what begins and ends +/// an array and an object, and what follows the name of a member and a +/// value. +const BEGIN_ARRAY: u8 = b'['; +const END_ARRAY: u8 = b']'; +const BEGIN_OBJECT: u8 = b'{'; +const END_OBJECT: u8 = b'}'; +const NAME_SEPARATOR: u8 = b':'; +const VALUE_SEPARATOR: u8 = b','; + +/// Whether `b` is what RFC 8259 calls whitespace: space, tab, newline +/// and carriage return. Form feed is not, unlike for +/// `u8::is_ascii_whitespace`. +pub const fn is_whitespace(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\n' | b'\r') +} + +/// The kind of a JSON value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// `null` + Null, + /// `true` or `false` + Bool, + /// A number. + Number, + /// A string. + String, + /// An array. + Array, + /// An object. + Object, +} + +/// A JSON number. One written without a fraction or an exponent that fits +/// into 128 bits is an integer, other than -0, which only a float can hold. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Number { + /// A number without fraction or exponent, other than -0. + Int(i128), + /// Any other number. + Float(f64), +} + +impl Number { + /// The number as u64, if it is a non-negative integer in range. + pub fn as_u64(self) -> Option { + match self { + Number::Int(i) => u64::try_from(i).ok(), + Number::Float(_) => None, + } + } + + /// The number as i64, if it is an integer in range. + pub fn as_i64(self) -> Option { + match self { + Number::Int(i) => i64::try_from(i).ok(), + Number::Float(_) => None, + } + } + + /// The number as f64, integers included. + pub fn as_f64(self) -> f64 { + match self { + Number::Int(i) => i as f64, + Number::Float(f) => f, + } + } +} + +impl From for Value { + fn from(n: Number) -> Value { + match n { + Number::Int(i) => Value::Int(i), + Number::Float(f) => Value::Float(f), + } + } +} + +/// An array or an object the parser is inside of. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Container { + /// An array. + Array, + /// An object. + Object, +} + +/// The keys of the objects a parser is inside of, a set for each of them. +/// The set of an object the parser left is emptied and taken again for the +/// next object that is inside of as many objects. So a text needs as many +/// sets as the most objects the parser is inside of at once, and not one +/// for every object. The set of the outermost object is kept apart, so that +/// a text whose objects are not nested needs that set and nothing more. +/// +/// Emptying a set that has keys takes time in proportion to its capacity, +/// and an emptied set keeps its capacity. So a set that grew past the +/// capacity for [`OBJECT_KEYS`] keys is shrunk back to it when it is +/// emptied. Otherwise every object that takes the set after a large one +/// would pay for the capacity of the large one. +#[derive(Default)] +struct Keys<'a> { + /// How many objects the parser is inside of. + objects: usize, + /// The keys of the outermost object the parser is inside of. + outermost: HashSet>, + /// The keys of the objects inside of that one, outermost first, and + /// behind them emptied sets kept for later objects. + inner: Vec>>, +} + +impl<'a> Keys<'a> { + /// The set of the innermost object the parser is inside of. + fn innermost(&mut self) -> Option<&mut HashSet>> { + match self.objects { + 0 => None, + 1 => Some(&mut self.outermost), + objects => self.inner.get_mut(objects - 2), + } + } + + /// Takes a set for the keys of an object the parser goes into. + fn open(&mut self) { + if self.objects > self.inner.len() { + self.inner.push(HashSet::new()); + } + self.objects += 1; + if let Some(keys) = self.innermost() { + keys.reserve(OBJECT_KEYS); + } + } + + /// Empties the set of the innermost object, which the parser left. + fn close(&mut self) { + if let Some(keys) = self.innermost() { + keys.clear(); + keys.shrink_to(OBJECT_KEYS); + } + self.objects -= 1; + } + + /// Notes `key` as a key of the innermost object. Returns false when + /// that object had the key before. + fn insert(&mut self, key: Cow<'a, str>) -> bool { + self.innermost().is_some_and(|keys| keys.insert(key)) + } +} + +/// An array or an object that [`Parser::skip`] is inside of. +#[derive(Clone, Copy)] +enum SkippedContainer { + /// An array. + Array, + /// An object, with where it starts in the text. That tells it apart + /// from the other objects. + Object(usize), +} + +/// What [`Parser::skip`] keeps of the value it reads. The value can be +/// nested to any depth, so the keys of all of its objects go into one set, +/// each with where its object starts, and not into a set for each object. +/// The parser keeps it from one value to the next and empties it in +/// between, the way [`Keys`] empties its sets. +#[derive(Default)] +struct SkippedValue<'a> { + /// The arrays and objects the parser is inside of, outermost first. + containers: Vec, + /// The keys of the objects so far, each with where its object starts. + keys: HashSet<(usize, Cow<'a, str>)>, +} + +impl SkippedValue<'_> { + /// Goes into the object that starts at `start`, with room for as many + /// more keys as an object of a manifest has. + fn open_object(&mut self, start: usize) { + self.keys.reserve(OBJECT_KEYS); + self.containers.push(SkippedContainer::Object(start)); + } + + /// Forgets the value it was kept for. A set of keys that grew past the + /// capacity for [`OBJECT_KEYS`] keys is shrunk back to it. + fn clear(&mut self) { + self.containers.clear(); + self.keys.clear(); + self.keys.shrink_to(OBJECT_KEYS); + } +} + +/// Reads a JSON text value by value, without building a [`Value`]. +/// +/// The parser stands in front of a value. [`Parser::peek`] says what kind +/// it is. The methods named after a kind read the value if it is of that +/// kind, and leave it alone if it is not. [`Parser::skip`] reads a value of +/// any kind. An array is entered with [`Parser::array`], and then +/// [`Parser::element`] says before every element whether there is one. An +/// object is entered with [`Parser::object`], and then [`Parser::key`] +/// returns the key of every member, whose value is read next. +/// +/// A text the parser reads to its end without an error is one [`parse`] +/// takes, and the other way around. Only what [`Parser::skip`] passes over +/// can be more: numbers too large for a float and arrays and objects nested +/// deeper than [`parse`] takes them. +/// +/// ``` +/// let mut parser = json::Parser::new(r#"{"name":"a","size":3,"more":[1,2]}"#); +/// let mut size = None; +/// assert!(parser.object()?); +/// while let Some(key) = parser.key()? { +/// match key.as_ref() { +/// "size" => size = parser.number()?.and_then(json::Number::as_u64), +/// _ => parser.skip()?, +/// } +/// } +/// parser.end()?; +/// assert_eq!(size, Some(3)); +/// # Ok::<(), json::ParseError>(()) +/// ``` +pub struct Parser<'a> { + text: &'a str, pos: usize, + /// The arrays and objects the parser is inside of, outermost first. + levels: [Container; MAX_OPEN], + depth: usize, + /// Whether the innermost of them has no member so far. + empty: bool, + /// The keys of the objects the parser is inside of. + keys: Keys<'a>, + /// What [`Parser::skip`] keeps of the value it reads. + skipped: SkippedValue<'a>, } -impl Parser<'_> { +impl<'a> Parser<'a> { + /// A parser in front of the value `text` holds. + pub fn new(text: &'a str) -> Parser<'a> { + Parser { + text, + pos: 0, + levels: [Container::Array; MAX_OPEN], + depth: 0, + empty: false, + keys: Keys::default(), + skipped: SkippedValue::default(), + } + } + + /// How many bytes of the text the parser has read. + pub fn offset(&self) -> usize { + self.pos + } + fn error(&self, message: &'static str) -> ParseError { ParseError { offset: self.pos, message, + kind: ParseErrorKind::Syntax, } } + fn bytes(&self) -> &'a [u8] { + self.text.as_bytes() + } + fn skip_whitespace(&mut self) { - while let Some(&b) = self.bytes.get(self.pos) { - if b == b' ' || b == b'\t' || b == b'\n' || b == b'\r' { - self.pos += 1; - } else { - break; - } + while self.byte().is_some_and(is_whitespace) { + self.pos += 1; } } - fn peek(&self) -> Option { - self.bytes.get(self.pos).copied() + fn byte(&self) -> Option { + self.bytes().get(self.pos).copied() } fn expect(&mut self, b: u8) -> Result<(), ParseError> { - if self.peek() == Some(b) { + if self.byte() == Some(b) { self.pos += 1; Ok(()) } else { @@ -341,242 +691,470 @@ impl Parser<'_> { } } - fn value(&mut self, depth: usize) -> Result { - if depth > MAX_DEPTH { + /// The kind of the value the parser stands in front of. It is an + /// error when there is no value. + pub fn peek(&mut self) -> Result { + if self.depth > MAX_DEPTH { return Err(self.error("nesting too deep")); } self.skip_whitespace(); - match self.peek() { + match self.byte() { None => Err(self.error("unexpected end of input")), - Some(b'{') => self.object(depth), - Some(b'[') => self.array(depth), - Some(b'"') => Ok(Value::String(self.string()?)), - Some(b't') => self.literal("true", Value::Bool(true)), - Some(b'f') => self.literal("false", Value::Bool(false)), - Some(b'n') => self.literal("null", Value::Null), - Some(b'-' | b'0'..=b'9') => self.number(), + Some(BEGIN_OBJECT) => Ok(Kind::Object), + Some(BEGIN_ARRAY) => Ok(Kind::Array), + Some(QUOTE) => Ok(Kind::String), + Some(b't' | b'f') => Ok(Kind::Bool), + Some(b'n') => Ok(Kind::Null), + Some(b'-' | b'0'..=b'9') => Ok(Kind::Number), Some(_) => Err(self.error("unexpected character")), } } - fn literal(&mut self, word: &str, value: Value) -> Result { - if self.bytes[self.pos..].starts_with(word.as_bytes()) { + fn literal(&mut self, word: &str) -> Result<(), ParseError> { + if self.bytes()[self.pos..].starts_with(word.as_bytes()) { self.pos += word.len(); - Ok(value) + Ok(()) } else { Err(self.error("invalid literal")) } } - fn object(&mut self, depth: usize) -> Result { - self.expect(b'{')?; - let mut object = Object::new(); - self.skip_whitespace(); - if self.peek() == Some(b'}') { + /// Reads the value if it is `null`, and says whether it was. + pub fn null(&mut self) -> Result { + if self.peek()? != Kind::Null { + return Ok(false); + } + self.literal("null")?; + Ok(true) + } + + /// Reads the boolean the parser stands in front of. + fn bool_token(&mut self) -> Result { + let value = self.byte() == Some(b't'); + self.literal(if value { "true" } else { "false" })?; + Ok(value) + } + + /// Reads the value if it is a boolean. + pub fn bool(&mut self) -> Result, ParseError> { + if self.peek()? != Kind::Bool { + return Ok(None); + } + self.bool_token().map(Some) + } + + /// Reads the value if it is a number. + pub fn number(&mut self) -> Result, ParseError> { + if self.peek()? != Kind::Number { + return Ok(None); + } + self.number_token().map(Some) + } + + /// Moves over a run of digits and says whether there was one. + fn digits(&mut self) -> bool { + let run = self.bytes()[self.pos..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count(); + self.pos += run; + run > 0 + } + + /// Moves over the number the parser stands in front of, which has to + /// keep to JSON's grammar, and returns its text and whether it has a + /// fraction or an exponent. + // Inlined into number_token(), which every number goes through. + #[inline(always)] + fn number_text(&mut self) -> Result<(&'a str, bool), ParseError> { + let start = self.pos; + if self.byte() == Some(b'-') { self.pos += 1; - return Ok(Value::Object(object)); - } - // Duplicate keys are refused. The object itself is a list, which is - // right for the small objects this crate builds and receives, and - // those are checked by looking through the keys so far. Past a few - // dozen keys a set takes over, so that a parser fed a large hostile - // object does not go quadratic over it. - const SCAN_UP_TO: usize = 32; - let mut seen: Option> = None; - loop { - self.skip_whitespace(); - if self.peek() != Some(b'"') { - return Err(self.error("expected a string key")); + } + // JSON's grammar is checked here: std's parsers would also take a + // plus sign, leading zeros, "inf" and "NaN". + match self.byte() { + Some(b'0') => self.pos += 1, + Some(b'1'..=b'9') => { + self.digits(); } - let key = self.string()?; - self.skip_whitespace(); - self.expect(b':')?; - let value = self.value(depth + 1)?; - let duplicate = match seen.as_mut() { - Some(set) => !set.insert(key.clone()), - None => object.entries.iter().any(|(k, _)| *k == key), - }; - if duplicate { - return Err(self.error("duplicate key")); + _ => return Err(self.error("invalid number")), + } + let mut is_float = false; + if self.byte() == Some(b'.') { + is_float = true; + self.pos += 1; + if !self.digits() { + return Err(self.error("invalid number")); } - object.entries.push((key, value)); - if seen.is_none() && object.entries.len() >= SCAN_UP_TO { - seen = Some(object.entries.iter().map(|(k, _)| k.clone()).collect()); + } + if matches!(self.byte(), Some(b'e' | b'E')) { + is_float = true; + self.pos += 1; + if matches!(self.byte(), Some(b'+' | b'-')) { + self.pos += 1; } - self.skip_whitespace(); - match self.peek() { - Some(b',') => self.pos += 1, - Some(b'}') => { - self.pos += 1; - return Ok(Value::Object(object)); - } - _ => return Err(self.error("expected ',' or '}'")), + if !self.digits() { + return Err(self.error("invalid number")); } } + Ok((&self.text[start..self.pos], is_float)) } - fn array(&mut self, depth: usize) -> Result { - self.expect(b'[')?; - let mut items = Vec::new(); - self.skip_whitespace(); - if self.peek() == Some(b']') { - self.pos += 1; - return Ok(Value::Array(items)); - } - loop { - items.push(self.value(depth + 1)?); - self.skip_whitespace(); - match self.peek() { - Some(b',') => self.pos += 1, - Some(b']') => { - self.pos += 1; - return Ok(Value::Array(items)); - } - _ => return Err(self.error("expected ',' or ']'")), + /// Reads the number the parser stands in front of. + fn number_token(&mut self) -> Result { + let (text, is_float) = self.number_text()?; + // What is too large for an integer is a float, and so is -0, + // which an integer would turn into 0. + if !is_float { + match text.parse::() { + Ok(0) if text.starts_with('-') => {} + Ok(i) => return Ok(Number::Int(i)), + Err(_) => {} } } + let f: f64 = text.parse().map_err(|_| self.error("invalid number"))?; + if !f.is_finite() { + return Err(self.error("number out of range")); + } + Ok(Number::Float(f)) } - fn hex4(&mut self) -> Result { - let s = self - .bytes - .get(self.pos..self.pos + 4) + /// Reads the hex digits of a `\u` escape, the UTF-16 unit they spell. + fn hex4(&mut self) -> Result { + let digits = self + .bytes() + .get(self.pos..self.pos + UNICODE_ESCAPE_DIGITS) .ok_or_else(|| self.error("truncated unicode escape"))?; - // from_str_radix would also take a sign; only hex digits are JSON. - if !s.iter().all(u8::is_ascii_hexdigit) { - return Err(self.error("invalid unicode escape")); - } - let text = std::str::from_utf8(s).map_err(|_| self.error("invalid unicode escape"))?; - let v = u32::from_str_radix(text, 16).map_err(|_| self.error("invalid unicode escape"))?; - self.pos += 4; - Ok(v) + // Four hex digits always fit into a unit. + let unit = digits + .iter() + .try_fold(0, |unit, &digit| { + Some((unit << HEX_DIGIT_BITS) | char::from(digit).to_digit(HEX)?) + }) + .and_then(|unit| u16::try_from(unit).ok()) + .ok_or_else(|| self.error("invalid unicode escape"))?; + self.pos += UNICODE_ESCAPE_DIGITS; + Ok(unit) + } + + /// Moves over the unescaped bytes of a string, those that stand for + /// themselves, up to the next quote, backslash or control character. + fn skip_unescaped(&mut self) { + self.pos += Word::unescaped_len(&self.bytes()[self.pos..]); } - fn string(&mut self) -> Result { - self.expect(b'"')?; - let mut out = Vec::new(); + /// Reads the string the parser stands in front of. A string without + /// an escape is a part of the text. + fn string_token(&mut self) -> Result, ParseError> { + self.expect(QUOTE)?; + let start = self.pos; + self.skip_unescaped(); + if self.byte() == Some(QUOTE) { + let unescaped = &self.text[start..self.pos]; + self.pos += 1; + return Ok(Cow::Borrowed(unescaped)); + } + let mut out = String::from(&self.text[start..self.pos]); loop { - let start = self.pos; - while let Some(&b) = self.bytes.get(self.pos) { - if b == b'"' || b == b'\\' || b < 0x20 { - break; - } - self.pos += 1; - } - out.extend_from_slice(&self.bytes[start..self.pos]); - match self.peek() { + match self.byte() { None => return Err(self.error("unterminated string")), - Some(b'"') => { + Some(QUOTE) => { self.pos += 1; break; } - Some(b'\\') => { + Some(ESCAPE) => { self.pos += 1; - let esc = self.peek().ok_or_else(|| self.error("unterminated string"))?; + let esc = self.byte().ok_or_else(|| self.error("unterminated string"))?; self.pos += 1; match esc { - b'"' => out.push(b'"'), - b'\\' => out.push(b'\\'), - b'/' => out.push(b'/'), - b'b' => out.push(0x08), - b'f' => out.push(0x0c), - b'n' => out.push(b'\n'), - b'r' => out.push(b'\r'), - b't' => out.push(b'\t'), + QUOTE => out.push('"'), + ESCAPE => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push(char::from(BACKSPACE)), + b'f' => out.push(char::from(FORM_FEED)), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), b'u' => { - let mut code = self.hex4()?; - if (0xD800..0xDC00).contains(&code) { - // A high surrogate must be followed by a low one. - if self.bytes.get(self.pos..self.pos + 2) != Some(b"\\u") { - return Err(self.error("unpaired surrogate")); - } - self.pos += 2; - let low = self.hex4()?; - if !(0xDC00..0xE000).contains(&low) { + let unit = self.hex4()?; + // A high surrogate and the low one that follows it are + // one character. No other surrogate is one. + let c = if HIGH_SURROGATES.contains(&unit) { + if !self.bytes()[self.pos..].starts_with(UNICODE_ESCAPE.as_bytes()) { return Err(self.error("unpaired surrogate")); } - code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00); - } else if (0xDC00..0xE000).contains(&code) { - return Err(self.error("unpaired surrogate")); - } - let c = char::from_u32(code).ok_or_else(|| self.error("invalid unicode escape"))?; - let mut buf = [0u8; 4]; - out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); + self.pos += UNICODE_ESCAPE.len(); + char::decode_utf16([unit, self.hex4()?]).next().and_then(Result::ok) + } else { + char::from_u32(u32::from(unit)) + }; + out.push(c.ok_or_else(|| self.error("unpaired surrogate"))?); } _ => return Err(self.error("invalid escape")), } } Some(_) => return Err(self.error("control character in string")), } + let start = self.pos; + self.skip_unescaped(); + out.push_str(&self.text[start..self.pos]); } - String::from_utf8(out).map_err(|_| self.error("invalid UTF-8 in string")) + Ok(Cow::Owned(out)) } - fn number(&mut self) -> Result { - let start = self.pos; - if self.peek() == Some(b'-') { - self.pos += 1; + /// Reads the value if it is a string. A string without an escape is + /// returned as the part of the text it is. + pub fn string(&mut self) -> Result>, ParseError> { + if self.peek()? != Kind::String { + return Ok(None); } - match self.peek() { - Some(b'0') => self.pos += 1, - Some(b'1'..=b'9') => { - while matches!(self.peek(), Some(b'0'..=b'9')) { - self.pos += 1; - } - } - _ => return Err(self.error("invalid number")), + self.string_token().map(Some) + } + + /// Goes into the array or object the parser stands in front of. + fn enter(&mut self, container: Container) { + self.pos += 1; + self.levels[self.depth] = container; + if container == Container::Object { + self.keys.open(); } - let mut is_float = false; - if self.peek() == Some(b'.') { - is_float = true; - self.pos += 1; - if !matches!(self.peek(), Some(b'0'..=b'9')) { - return Err(self.error("invalid number")); + self.depth += 1; + self.empty = true; + } + + /// Leaves the innermost array or object, whose end was read. + fn leave(&mut self) { + self.depth -= 1; + if self.levels[self.depth] == Container::Object { + self.keys.close(); + } + self.empty = false; + } + + /// Goes into the value if it is an array, and says whether it is one. + /// [`Parser::element`] is to be asked before every element then. + pub fn array(&mut self) -> Result { + if self.peek()? != Kind::Array { + return Ok(false); + } + self.enter(Container::Array); + Ok(true) + } + + /// Whether the array the parser is in has another element. The parser + /// stands in front of it then. Otherwise it has left the array. + pub fn element(&mut self) -> Result { + debug_assert!(self.depth > 0 && self.levels[self.depth - 1] == Container::Array); + let first = std::mem::replace(&mut self.empty, false); + let more = self.next_element(first)?; + if !more { + self.leave(); + } + Ok(more) + } + + /// Moves on in an array, at its start if `first`: over the comma in + /// front of the next element, or over the bracket that ends the array. + /// Says whether an element follows. + fn next_element(&mut self, first: bool) -> Result { + self.skip_whitespace(); + match self.byte() { + Some(END_ARRAY) => { + self.pos += 1; + Ok(false) } - while matches!(self.peek(), Some(b'0'..=b'9')) { + _ if first => Ok(true), + Some(VALUE_SEPARATOR) => { self.pos += 1; + Ok(true) } + _ => Err(self.error("expected ',' or ']'")), } - if matches!(self.peek(), Some(b'e' | b'E')) { - is_float = true; - self.pos += 1; - if matches!(self.peek(), Some(b'+' | b'-')) { + } + + /// Goes into the value if it is an object, and says whether it is + /// one. [`Parser::key`] returns the key of every member then. + pub fn object(&mut self) -> Result { + if self.peek()? != Kind::Object { + return Ok(false); + } + self.enter(Container::Object); + Ok(true) + } + + /// The key of the next member of the object the parser is in. The + /// parser stands in front of the member's value then. Without another + /// member it has left the object. A key the object had before is an + /// error of the kind [`ParseErrorKind::DuplicateKey`], which is + /// reported right behind the key. + pub fn key(&mut self) -> Result>, ParseError> { + debug_assert!(self.depth > 0 && self.levels[self.depth - 1] == Container::Object); + let first = std::mem::replace(&mut self.empty, false); + let Some(key) = self.member(first)? else { + self.leave(); + return Ok(None); + }; + if !self.keys.insert(key.clone()) { + return Err(self.duplicate_key()); + } + self.name_separator()?; + Ok(Some(key)) + } + + /// The error for a key that the object it is in had before, found + /// right behind the key. + fn duplicate_key(&self) -> ParseError { + ParseError { + kind: ParseErrorKind::DuplicateKey, + ..self.error("duplicate key") + } + } + + /// Moves on in an object, at its start if `first`: over the comma in + /// front of the next member and over its key, which it returns, or over + /// the brace that ends the object. + // Inlined into key(), which every member of every object goes through. + #[inline(always)] + fn member(&mut self, first: bool) -> Result>, ParseError> { + self.skip_whitespace(); + match self.byte() { + Some(END_OBJECT) => { self.pos += 1; + return Ok(None); } - if !matches!(self.peek(), Some(b'0'..=b'9')) { - return Err(self.error("invalid number")); + _ if first => {} + Some(VALUE_SEPARATOR) => { + self.pos += 1; + self.skip_whitespace(); } - while matches!(self.peek(), Some(b'0'..=b'9')) { + _ => return Err(self.error("expected ',' or '}'")), + } + if self.byte() != Some(QUOTE) { + return Err(self.error("expected a string key")); + } + self.string_token().map(Some) + } + + /// Moves over the colon between the key of a member and its value. + fn name_separator(&mut self) -> Result<(), ParseError> { + self.skip_whitespace(); + self.expect(NAME_SEPARATOR) + } + + /// Reads the value, whatever kind it is. What it reads is held to + /// JSON's grammar and nothing more: a number is not converted, so it can + /// be of any size, and arrays and objects can be nested to any depth. + /// Strings, keys among them, are read as everywhere else, and a key + /// twice in an object is an error. + pub fn skip(&mut self) -> Result<(), ParseError> { + let skipped = self.skip_value(); + self.skipped.clear(); + skipped + } + + /// Reads the value for [`Parser::skip`], with what that keeps. + fn skip_value(&mut self) -> Result<(), ParseError> { + // The arrays and objects of the value are not recursed into, so + // their depth is not limited. + loop { + let kind = self.peek()?; + match kind { + Kind::Null => self.literal("null")?, + Kind::Bool => self.bool_token().map(drop)?, + Kind::Number => self.number_text().map(drop)?, + Kind::String => self.string_token().map(drop)?, + Kind::Array => self.skipped.containers.push(SkippedContainer::Array), + Kind::Object => self.skipped.open_object(self.pos), + } + // Into the array or object that starts here, or out of what + // ends here, up to the next value. + let mut first = matches!(kind, Kind::Array | Kind::Object); + if first { self.pos += 1; } + loop { + let Some(&innermost) = self.skipped.containers.last() else { + return Ok(()); + }; + if self.next_skipped(innermost, first)? { + break; + } + self.skipped.containers.pop(); + first = false; + } } - let text = std::str::from_utf8(&self.bytes[start..self.pos]).expect("ASCII digits"); - if !is_float { - if let Ok(i) = text.parse::() { - return Ok(Value::Int(i)); + } + + /// Moves on in `innermost`, the innermost of the arrays and objects + /// [`Parser::skip`] is inside of, at its start if `first`: over what + /// comes in front of its next value, or over its end. Says whether a + /// value follows. + fn next_skipped(&mut self, innermost: SkippedContainer, first: bool) -> Result { + let SkippedContainer::Object(object) = innermost else { + return self.next_element(first); + }; + let Some(key) = self.member(first)? else { + return Ok(false); + }; + if !self.skipped.keys.insert((object, key)) { + return Err(self.duplicate_key()); + } + self.name_separator()?; + Ok(true) + } + + /// Reads the value into a [`Value`]. + pub fn value(&mut self) -> Result { + Ok(match self.peek()? { + Kind::Null => { + self.literal("null")?; + Value::Null } + Kind::Bool => Value::Bool(self.bool_token()?), + Kind::Number => self.number_token()?.into(), + Kind::String => Value::String(self.string_token()?.into_owned()), + Kind::Array => { + self.enter(Container::Array); + let mut items = Vec::new(); + while self.element()? { + items.push(self.value()?); + } + Value::Array(items) + } + Kind::Object => { + self.enter(Container::Object); + let mut object = Object::new(); + while let Some(key) = self.key()? { + let value = self.value()?; + object.entries.push((key.into_owned(), value)); + } + Value::Object(object) + } + }) + } + + /// Checks that the value at the top was read whole and that nothing + /// but whitespace is left of the text. + pub fn end(&mut self) -> Result<(), ParseError> { + self.skip_whitespace(); + if self.depth != 0 { + return Err(self.error("unexpected end of input")); } - let f: f64 = text.parse().map_err(|_| self.error("invalid number"))?; - if !f.is_finite() { - return Err(self.error("number out of range")); + if self.pos != self.text.len() { + return Err(self.error("trailing characters")); } - Ok(Value::Float(f)) + Ok(()) } } /// Parses a complete JSON text. Leading and trailing whitespace is allowed, /// anything else after the value is an error. pub fn parse(text: &str) -> Result { - let mut p = Parser { - bytes: text.as_bytes(), - pos: 0, - }; - let v = p.value(0)?; - p.skip_whitespace(); - if p.pos != p.bytes.len() { - return Err(p.error("trailing characters")); - } - Ok(v) + let mut parser = Parser::new(text); + let value = parser.value()?; + parser.end()?; + Ok(value) } /// Writes `s` as a JSON string. The runs between escapes go out as they @@ -718,12 +1296,27 @@ mod tests { assert_eq!(parse("1.0").unwrap(), Value::Float(1.0)); assert_eq!(Value::Float(1.0).to_string(), "1.0"); assert_eq!(Value::Float(f64::NAN).to_string(), "null"); + // -0 is a float, which keeps its sign, and no integer. + let zero = parse("-0").unwrap(); + assert!(matches!(zero, Value::Float(f) if f.is_sign_negative()), "{:?}", zero); + assert_eq!( + (zero.as_u64(), zero.as_i64(), zero.to_string()), + (None, None, "-0.0".into()) + ); + assert!(matches!(Parser::new("-0").number(), Ok(Some(Number::Float(f))) if f.is_sign_negative())); + assert_eq!(parse("0"), Ok(Value::Int(0))); assert_eq!( parse(" \t\n{ \"a\" : [ 1 , 2 ] } \r\n").unwrap().to_string(), r#"{"a":[1,2]}"# ); } + #[test] + fn whitespace_is_four_bytes() { + let whitespace: Vec = (0..=u8::MAX).filter(|&b| is_whitespace(b)).collect(); + assert_eq!(whitespace, b"\t\n\r "); + } + #[test] fn rejects_garbage() { for text in [ @@ -747,6 +1340,10 @@ mod tests { "\"\\ude00\"", "{\"a\":1,\"a\":2}", "[1] x", + // Form feed and vertical tab are no whitespace in JSON. + "\u{c}1", + "[1,\u{c}2]", + "{\"a\":1}\u{b}", "NaN", "Infinity", "\"\\u12\"", @@ -764,9 +1361,9 @@ mod tests { assert_eq!(parse(&wide).unwrap().as_object().unwrap().len(), 20_000); let dup = format!("{{{},\"k1\":0}}", keys.join(",")); assert!(parse(&dup).is_err()); - // A duplicate is found on both sides of the point where the check - // switches from scanning the keys to a set, and right at it. - for n in [5, 31, 32, 33, 40] { + // A duplicate of the first, a middle or the last key is found, in + // small objects and in larger ones. + for n in [1, 5, 40] { let keys: Vec = (0..n).map(|i| format!("\"k{}\":{}", i, i)).collect(); assert_eq!( parse(&format!("{{{}}}", keys.join(","))) @@ -805,4 +1402,565 @@ mod tests { assert_eq!(v.to_string(), "\"a\\\"b\\\\c\\n\\t\\u0001é\""); assert_eq!(parse(&v.to_string()).unwrap(), v); } + + /// Reads `text` with the methods named after the kinds and writes what + /// they return back out. + fn walk(p: &mut Parser<'_>, out: &mut String) -> Result<(), ParseError> { + match p.peek()? { + Kind::Null => { + assert!(p.null()?); + out.push_str("null"); + } + Kind::Bool => out.push_str(if p.bool()?.unwrap() { "true" } else { "false" }), + Kind::Number => out.push_str(&Value::from(p.number()?.unwrap()).to_string()), + Kind::String => out.push_str(&Value::from(p.string()?.unwrap().as_ref()).to_string()), + Kind::Array => { + assert!(p.array()?); + out.push('['); + let mut elements = 0; + while p.element()? { + if elements > 0 { + out.push(','); + } + elements += 1; + walk(p, out)?; + } + out.push(']'); + } + Kind::Object => { + assert!(p.object()?); + out.push('{'); + let mut members = 0; + while let Some(key) = p.key()? { + if members > 0 { + out.push(','); + } + members += 1; + out.push_str(&Value::from(key.as_ref()).to_string()); + out.push(':'); + walk(p, out)?; + } + out.push('}'); + } + } + Ok(()) + } + + /// What [`parse`] refuses of a text that is JSON, and skipping over the + /// text does not. + const LIMITS: [&str; 2] = ["number out of range", "nesting too deep"]; + + /// What [`parse`] says about `text`, what skipping over it says and what + /// reading it value by value says: the same value or the same error. + /// Skipping goes on where a number is too large or the nesting too + /// deep for the others. + fn three_ways(text: &str) -> Result { + let parsed = parse(text).map(|v| v.to_string()); + let mut p = Parser::new(text); + let skipped = p.skip().and_then(|()| p.end()); + match &parsed { + Err(e) if LIMITS.contains(&e.message) => {} + _ => assert_eq!(skipped, parsed.clone().map(drop), "{:?}", text), + } + let mut p = Parser::new(text); + let mut out = String::new(); + let walked = walk(&mut p, &mut out).and_then(|()| p.end()).map(|()| out); + assert_eq!(walked, parsed, "{:?}", text); + parsed + } + + #[test] + fn parser_reads_value_by_value() { + let text = r#" {"name" : "a/b", "esc":"x\ny", "size":18446744073709551615, "neg":-1, "f":1.5, + "list":[1,[],{}, null ,true,false], "o":{"k":"v"}, "n":null} "#; + let mut p = Parser::new(text); + assert_eq!(p.peek(), Ok(Kind::Object)); + // A method of another kind reads nothing. + assert_eq!(p.string(), Ok(None)); + assert_eq!(p.number(), Ok(None)); + assert_eq!(p.bool(), Ok(None)); + assert_eq!(p.null(), Ok(false)); + assert_eq!(p.array(), Ok(false)); + assert_eq!(p.offset(), 1); + assert_eq!(p.object(), Ok(true)); + assert_eq!(p.key().unwrap().as_deref(), Some("name")); + assert_eq!(p.object(), Ok(false)); + // A string without an escape is a part of the text, one with an + // escape is not. + assert!(matches!(p.string(), Ok(Some(Cow::Borrowed("a/b"))))); + assert_eq!(p.key().unwrap().as_deref(), Some("esc")); + assert!(matches!(p.string(), Ok(Some(Cow::Owned(s))) if s == "x\ny")); + assert_eq!(p.key().unwrap().as_deref(), Some("size")); + assert_eq!(p.number().unwrap().and_then(Number::as_u64), Some(u64::MAX)); + assert_eq!(p.key().unwrap().as_deref(), Some("neg")); + let neg = p.number().unwrap().unwrap(); + assert_eq!((neg.as_u64(), neg.as_i64(), neg.as_f64()), (None, Some(-1), -1.0)); + assert_eq!(p.key().unwrap().as_deref(), Some("f")); + let f = p.number().unwrap().unwrap(); + assert_eq!( + (f, f.as_u64(), f.as_i64(), f.as_f64()), + (Number::Float(1.5), None, None, 1.5) + ); + assert_eq!(p.key().unwrap().as_deref(), Some("list")); + assert_eq!(p.array(), Ok(true)); + let mut kinds = Vec::new(); + while p.element().unwrap() { + kinds.push(p.peek().unwrap()); + p.skip().unwrap(); + } + assert_eq!( + kinds, + [ + Kind::Number, + Kind::Array, + Kind::Object, + Kind::Null, + Kind::Bool, + Kind::Bool + ] + ); + assert_eq!(p.key().unwrap().as_deref(), Some("o")); + assert_eq!(p.value().unwrap().to_string(), r#"{"k":"v"}"#); + assert_eq!(p.key().unwrap().as_deref(), Some("n")); + assert_eq!(p.null(), Ok(true)); + assert_eq!(p.key(), Ok(None)); + assert_eq!(p.end(), Ok(())); + assert_eq!(p.offset(), text.len()); + assert_eq!( + three_ways(text).unwrap(), + r#"{"name":"a/b","esc":"x\ny","size":18446744073709551615,"neg":-1,"f":1.5,"list":[1,[],{},null,true,false],"o":{"k":"v"},"n":null}"# + ); + // An array or an object that was not read to its end is not the + // end of the text. + let mut p = Parser::new("[1]"); + assert_eq!(p.array(), Ok(true)); + assert_eq!(p.element(), Ok(true)); + assert_eq!(p.skip(), Ok(())); + assert!(p.end().is_err()); + assert_eq!(p.element(), Ok(false)); + assert_eq!(p.end(), Ok(())); + } + + #[test] + fn parser_agrees_with_parse() { + for text in [ + "null", + " true ", + "false", + "0", + "-0", + "1e5", + "\"\"", + "\"a\\u00e9\\ud83d\\ude00\"", + "[]", + "[ ]", + "{}", + "{ }", + "[[[]],{\"a\":{\"a\":[{}]}}]", + "{\"a\":1,\"b\":{\"a\":1},\"c\":[{\"a\":1},{\"a\":2}]}", + ] { + assert!(three_ways(text).is_ok(), "{:?}", text); + } + // The errors, with where they are found. + for (text, offset, message) in [ + ("", 0, "unexpected end of input"), + (" ", 2, "unexpected end of input"), + ("x", 0, "unexpected character"), + ("tru", 0, "invalid literal"), + ("nul", 0, "invalid literal"), + ("-", 1, "invalid number"), + ("1.", 2, "invalid number"), + ("1e", 2, "invalid number"), + ("1e999", 5, "number out of range"), + ("01", 1, "trailing characters"), + ("\"abc", 4, "unterminated string"), + ("\"a\\", 3, "unterminated string"), + ("\"a\u{1}\"", 2, "control character in string"), + ("\"\\x\"", 3, "invalid escape"), + ("\"\\u12\"", 3, "truncated unicode escape"), + ("\"\\u12x4\"", 3, "invalid unicode escape"), + ("\"\\ud83d\"", 7, "unpaired surrogate"), + ("\"\\ud83d\\u0041\"", 13, "unpaired surrogate"), + ("\"\\ude00\"", 7, "unpaired surrogate"), + ("[1,]", 3, "unexpected character"), + ("[1 2]", 3, "expected ',' or ']'"), + ("[1", 2, "expected ',' or ']'"), + ("{\"a\":1,}", 7, "expected a string key"), + ("{a:1}", 1, "expected a string key"), + ("{\"a\" 1}", 5, "unexpected character"), + ("{\"a\":1 \"b\":2}", 7, "expected ',' or '}'"), + ("{\"a\":}", 5, "unexpected character"), + ("[1] x", 4, "trailing characters"), + ] { + let kind = ParseErrorKind::Syntax; + assert_eq!( + three_ways(text), + Err(ParseError { offset, message, kind }), + "{:?}", + text + ); + } + // A key twice in an object is an error of its own kind, found right + // behind the key. + for (text, offset) in [ + ("{\"a\":1,\"a\":2}", 10), + ("{\"a\":1,\"\\u0061\":[1, 2] ,\"b\":3}", 15), + ("{\"a\":1,\"b\":{\"c\":1,\"c\":2},\"d\":}", 21), + // The same key in another object is no duplicate. + ("{\"a\":{\"a\":1},\"b\":[{\"a\":1}],\"a\":2}", 30), + // What follows the key is not read. + ("{\"a\":1,\"a\":[}", 10), + ("{\"a\":1,\"a\" 2}", 10), + ] { + let e = ParseError { + offset, + message: "duplicate key", + kind: ParseErrorKind::DuplicateKey, + }; + assert_eq!(three_ways(text), Err(e), "{:?}", text); + } + } + + /// Reads `text` with the parser that is inside of an object, at the + /// value of its key `k`, by skipping over the value. + fn skipped(text: &str) -> Result<(), ParseError> { + let text = format!("{{\"k\":{}}}", text); + let mut p = Parser::new(&text); + assert_eq!(p.object(), Ok(true)); + assert_eq!(p.key().unwrap().as_deref(), Some("k")); + p.skip()?; + assert_eq!(p.key()?, None); + p.end() + } + + #[test] + fn skipping_holds_values_to_the_grammar() { + // Numbers of any size, which parse() and number() refuse or turn + // into floats. + let digits = "9".repeat(400); + for number in ["1e400", "-1e400", "1E+400", "1e-400", digits.as_str(), "-0.5e999999"] { + assert_eq!(skipped(number), Ok(()), "{}", number); + assert_eq!(skipped(&format!("[{0},{{\"x\":{0}}}]", number)), Ok(()), "{}", number); + } + // Nesting of any depth, which a skip that recursed would run out + // of stack for. + let deep = 100_000; + for (open, close) in [("[", "]"), ("{\"k\":", "}"), ("[{\"a\":[1],\"k\":", "}]")] { + let nested = format!("{}null{}", open.repeat(deep), close.repeat(deep)); + assert_eq!(skipped(&nested), Ok(()), "{}", open); + assert_eq!(parse(&nested).unwrap_err().message, "nesting too deep"); + } + // The grammar of what is skipped is checked all the same. + for (text, offset, message) in [ + ("1.", 7, "invalid number"), + ("-", 6, "invalid number"), + ("01", 6, "expected ',' or '}'"), + ("[1 2]", 8, "expected ',' or ']'"), + ("[1,]", 8, "unexpected character"), + ("{\"a\":1,}", 12, "expected a string key"), + ("{\"a\" 1}", 10, "unexpected character"), + ("[[[[", 9, "unexpected character"), + ("[[[]]", 10, "expected ',' or ']'"), + ("\"\\x\"", 8, "invalid escape"), + ("nul", 5, "invalid literal"), + ] { + let e = skipped(text).unwrap_err(); + assert_eq!((e.offset, e.message), (offset, message), "{}", text); + } + // A key twice in an object, at any depth, found right behind the + // key. + let repeated = format!("{}{{\"a\":1,\"a\":2}}{}", "[".repeat(deep), "]".repeat(deep)); + let e = skipped(&repeated).unwrap_err(); + assert_eq!( + (e.kind, e.offset), + ( + ParseErrorKind::DuplicateKey, + "{\"k\":".len() + deep + "{\"a\":1,\"a\"".len() + ) + ); + let e = skipped("{\"a\":{\"b\":1},\"a\":[{\"a\":1}]}").unwrap_err(); + assert_eq!((e.kind, e.offset), (ParseErrorKind::DuplicateKey, 21)); + assert_eq!(skipped("{\"a\":{\"a\":{\"a\":1}},\"b\":[{\"a\":1},{\"a\":1}]}"), Ok(())); + } + + #[test] + fn parser_limits_nesting() { + // A value has at most MAX_DEPTH arrays and objects around it. + for (open, close) in [("[", "]"), ("{\"k\":", "}")] { + let nested = |n: usize, inner: &str| format!("{}{}{}", open.repeat(n), inner, close.repeat(n)); + assert!(three_ways(&nested(MAX_DEPTH, "1")).is_ok()); + assert!(three_ways(&nested(MAX_DEPTH, "[]")).is_ok()); + assert!(three_ways(&nested(MAX_DEPTH, "{}")).is_ok()); + for inner in ["1", "[]", "{}"] { + let e = three_ways(&nested(MAX_DEPTH + 1, inner)).unwrap_err(); + assert_eq!(e.message, "nesting too deep", "{}", inner); + assert_eq!(e.offset, open.len() * (MAX_DEPTH + 1)); + } + } + } + + /// How many members the objects of the tests below have at most. + const MANY_MEMBERS: usize = 100; + + #[test] + fn parser_finds_duplicates_in_large_and_nested_objects() { + // Every object has its own keys, also inside another one. + let members = |prefix: &str, n: usize| -> String { + (0..n) + .map(|i| format!("\"{}{}\":{}", prefix, i, i)) + .collect::>() + .join(",") + }; + for outer in [0, 1, 2, MANY_MEMBERS] { + for inner in [1, 2, MANY_MEMBERS] { + let comma = if outer > 0 { "," } else { "" }; + let unique = format!( + "{{{}{}\"in\":{{{}}},\"last\":[{{{}}}]}}", + members("o", outer), + comma, + members("i", inner), + members("i", inner) + ); + let value = three_ways(&unique).unwrap(); + assert_eq!(parse(&value).unwrap().as_object().unwrap().len(), outer + 2); + for at in [0, inner / 2, inner - 1] { + let repeated = format!( + "{{{}{}\"in\":{{{},\"i{}\":0}}}}", + members("o", outer), + comma, + members("i", inner), + at + ); + assert_eq!(three_ways(&repeated).unwrap_err().message, "duplicate key"); + } + if outer > 0 { + // The outer object still knows its keys after the inner one. + let repeated = format!( + "{{{},\"in\":{{{}}},\"o{}\":0}}", + members("o", outer), + members("i", inner), + outer - 1 + ); + assert_eq!(three_ways(&repeated).unwrap_err().message, "duplicate key"); + } + } + } + } + + #[test] + fn parser_starts_every_object_without_keys() { + // An object starts without the keys of the objects that were as + // deep before it, also behind a large one, and still finds a key + // twice. + let large = (0..MANY_MEMBERS) + .map(|i| format!("\"k{}\":{}", i, i)) + .collect::>() + .join(","); + for (text, duplicate) in [ + (format!("[{{{0}}},{{{0}}},{{\"k1\":1}},{{}}]", large), None), + ( + format!("[{{{0}}},{{\"k1\":1,\"k1\":2}}]", large), + Some("{\"k1\":1,\"k1\""), + ), + ( + format!("{{\"a\":{{\"b\":{{{0}}}}},\"b\":{{{0}}},\"c\":[[{{{0}}}]]}}", large), + None, + ), + ( + format!("{{\"a\":{{\"b\":{{{0}}}}},\"b\":{{\"c\":1,\"c\":2}}}}", large), + Some("{\"c\":1,\"c\""), + ), + ] { + let result = three_ways(&text).map(drop); + let e = duplicate.map(|key| ParseError { + offset: text.find(key).unwrap() + key.len(), + message: "duplicate key", + kind: ParseErrorKind::DuplicateKey, + }); + assert_eq!(result, e.map_or(Ok(()), Err), "{}", text); + } + // So does every value that is skipped. + let text = format!("{{\"a\":{{{0}}},\"b\":[{{{0}}}],\"c\":{{\"k1\":1,\"k1\":2}}}}", large); + let mut p = Parser::new(&text); + assert_eq!(p.object(), Ok(true)); + for key in ["a", "b"] { + assert_eq!(p.key().unwrap().as_deref(), Some(key)); + assert_eq!(p.skip(), Ok(())); + } + assert_eq!(p.key().unwrap().as_deref(), Some("c")); + let e = p.skip().unwrap_err(); + assert_eq!( + (e.kind, e.offset), + (ParseErrorKind::DuplicateKey, text.len() - ":2}}".len()) + ); + } + + #[test] + fn parser_knows_keys_written_with_an_escape() { + // A key with an escape is the key it stands for. + for text in [ + r#"{"a":1,"\u0061":2}"#, + r#"{"\u0061":1,"a":2}"#, + r#"{"\u0061":1,"\u0061":2}"#, + r#"{"a\n":1,"b":2,"a\u000a":3}"#, + r#"{"x":{"a":1,"b":2,"\u0061":3}}"#, + r#"{"\u0061":1,"x":{"b":1},"a":2}"#, + r#"{"a":1,"x":{"b":1,"c":{}},"\u0061":2}"#, + ] { + assert_eq!(three_ways(text).unwrap_err().message, "duplicate key", "{}", text); + } + for text in [ + r#"{"a":1,"b":2}"#, + r#"{"a":1,"b":2,"c":3}"#, + r#"{"a":{"a":{"a":1}},"b":{"a":1,"b":2},"c":[{"a":1,"b":2}]}"#, + ] { + assert!(three_ways(text).is_ok(), "{}", text); + } + // With few and with many keys around it. + for around in [0, 1, 2, MANY_MEMBERS] { + let keys: Vec = (0..around).map(|i| format!("\"k{}\":{}", i, i)).collect(); + for at in [0, around / 2, around] { + let mut members = keys.clone(); + members.insert(at, r#""k":0"#.to_string()); + assert!(three_ways(&format!("{{{}}}", members.join(","))).is_ok()); + for repeated in [r#""k":1"#, r#""\u006b":1"#] { + for again in [0, members.len() / 2, members.len()] { + let mut members = members.clone(); + members.insert(again, repeated.to_string()); + let text = format!("{{{}}}", members.join(",")); + assert_eq!(three_ways(&text).unwrap_err().message, "duplicate key", "{}", text); + } + } + } + } + } + + #[test] + fn parser_finds_the_end_of_a_string() { + // What a string can hold, some of it one bit away from what ends + // it: 0xa2 and 0xdc are a quote and a backslash with the high bit + // set, and 0x9f is a control character with it. + let fillers = [ + "a", + " ", + "!", + "#", + "[", + "]", + "\x7f", + "\u{e9}", + "\u{a2}", + "\u{9f}", + "\u{70c}", + "\u{20ac}", + "\u{1f600}", + ]; + for filler in fillers { + for before in 0..(3 * Word::SIZE + 2) { + let unescaped = filler.repeat(before); + for behind in ["", "x", "tail of the text"] { + // The string ends at its quote, whatever follows. + let text = format!("[\"{}\",\"{}\"]", unescaped, behind); + let expected = Value::Array(vec![Value::from(unescaped.as_str()), Value::from(behind)]); + assert_eq!(three_ways(&text), Ok(expected.to_string()), "{:?}", text); + let mut p = Parser::new(&text); + assert_eq!(p.array(), Ok(true)); + assert_eq!(p.element(), Ok(true)); + assert!(matches!(p.string(), Ok(Some(Cow::Borrowed(s))) if s == unescaped)); + // An escape, anywhere. + let text = format!("\"{}\\n{}\\\"{}\\\\\"", unescaped, behind, unescaped); + let expected = format!("{}\n{}\"{}\\", unescaped, behind, unescaped); + assert_eq!( + three_ways(&text), + Ok(Value::from(expected.as_str()).to_string()), + "{:?}", + text + ); + // A control character, anywhere. + for control in ["\0", "\x01", "\n", "\x1f"] { + let text = format!("\"{}{}{}\"", unescaped, control, behind); + let e = ParseError { + offset: 1 + unescaped.len(), + message: "control character in string", + kind: ParseErrorKind::Syntax, + }; + assert_eq!(three_ways(&text), Err(e), "{:?}", text); + } + // No end at all. + let text = format!("\"{}{}", unescaped, behind); + let e = ParseError { + offset: text.len(), + message: "unterminated string", + kind: ParseErrorKind::Syntax, + }; + assert_eq!(three_ways(&text), Err(e), "{:?}", text); + } + } + } + // Every byte a word can have in every place of it. + for byte in 0..=u8::MAX { + for at in 0..Word::SIZE { + let mut bytes = [b'a'; Word::SIZE]; + bytes[at] = byte; + let special = byte == QUOTE || byte == ESCAPE || byte < FIRST_PRINTABLE; + assert_eq!( + Word::new(bytes).first_special(), + special.then_some(at), + "{:#x} at {}", + byte, + at + ); + // The first of two is the one that is found. + for second in [QUOTE, ESCAPE, 0, FIRST_PRINTABLE - 1, FIRST_PRINTABLE, 0x80, u8::MAX] { + for behind in at + 1..Word::SIZE { + let mut bytes = bytes; + bytes[behind] = second; + let first = if special { + Some(at) + } else { + (second == QUOTE || second == ESCAPE || second < FIRST_PRINTABLE).then_some(behind) + }; + assert_eq!(Word::new(bytes).first_special(), first); + } + } + } + } + } + + #[test] + fn parser_reads_numbers_of_any_length() { + let mut texts: Vec = Vec::new(); + for digits in 1..=45 { + texts.push("9".repeat(digits)); + texts.push(format!("1{}", "0".repeat(digits - 1))); + texts.push(format!("1{}7", "0".repeat(digits - 1))); + } + for near in [u128::from(u64::MAX), i128::MAX as u128, i128::MAX as u128 + 1] { + for value in [near - 1, near, near + 1, near + 2] { + texts.push(value.to_string()); + } + } + for text in texts { + for text in [text.clone(), format!("-{}", text)] { + // An integer that fits into 128 bits is exact. A larger one + // is the nearest float. + let expected = match text.parse::() { + Ok(i) => Value::Int(i), + Err(_) => Value::Float(text.parse().unwrap()), + }; + assert_eq!(parse(&text), Ok(expected.clone()), "{}", text); + assert_eq!(three_ways(&text), Ok(expected.to_string()), "{}", text); + let mut p = Parser::new(&text); + let number = p.number().unwrap().unwrap(); + assert_eq!(number.as_u64(), text.parse::().ok(), "{}", text); + assert_eq!(number.as_i64(), text.parse::().ok(), "{}", text); + // With a fraction or an exponent it is a float. + for float in [format!("{}.0", text), format!("{}e0", text), format!("{}.5E+1", text)] { + let expected = Value::Float(float.parse().unwrap()); + assert_eq!(parse(&float), Ok(expected), "{}", float); + assert!(three_ways(&float).is_ok(), "{}", float); + } + } + } + } } From 798eb7a37652e9cbec662c653d13282b447e10a4 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 02/19] json: add writers for objects and arrays Currently the only way to write JSON is to build a Value and print it. That's what the manifest writers in the fat crate do for every record: put each field into an Object with a String for its key, sort the Object and format it into a fresh String. That's a lot of allocations for a single line of text. Add ObjectWriter and ArrayWriter. They append an object or an array to a String member by member and close it when they are dropped. ObjectWriter::key() and ArrayWriter::element() hand out a ValueWriter which writes the value: null, a boolean, an unsigned integer, a string, anything that implements Display, or another object or array. The caller keeps the keys of an object unique and writes them in the order it wants. key() and element() don't write anything themselves. The ValueWriter they hand out carries the key and a reference to the flag of the object or array that says whether a comma is needed. Every value method writes the comma, the key and the colon together with the value. So a member exists exactly when its value was written, the text is always valid JSON, and this is a correct way to write an optional member: let v = object.key("k"); if let Some(s) = maybe { v.string(s); } If key() wrote the key right away, a ValueWriter that is dropped without a value would leave {"k":} or [1,] behind. #[must_use] doesn't catch that once the ValueWriter is bound to a variable and only used on one branch, like above. Note that the key has to live as long as the ValueWriter. So a ValueWriter kept in a variable can't take a temporary as its key. While at it, let the printer of a Value and the writers share the code that escapes strings. escape() looks for the bytes that need an escape eight bytes at a time, the same way the parser looks for the end of a string, and copies everything in between in one go. Value and Object print themselves in their Display implementations now instead of going through write_value() and write_object(). Note that floats are printed with Debug now. It writes the shortest text that reads back as the same float, and always one that reads back as a float. Currently a whole number is printed with Display and ".0" appended, and anything else with Display alone. That writes 1e21 as 22 digits and ".0", and 5e-324 as 326 bytes. Debug writes "1e21" and "5e-324". Both forms read back with the same bits, and nothing outside of this crate prints floats. Signed-off-by: Christian Brauner (Amutable) --- src/json/lib.rs | 431 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 368 insertions(+), 63 deletions(-) diff --git a/src/json/lib.rs b/src/json/lib.rs index 1096e4d..717f4c0 100644 --- a/src/json/lib.rs +++ b/src/json/lib.rs @@ -3,8 +3,9 @@ //! a compact serializer. //! //! [`parse`] reads a text into a [`Value`], and a `Value` prints itself as -//! compact text. [`Parser`] reads a text value by value, for a caller that -//! has types of its own and does not want a `Value` in between. +//! compact text. [`Parser`] reads a text value by value, and +//! [`ObjectWriter`] and [`ArrayWriter`] write one member by member, for a +//! caller that has types of its own and does not want a `Value` in between. //! //! Numbers keep their nature: anything written without a fraction or an //! exponent that fits into 128 bits stays an integer, so 64-bit sizes and @@ -17,7 +18,7 @@ use std::borrow::Cow; use std::collections::HashSet; -use std::fmt; +use std::fmt::{self, Write as _}; use std::str::FromStr; /// A JSON value. @@ -1157,83 +1158,248 @@ pub fn parse(text: &str) -> Result { Ok(value) } -/// Writes `s` as a JSON string. The runs between escapes go out as they -/// are. -fn write_string(out: &mut W, s: &str) -> fmt::Result { - out.write_char('"')?; - let mut plain = 0; - for (i, c) in s.char_indices() { - let escape = match c { - '"' => Some("\\\""), - '\\' => Some("\\\\"), - '\n' => Some("\\n"), - '\r' => Some("\\r"), - '\t' => Some("\\t"), - '\u{08}' => Some("\\b"), - '\u{0c}' => Some("\\f"), - c if u32::from(c) < 0x20 => None, - _ => continue, +/// Writes the inside of the JSON string for `s`: the runs between escapes +/// as they are, and an escape for every character that needs one. +fn escape(out: &mut W, s: &str) -> fmt::Result { + let bytes = s.as_bytes(); + // Where the current unescaped run starts. + let mut unescaped = 0; + loop { + let at = unescaped + Word::unescaped_len(&bytes[unescaped..]); + let Some(&b) = bytes.get(at) else { + return out.write_str(&s[unescaped..]); }; - out.write_str(&s[plain..i])?; - match escape { - Some(escape) => out.write_str(escape)?, - None => write!(out, "\\u{:04x}", u32::from(c))?, - } - plain = i + c.len_utf8(); + out.write_str(&s[unescaped..at])?; + match b { + QUOTE => out.write_str("\\\"")?, + ESCAPE => out.write_str("\\\\")?, + b'\n' => out.write_str("\\n")?, + b'\r' => out.write_str("\\r")?, + b'\t' => out.write_str("\\t")?, + BACKSPACE => out.write_str("\\b")?, + FORM_FEED => out.write_str("\\f")?, + _ => write!(out, "{}{:0digits$x}", UNICODE_ESCAPE, b, digits = UNICODE_ESCAPE_DIGITS)?, + } + unescaped = at + 1; } - out.write_str(&s[plain..])?; +} + +/// Writes `s` as a JSON string. +fn write_string(out: &mut W, s: &str) -> fmt::Result { + out.write_char('"')?; + escape(out, s)?; out.write_char('"') } -fn write_value(out: &mut W, v: &Value) -> fmt::Result { - match v { - Value::Null => out.write_str("null"), - Value::Bool(b) => out.write_str(if *b { "true" } else { "false" }), - Value::Int(i) => write!(out, "{}", i), - // A float that is a whole number keeps a fraction, so that it reads - // back as a float. - Value::Float(f) if f.is_finite() && f.fract() == 0.0 => write!(out, "{}.0", f), - Value::Float(f) if f.is_finite() => write!(out, "{}", f), - Value::Float(_) => out.write_str("null"), - Value::String(s) => write_string(out, s), - Value::Array(a) => { - out.write_char('[')?; - for (i, item) in a.iter().enumerate() { - if i > 0 { - out.write_char(',')?; +/// Appends `s` to `out` as a JSON string. +fn push_string(out: &mut String, s: &str) { + write_string(out, s).expect("a String takes any write"); +} + +impl fmt::Display for Value { + /// Compact serialization without any whitespace. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Value::Null => f.write_str("null"), + Value::Bool(b) => f.write_str(if *b { "true" } else { "false" }), + Value::Int(i) => write!(f, "{}", i), + // Debug writes the shortest text that reads back as the same + // float, and always one that reads back as a float. + Value::Float(x) if x.is_finite() => write!(f, "{:?}", x), + Value::Float(_) => f.write_str("null"), + Value::String(s) => write_string(f, s), + Value::Array(a) => { + f.write_char('[')?; + for (i, item) in a.iter().enumerate() { + if i > 0 { + f.write_char(',')?; + } + item.fmt(f)?; } - write_value(out, item)?; + f.write_char(']') } - out.write_char(']') + Value::Object(o) => o.fmt(f), } - Value::Object(o) => write_object(out, o), } } -fn write_object(out: &mut W, o: &Object) -> fmt::Result { - out.write_char('{')?; - for (i, (k, item)) in o.iter().enumerate() { - if i > 0 { - out.write_char(',')?; +impl fmt::Display for Object { + /// Compact serialization without any whitespace. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('{')?; + for (i, (k, item)) in self.iter().enumerate() { + if i > 0 { + f.write_char(',')?; + } + write_string(f, k)?; + f.write_char(':')?; + item.fmt(f)?; } - write_string(out, k)?; - out.write_char(':')?; - write_value(out, item)?; + f.write_char('}') } - out.write_char('}') } -impl fmt::Display for Value { - /// Compact serialization without any whitespace. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write_value(f, self) +/// Writes a JSON object into a string member by member, without a +/// [`Value`] in between. The object is closed when the writer is dropped. +/// +/// A member is written together with its value, so a member whose value +/// is never written is left out: +/// +/// ``` +/// let mut text = String::new(); +/// let mut object = json::ObjectWriter::new(&mut text); +/// object.key("name").string("a\"b"); +/// object.key("sizes").array().element().unsigned(3); +/// let label: Option<&str> = None; +/// let value = object.key("label"); +/// if let Some(label) = label { +/// value.string(label); +/// } +/// drop(object); +/// assert_eq!(text, r#"{"name":"a\"b","sizes":[3]}"#); +/// ``` +#[derive(Debug)] +pub struct ObjectWriter<'a> { + out: &'a mut String, + /// Whether a member was written, so the next one needs a comma. + members: bool, +} + +impl<'a> ObjectWriter<'a> { + /// Opens an object at the end of `out`. + pub fn new(out: &'a mut String) -> ObjectWriter<'a> { + out.push('{'); + ObjectWriter { out, members: false } + } + + /// Starts the member `key`. What is returned writes the member when it + /// writes the value, and nothing if it is dropped without one. The + /// caller keeps the keys of an object distinct. + pub fn key<'k>(&'k mut self, key: &'k str) -> ValueWriter<'k> { + ValueWriter { + out: self.out, + key: Some(key), + follows: &mut self.members, + } } } -impl fmt::Display for Object { - /// Compact serialization without any whitespace. - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write_object(f, self) +impl Drop for ObjectWriter<'_> { + fn drop(&mut self) { + self.out.push('}'); + } +} + +/// Writes a JSON array into a string element by element, without a +/// [`Value`] in between. The array is closed when the writer is dropped. +#[derive(Debug)] +pub struct ArrayWriter<'a> { + out: &'a mut String, + /// Whether an element was written, so the next one needs a comma. + elements: bool, +} + +impl<'a> ArrayWriter<'a> { + /// Opens an array at the end of `out`. + pub fn new(out: &'a mut String) -> ArrayWriter<'a> { + out.push('['); + ArrayWriter { out, elements: false } + } + + /// Starts an element. What is returned writes the element when it + /// writes the value, and nothing if it is dropped without one. + pub fn element(&mut self) -> ValueWriter<'_> { + ValueWriter { + out: self.out, + key: None, + follows: &mut self.elements, + } + } +} + +impl Drop for ArrayWriter<'_> { + fn drop(&mut self) { + self.out.push(']'); + } +} + +/// The place of one value in the text an [`ObjectWriter`] or an +/// [`ArrayWriter`] writes. Every method writes the value, and with it the +/// comma in front of it and the key of a member. A `ValueWriter` that is +/// dropped without a value writes nothing. +#[derive(Debug)] +#[must_use = "a member or an element is only written with its value"] +pub struct ValueWriter<'a> { + out: &'a mut String, + /// The key of a member, none for an element. + key: Option<&'a str>, + /// Whether the object or the array has a value already, so this one + /// needs a comma in front. Set when this one is written. + follows: &'a mut bool, +} + +impl<'a> ValueWriter<'a> { + /// Writes what goes in front of the value: the comma after the value + /// before it and the key of a member. Returns where the value goes. + fn begin(self) -> &'a mut String { + if *self.follows { + self.out.push(','); + } + *self.follows = true; + if let Some(key) = self.key { + push_string(self.out, key); + self.out.push(':'); + } + self.out + } + + /// Writes `null`. + pub fn null(self) { + self.begin().push_str("null"); + } + + /// Writes `true` or `false`. + pub fn bool(self, value: bool) { + self.begin().push_str(if value { "true" } else { "false" }); + } + + /// Writes an integer. + pub fn unsigned(self, value: u64) { + write!(self.begin(), "{}", value).expect("a String takes any write"); + } + + /// Writes a string. + pub fn string(self, value: &str) { + push_string(self.begin(), value); + } + + /// Writes what `value` prints as a string. + pub fn display(self, value: impl fmt::Display) { + /// Escapes what is written to it. + struct Escaper<'a>(&'a mut String); + + impl fmt::Write for Escaper<'_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + escape(self.0, s) + } + } + + let out = self.begin(); + out.push('"'); + write!(Escaper(out), "{}", value).expect("a Display implementation returned an error"); + out.push('"'); + } + + /// Opens an object as the value. The member or the element is written + /// with it, even if the object stays empty. + pub fn object(self) -> ObjectWriter<'a> { + ObjectWriter::new(self.begin()) + } + + /// Opens an array as the value. The member or the element is written + /// with it, even if the array stays empty. + pub fn array(self) -> ArrayWriter<'a> { + ArrayWriter::new(self.begin()) } } @@ -1263,7 +1429,10 @@ mod tests { (1.0, "1.0"), (-0.0, "-0.0"), (1.5, "1.5"), - (1e21, "1000000000000000000000.0"), + (1e15, "1000000000000000.0"), + (1e21, "1e21"), + (-2.5e-8, "-2.5e-8"), + (5e-324, "5e-324"), (f64::NAN, "null"), (f64::INFINITY, "null"), ] { @@ -1401,6 +1570,51 @@ mod tests { let v = Value::from("a\"b\\c\n\t\u{01}é"); assert_eq!(v.to_string(), "\"a\\\"b\\\\c\\n\\t\\u0001é\""); assert_eq!(parse(&v.to_string()).unwrap(), v); + // Every control character has an escape, the ones with a letter + // of their own use it. + let all: String = (0u8..0x20).map(char::from).collect(); + let text = Value::from(all.as_str()).to_string(); + assert!(text.starts_with("\"\\u0000\\u0001") && text.contains("\\b\\t\\n\\u000b\\f\\r\\u000e")); + assert!(text.ends_with("\\u001f\""), "{}", text); + assert_eq!(parse(&text).unwrap().as_str(), Some(all.as_str())); + // What needs an escape gets it wherever it is in the string, and + // nothing else does. + let escape_of = |c: char| match c { + '"' => "\\\"".to_string(), + '\\' => "\\\\".to_string(), + '\n' => "\\n".to_string(), + '\u{1}' => "\\u0001".to_string(), + c => c.to_string(), + }; + for filler in [ + "a", + " ", + "!", + "#", + "[", + "]", + "\x7f", + "\u{e9}", + "\u{a2}", + "\u{9f}", + "\u{70c}", + "\u{1f600}", + ] { + for before in 0..(2 * Word::SIZE + 2) { + for special in ['"', '\\', '\n', '\u{1}', 'x'] { + for behind in ["", "y", "the rest of the string"] { + let string = format!("{}{}{}{}", filler.repeat(before), special, behind, special); + let escaped: String = string.chars().map(escape_of).collect(); + let text = Value::from(string.as_str()).to_string(); + assert_eq!(text, format!("\"{}\"", escaped), "{:?}", string); + assert_eq!(parse(&text).unwrap().as_str(), Some(string.as_str())); + let mut written = String::new(); + ObjectWriter::new(&mut written).key(&string).display(&string); + assert_eq!(written, format!("{{\"{}\":\"{}\"}}", escaped, escaped), "{:?}", string); + } + } + } + } } /// Reads `text` with the methods named after the kinds and writes what @@ -1963,4 +2177,95 @@ mod tests { } } } + + #[test] + fn writers() { + let mut text = String::new(); + { + let mut object = ObjectWriter::new(&mut text); + object.key("s").string("a\"b\\c\n\u{1}é"); + object.key("key \"quoted\"").null(); + object.key("t").bool(true); + object.key("f").bool(false); + object.key("zero").unsigned(0); + object.key("ten").unsigned(10); + object.key("max").unsigned(u64::MAX); + object.key("shown").display(format_args!("{}:{:?}", 5, "x\ty")); + object.key("empty object").object(); + object.key("empty array").array(); + let mut array = object.key("array").array(); + array.element().unsigned(1); + array.element().string("two"); + array.element().array().element().null(); + let mut inner = array.element().object(); + inner.key("k").unsigned(3); + drop(inner); + drop(array); + object.key("last").string(""); + } + assert_eq!( + text, + concat!( + r#"{"s":"a\"b\\c\n\u0001é","key \"quoted\"":null,"t":true,"f":false,"zero":0,"ten":10,"#, + r#""max":18446744073709551615,"shown":"5:\"x\\ty\"","empty object":{},"empty array":[],"#, + r#""array":[1,"two",[null],{"k":3}],"last":""}"# + ) + ); + // What the writers write is what the value prints. + let value = parse(&text).unwrap(); + assert_eq!(value.to_string(), text); + assert_eq!(value.get("s").unwrap().as_str(), Some("a\"b\\c\n\u{1}é")); + assert_eq!(value.get("shown").unwrap().as_str(), Some("5:\"x\\ty\"")); + assert_eq!(value.get("max").unwrap().as_u64(), Some(u64::MAX)); + // A writer appends to what the string holds. + let mut text = String::from("\u{1e}"); + ArrayWriter::new(&mut text).element().unsigned(7); + text.push('\n'); + assert_eq!(text, "\u{1e}[7]\n"); + } + + #[test] + fn dropped_value_writers_write_nothing() { + // A member or an element whose value is never written is left + // out, in the first, a middle and the last place. + let values = [("a", 1), ("b", 2), ("c", 3)]; + for (left_out, object_text, array_text) in [ + (0, r#"{"b":2,"c":3}"#, "[2,3]"), + (1, r#"{"a":1,"c":3}"#, "[1,3]"), + (2, r#"{"a":1,"b":2}"#, "[1,2]"), + ] { + let mut object_written = String::new(); + let mut array_written = String::new(); + { + let mut object = ObjectWriter::new(&mut object_written); + let mut array = ArrayWriter::new(&mut array_written); + for (place, (key, value)) in values.into_iter().enumerate() { + let member = object.key(key); + let element = array.element(); + if place != left_out { + member.unsigned(value); + element.unsigned(value); + } + } + } + assert_eq!(object_written, object_text); + assert_eq!(array_written, array_text); + } + // Nor does a writer dropped with let _ write anything, nor the + // only one of an object or an array. + let mut text = String::new(); + { + let mut object = ObjectWriter::new(&mut text); + let _ = object.key("a"); + let mut inner = object.key("b").object(); + let _ = inner.key("c"); + drop(inner); + let mut inner = object.key("d").array(); + let _ = inner.element(); + drop(inner); + let _ = object.key("e"); + } + assert_eq!(text, r#"{"b":{},"d":[]}"#); + assert_eq!(parse(&text).unwrap().to_string(), text); + } } From e5e23d339dc3d61462f32be80045f5de402e1f9f Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 03/19] json: let callers refuse noncharacters and NUL in strings JSON lets a string hold any Unicode scalar value. Formats built on JSON often allow less, and UAPI.16 manifests are one of them. The specification says that strings must not contain noncharacters or NUL, that this applies to a string after its escapes have been decoded, and that a consumer has to refuse a manifest with such a string instead of repairing it. Add StringRules with NO_NONCHARACTERS and NO_NUL. A parser made with Parser::with_rules() refuses every string that breaks one of them, keys included, whether the character is written as it is or as an escape. The error is reported right behind the string and is of the new kind ParseErrorKind::StringRule. StringRules::admits() checks a string the same way, for code that writes JSON and has to know whether a string can go out as it is. This has to happen in the parser. A reader passes over the fields it doesn't know but the rules apply to their strings too, and the parser is the only place that sees every string. Most strings are plain ASCII, so let's keep the check cheap for them. A string without an escape can't hold a NUL since JSON wants every control character in a string escaped. And every noncharacter starts with the byte 0xef or a higher one in UTF-8, while no continuation byte is that high. So only a string with such a byte is walked character by character. Whether it has one is found with is_ascii() and a fold the compiler turns into vector instructions. Signed-off-by: Christian Brauner (Amutable) --- src/json/lib.rs | 340 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 339 insertions(+), 1 deletion(-) diff --git a/src/json/lib.rs b/src/json/lib.rs index 717f4c0..ff97f3f 100644 --- a/src/json/lib.rs +++ b/src/json/lib.rs @@ -300,7 +300,8 @@ pub struct ParseError { pub offset: usize, /// What went wrong. pub message: &'static str, - /// Whether the text is not JSON or has a key twice in an object. + /// Whether the text is not JSON, has a key twice in an object, or + /// breaks a rule of the parser. pub kind: ParseErrorKind, } @@ -312,6 +313,8 @@ pub enum ParseErrorKind { /// An object has a key twice. RFC 8259 leaves open what such an object /// means, and the parser refuses it. DuplicateKey, + /// A string breaks one of the [`StringRules`] the parser was made with. + StringRule, } impl fmt::Display for ParseError { @@ -490,6 +493,116 @@ impl From for Value { } } +/// What the strings of a text may not hold beyond what JSON forbids. +/// +/// JSON lets a string hold any Unicode scalar value. Formats built on JSON +/// often rule out more, and a [`Parser`] made with +/// [`Parser::with_rules`] refuses those strings, keys included, however +/// they are written: as they are or with escapes. +/// +/// ``` +/// use json::{Parser, StringRules}; +/// +/// let mut parser = Parser::with_rules(r#""a\u0000b""#, StringRules::NO_NUL); +/// assert_eq!(parser.string().unwrap_err().message, "NUL in string"); +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct StringRules(u8); + +impl StringRules { + /// No noncharacter, as I-JSON (RFC 7493) asks: U+FDD0 to U+FDEF and + /// the last two code points of every plane, U+FFFE and U+FFFF, U+1FFFE + /// and U+1FFFF and so on. + pub const NO_NONCHARACTERS: StringRules = StringRules(1 << 0); + /// No NUL character, which JSON only lets a string have as `\u0000`. + pub const NO_NUL: StringRules = StringRules(1 << 1); + /// No rule beyond those of JSON. + pub const NONE: StringRules = StringRules(0); + + /// Whether every rule of `rules` is among these. + pub const fn contains(self, rules: StringRules) -> bool { + self.0 & rules.0 == rules.0 + } + + /// These rules and those of `rules`. + pub const fn union(self, rules: StringRules) -> StringRules { + StringRules(self.0 | rules.0) + } + + /// These rules but those of `rules`. + pub const fn without(self, rules: StringRules) -> StringRules { + StringRules(self.0 & !rules.0) + } + + /// Whether the string `s` keeps to these rules. + pub fn admits(self, s: &str) -> bool { + self.broken_in(s).is_none() + } + + /// Which of these rules the string `s` breaks first, if one. + fn broken_in(self, s: &str) -> Option<&'static str> { + if self == StringRules::NONE { + return None; + } + // A string without a byte as high as NONCHARACTER_LEAD has no + // noncharacter, so only a NUL can break a rule. Such bytes are + // looked for many at a time: by is_ascii, the cheapest look for + // ASCII strings, which most are, and by a fold without an early + // end, which the compiler turns into vector instructions. A look at + // every character takes about fifteen instructions for each. + let lead = !s.is_ascii() && s.bytes().fold(false, |lead, b| lead | (b >= NONCHARACTER_LEAD)); + if lead { + s.chars().find_map(|c| self.broken_by(c)) + } else { + (self.contains(StringRules::NO_NUL) && s.contains(NUL)).then_some(NUL_IN_STRING) + } + } + + /// Whether a string holding `c` breaks one of these rules, and which. + fn broken_by(self, c: char) -> Option<&'static str> { + if c == NUL && self.contains(StringRules::NO_NUL) { + Some(NUL_IN_STRING) + } else if self.contains(StringRules::NO_NONCHARACTERS) && is_noncharacter(c) { + Some("noncharacter in string") + } else { + None + } + } +} + +/// The character [`StringRules::NO_NUL`] rules out, and what a string that +/// holds it is told. +const NUL: char = '\0'; +const NUL_IN_STRING: &str = "NUL in string"; + +impl std::ops::BitOr for StringRules { + type Output = StringRules; + + fn bitor(self, rules: StringRules) -> StringRules { + self.union(rules) + } +} + +/// The noncharacters that are not at the end of a plane. +const NONCHARACTER_BLOCK: std::ops::RangeInclusive = 0xFDD0..=0xFDEF; +/// The bits that are set in the last two code points of every plane, and +/// only in them. +const PLANE_END: u32 = 0xFFFE; +/// The first byte of the lowest noncharacter in UTF-8. Higher characters +/// start with the same byte or a higher one, and no byte after the first +/// one of a character is as high, so a string without it has none. +const NONCHARACTER_LEAD: u8 = match char::from_u32(*NONCHARACTER_BLOCK.start()) { + Some(lowest) => lowest.encode_utf8(&mut [0; 4]).as_bytes()[0], + None => panic!("the lowest noncharacter is a character"), +}; + +/// Whether `c` is a noncharacter, a code point Unicode keeps for use +/// inside a program. +fn is_noncharacter(c: char) -> bool { + let code = u32::from(c); + NONCHARACTER_BLOCK.contains(&code) || code & PLANE_END == PLANE_END +} + /// An array or an object the parser is inside of. #[derive(Clone, Copy, PartialEq, Eq)] enum Container { @@ -640,11 +753,19 @@ pub struct Parser<'a> { keys: Keys<'a>, /// What [`Parser::skip`] keeps of the value it reads. skipped: SkippedValue<'a>, + /// What strings may not hold beyond what JSON forbids. + rules: StringRules, } impl<'a> Parser<'a> { /// A parser in front of the value `text` holds. pub fn new(text: &'a str) -> Parser<'a> { + Parser::with_rules(text, StringRules::NONE) + } + + /// A parser in front of the value `text` holds that refuses strings + /// which break `rules`. + pub fn with_rules(text: &'a str, rules: StringRules) -> Parser<'a> { Parser { text, pos: 0, @@ -653,6 +774,7 @@ impl<'a> Parser<'a> { empty: false, keys: Keys::default(), skipped: SkippedValue::default(), + rules, } } @@ -854,6 +976,9 @@ impl<'a> Parser<'a> { if self.byte() == Some(QUOTE) { let unescaped = &self.text[start..self.pos]; self.pos += 1; + // The unescaped run ends at every control character, so only an + // escape can put a NUL into a string. + self.check_rules(unescaped, self.rules.without(StringRules::NO_NUL))?; return Ok(Cow::Borrowed(unescaped)); } let mut out = String::from(&self.text[start..self.pos]); @@ -901,9 +1026,21 @@ impl<'a> Parser<'a> { self.skip_unescaped(); out.push_str(&self.text[start..self.pos]); } + self.check_rules(&out, self.rules)?; Ok(Cow::Owned(out)) } + /// Fails if the string `s` breaks one of `rules`, rules of the parser. + fn check_rules(&self, s: &str, rules: StringRules) -> Result<(), ParseError> { + match rules.broken_in(s) { + Some(message) => Err(ParseError { + kind: ParseErrorKind::StringRule, + ..self.error(message) + }), + None => Ok(()), + } + } + /// Reads the value if it is a string. A string without an escape is /// returned as the part of the text it is. pub fn string(&mut self) -> Result>, ParseError> { @@ -1913,6 +2050,207 @@ mod tests { } } + #[test] + fn parser_applies_string_rules() { + let strict = StringRules::NO_NONCHARACTERS | StringRules::NO_NUL; + // Reads `text` the way a reader of a format with these rules does: + // every key and every value, also those it passes over. + let read = |text: &str, rules: StringRules| -> Result<(), ParseError> { + let mut parser = Parser::with_rules(text, rules); + parser.skip()?; + parser.end() + }; + let refused = [ + ("\"\u{fdd0}\"", "noncharacter in string"), + ("\"\u{fdef}\"", "noncharacter in string"), + ("\"a\u{fffe}\"", "noncharacter in string"), + ("\"\u{ffff}\"", "noncharacter in string"), + ("\"\u{1fffe}\"", "noncharacter in string"), + ("\"\u{10ffff}\"", "noncharacter in string"), + (r#""﷐""#, "noncharacter in string"), + (r#""￿""#, "noncharacter in string"), + (r#""🿾""#, "noncharacter in string"), + (r#""􏿿""#, "noncharacter in string"), + (r#""a\u0000b""#, "NUL in string"), + (r#"{"a\u0000":1}"#, "NUL in string"), + ("{\"\u{ffff}\":1}", "noncharacter in string"), + (r#"{"x":["￿"]}"#, "noncharacter in string"), + ]; + for (text, message) in refused { + assert!(read(text, StringRules::NONE).is_ok(), "{}", text); + assert_eq!(read(text, strict).unwrap_err().message, message, "{}", text); + } + // Each rule on its own. + assert!(read(r#""\u0000""#, StringRules::NO_NONCHARACTERS).is_ok()); + assert!(read(r#""￿""#, StringRules::NO_NUL).is_ok()); + // Their neighbours and the replacement character are fine. + for text in [ + "\"\u{fdcf}\u{fdf0}\u{fffd}\u{e000}\u{1fffd}\u{10fffd}\"", + r#""﷏ﷰ�🿽\u0001""#, + r#"{"a":"b","c":[1,"d"]}"#, + ] { + assert!(read(text, strict).is_ok(), "{}", text); + } + } + + /// How many code points a plane has. + const PLANE_SIZE: u32 = 1 << 16; + + /// Every noncharacter: those of the block and the last two code points + /// of each of the 17 planes. + fn noncharacters() -> Vec { + let planes = 0..=u32::from(char::MAX) / PLANE_SIZE; + let ends = planes.flat_map(|plane| [plane * PLANE_SIZE + PLANE_END, plane * PLANE_SIZE + PLANE_END + 1]); + NONCHARACTER_BLOCK.chain(ends).filter_map(char::from_u32).collect() + } + + /// `c` written with `\u` escapes, two of them for a surrogate pair. + fn escaped(c: char) -> String { + c.encode_utf16(&mut [0; 2]).iter().fold(String::new(), |mut out, unit| { + write!(out, "\\u{:04x}", unit).expect("a String takes any write"); + out + }) + } + + /// The rules are checked character by character only in strings + /// beyond ASCII, and a NUL is only looked for in strings with an + /// escape: what they find is the same for every kind of string. + #[test] + fn string_rules_in_every_kind_of_string() { + let strict = StringRules::NO_NONCHARACTERS | StringRules::NO_NUL; + let read = |text: &str, rules: StringRules| -> Result<(), ParseError> { + let mut parser = Parser::with_rules(text, rules); + parser.skip()?; + parser.end() + }; + // A string as a value and as a key, with nothing else in the text. + let texts = |string: &str| [format!("\"{}\"", string), format!("{{\"{}\":[1]}}", string)]; + // The strings with `c` written into them: alone, behind ASCII, + // ahead of it, behind more than a word of it, with an escape + // before it, and next to characters beyond ASCII that start with + // a lower byte than any noncharacter and with the same byte. + let strings = |c: &str| { + let long = "x".repeat(70); + [ + c.to_string(), + format!("abc{}", c), + format!("{}abc", c), + format!("{}{}", long, c), + format!("{}{}{}", long, c, long), + format!("a\\n{}", c), + format!("\u{e9}{}", c), + format!("{}\u{efff}{}", long, c), + format!("{}\u{f000}", c), + ] + }; + // Unicode has 66 of them. + let noncharacters = noncharacters(); + assert_eq!(noncharacters.len(), 66); + for &c in &noncharacters { + for written in [c.to_string(), escaped(c)] { + for string in strings(&written) { + let [value, key] = texts(&string); + for rules in [strict, StringRules::NO_NONCHARACTERS] { + // Reported right behind the string. + let e = read(&value, rules).unwrap_err(); + assert_eq!( + (e.message, e.offset), + ("noncharacter in string", value.len()), + "{:?}", + value + ); + assert_eq!(e.kind, ParseErrorKind::StringRule); + let e = read(&key, rules).unwrap_err(); + let behind = string.len() + "{\"\"".len(); + assert_eq!((e.message, e.offset), ("noncharacter in string", behind), "{:?}", key); + } + } + for text in strings(&written).iter().flat_map(|string| texts(string)) { + assert!(read(&text, StringRules::NO_NUL).is_ok(), "{:?}", text); + assert!(read(&text, StringRules::NONE).is_ok(), "{:?}", text); + } + } + for string in strings(&c.to_string()) { + assert!(!strict.admits(&string), "{:?}", string); + assert!(StringRules::NO_NUL.admits(&string), "{:?}", string); + } + } + // The code points next to them are none. + let neighbours = (0..=u32::from(char::MAX) / PLANE_SIZE) + .map(|plane| plane * PLANE_SIZE + PLANE_END - 1) + .chain([*NONCHARACTER_BLOCK.start() - 1, *NONCHARACTER_BLOCK.end() + 1]); + for c in neighbours.filter_map(char::from_u32) { + for written in [c.to_string(), escaped(c)] { + for text in strings(&written).iter().flat_map(|string| texts(string)) { + assert!(read(&text, strict).is_ok(), "{:?}", text); + } + } + assert!(strings(&c.to_string()).iter().all(|string| strict.admits(string))); + } + // A NUL can only be written as an escape: as it is, it is a control + // character, which no string may have. + for string in strings("\0") { + let e = read(&format!("\"{}\"", string), StringRules::NONE).unwrap_err(); + assert_eq!(e.message, "control character in string"); + } + for string in strings(r"\u0000") { + let [value, key] = texts(&string); + for rules in [strict, StringRules::NO_NUL] { + let e = read(&value, rules).unwrap_err(); + assert_eq!((e.message, e.offset), ("NUL in string", value.len()), "{:?}", value); + assert_eq!(e.kind, ParseErrorKind::StringRule); + let e = read(&key, rules).unwrap_err(); + let behind = string.len() + "{\"\"".len(); + assert_eq!((e.message, e.offset), ("NUL in string", behind), "{:?}", key); + } + for text in [value, key] { + assert!(read(&text, StringRules::NO_NONCHARACTERS).is_ok(), "{:?}", text); + } + } + for string in strings("\0") { + assert!( + !strict.admits(&string) && !StringRules::NO_NUL.admits(&string), + "{:?}", + string + ); + assert!(StringRules::NO_NONCHARACTERS.admits(&string), "{:?}", string); + } + // What breaks a rule first is what is reported. + for (text, message) in [ + (r#""\u0000\ufdd0""#, "NUL in string"), + (r#""\ufdd0\u0000""#, "noncharacter in string"), + ("\"\u{fdd0}\\u0000\"", "noncharacter in string"), + ("\"\\u0000\u{fdd0}\"", "NUL in string"), + ] { + assert_eq!(read(text, strict).unwrap_err().message, message, "{}", text); + } + assert_eq!(strict.without(StringRules::NO_NUL), StringRules::NO_NONCHARACTERS); + assert_eq!(strict.without(strict), StringRules::NONE); + assert_eq!( + StringRules::NO_NUL.without(StringRules::NO_NONCHARACTERS), + StringRules::NO_NUL + ); + } + + /// What looking for a noncharacter by the bytes of a string relies on, + /// for every character there is. + #[test] + fn noncharacters_start_with_a_high_byte() { + let mut utf8 = [0; 4]; + let lowest = char::from_u32(*NONCHARACTER_BLOCK.start()).unwrap(); + assert_eq!(lowest.encode_utf8(&mut utf8).as_bytes()[0], NONCHARACTER_LEAD); + let mut first = 0; + for c in (0..=u32::from(char::MAX)).filter_map(char::from_u32) { + let (&lead, rest) = c.encode_utf8(&mut utf8).as_bytes().split_first().unwrap(); + assert!(rest.iter().all(|&b| b < NONCHARACTER_LEAD), "{:?}", c); + assert!(lead >= first, "{:?}", c); + first = lead; + if is_noncharacter(c) { + assert!(lead >= NONCHARACTER_LEAD, "{:?}", c); + } + } + } + /// How many members the objects of the tests below have at most. const MANY_MEMBERS: usize = 100; From 93fb679b39b6f3d125b7af50d5b6fa42cd2d1973 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 04/19] uapi16: add a crate for UAPI.16 file manifests A UAPI.16 file manifest describes a tree of files as a sequence of JSON records: the root of the tree first, then a file object for every file, then optional signature objects and a trailer. Currently ufat handles manifests in src/fat/manifest, which is tied to ufat and to FAT and applies the limits of Linux in places, such as 255 bytes for a component of a name. Manifests aren't a FAT thing though. Other file systems want to build images from them too, and we might want to publish the code as a crate of its own at some point. So let's add a uapi16 crate that does manifests and nothing else. It compares names exactly, knows no limits but the ones of the specification, and reads a manifest record by record instead of holding all of it. ufat moves over to it later in this series. This starts the crate with what everything else builds on, the names of file objects. A Name is what the specification allows as a name: a normalized relative path whose components are separated by single slashes, none of them empty, "." or "..". It has no control characters and, like every string of a manifest, no noncharacters. It is at most 4095 bytes long and its components aren't limited on their own. "Uapi16Manifest" and names that start with "Uapi16Manifest." are reserved for the manifest and what belongs to it. Name::ROOT, the empty name, stands in for the root file object, which has none. If a string isn't a name InvalidName says why: it is empty, too long or reserved, it has a control character or a noncharacter, or one of its components is empty, "." or "..". So code that reads a manifest can tell people what is actually wrong with a name. Names are ordered the way the specification orders the file objects of a manifest in code point order: component by component, each compared by its bytes. That's the same as comparing the whole names with "/" lower than any other byte. So a/x comes before a-b, although "-" is lower than "/". Ord for Name finds the first byte the two names differ in and decides there, so a comparison is a single pass over the bytes they share. Name::join() adds a component to the name of a directory and only checks that component, so building the names of a tree on the way down costs time in proportion to their length. Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 7 + Cargo.toml | 2 + HACKING.md | 4 +- src/uapi16/Cargo.toml | 18 + src/uapi16/lib.rs | 51 +++ src/uapi16/name.rs | 762 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 842 insertions(+), 2 deletions(-) create mode 100644 src/uapi16/Cargo.toml create mode 100644 src/uapi16/lib.rs create mode 100644 src/uapi16/name.rs diff --git a/Cargo.lock b/Cargo.lock index dad5877..3763583 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -147,6 +147,13 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uapi16" +version = "0.1.0" +dependencies = [ + "json", +] + [[package]] name = "ufat" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 90ad7b4..7710f84 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "src/dlopen-note", "src/fat", "src/json", + "src/uapi16", "src/varlink", "tools", "tests/crash", @@ -23,6 +24,7 @@ default-members = [ "src/dlopen-note", "src/fat", "src/json", + "src/uapi16", "src/varlink", "tests/crash", ] diff --git a/HACKING.md b/HACKING.md index c26f013..47c97ca 100644 --- a/HACKING.md +++ b/HACKING.md @@ -48,8 +48,8 @@ With rustup, `cargo +1.85.0` selects rustc 1.85: `cargo test` runs: -- the unit tests of the library and of the json, varlink, dlopen, - dlopen-note and blkid crates, +- the unit tests of the library and of the json, uapi16, varlink, + dlopen, dlopen-note and blkid crates, - the integration tests in tests/, - the crash consistency harness. diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml new file mode 100644 index 0000000..466c68f --- /dev/null +++ b/src/uapi16/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +[package] +name = "uapi16" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lib] +path = "lib.rs" + +[dependencies] +json.workspace = true + +[lints] +workspace = true diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs new file mode 100644 index 0000000..69e33bd --- /dev/null +++ b/src/uapi16/lib.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! UAPI.16 file manifests: reading, checking and writing them. +//! +//! A [UAPI.16 file manifest] describes a tree of files. It is an RFC 7464 +//! JSON text sequence: one JSON object per record, each record after an +//! ASCII record separator. The first object describes the root of the +//! tree. One object for every file follows, with its name, its type and +//! what else is known of it: size, hash, owner, mode, time. Signature +//! objects can come after the file objects, and a trailer object ends the +//! manifest. +//! +//! [UAPI.16 file manifest]: https://uapi-group.org/specifications/specs/file_manifest/ + +#![deny(unsafe_code)] +#![warn(missing_docs)] + +mod name; + +pub use name::{InvalidName, Name}; + +/// The name of a manifest that is stored in the tree it describes. +pub const FILENAME: &str = "Uapi16Manifest"; +/// What the name of a manifest ends in that is stored next to what it +/// describes. +pub const SUFFIX: &str = ".Uapi16Manifest"; + +/// What the strings of a manifest may not hold beyond what JSON forbids: +/// noncharacters and the NUL character, escaped or not. +pub(crate) const STRING_RULES: json::StringRules = json::StringRules::NO_NONCHARACTERS.union(json::StringRules::NO_NUL); + +/// What the tests of this crate build manifests from. +#[cfg(test)] +pub(crate) mod testing { + use super::Name; + + /// The names of the full tree in which every directory has an entry + /// for each of `pieces`, down to `depth` components: every name of at + /// most `depth` components made of `pieces`, the root among them. + pub(crate) fn full_tree_names(pieces: &[&str], depth: usize) -> Vec { + let mut names = vec![Name::ROOT]; + let mut level = vec![Name::ROOT]; + for _ in 0..depth { + level = level + .iter() + .flat_map(|parent| pieces.iter().map(move |piece| parent.join(piece).unwrap())) + .collect(); + names.extend(level.iter().cloned()); + } + names + } +} diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs new file mode 100644 index 0000000..a761a11 --- /dev/null +++ b/src/uapi16/name.rs @@ -0,0 +1,762 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The names of file objects. + +use std::cmp::Ordering; +use std::fmt; +use std::iter; +use std::ops::Deref; +use std::str::FromStr; + +use json::StringRules; + +use crate::{FILENAME, STRING_RULES}; + +/// What separates the components of a name. +const SEPARATOR: char = '/'; +/// The separator as the one byte it is in UTF-8. Being ASCII, that byte is +/// in no other character, so the components of a name are found by +/// looking at its bytes. +const SEPARATOR_BYTE: u8 = SEPARATOR as u8; +/// The components that stand for a directory itself and for the one above +/// it. A name has neither. +const CURRENT: &str = "."; +const PARENT: &str = ".."; +/// What follows [`FILENAME`] in the name of a file that belongs to the +/// manifest, such as its signature or a compressed copy. +const SUFFIX_SEPARATOR: char = '.'; +/// The control characters a name may not have are the bytes below the +/// space, ASCII 0 to 31, and delete, ASCII 127. +const SPACE: u8 = b' '; +const DELETE: u8 = 0x7f; +/// What the text of a name may not hold besides control characters: what +/// the strings of a manifest may not hold, except for the NUL character, +/// which is a control character. That leaves the noncharacters. +const RULES: StringRules = STRING_RULES.without(StringRules::NO_NUL); + +/// The name of a file object: the path of the file below the root of the +/// tree the manifest describes. +/// +/// A name is a normalized relative path. Its components are separated by +/// single slashes, and none of them is empty, `.` or `..`. It has no +/// control characters and no noncharacters, and it is at most +/// [`Name::MAX_LEN`] bytes long. Its components are not limited on their +/// own. It is not `Uapi16Manifest` and does not begin with +/// `Uapi16Manifest.`, the names the manifest itself and what belongs to it +/// have inside the tree. +/// +/// Names are ordered the way the specification orders the file objects of +/// a manifest in code point order: component by component, each compared +/// by its bytes, so that the name of a directory comes right before the +/// names below it. That is not the order of the names as strings: `a/x` +/// comes before `a-b`. +/// +/// The root file object has no name. Its name here is the empty one, +/// [`Name::ROOT`], which no file has, and which comes before every other +/// name. +/// +/// ``` +/// use uapi16::{InvalidName, Name}; +/// +/// let name = Name::new("EFI/BOOT")?; +/// assert_eq!(name.join("BOOTX64.EFI")?, "EFI/BOOT/BOOTX64.EFI"); +/// assert_eq!("EFI//BOOT".parse::(), Err(InvalidName::EmptyComponent)); +/// assert_eq!(Name::new("../etc/passwd"), Err(InvalidName::ContainsDotComponent)); +/// assert!(Name::new("a/x")? < Name::new("a-b")?); +/// # Ok::<(), InvalidName>(()) +/// ``` +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Name(String); + +/// Why a string is not the name of a file object, see [`Name`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum InvalidName { + /// The string is empty. No file object has that name: [`Name::ROOT`] + /// only stands in for the root file object, which has no name. + Empty, + /// It is longer than [`Name::MAX_LEN`] bytes. + TooLong, + /// It is `Uapi16Manifest` or begins with `Uapi16Manifest.`, which the + /// specification reserves for the manifest and what belongs to it. + Reserved, + /// It contains a control character: ASCII 0 to 31 or 127. + ContainsControlCharacter, + /// It contains a noncharacter, which no string of a manifest may have. + ContainsNoncharacter, + /// One of its components is empty: it begins or ends with a slash, or + /// it has two slashes in a row. + EmptyComponent, + /// It contains a component that is `.` or `..`. + ContainsDotComponent, + /// The component given to [`Name::join`] contains a slash, so it is + /// more than one component. + ContainsSeparator, +} + +impl fmt::Display for InvalidName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + InvalidName::Empty => f.write_str("name is empty"), + InvalidName::TooLong => write!(f, "name is longer than {} bytes", Name::MAX_LEN), + InvalidName::Reserved => f.write_str("name is reserved for the manifest"), + InvalidName::ContainsControlCharacter => f.write_str("name contains a control character"), + InvalidName::ContainsNoncharacter => f.write_str("name contains a noncharacter"), + InvalidName::EmptyComponent => f.write_str("name has an empty component"), + InvalidName::ContainsDotComponent => write!(f, "name contains a '{}' or '{}' component", CURRENT, PARENT), + InvalidName::ContainsSeparator => write!(f, "name component contains '{}'", SEPARATOR), + } + } +} + +impl std::error::Error for InvalidName {} + +impl Name { + /// The name of the root file object: the empty one. + pub const ROOT: Name = Name(String::new()); + + /// The most bytes a name has, as the specification says. + pub const MAX_LEN: usize = 4095; + + /// Takes `name` as the name of a file object, if it is one. If it is + /// not, the error says why. + pub fn new(name: impl Into) -> Result { + let name = name.into(); + if name.is_empty() { + return Err(InvalidName::Empty); + } + if name.len() > Name::MAX_LEN { + return Err(InvalidName::TooLong); + } + if Name::is_reserved(&name) { + return Err(InvalidName::Reserved); + } + // The separator is neither a control character nor a noncharacter, + // so the text of the components is checked all at once. + Name::check_text(&name)?; + for component in name.as_bytes().split(|&b| b == SEPARATOR_BYTE) { + Name::check_component(component)?; + } + Ok(Name(name)) + } + + /// The name of the entry `component` of the directory this name is + /// the name of. Only the new component is looked at, so the names of + /// a deep tree are cheap to make on the way down. + pub fn join(&self, component: &str) -> Result { + if component.contains(SEPARATOR) { + return Err(InvalidName::ContainsSeparator); + } + if self.is_root() { + return Name::new(component); + } + let len = self.0.len() + SEPARATOR.len_utf8() + component.len(); + if len > Name::MAX_LEN { + return Err(InvalidName::TooLong); + } + // In the order of Name::new(), so that a component is refused for + // the reason the whole name would be refused for. + Name::check_text(component)?; + Name::check_component(component.as_bytes())?; + let mut name = String::with_capacity(len); + name.push_str(&self.0); + name.push(SEPARATOR); + name.push_str(component); + Ok(Name(name)) + } + + /// Checks that `text` can be in a name: it has no control characters, + /// and nothing that the strings of a manifest may not hold. + fn check_text(text: &str) -> Result<(), InvalidName> { + // Every byte is looked at, not only those up to the first control + // character, and with two comparisons instead of is_ascii_control(), + // which the compiler turns into a branch. Without an early end and + // without a branch the compiler looks at many bytes at a time. + let control = text + .bytes() + .fold(false, |control, b| control | (b < SPACE) | (b == DELETE)); + if control { + return Err(InvalidName::ContainsControlCharacter); + } + if !RULES.admits(text) { + return Err(InvalidName::ContainsNoncharacter); + } + Ok(()) + } + + /// Checks the bytes `component` between two separators as a component + /// as far as its shape goes: it is not empty, and it does not stand + /// for a directory itself or for the one above it. + fn check_component(component: &[u8]) -> Result<(), InvalidName> { + if component.is_empty() { + return Err(InvalidName::EmptyComponent); + } + if component == CURRENT.as_bytes() || component == PARENT.as_bytes() { + return Err(InvalidName::ContainsDotComponent); + } + Ok(()) + } + + /// The components of the name, the first one first. The root has none. + pub fn components(&self) -> impl DoubleEndedIterator { + // The root's empty name would make one empty component. + self.0.split(SEPARATOR).filter(|component| !component.is_empty()) + } + + /// The name of the directory the file is in, which is the empty name + /// of the root for a file at the top. The root has none. + pub fn parent(&self) -> Option<&str> { + if self.is_root() { + return None; + } + Some(self.0.rsplit_once(SEPARATOR).map_or("", |(parent, _)| parent)) + } + + /// The name of the file in its directory, its last component. The + /// root has none. + pub fn file_name(&self) -> Option<&str> { + self.components().next_back() + } + + /// Whether `name` is one the specification reserves for the manifest + /// and what belongs to it: `Uapi16Manifest`, or a name that begins + /// with `Uapi16Manifest.`. A file of such a name is not listed in a + /// manifest. + pub fn is_reserved(name: &str) -> bool { + name.strip_prefix(FILENAME) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(SUFFIX_SEPARATOR)) + } + + /// Whether this is the name of the root file object. + pub fn is_root(&self) -> bool { + self.0.is_empty() + } + + /// The name as a string. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl Deref for Name { + type Target = str; + + fn deref(&self) -> &str { + &self.0 + } +} + +impl Ord for Name { + fn cmp(&self, other: &Name) -> Ordering { + NamePair::new(&self.0, &other.0).ordering() + } +} + +/// Two names, looked at from the first byte in which they differ. If one +/// name is the first part of the other, that is where it ends. +/// +/// The names are the same in all bytes before that one, so the bytes from +/// there on settle both how the names are ordered and whether the second +/// one may follow the first in a manifest. That is why one pass over the +/// bytes the names share answers all of it. The root's empty name is a +/// name here, too. +pub(crate) struct NamePair<'a> { + /// The bytes of the first name from the first byte in which the names + /// differ on, and those of the second one. + first: &'a [u8], + second: &'a [u8], +} + +impl<'a> NamePair<'a> { + /// The pair of the names `first` and `second`. + pub(crate) fn new(first: &'a str, second: &'a str) -> NamePair<'a> { + let (first, second) = (first.as_bytes(), second.as_bytes()); + let common = iter::zip(first, second).take_while(|(a, b)| a == b).count(); + NamePair { + first: &first[common..], + second: &second[common..], + } + } + + /// How the names are ordered, see [`Name`]: component by component, + /// each compared by its bytes. + /// + /// That is the order of the bytes of the whole names with the separator + /// taken as lower than any other byte, so the first bytes in which the + /// names differ decide it. All components that end before those bytes + /// are the same in both names, and the one they are in starts at the + /// same byte in both: + /// - If one name ends there, its component there is the first part of + /// the other's, or the other name goes on with a separator to a + /// component it does not have at all. Either way it comes first. + /// - If one name has the separator there, its component ends there and + /// is the first part of the other's, which goes on. It comes first, + /// as the separator is lowest. + /// - Otherwise both components go on, and the bytes there are the first + /// ones in which they differ. + pub(crate) fn ordering(&self) -> Ordering { + let rank = |rest: &[u8]| rest.first().map(|&b| (b != SEPARATOR_BYTE, b)); + rank(self.first).cmp(&rank(self.second)) + } +} + +impl PartialOrd for Name { + fn partial_cmp(&self, other: &Name) -> Option { + Some(self.cmp(other)) + } +} + +impl AsRef for Name { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for Name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl FromStr for Name { + type Err = InvalidName; + + fn from_str(name: &str) -> Result { + Name::new(name) + } +} + +impl TryFrom for Name { + type Error = InvalidName; + + fn try_from(name: String) -> Result { + Name::new(name) + } +} + +impl TryFrom<&str> for Name { + type Error = InvalidName; + + fn try_from(name: &str) -> Result { + Name::new(name) + } +} + +impl From for String { + fn from(name: Name) -> String { + name.0 + } +} + +impl PartialEq for Name { + fn eq(&self, other: &str) -> bool { + self.0 == other + } +} + +impl PartialEq<&str> for Name { + fn eq(&self, other: &&str) -> bool { + self.0 == *other + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::full_tree_names; + + #[test] + fn names() { + for name in [ + "a", + "a/b", + "EFI/BOOT/BOOTX64.EFI", + "with space", + "\u{fc}mlaut \u{221e}.txt", + "...", + "a/...", + ".hidden", + "a.", + "Uapi16Manifest2", + "Uapi16Manifes", + "uapi16manifest", + "sub/Uapi16Manifest", + "sub/Uapi16Manifest.sig", + "xUapi16Manifest.sig", + ] { + let parsed = Name::new(name).unwrap_or_else(|_| panic!("{:?}", name)); + assert_eq!(parsed, name); + assert_eq!(parsed.as_str(), name); + assert_eq!(parsed.to_string(), name); + assert!(!parsed.is_root()); + assert_eq!(name.parse::(), Ok(parsed.clone())); + assert_eq!(Name::try_from(name), Ok(parsed.clone())); + assert_eq!(Name::try_from(name.to_string()), Ok(parsed.clone())); + assert_eq!(String::from(parsed), name); + } + for (name, reason) in [ + ("", InvalidName::Empty), + ("/", InvalidName::EmptyComponent), + ("/abs", InvalidName::EmptyComponent), + ("a/", InvalidName::EmptyComponent), + ("a//b", InvalidName::EmptyComponent), + (".", InvalidName::ContainsDotComponent), + ("..", InvalidName::ContainsDotComponent), + ("a/.", InvalidName::ContainsDotComponent), + ("a/..", InvalidName::ContainsDotComponent), + ("./a", InvalidName::ContainsDotComponent), + ("../a", InvalidName::ContainsDotComponent), + ("a/./b", InvalidName::ContainsDotComponent), + ("a/../b", InvalidName::ContainsDotComponent), + ("a\nb", InvalidName::ContainsControlCharacter), + ("a\0b", InvalidName::ContainsControlCharacter), + ("a/\u{1}", InvalidName::ContainsControlCharacter), + ("a\u{7f}", InvalidName::ContainsControlCharacter), + ("\u{fdd0}", InvalidName::ContainsNoncharacter), + ("a\u{fffe}", InvalidName::ContainsNoncharacter), + ("a/\u{10ffff}", InvalidName::ContainsNoncharacter), + ("Uapi16Manifest", InvalidName::Reserved), + ("Uapi16Manifest.", InvalidName::Reserved), + ("Uapi16Manifest.sig", InvalidName::Reserved), + ("Uapi16Manifest.gz", InvalidName::Reserved), + ("Uapi16Manifest.d/inside", InvalidName::Reserved), + ] { + assert_eq!(Name::new(name), Err(reason), "{:?}", name); + assert_eq!(name.parse::(), Err(reason), "{:?}", name); + } + // The control characters of Latin-1 are not ASCII control + // characters. + assert!(Name::new("a\u{85}b").is_ok()); + } + + /// The error says what is wrong with the name. + #[test] + fn messages() { + for (reason, text) in [ + (InvalidName::Empty, "name is empty"), + (InvalidName::TooLong, "name is longer than 4095 bytes"), + (InvalidName::Reserved, "name is reserved for the manifest"), + ( + InvalidName::ContainsControlCharacter, + "name contains a control character", + ), + (InvalidName::ContainsNoncharacter, "name contains a noncharacter"), + (InvalidName::EmptyComponent, "name has an empty component"), + ( + InvalidName::ContainsDotComponent, + "name contains a '.' or '..' component", + ), + (InvalidName::ContainsSeparator, "name component contains '/'"), + ] { + assert_eq!(reason.to_string(), text); + } + } + + #[test] + fn lengths() { + // The whole name is limited, its components are not on their own. + let longest = "x".repeat(Name::MAX_LEN); + assert!(Name::new(longest.as_str()).is_ok()); + assert_eq!(Name::new(format!("{}x", longest)), Err(InvalidName::TooLong)); + let component = "y".repeat(1000); + let deep = [component.as_str(); 4].join("/"); + assert!(Name::new(deep.as_str()).is_ok()); + let fits = format!("{}/{}", deep, "z".repeat(Name::MAX_LEN - deep.len() - 1)); + assert_eq!(fits.len(), Name::MAX_LEN); + assert!(Name::new(fits.as_str()).is_ok()); + assert_eq!(Name::new(format!("{}z", fits)), Err(InvalidName::TooLong)); + // The limit counts bytes, not characters. + let euro = '\u{20ac}'; + assert_eq!(euro.len_utf8(), 3); + assert!(Name::new(euro.to_string().repeat(Name::MAX_LEN / 3)).is_ok()); + assert_eq!( + Name::new(euro.to_string().repeat(Name::MAX_LEN / 3 + 1)), + Err(InvalidName::TooLong) + ); + } + + #[test] + fn order() { + // In the order the specification sorts the names of a manifest in. + let names: Vec = [ + "", + "a", + "a/b", + "a/b/c", + "a/x", + "a-b", + "a.b", + "a0", + "b", + "\u{e9}", + "\u{ff61}", + "\u{1f600}", + ] + .into_iter() + .map(|name| { + if name.is_empty() { + Name::ROOT + } else { + Name::new(name).unwrap() + } + }) + .collect(); + for (i, a) in names.iter().enumerate() { + for (j, b) in names.iter().enumerate() { + assert_eq!(a.cmp(b), i.cmp(&j), "{:?} {:?}", a, b); + assert_eq!(a.partial_cmp(b), Some(i.cmp(&j))); + } + } + // As strings they are not in that order. + assert!(names[5].as_str() < names[4].as_str()); + } + + /// The components the names of the tests below are made of: one that + /// is the first part of others, bytes below the separator and above + /// it, and characters beyond ASCII. + const PIECES: [&str; 8] = ["a", "ab", "a b", "a-b", "a.b", "a0", "\u{e9}", "\u{1f600}"]; + + /// Names are in the order of their components, whatever order the + /// bytes of the whole names are in. + #[test] + fn order_of_components() { + let names = full_tree_names(&PIECES, 3); + for a in &names { + for b in &names { + assert_eq!(a.cmp(b), a.components().cmp(b.components()), "{:?} {:?}", a, b); + } + } + // The separator comes before any other byte, also before those + // that are lower as bytes: the space to the full stop. + for byte in b' '..SEPARATOR_BYTE { + let other = Name::new(format!("a{}b", char::from(byte))).unwrap(); + for name in ["a/b", "a/x", "a/b/c", "a/\u{e9}"] { + assert!(Name::new(name).unwrap() < other, "{:?} {:?}", name, other); + } + let other = Name::new(format!("a{}", char::from(byte))).unwrap(); + assert!(Name::new("a/b").unwrap() < other, "{:?}", other); + } + // A name comes before the names it is the first part of. + for (first, second) in [ + ("a", "a/b"), + ("a", "ab"), + ("a", "a b"), + ("a/b", "a/bc"), + ("a/b", "a/b/c"), + ("a/b/c", "a/bc"), + ("a/b", "ab"), + ("\u{e9}", "\u{e9}/a"), + ] { + let (first, second) = (Name::new(first).unwrap(), Name::new(second).unwrap()); + assert_eq!(first.cmp(&second), Ordering::Less, "{:?} {:?}", first, second); + assert_eq!(second.cmp(&first), Ordering::Greater, "{:?} {:?}", first, second); + } + } + + /// Everything that makes `name` not a name by the definition of + /// [`Name`], with every component and every character of it looked at + /// on its own. Nothing if it is a name. + fn reasons(name: &str) -> Vec { + let mut reasons = Vec::new(); + if name.is_empty() { + reasons.push(InvalidName::Empty); + } + if name.len() > Name::MAX_LEN { + reasons.push(InvalidName::TooLong); + } + if Name::is_reserved(name) { + reasons.push(InvalidName::Reserved); + } + if name.chars().any(|c| c.is_ascii_control()) { + reasons.push(InvalidName::ContainsControlCharacter); + } + // The NUL character, which the strings of a manifest may not hold + // either, is a control character. + let noncharacter = |c: char| !c.is_ascii_control() && !STRING_RULES.admits(c.encode_utf8(&mut [0; 4])); + if name.chars().any(noncharacter) { + reasons.push(InvalidName::ContainsNoncharacter); + } + for component in name.split(SEPARATOR) { + if component.is_empty() { + reasons.push(InvalidName::EmptyComponent); + } + if component == CURRENT || component == PARENT { + reasons.push(InvalidName::ContainsDotComponent); + } + } + reasons + } + + /// Every string of a few of the characters below is a name if the + /// definition says so, and only then: on its own and in long names, + /// whose bytes are looked at many at a time. If it is not one, the + /// reason given is one of the reasons it is not. + #[test] + fn names_by_the_definition() { + let characters = [ + 'a', + '.', + SEPARATOR, + ' ', + '\0', + '\u{1f}', + '\u{7f}', + '\u{85}', + '\u{e9}', + '\u{fdd0}', + '\u{fffe}', + '\u{10ffff}', + ]; + let mut strings = vec![String::new()]; + let mut level = vec![String::new()]; + for _ in 0..4 { + level = level + .iter() + .flat_map(|string| characters.iter().map(move |c| format!("{}{}", string, c))) + .collect(); + strings.extend(level.iter().cloned()); + } + let head = "abcdefgh/".repeat(8); + let tail = "/abcdefgh".repeat(8); + let mut valid = [0; 2]; + for string in &strings { + for name in [ + string.clone(), + format!("{}{}", head, string), + format!("{}{}", string, tail), + format!("{}{}{}", head, string, tail), + ] { + let reasons = reasons(&name); + match Name::new(name.as_str()) { + Ok(_) => assert!(reasons.is_empty(), "{:?} {:?}", name, reasons), + Err(reason) => assert!(reasons.contains(&reason), "{:?} {:?} {:?}", name, reason, reasons), + } + valid[usize::from(reasons.is_empty())] += 1; + } + } + // Both kinds come up. + assert!(valid.iter().all(|&count| count > 0), "{:?}", valid); + // A character a name may not have is found wherever it is. + let name = format!("{}end", head); + for at in 0..=name.len() { + for (c, reason) in [ + ('\0', Some(InvalidName::ContainsControlCharacter)), + ('\u{1f}', Some(InvalidName::ContainsControlCharacter)), + ('\u{7f}', Some(InvalidName::ContainsControlCharacter)), + ('\u{fdd0}', Some(InvalidName::ContainsNoncharacter)), + ('\u{10ffff}', Some(InvalidName::ContainsNoncharacter)), + (' ', None), + ('\u{85}', None), + ('\u{e9}', None), + ] { + let mut with = name.clone(); + with.insert(at, c); + assert_eq!(Name::new(with.as_str()).err(), reason, "{:?}", with); + } + } + } + + #[test] + fn components_and_parents() { + let name = Name::new("a/b/c").unwrap(); + assert_eq!(name.components().collect::>(), ["a", "b", "c"]); + assert_eq!(name.components().next_back(), Some("c")); + assert_eq!(name.parent(), Some("a/b")); + assert_eq!(name.file_name(), Some("c")); + let top = Name::new("a").unwrap(); + assert_eq!(top.parent(), Some("")); + assert_eq!(top.file_name(), Some("a")); + assert_eq!(Name::ROOT.components().count(), 0); + assert_eq!(Name::ROOT.parent(), None); + assert_eq!(Name::ROOT.file_name(), None); + } + + #[test] + fn the_root() { + assert!(Name::ROOT.is_root()); + assert_eq!(Name::ROOT, ""); + assert_eq!(Name::default(), Name::ROOT); + assert_eq!(Name::new(""), Err(InvalidName::Empty)); + } + + #[test] + fn reserved() { + for name in [ + "Uapi16Manifest", + "Uapi16Manifest.", + "Uapi16Manifest.sig", + "Uapi16Manifest.d/x", + ] { + assert!(Name::is_reserved(name), "{:?}", name); + } + for name in [ + "", + "Uapi16Manifest2", + "Uapi16Manifes", + "sub/Uapi16Manifest", + "x.Uapi16Manifest", + ] { + assert!(!Name::is_reserved(name), "{:?}", name); + } + } + + /// Joining gives the name the whole path gives, and refuses what the + /// whole path is refused for, for the same reason. A component with a + /// separator is more than one and refused. + #[test] + fn joining() { + let long = "x".repeat(1000); + let parents = [ + Name::ROOT, + Name::new("a").unwrap(), + Name::new("a/b c").unwrap(), + Name::new("Uapi16Manifest2").unwrap(), + ]; + for parent in &parents { + for component in [ + "c", + "c d", + ".x", + "...", + long.as_str(), + "", + ".", + "..", + "a/b", + "/", + "a/..", + "a\tb", + "a\u{fffe}", + "Uapi16Manifest", + "Uapi16Manifest.sig", + "Uapi16Manifest2", + ] { + let whole = if parent.is_root() { + component.to_string() + } else { + format!("{}/{}", parent, component) + }; + let expected = if component.contains(SEPARATOR) { + Err(InvalidName::ContainsSeparator) + } else { + Name::new(whole) + }; + assert_eq!(parent.join(component), expected, "{:?} {:?}", parent, component); + } + } + assert_eq!(Name::ROOT.join("a").unwrap().join("b").unwrap(), "a/b"); + // The length of the whole name counts. + let mut deep = Name::ROOT; + while deep.len() + 2 * (long.len() + 1) <= Name::MAX_LEN { + deep = deep.join(&long).unwrap(); + } + let room = Name::MAX_LEN - (deep.len() + 1); + assert!(room > 0); + assert_eq!(deep.join(&"y".repeat(room)).unwrap().len(), Name::MAX_LEN); + assert_eq!(deep.join(&"y".repeat(room + 1)), Err(InvalidName::TooLong)); + // A component that is too long, and wrong in another way too, is + // refused for its length, as the whole name is. + let wrong = format!("{}\n", "y".repeat(room)); + assert_eq!(deep.join(&wrong), Err(InvalidName::TooLong)); + assert_eq!(Name::new(format!("{}/{}", deep, wrong)), Err(InvalidName::TooLong)); + } +} From 2b6be686f06625c4c7f724354d0c8e91a946e0be Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 05/19] uapi16: add the hashes A manifest gives the SHA-256 hash of the contents of a file in sha256, and the hashes of the data a contents object refers to in encodedSha256 and originalSha256. Add Sha256 for such a hash. It prints as 64 lower case hex digits and parses from 64 hex digits of either case and nothing else. Note that systemd passes over whitespace between the digits while we refuse it. The specification wants 64 hexadecimal digits, and the clarification in [1] makes refusing anything else explicit. Sha256Context computes the hash of data that comes in pieces. It implements io::Write so the contents of a file can be hashed with io::copy() while they are read, and Finalize::finalize() consumes it and returns the hash. The hashing itself is done by the sha2 crate, which the workspace already uses. The specification leaves room for other hash algorithms, each with fields of its own next to the SHA-256 ones. The Digest trait is what such an algorithm would implement: the hash of no data and a context that computes the hash. The context implements Finalize so that code written against Digest can get the hash out of it. [1]: https://github.com/uapi-group/specifications/pull/260 Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 1 + src/uapi16/Cargo.toml | 1 + src/uapi16/digest.rs | 258 ++++++++++++++++++++++++++++++++++++++++++ src/uapi16/hex.rs | 58 ++++++++++ src/uapi16/lib.rs | 3 + 5 files changed, 321 insertions(+) create mode 100644 src/uapi16/digest.rs create mode 100644 src/uapi16/hex.rs diff --git a/Cargo.lock b/Cargo.lock index 3763583..bfbf5b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -152,6 +152,7 @@ name = "uapi16" version = "0.1.0" dependencies = [ "json", + "sha2", ] [[package]] diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index 466c68f..68f9041 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -13,6 +13,7 @@ path = "lib.rs" [dependencies] json.workspace = true +sha2.workspace = true [lints] workspace = true diff --git a/src/uapi16/digest.rs b/src/uapi16/digest.rs new file mode 100644 index 0000000..4a88faa --- /dev/null +++ b/src/uapi16/digest.rs @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The hashes a manifest gives for the contents of files. + +use std::fmt; +use std::io; +use std::str::FromStr; + +use sha2::Digest as _; + +use crate::hex::Hex; + +/// A hash a manifest gives for contents. +/// +/// The specification defines one algorithm, SHA-256, which is [`Sha256`], +/// and says that another one gets fields of its own next to the SHA-256 +/// ones. A type with this trait gives the hash of no data and a context +/// that computes the hash of data that comes in pieces. +pub trait Digest: Copy + Eq { + /// The hash of no data. Contents of size 0 have this hash, and only + /// they do. + const EMPTY: Self; + + /// Computes the hash of data that comes in pieces. What is written to + /// it is the data, and [`Finalize::finalize`] gives the hash of all of + /// it. + type Context: Default + io::Write + Finalize; +} + +/// The computation of a hash, which ends with the hash of all the data, +/// such as [`Digest::Context`]. +pub trait Finalize { + /// The hash it computes. + type Digest: Digest; + + /// Ends the computation and gives the hash of all the data. + fn finalize(self) -> Self::Digest; +} + +/// A SHA-256 hash, as the `sha256` field of a file object and the +/// `encodedSha256` and `originalSha256` fields of a contents object have +/// it. +/// +/// It prints as 64 lower case hex digits and parses from 64 hex digits of +/// either case. Text with anything else in it, such as whitespace between +/// the digits, is refused. +/// +/// ``` +/// use uapi16::{Digest, Sha256}; +/// +/// let hash = Sha256::digest(b"hello"); +/// assert_eq!( +/// hash.to_string(), +/// "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" +/// ); +/// assert_eq!(hash.to_string().parse(), Ok(hash)); +/// let spaced = "2cf2 4dba 5fb0 a30e 26e8 3b2a c5b9 e29e 1b16 1e5c 1fa7 425e 7304 3362 938b 9824"; +/// assert!(spaced.parse::().is_err()); +/// assert_eq!(Sha256::digest(b""), Sha256::EMPTY); +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Sha256([u8; Sha256::SIZE]); + +/// A string that is not the hex digits of a hash. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidDigest(()); + +impl fmt::Display for InvalidDigest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not the hex digits of a hash") + } +} + +impl std::error::Error for InvalidDigest {} + +impl Sha256 { + /// The size of the hash in bytes. + pub const SIZE: usize = 32; + + /// The hash of `data`. + pub fn digest(data: &[u8]) -> Sha256 { + Sha256(sha2::Sha256::digest(data).into()) + } + + /// The bytes of the hash. + pub fn as_bytes(&self) -> &[u8; Sha256::SIZE] { + &self.0 + } +} + +impl Digest for Sha256 { + const EMPTY: Sha256 = Sha256([ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, + 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, + ]); + + type Context = Sha256Context; +} + +impl From<[u8; Sha256::SIZE]> for Sha256 { + fn from(bytes: [u8; Sha256::SIZE]) -> Sha256 { + Sha256(bytes) + } +} + +impl From for [u8; Sha256::SIZE] { + fn from(hash: Sha256) -> [u8; Sha256::SIZE] { + hash.0 + } +} + +impl AsRef<[u8]> for Sha256 { + fn as_ref(&self) -> &[u8] { + &self.0 + } +} + +impl fmt::Display for Sha256 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Hex(&self.0).fmt(f) + } +} + +impl fmt::Debug for Sha256 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Sha256({})", self) + } +} + +impl FromStr for Sha256 { + type Err = InvalidDigest; + + fn from_str(text: &str) -> Result { + Hex::decode_array(text).map(Sha256).ok_or(InvalidDigest(())) + } +} + +/// Computes the [`Sha256`] of data that comes in pieces, such as the +/// contents of a file a manifest is written for. +/// +/// ``` +/// use std::io::Write; +/// use uapi16::{Finalize, Sha256, Sha256Context}; +/// +/// let mut context = Sha256Context::default(); +/// context.update(b"hel"); +/// context.write_all(b"lo")?; +/// assert_eq!(context.finalize(), Sha256::digest(b"hello")); +/// # Ok::<(), std::io::Error>(()) +/// ``` +#[derive(Clone, Debug, Default)] +pub struct Sha256Context(sha2::Sha256); + +impl Sha256Context { + /// Takes more of the data. + pub fn update(&mut self, data: &[u8]) { + self.0.update(data); + } +} + +impl Finalize for Sha256Context { + type Digest = Sha256; + + fn finalize(self) -> Sha256 { + Sha256(self.0.finalize().into()) + } +} + +impl io::Write for Sha256Context { + fn write(&mut self, data: &[u8]) -> io::Result { + self.update(data); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The FIPS 180-4 vectors. + #[test] + fn vectors() { + for (data, expected) in [ + ( + &b""[..], + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ), + ( + &b"abc"[..], + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ), + ( + &b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"[..], + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", + ), + ] { + assert_eq!(Sha256::digest(data).to_string(), expected); + let mut context = Sha256Context::default(); + for piece in data.chunks(7) { + context.update(piece); + } + assert_eq!(context.finalize(), Sha256::digest(data)); + } + assert_eq!(Sha256::digest(b""), Sha256::EMPTY); + } + + /// The hash of `data` computed with nothing but what [`Digest`] gives: + /// a context that takes the data and is then finalized. + fn computed(data: &[u8]) -> D { + use std::io::Write; + + let mut context = D::Context::default(); + context.write_all(data).unwrap(); + context.finalize() + } + + #[test] + fn contexts() { + assert_eq!(computed::(b""), Sha256::EMPTY); + assert_eq!(computed::(b"hello"), Sha256::digest(b"hello")); + } + + #[test] + fn text() { + let hash = Sha256::digest(b"hello"); + let hex = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + assert_eq!(hash.to_string(), hex); + assert_eq!(format!("{:?}", hash), format!("Sha256({})", hex)); + assert_eq!(hex.parse(), Ok(hash)); + assert_eq!(hex.to_uppercase().parse(), Ok(hash)); + // Exactly 64 hex digits and nothing else, so also no whitespace + // between them, which systemd passes over. + let spaced = "2cf2 4dba 5fb0 a30e 26e8 3b2a c5b9 e29e 1b16 1e5c 1fa7 425e 7304 3362 938b 9824"; + for text in [ + "", + "00", + &hex[1..], + &format!("{}0", hex), + &format!("{}00", hex), + &"zz".repeat(32), + spaced, + &format!(" {}", hex), + &format!("{}\n", hex), + &format!("{}\t{}", &hex[..32], &hex[32..]), + &format!("{} {}", &hex[..31], &hex[32..]), + &format!("+{}", &hex[1..]), + &format!("0x{}", &hex[2..]), + ] { + assert_eq!(text.parse::(), Err(InvalidDigest(())), "{:?}", text); + } + assert_eq!(Sha256::from(*hash.as_bytes()), hash); + assert_eq!(<[u8; 32]>::from(hash), *hash.as_bytes()); + assert_eq!(hash.as_ref(), &hash.as_bytes()[..]); + } +} diff --git a/src/uapi16/hex.rs b/src/uapi16/hex.rs new file mode 100644 index 0000000..77f99b5 --- /dev/null +++ b/src/uapi16/hex.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Hex, the way a manifest spells hashes and the key of a signature. + +use std::fmt; + +/// The bits of one hex digit. +const DIGIT_BITS: u32 = 4; +/// The digits one byte takes. +const DIGITS_PER_BYTE: usize = 2; +/// The digits, as they are written. +const DIGITS: &[u8; 1 << DIGIT_BITS] = b"0123456789abcdef"; +/// How many bytes are formatted at a time. +const CHUNK: usize = 32; + +/// Bytes that print as lower case hex. +pub(crate) struct Hex<'a>(pub(crate) &'a [u8]); + +impl Hex<'_> { + /// The value of a hex digit of either case. + fn value(digit: u8) -> Option { + // The value of a digit is less than 16, so it fits. + char::from(digit).to_digit(1 << DIGIT_BITS).map(|value| value as u8) + } + + /// The values of the bytes of `text` as hex digits, one for each byte. + /// A byte that is not a hex digit, whitespace too, is None. + fn values(text: &str) -> impl Iterator> + '_ { + text.bytes().map(Hex::value) + } + + /// Decodes the `N` bytes `text` spells, two hex digits for each. Fewer + /// or more digits, or anything that is not a digit, are None. + pub(crate) fn decode_array(text: &str) -> Option<[u8; N]> { + let mut out = [0u8; N]; + let mut values = Hex::values(text); + for byte in &mut out { + *byte = (values.next()?? << DIGIT_BITS) | values.next()??; + } + values.next().is_none().then_some(out) + } +} + +impl fmt::Display for Hex<'_> { + /// The digits come from a table, a chunk of bytes at a time: writing + /// each byte with `{:02x}` is twenty times slower. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut text = [0u8; CHUNK * DIGITS_PER_BYTE]; + for chunk in self.0.chunks(CHUNK) { + for (digits, byte) in text.chunks_exact_mut(DIGITS_PER_BYTE).zip(chunk) { + digits[0] = DIGITS[usize::from(byte >> DIGIT_BITS)]; + digits[1] = DIGITS[usize::from(*byte) % DIGITS.len()]; + } + let text = &text[..chunk.len() * DIGITS_PER_BYTE]; + f.write_str(std::str::from_utf8(text).expect("ASCII"))?; + } + Ok(()) + } +} diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 69e33bd..d4dc2f3 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -14,8 +14,11 @@ #![deny(unsafe_code)] #![warn(missing_docs)] +mod digest; +mod hex; mod name; +pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; pub use name::{InvalidName, Name}; /// The name of a manifest that is stored in the tree it describes. From 8ecdc41e97abd09d8370d7cc4fa89606e3602eaa Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 06/19] uapi16: add the objects of a manifest Add the types for what a manifest is made of. RootObject is the root file object, FileObject a file object, Contents a contents object and Signature a signature object. The root file object and the file objects don't carry the same fields. Only the root has fsUUID, fsLabel, fatSerial, gptDiskUuid, order and features. And the root has no name and is a directory, so it has no inodeToken and no device numbers, and the specification gives it neither the gpt fields of a partition nor the DOS attributes. It has no size, sha256 or contents either. That's our reading of the specification rather than something it says outright, and systemd's reader takes them on the root. But where a directory has a sub-manifest of its own, the fields that refer to the sub-manifest itself, such as size, contents and sha256, go on the dir object of the outer manifest, and the root file object of the sub-manifest may repeat the inode attributes of the directory. So on a root these fields have nothing to refer to. A single type with every field would let the root carry everything a file object can and a file object everything the root can, and the reader would have to catch both at runtime. So let's give each of them a type of its own. What they share is split out. In that same paragraph about sub-manifests the specification calls mode, uid, gid, userName, groupName, mTimeNSec and extendedAttributes the inode attributes of the directory. InodeAttributes holds those, plus readOnly and the Linux inode flags, which the root may have as well. validSinceUSec, validUntilUSec and validity aren't inode attributes but both objects have them too, and on the root they cover the whole manifest. They go into ValidityWindow. RootObject and FileObject embed both. Note that there's no embedding in Rust that would let object.mode work for a field of the embedded struct. Deref to the inner struct is the known anti-pattern: it doesn't allow split borrows of object.name and object.mode, struct literals or patterns with those fields don't work, and there can only be one target. So access is spelled out as object.inode.mode and root.inode.mtime_nsec. The fields get types that only hold what the specification allows: - InodeType for type. - Mode for mode, which takes the permission bits, setuid, setgid and the sticky bit and nothing else. - Uuid for fsUUID and the gpt UUIDs. It prints the text form of RFC 9562, and parses that form in either case as well as 32 hex digits without the hyphens, both optionally with "urn:uuid:" in front. The groups of the text form are named after the fields of a version 1 UUID instead of being bare numbers. - DosFlags for the DOS attributes hidden, system and archive, which only a file object has, and InodeFlags for the Linux inode flags. FlagStates says for every flag of one kind whether an object has it set, cleared, or doesn't say. - GptPartition for the gpt fields that describe a regular file as a partition. GptPartition::FLAG_READ_ONLY is the bit of gptFlags that readOnly stands for. - FatSerial for fatSerial, written as 1234-ABCD. FileSystemIdentity::volume_serial() takes fatSerial or else derives the serial number from the first four bytes of fsUUID, as the specification asks. - Validity for validity, and Validity::as_str() for its value in a manifest. Features is the set of features a manifest records, which the features field of the root file object lists by the names of the specification. That includes the features upstream added for readOnly, fsUUID, fsLabel, fatSerial and each of the gpt fields (cf. [1]). Without the field a manifest records what the specification says: device, gid, hardlink, mode, sha256, size, symlink and uid. Only the names of the specification parse. "hash", which systemd-manifest make takes for sha256 on its command line, isn't one of them. RootObject::stated_features() and FileObject::stated_features() say which features the fields of an object belong to, which is what has to be checked against the features of its manifest. Order is the value of the order field, and "codepoint" is the only one the specification defines. InodeAttributes::is_read_only() says whether a file gets the read-only attribute in a file system with DOS attributes, such as FAT: readOnly, or else derived from mode. The specification allows deriving it from mode for the DOS attribute only, and only where the manifest doesn't list the read-only feature. Where it does, an object without readOnly isn't read-only, and a reader fills that in. The read-only flag of a GPT partition is readOnly alone. check_validity() checks validity, validSinceUSec and validUntilUSec against a point in time: those of a file object, or on the root file object those of the whole manifest. FileObject::filled_in and Contents::filled_in mark the sizes and hashes a reader filled in because they follow from other fields, so that a writer can leave them out again. Whoever sets such a field takes it out of filled_in. FileSystemIdentity::is_valid_label() says which labels a manifest can carry in fsLabel. Error is the error of the crate. Its kind says what went wrong, and the error names the number of the record, the file object and the field it is about wherever that's known. All of it lives behind a single allocation so a Result stays small. Field names every field of every object as the manifest spells it, in Field::as_str() and nowhere else. [1]: https://github.com/uapi-group/specifications/commit/1eb019da9ae71155d8514865e7ea712c1ffeab32 Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 1 + src/uapi16/Cargo.toml | 1 + src/uapi16/error.rs | 335 +++++++++ src/uapi16/features.rs | 376 ++++++++++ src/uapi16/lib.rs | 16 + src/uapi16/object.rs | 1621 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 2350 insertions(+) create mode 100644 src/uapi16/error.rs create mode 100644 src/uapi16/features.rs create mode 100644 src/uapi16/object.rs diff --git a/Cargo.lock b/Cargo.lock index bfbf5b5..68a646d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -152,6 +152,7 @@ name = "uapi16" version = "0.1.0" dependencies = [ "json", + "libc", "sha2", ] diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index 68f9041..bec37f0 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -13,6 +13,7 @@ path = "lib.rs" [dependencies] json.workspace = true +libc.workspace = true sha2.workspace = true [lints] diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs new file mode 100644 index 0000000..6b6bdd0 --- /dev/null +++ b/src/uapi16/error.rs @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The error of this crate. + +use std::fmt; +use std::io; + +/// Why a file object must not be used now. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Invalid { + /// Its `validity` is `revoked`. + Revoked, + /// The time is before its `validSinceUSec`. + NotYetValid, + /// The time is not before its `validUntilUSec`. + Expired, +} + +/// What kind of error an [`Error`] is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ErrorKind { + /// A file object is revoked or outside its validity window. + NotValid(Invalid), + /// Reading or writing failed. + Io, +} + +/// A field of an object of a manifest. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Field { + /// `name` of a file object. + Name, + /// `mediaType` of any object. + MediaType, + /// `type` of a file object. + Type, + /// `size` of a file object. + Size, + /// `mode` of a file object. + Mode, + /// `uid` of a file object. + Uid, + /// `gid` of a file object. + Gid, + /// `userName` of a file object. + UserName, + /// `groupName` of a file object. + GroupName, + /// `major` of a file object. + Major, + /// `minor` of a file object. + Minor, + /// `mTimeNSec` of a file object. + MTimeNSec, + /// `inodeToken` of a file object. + InodeToken, + /// `extendedAttributes` of a file object. + ExtendedAttributes, + /// `gptLabel` of a file object. + GptLabel, + /// `gptUuid` of a file object. + GptUuid, + /// `gptTypeUuid` of a file object. + GptTypeUuid, + /// `gptDiskUuid` of the root file object. + GptDiskUuid, + /// `gptFlags` of a file object. + GptFlags, + /// `gptFlagNoAuto` of a file object. + GptFlagNoAuto, + /// `gptFlagGrowFileSystem` of a file object. + GptFlagGrowFileSystem, + /// `readOnly` of a file object. + ReadOnly, + /// `flagHidden` of a file object. + FlagHidden, + /// `flagSystem` of a file object. + FlagSystem, + /// `flagArchive` of a file object. + FlagArchive, + /// `flagAppendOnly` of a file object. + FlagAppendOnly, + /// `flagImmutable` of a file object. + FlagImmutable, + /// `flagNoAtime` of a file object. + FlagNoAtime, + /// `flagNoCow` of a file object. + FlagNoCow, + /// `flagNoDump` of a file object. + FlagNoDump, + /// `fatSerial` of the root file object. + FatSerial, + /// `fsUUID` of the root file object. + FsUuid, + /// `fsLabel` of the root file object. + FsLabel, + /// `order` of the root file object. + Order, + /// `features` of the root file object. + Features, + /// `contents` of a file object. + Contents, + /// `sha256` of a file object. + Sha256, + /// `validSinceUSec` of a file object. + ValidSinceUSec, + /// `validUntilUSec` of a file object. + ValidUntilUSec, + /// `validity` of a file object. + Validity, + /// `file` of a contents object. + File, + /// `url` of a contents object. + Url, + /// `literal` of a contents object. + Literal, + /// `encoding` of a contents object. + Encoding, + /// `encodedSize` of a contents object. + EncodedSize, + /// `encodedSha256` of a contents object. + EncodedSha256, + /// `originalSize` of a contents object. + OriginalSize, + /// `originalSha256` of a contents object. + OriginalSha256, + /// `offset` of a contents object. + Offset, + /// `httpHeaders` of a contents object. + HttpHeaders, + /// `text` of the value of an extended attribute. + Text, + /// `base64` of the value of an extended attribute. + Base64, + /// `mechanism` of a signature object. + Mechanism, + /// `key` of a signature object. + Key, + /// `data` of a signature object. + Data, +} + +impl Field { + /// The field as its object spells it. + pub const fn as_str(self) -> &'static str { + match self { + Field::Name => "name", + Field::MediaType => "mediaType", + Field::Type => "type", + Field::Size => "size", + Field::Mode => "mode", + Field::Uid => "uid", + Field::Gid => "gid", + Field::UserName => "userName", + Field::GroupName => "groupName", + Field::Major => "major", + Field::Minor => "minor", + Field::MTimeNSec => "mTimeNSec", + Field::InodeToken => "inodeToken", + Field::ExtendedAttributes => "extendedAttributes", + Field::GptLabel => "gptLabel", + Field::GptUuid => "gptUuid", + Field::GptTypeUuid => "gptTypeUuid", + Field::GptDiskUuid => "gptDiskUuid", + Field::GptFlags => "gptFlags", + Field::GptFlagNoAuto => "gptFlagNoAuto", + Field::GptFlagGrowFileSystem => "gptFlagGrowFileSystem", + Field::ReadOnly => "readOnly", + Field::FlagHidden => "flagHidden", + Field::FlagSystem => "flagSystem", + Field::FlagArchive => "flagArchive", + Field::FlagAppendOnly => "flagAppendOnly", + Field::FlagImmutable => "flagImmutable", + Field::FlagNoAtime => "flagNoAtime", + Field::FlagNoCow => "flagNoCow", + Field::FlagNoDump => "flagNoDump", + Field::FatSerial => "fatSerial", + Field::FsUuid => "fsUUID", + Field::FsLabel => "fsLabel", + Field::Order => "order", + Field::Features => "features", + Field::Contents => "contents", + Field::Sha256 => "sha256", + Field::ValidSinceUSec => "validSinceUSec", + Field::ValidUntilUSec => "validUntilUSec", + Field::Validity => "validity", + Field::File => "file", + Field::Url => "url", + Field::Literal => "literal", + Field::Encoding => "encoding", + Field::EncodedSize => "encodedSize", + Field::EncodedSha256 => "encodedSha256", + Field::OriginalSize => "originalSize", + Field::OriginalSha256 => "originalSha256", + Field::Offset => "offset", + Field::HttpHeaders => "httpHeaders", + Field::Text => "text", + Field::Base64 => "base64", + Field::Mechanism => "mechanism", + Field::Key => "key", + Field::Data => "data", + } + } +} + +impl fmt::Display for Field { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// What an error was caused by. +#[derive(Debug)] +enum Cause { + Io(io::Error), +} + +/// What went wrong reading a manifest, or using one. +/// +/// [`Error::kind`] says what kind of error it is. The other methods say +/// what it is about, as far as that is known: the record of the manifest, +/// the name of the file object, the field. The error prints as a sentence +/// for a person. +/// +/// The parts live behind one allocation, like those of [`io::Error`], so +/// that a `Result` stays small. +#[derive(Debug)] +pub struct Error(Box); + +#[derive(Debug)] +struct Inner { + kind: ErrorKind, + message: String, + record_number: Option, + name: Option, + field: Option, + cause: Option, +} + +impl Error { + pub(crate) fn new(kind: ErrorKind, message: String) -> Error { + Error(Box::new(Inner { + kind, + message, + record_number: None, + name: None, + field: None, + cause: None, + })) + } + + /// Names the file object the error is about. + #[must_use] + pub(crate) fn named(mut self, name: impl Into) -> Error { + self.0.name = Some(name.into()); + self + } + + /// Notes the I/O error behind this one. + #[must_use] + pub(crate) fn caused_by(mut self, error: io::Error) -> Error { + self.0.cause = Some(Cause::Io(error)); + self + } +} + +impl Error { + /// What kind of error this is. + pub fn kind(&self) -> ErrorKind { + self.0.kind + } + + /// The number of the record the error is about, counting from 0. + pub fn record_number(&self) -> Option { + self.0.record_number + } + + /// The name of the file object the error is about, as its record has + /// it. The name can be the very thing that is wrong. + pub fn name(&self) -> Option<&str> { + self.0.name.as_deref() + } + + /// The field the error is about. + pub fn field(&self) -> Option { + self.0.field + } + + /// The I/O error behind this one, if there is one. + pub fn io_error(&self) -> Option<&io::Error> { + match &self.0.cause { + Some(Cause::Io(e)) => Some(e), + _ => None, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match (&self.0.kind, &self.0.cause) { + (ErrorKind::Io, Some(Cause::Io(e))) => e.fmt(f), + _ => f.write_str(&self.0.message), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match &self.0.cause { + Some(Cause::Io(e)) => Some(e), + None => None, + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Error { + Error::new(ErrorKind::Io, String::new()).caused_by(e) + } +} + +impl From for io::Error { + /// An I/O error comes back as it went in. Any other error becomes + /// the payload of an I/O error of the kind `InvalidData`. + fn from(e: Error) -> io::Error { + match *e.0 { + Inner { + kind: ErrorKind::Io, + cause: Some(Cause::Io(e)), + .. + } => e, + inner => io::Error::new(io::ErrorKind::InvalidData, Error(Box::new(inner))), + } + } +} diff --git a/src/uapi16/features.rs b/src/uapi16/features.rs new file mode 100644 index 0000000..3ab9ada --- /dev/null +++ b/src/uapi16/features.rs @@ -0,0 +1,376 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! What a manifest says about itself in its root file object: the features +//! it records and the order it lists its file objects in. + +use std::fmt; +use std::ops::{BitAnd, BitOr, BitOrAssign}; +use std::str::FromStr; + +/// The file system and partition table features a manifest records, which +/// its root file object lists in the field `features`. +/// +/// A feature stands for fields of the file objects and of the root file +/// object: `mtime` for `mTimeNSec`, `device` for `major` and `minor`, +/// `fs-uuid` for `fsUUID`. An object carries the fields of the features its +/// manifest lists and no others. For some features the list also says what +/// a missing field means: with [`Features::HARDLINK`] a file object without +/// an `inodeToken` is not a hard link of another one, with +/// [`Features::USER_XATTR`] one without extended attributes has none, and +/// with [`Features::FS_LABEL`] a root file object without `fsLabel` is for +/// a file system without a label. With [`Features::GPT_FLAGS`] a partition +/// without `gptFlags` has all its attribute flags cleared, and with +/// [`Features::READ_ONLY`] or the feature of a single flag, such as +/// [`Features::FLAG_HIDDEN`] or [`Features::GPT_FLAG_NO_AUTO`], an object +/// without the field has that flag cleared. Where the list doesn't name the +/// feature, nothing is known about these properties. +/// +/// A manifest that does not list its features records +/// [`Features::DEFAULT`], what `systemd-manifest make` records unless it +/// is told otherwise. +/// +/// ``` +/// use uapi16::Features; +/// +/// let features = Features::SIZE | Features::SHA256; +/// assert!(features.contains(Features::SIZE) && !features.contains(Features::MTIME)); +/// assert_eq!(Features::from_names(["size", "sha256"]), Ok(features)); +/// assert_eq!(features.names().collect::>(), ["sha256", "size"]); +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Features(u32); + +/// A name that is not the name of a feature, see [`Features`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UnknownFeature(()); + +impl fmt::Display for UnknownFeature { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not a feature of a manifest") + } +} + +impl std::error::Error for UnknownFeature {} + +impl Features { + /// `mode`: the access mode, the field `mode`. + pub const MODE: Features = Features(1 << 0); + /// `uid`: the owning user, the field `uid`. + pub const UID: Features = Features(1 << 1); + /// `gid`: the owning group, the field `gid`. + pub const GID: Features = Features(1 << 2); + /// `user-name`: the name of the owning user, the field `userName`. + pub const USER_NAME: Features = Features(1 << 3); + /// `group-name`: the name of the owning group, the field `groupName`. + pub const GROUP_NAME: Features = Features(1 << 4); + /// `size`: the size of the contents, the field `size`. + pub const SIZE: Features = Features(1 << 5); + /// `sha256`: the hash of the contents, the field `sha256`. + pub const SHA256: Features = Features(1 << 6); + /// `symlink`: the targets of symbolic links, the field `contents` of + /// file objects of the type `lnk`. Every one of them has its target in + /// `contents` then, as a literal. + pub const SYMLINK: Features = Features(1 << 7); + /// `device`: the numbers of device nodes, the fields `major` and + /// `minor`. + pub const DEVICE: Features = Features(1 << 8); + /// `hardlink`: which file objects are names of one file, the field + /// `inodeToken`. + pub const HARDLINK: Features = Features(1 << 9); + /// `mtime`: the modification time, the field `mTimeNSec`. + pub const MTIME: Features = Features(1 << 10); + /// `user-xattr`: the extended attributes of the `user` namespace, the + /// key `user` of the field `extendedAttributes`. + pub const USER_XATTR: Features = Features(1 << 11); + /// `flag-hidden`: the DOS attribute hidden, the field `flagHidden`. + pub const FLAG_HIDDEN: Features = Features(1 << 12); + /// `flag-system`: the DOS attribute system, the field `flagSystem`. + pub const FLAG_SYSTEM: Features = Features(1 << 13); + /// `flag-archive`: the DOS attribute archive, the field `flagArchive`. + pub const FLAG_ARCHIVE: Features = Features(1 << 14); + /// `flag-append-only`: the inode flag append only, the field + /// `flagAppendOnly`. + pub const FLAG_APPEND_ONLY: Features = Features(1 << 15); + /// `flag-immutable`: the inode flag immutable, the field + /// `flagImmutable`. + pub const FLAG_IMMUTABLE: Features = Features(1 << 16); + /// `flag-no-atime`: the inode flag no atime updates, the field + /// `flagNoAtime`. + pub const FLAG_NO_ATIME: Features = Features(1 << 17); + /// `flag-no-cow`: the inode flag no copy on write, the field + /// `flagNoCow`. + pub const FLAG_NO_COW: Features = Features(1 << 18); + /// `flag-no-dump`: the inode flag no dump, the field `flagNoDump`. + pub const FLAG_NO_DUMP: Features = Features(1 << 19); + /// `read-only`: whether a file is read-only, the field `readOnly`. + pub const READ_ONLY: Features = Features(1 << 20); + /// `fs-uuid`: the UUID of the file system, the field `fsUUID`. + pub const FS_UUID: Features = Features(1 << 21); + /// `fs-label`: the label of the file system, the field `fsLabel`. + pub const FS_LABEL: Features = Features(1 << 22); + /// `fat-serial`: the volume serial number of a FAT or exFAT file + /// system, the field `fatSerial`. + pub const FAT_SERIAL: Features = Features(1 << 23); + /// `gpt-label`: the label of a partition, the field `gptLabel`. + pub const GPT_LABEL: Features = Features(1 << 24); + /// `gpt-uuid`: the UUID of a partition, the field `gptUuid`. + pub const GPT_UUID: Features = Features(1 << 25); + /// `gpt-type-uuid`: the type UUID of a partition, the field + /// `gptTypeUuid`. + pub const GPT_TYPE_UUID: Features = Features(1 << 26); + /// `gpt-disk-uuid`: the disk UUID of the partition table, the field + /// `gptDiskUuid`. + pub const GPT_DISK_UUID: Features = Features(1 << 27); + /// `gpt-flags`: the attribute flags of a partition, the field + /// `gptFlags`. + pub const GPT_FLAGS: Features = Features(1 << 28); + /// `gpt-flag-no-auto`: the partition attribute flag no auto, the field + /// `gptFlagNoAuto`. + pub const GPT_FLAG_NO_AUTO: Features = Features(1 << 29); + /// `gpt-flag-grow-file-system`: the partition attribute flag grow file + /// system, the field `gptFlagGrowFileSystem`. + pub const GPT_FLAG_GROW_FILE_SYSTEM: Features = Features(1 << 30); + + /// No feature: the file objects carry names, inode types and the + /// fields that belong to no feature. + pub const NONE: Features = Features(0); + /// What a manifest records that does not list its features, as the + /// specification says: the access mode, the owner, size and hash, the + /// targets of symbolic links, device numbers and hard links. + pub const DEFAULT: Features = Features( + Features::DEVICE.0 + | Features::GID.0 + | Features::HARDLINK.0 + | Features::MODE.0 + | Features::SHA256.0 + | Features::SIZE.0 + | Features::SYMLINK.0 + | Features::UID.0, + ); + /// Every feature. + pub const ALL: Features = Features((1 << Features::NAMES.len()) - 1); + + /// Every single feature with its name, in the order of the names. + const NAMES: [(Features, &'static str); 31] = [ + (Features::DEVICE, "device"), + (Features::FAT_SERIAL, "fat-serial"), + (Features::FLAG_APPEND_ONLY, "flag-append-only"), + (Features::FLAG_ARCHIVE, "flag-archive"), + (Features::FLAG_HIDDEN, "flag-hidden"), + (Features::FLAG_IMMUTABLE, "flag-immutable"), + (Features::FLAG_NO_ATIME, "flag-no-atime"), + (Features::FLAG_NO_COW, "flag-no-cow"), + (Features::FLAG_NO_DUMP, "flag-no-dump"), + (Features::FLAG_SYSTEM, "flag-system"), + (Features::FS_LABEL, "fs-label"), + (Features::FS_UUID, "fs-uuid"), + (Features::GID, "gid"), + (Features::GPT_DISK_UUID, "gpt-disk-uuid"), + (Features::GPT_FLAG_GROW_FILE_SYSTEM, "gpt-flag-grow-file-system"), + (Features::GPT_FLAG_NO_AUTO, "gpt-flag-no-auto"), + (Features::GPT_FLAGS, "gpt-flags"), + (Features::GPT_LABEL, "gpt-label"), + (Features::GPT_TYPE_UUID, "gpt-type-uuid"), + (Features::GPT_UUID, "gpt-uuid"), + (Features::GROUP_NAME, "group-name"), + (Features::HARDLINK, "hardlink"), + (Features::MODE, "mode"), + (Features::MTIME, "mtime"), + (Features::READ_ONLY, "read-only"), + (Features::SHA256, "sha256"), + (Features::SIZE, "size"), + (Features::SYMLINK, "symlink"), + (Features::UID, "uid"), + (Features::USER_NAME, "user-name"), + (Features::USER_XATTR, "user-xattr"), + ]; + + /// Whether every feature of `features` is among these. + pub const fn contains(self, features: Features) -> bool { + self.0 & features.0 == features.0 + } + + /// These features without those of `features`. + #[must_use] + pub const fn without(self, features: Features) -> Features { + Features(self.0 & !features.0) + } + + /// These features and those of `features`. + #[must_use] + pub const fn union(self, features: Features) -> Features { + Features(self.0 | features.0) + } + + /// The features with the names `names`, the names the specification + /// has for them. + pub fn from_names<'a>(names: impl IntoIterator) -> Result { + names + .into_iter() + .try_fold(Features::NONE, |features, name| Ok(features | name.parse()?)) + } + + /// The names of the features as the specification has them, in the + /// order of the strings, as `features` lists them. + pub fn names(self) -> impl Iterator { + Features::NAMES + .iter() + .filter(move |(feature, _)| self.contains(*feature)) + .map(|&(_, name)| name) + } + + /// Takes the name of a feature from the list of a manifest: one of the + /// names of the specification. A name the specification does not have + /// is None, which a reader passes over. + pub(crate) fn listed(name: &str) -> Option { + Features::NAMES + .into_iter() + .find(|(_, known)| *known == name) + .map(|(feature, _)| feature) + } +} + +impl Default for Features { + /// [`Features::DEFAULT`]. + fn default() -> Features { + Features::DEFAULT + } +} + +impl BitOr for Features { + type Output = Features; + + fn bitor(self, other: Features) -> Features { + Features(self.0 | other.0) + } +} + +impl BitOrAssign for Features { + fn bitor_assign(&mut self, other: Features) { + self.0 |= other.0; + } +} + +impl BitAnd for Features { + type Output = Features; + + /// The features both have, those a tool that combines two manifests + /// can keep. + fn bitand(self, other: Features) -> Features { + Features(self.0 & other.0) + } +} + +impl FromStr for Features { + type Err = UnknownFeature; + + /// The one feature with the name `name`, as the specification names + /// it. + fn from_str(name: &str) -> Result { + Features::listed(name).ok_or(UnknownFeature(())) + } +} + +impl fmt::Debug for Features { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Features(")?; + for (i, name) in self.names().enumerate() { + if i > 0 { + f.write_str(" | ")?; + } + f.write_str(name)?; + } + f.write_str(")") + } +} + +/// The order a manifest lists its file objects in, which its root file +/// object declares in the field `order`. +/// +/// A manifest that declares an order keeps to it, and a reader that relies +/// on it checks it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Order { + /// `codepoint`: the names of the file objects strictly increase in the + /// order of [`Name`](crate::Name). + CodePoint, +} + +impl Order { + /// The value of `order` that declares this order. + pub const fn as_str(self) -> &'static str { + match self { + Order::CodePoint => "codepoint", + } + } +} + +impl fmt::Display for Order { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + // The names are in the order of the strings, as `features` lists + // them, and every feature has one. + let names: Vec<&str> = Features::ALL.names().collect(); + let mut sorted = names.clone(); + sorted.sort_unstable(); + assert_eq!(names, sorted); + assert_eq!(names.len(), Features::NAMES.len()); + assert_eq!(Features::from_names(names.iter().copied()), Ok(Features::ALL)); + for (feature, name) in Features::NAMES { + assert_eq!(name.parse(), Ok(feature)); + assert_eq!(Features::listed(name), Some(feature)); + assert_eq!(feature.names().collect::>(), [name]); + } + assert_eq!(Features::from_names([]), Ok(Features::NONE)); + assert_eq!(Features::NONE.names().count(), 0); + // Only the names of the specification, not the word systemd-manifest + // has for sha256 on its command line. + for unknown in [ + "", + "Mode", + "userXattr", + "user_xattr", + "flag-hidden ", + "x", + "hash", + "readOnly", + "gpt-flag", + ] { + assert_eq!(unknown.parse::(), Err(UnknownFeature(())), "{:?}", unknown); + assert_eq!(Features::listed(unknown), None, "{:?}", unknown); + } + assert_eq!(Features::from_names(["size", "hash"]), Err(UnknownFeature(()))); + } + + #[test] + fn the_default() { + assert_eq!( + Features::DEFAULT.names().collect::>(), + ["device", "gid", "hardlink", "mode", "sha256", "size", "symlink", "uid"] + ); + assert_eq!(Features::default(), Features::DEFAULT); + } + + #[test] + fn sets() { + let some = Features::from_names(["size", "sha256", "mtime", "size"]).unwrap(); + assert_eq!(some, Features::SIZE | Features::SHA256 | Features::MTIME); + assert!(some.contains(Features::SIZE) && some.contains(Features::SIZE | Features::MTIME)); + assert!(!some.contains(Features::MODE) && !some.contains(Features::SIZE | Features::MODE)); + assert!(some.contains(Features::NONE) && Features::NONE.contains(Features::NONE)); + assert_eq!(some & Features::DEFAULT, Features::SIZE | Features::SHA256); + let mut more = some; + more |= Features::MODE; + assert_eq!(more, some | Features::MODE); + assert_eq!(format!("{:?}", some), "Features(mtime | sha256 | size)"); + } +} diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index d4dc2f3..d3b2691 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -9,17 +9,33 @@ //! objects can come after the file objects, and a trailer object ends the //! manifest. //! +//! - [`RootObject`], [`FileObject`], [`Contents`] and [`Signature`] are the +//! objects, and [`Name`], [`InodeType`], [`Mode`], [`DosFlags`], +//! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What +//! the root file object and a file object both have is in +//! [`InodeAttributes`] and [`ValidityWindow`]. +//! //! [UAPI.16 file manifest]: https://uapi-group.org/specifications/specs/file_manifest/ #![deny(unsafe_code)] #![warn(missing_docs)] mod digest; +mod error; +mod features; mod hex; mod name; +mod object; pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; +pub use error::{Error, ErrorKind, Field, Invalid}; +pub use features::{Features, Order, UnknownFeature}; pub use name::{InvalidName, Name}; +pub use object::{ + Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, GptPartition, InodeAttributes, + InodeFlags, InodeType, InvalidFatSerial, InvalidUuid, Location, Mode, RootObject, Signature, UnknownInodeType, + Uuid, Validity, ValidityWindow, +}; /// The name of a manifest that is stored in the tree it describes. pub const FILENAME: &str = "Uapi16Manifest"; diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs new file mode 100644 index 0000000..f6b7218 --- /dev/null +++ b/src/uapi16/object.rs @@ -0,0 +1,1621 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The objects of a manifest. + +use std::collections::BTreeMap; +use std::fmt; +use std::num::NonZeroU64; +use std::ops::{BitAnd, BitOr, Not}; +use std::str::FromStr; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::error::{Error, ErrorKind, Field, Invalid}; +use crate::hex::Hex; +use crate::{Features, Name, Order, Sha256, STRING_RULES}; + +/// The inode type of a file object, its `type` field. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum InodeType { + /// `reg`: a regular file. + Regular, + /// `dir`: a directory. + Directory, + /// `lnk`: a symbolic link. + Symlink, + /// `fifo`: a FIFO. + Fifo, + /// `chr`: a character device node. + CharDevice, + /// `blk`: a block device node. + BlockDevice, + /// `sock`: a socket. + Socket, +} + +/// A string that is not the name of an inode type. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UnknownInodeType(()); + +impl fmt::Display for UnknownInodeType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not an inode type") + } +} + +impl std::error::Error for UnknownInodeType {} + +impl InodeType { + /// The name the type has in a manifest. + pub const fn as_str(self) -> &'static str { + match self { + InodeType::Regular => "reg", + InodeType::Directory => "dir", + InodeType::Symlink => "lnk", + InodeType::Fifo => "fifo", + InodeType::CharDevice => "chr", + InodeType::BlockDevice => "blk", + InodeType::Socket => "sock", + } + } + + /// Whether an object of this type has contents: a regular file its + /// data, a symbolic link its target and a directory a manifest of its + /// own. Only such an object has a size, contents objects and a hash. + pub const fn has_contents(self) -> bool { + matches!(self, InodeType::Regular | InodeType::Symlink | InodeType::Directory) + } + + /// Whether this is a device node, which has a major and a minor + /// number. + pub const fn is_device(self) -> bool { + matches!(self, InodeType::CharDevice | InodeType::BlockDevice) + } +} + +impl fmt::Display for InodeType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl FromStr for InodeType { + type Err = UnknownInodeType; + + fn from_str(name: &str) -> Result { + Ok(match name { + "reg" => InodeType::Regular, + "dir" => InodeType::Directory, + "lnk" => InodeType::Symlink, + "fifo" => InodeType::Fifo, + "chr" => InodeType::CharDevice, + "blk" => InodeType::BlockDevice, + "sock" => InodeType::Socket, + _ => return Err(UnknownInodeType(())), + }) + } +} + +/// The access mode of a file object, its `mode` field: the permission +/// bits with the set-user-ID, the set-group-ID and the sticky bit. +/// +/// ``` +/// use uapi16::Mode; +/// +/// let mode = Mode::new(0o644).unwrap(); +/// assert!(mode.is_writable()); +/// assert!(!Mode::new(0o444).unwrap().is_writable()); +/// assert_eq!(Mode::new(0o10000), None); +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Mode(u32); + +impl Mode { + /// Every bit a mode can have. + const ALL: u32 = libc::S_ISUID | libc::S_ISGID | libc::S_ISVTX | libc::S_IRWXU | libc::S_IRWXG | libc::S_IRWXO; + /// The write permission of the owner, of the group and of everybody + /// else. + const WRITE: u32 = libc::S_IWUSR | libc::S_IWGRP | libc::S_IWOTH; + + /// The mode with the bits `bits`, unless there are others among them + /// than a mode has. + pub const fn new(bits: u32) -> Option { + if bits & !Mode::ALL == 0 { + Some(Mode(bits)) + } else { + None + } + } + + /// The bits of the mode. + pub const fn bits(self) -> u32 { + self.0 + } + + /// Whether anybody has write permission. + pub const fn is_writable(self) -> bool { + self.0 & Mode::WRITE != 0 + } +} + +impl From for u32 { + fn from(mode: Mode) -> u32 { + mode.0 + } +} + +impl fmt::Debug for Mode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Mode({:#o})", self.0) + } +} + +/// The `validity` field of a file object. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Validity { + /// `good`, and any value the specification adds later. + #[default] + Good, + /// `revoked`: the file is not to be used anymore. + Revoked, +} + +impl Validity { + /// The value of `validity` that says this. + pub const fn as_str(self) -> &'static str { + match self { + Validity::Good => "good", + Validity::Revoked => "revoked", + } + } +} + +impl fmt::Display for Validity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// When a file may be used: from `validSinceUSec` on and before +/// `validUntilUSec`, unless `validity` says it is revoked. +/// +/// A file object and the root file object both have these fields. What is +/// true of a directory is true of everything in it, so the window of the +/// root file object is that of the whole manifest. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub struct ValidityWindow { + /// `validSinceUSec`: the file is not to be used before this time, in + /// microseconds since the epoch. + pub since_usec: u64, + /// `validUntilUSec`: the file is not to be used from this time on, in + /// microseconds since the epoch. + pub until_usec: Option, + /// `validity`: whether the file is revoked. + pub state: Validity, +} + +impl ValidityWindow { + /// Checks that what the window is of, which a message calls `subject`, + /// may be used at the time `now_usec`, in microseconds since the epoch: + /// that it is not revoked and that the time is inside the window. + fn check(&self, now_usec: u64, subject: impl fmt::Display) -> Result<(), Error> { + let (reason, state) = if self.state == Validity::Revoked { + (Invalid::Revoked, "is revoked") + } else if now_usec < self.since_usec { + (Invalid::NotYetValid, "is not valid yet") + } else if self.until_usec.is_some_and(|until| now_usec >= until) { + (Invalid::Expired, "has expired") + } else { + return Ok(()); + }; + Err(Error::new( + ErrorKind::NotValid(reason), + format!("{} {}", subject, state), + )) + } +} + +/// A UUID, as the `fsUUID`, `gptUuid`, `gptTypeUuid` and `gptDiskUuid` +/// fields carry one. +/// +/// It prints the way RFC 9562 writes it, in lower case. It parses from +/// that form in either case, from 32 hex digits without the hyphens, and +/// from both with `urn:uuid:` in front. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct Uuid([u8; Uuid::SIZE]); + +/// A string that is not a UUID. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidUuid(()); + +impl fmt::Display for InvalidUuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not a UUID") + } +} + +impl std::error::Error for InvalidUuid {} + +impl Uuid { + /// The size of a UUID in bytes. + pub const SIZE: usize = 16; + /// The bytes of the fields the text form writes as groups, which the + /// hyphens separate. They are named after the fields of the time-based + /// UUID, version 1 in RFC 9562, whose layout the text form follows. + const TIME_LOW: usize = 4; + const TIME_MID: usize = 2; + const TIME_HIGH_AND_VERSION: usize = 2; + const CLOCK_SEQ_AND_VARIANT: usize = 2; + const NODE: usize = 6; + const GROUPS: [usize; 5] = [ + Uuid::TIME_LOW, + Uuid::TIME_MID, + Uuid::TIME_HIGH_AND_VERSION, + Uuid::CLOCK_SEQ_AND_VARIANT, + Uuid::NODE, + ]; + /// What separates the groups. + const HYPHEN: u8 = b'-'; + /// What a UUID can have in front, in either case. + const URN: &'static str = "urn:uuid:"; + /// The hex digits of one byte. + const DIGITS_PER_BYTE: usize = 2; + + /// The UUID with the bytes `bytes`. + pub const fn new(bytes: [u8; Uuid::SIZE]) -> Uuid { + Uuid(bytes) + } + + /// The bytes of the UUID. + pub fn as_bytes(&self) -> &[u8; Uuid::SIZE] { + &self.0 + } +} + +impl fmt::Display for Uuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut rest = &self.0[..]; + for (i, &group) in Uuid::GROUPS.iter().enumerate() { + if i > 0 { + fmt::Write::write_char(f, char::from(Uuid::HYPHEN))?; + } + let (bytes, tail) = rest.split_at(group); + Hex(bytes).fmt(f)?; + rest = tail; + } + Ok(()) + } +} + +impl fmt::Debug for Uuid { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Uuid({})", self) + } +} + +impl FromStr for Uuid { + type Err = InvalidUuid; + + fn from_str(text: &str) -> Result { + // Compare bytes: the string comes from a manifest, and cutting it + // at a byte offset could cut a character. + let text = match text.as_bytes().split_at_checked(Uuid::URN.len()) { + Some((urn, rest)) if urn.eq_ignore_ascii_case(Uuid::URN.as_bytes()) => rest, + _ => text.as_bytes(), + }; + let mut digits = [0u8; Uuid::SIZE * Uuid::DIGITS_PER_BYTE]; + let hyphens = Uuid::GROUPS.len() - 1; + let hyphenated = text.len() == digits.len() + hyphens; + if !hyphenated && text.len() != digits.len() { + return Err(InvalidUuid(())); + } + // The digits without the hyphens between the groups. Anything else + // that is not a hex digit fails to decode. + let mut out = &mut digits[..]; + let mut rest = text; + for (i, &group) in Uuid::GROUPS.iter().enumerate() { + if hyphenated && i > 0 { + rest = rest.strip_prefix(&[Uuid::HYPHEN]).ok_or(InvalidUuid(()))?; + } + let (hex, tail) = rest + .split_at_checked(group * Uuid::DIGITS_PER_BYTE) + .ok_or(InvalidUuid(()))?; + let (group_digits, left) = out.split_at_mut(hex.len()); + group_digits.copy_from_slice(hex); + out = left; + rest = tail; + } + std::str::from_utf8(&digits) + .ok() + .and_then(Hex::decode_array) + .map(Uuid) + .ok_or(InvalidUuid(())) + } +} + +/// The `gpt` fields of a file object that describe a regular file as a +/// partition of a GPT partition table: those of its entry in the table. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct GptPartition { + /// `gptLabel`: the partition label, at most 36 UTF-16 units. + pub label: Option, + /// `gptUuid`: the partition UUID. + pub uuid: Option, + /// `gptTypeUuid`: the partition type UUID. + pub type_uuid: Option, + /// `gptFlags`: the attribute flags of the partition entry. + pub flags: Option, + /// `gptFlagNoAuto`: the flag of that name in the Discoverable + /// Partitions Specification, [`GptPartition::FLAG_NO_AUTO`]. + pub no_auto: Option, + /// `gptFlagGrowFileSystem`: the flag of that name in the Discoverable + /// Partitions Specification, [`GptPartition::FLAG_GROW_FILE_SYSTEM`]. + pub grow_file_system: Option, +} + +impl GptPartition { + /// The bits the flags of the Discoverable Partitions Specification + /// have in the attribute flags. + const NO_AUTO_BIT: u32 = 63; + const READ_ONLY_BIT: u32 = 60; + const GROW_FILE_SYSTEM_BIT: u32 = 59; + /// The flag `gptFlagNoAuto` mirrors in `gptFlags`. + pub const FLAG_NO_AUTO: u64 = 1 << GptPartition::NO_AUTO_BIT; + /// The flag `readOnly` mirrors in `gptFlags`. It has no `gptFlag` + /// field of its own. + pub const FLAG_READ_ONLY: u64 = 1 << GptPartition::READ_ONLY_BIT; + /// The flag `gptFlagGrowFileSystem` mirrors in `gptFlags`. + pub const FLAG_GROW_FILE_SYSTEM: u64 = 1 << GptPartition::GROW_FILE_SYSTEM_BIT; + /// The longest partition label, in UTF-16 units. + pub const LABEL_MAX: usize = 36; + + /// Whether any of the fields is set. Only a regular file describes a + /// partition. + pub fn describes_partition(&self) -> bool { + self.label.is_some() + || self.uuid.is_some() + || self.type_uuid.is_some() + || self.flags.is_some() + || self.no_auto.is_some() + || self.grow_file_system.is_some() + } +} + +/// A set of flags of one kind that the specification has a field for each: +/// [`DosFlags`] and [`InodeFlags`]. [`FlagStates`] says the states of the +/// flags of one kind. +/// +/// It is public only so that it can bound the methods of [`FlagStates`]. +/// The crate does not export it, so no other crate can name or implement +/// it. +pub trait FlagSet: + Copy + PartialEq + BitAnd + BitOr + Not + 'static +{ + /// Every single flag with its field and the feature that records it, in + /// the order of the names of the fields. + const FIELDS: &'static [(Self, Field, Features)]; +} + +/// What [`DosFlags`] and [`InodeFlags`] both have besides their flags: +/// `contains()`, `without()`, the operators of sets and a `Debug` that +/// lists the fields of the flags. +macro_rules! flag_set { + ($flags:ident) => { + impl $flags { + /// Whether every flag of `flags` is among these. + pub const fn contains(self, flags: $flags) -> bool { + self.0 & flags.0 == flags.0 + } + + /// These flags without those of `flags`. + #[must_use] + pub const fn without(self, flags: $flags) -> $flags { + $flags(self.0 & !flags.0) + } + } + + impl BitOr for $flags { + type Output = $flags; + + fn bitor(self, other: $flags) -> $flags { + $flags(self.0 | other.0) + } + } + + impl BitAnd for $flags { + type Output = $flags; + + fn bitand(self, other: $flags) -> $flags { + $flags(self.0 & other.0) + } + } + + impl Not for $flags { + type Output = $flags; + + /// The flags of this kind that are not among these. + fn not(self) -> $flags { + $flags::ALL.without(self) + } + } + + impl fmt::Debug for $flags { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(concat!(stringify!($flags), "("))?; + let fields = $flags::FIELDS.iter().filter(|(flag, _, _)| self.contains(*flag)); + for (i, (_, field, _)) in fields.enumerate() { + if i > 0 { + f.write_str(" | ")?; + } + f.write_str(field.as_str())?; + } + f.write_str(")") + } + } + }; +} + +/// The DOS attributes the specification has a field for, one each: hidden, +/// system and archive. +/// +/// They are the attributes of FAT, of exFAT and of file systems like them. +/// The read-only attribute has no field of its own. `readOnly` stands for +/// it, see [`InodeAttributes::read_only`]. Only regular files and +/// directories have DOS attributes, and the root directory has none: the +/// root directory of FAT has no directory entry to keep them in. +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct DosFlags(u8); + +impl DosFlags { + /// `flagHidden`: the DOS attribute `ATTR_HIDDEN`. + pub const HIDDEN: DosFlags = DosFlags(1 << 0); + /// `flagSystem`: the DOS attribute `ATTR_SYSTEM`. + pub const SYSTEM: DosFlags = DosFlags(1 << 1); + /// `flagArchive`: the DOS attribute `ATTR_ARCHIVE`. + pub const ARCHIVE: DosFlags = DosFlags(1 << 2); + + /// No DOS attribute. + pub const NONE: DosFlags = DosFlags(0); + /// Every DOS attribute. + pub const ALL: DosFlags = DosFlags(DosFlags::HIDDEN.0 | DosFlags::SYSTEM.0 | DosFlags::ARCHIVE.0); +} + +impl FlagSet for DosFlags { + const FIELDS: &'static [(DosFlags, Field, Features)] = &[ + (DosFlags::ARCHIVE, Field::FlagArchive, Features::FLAG_ARCHIVE), + (DosFlags::HIDDEN, Field::FlagHidden, Features::FLAG_HIDDEN), + (DosFlags::SYSTEM, Field::FlagSystem, Features::FLAG_SYSTEM), + ]; +} + +flag_set!(DosFlags); + +/// The Linux inode flags the specification has a field for, one each: +/// some of those `chattr(1)` changes. +/// +/// Only regular files and directories have them, the root directory among +/// them. +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct InodeFlags(u8); + +impl InodeFlags { + /// `flagAppendOnly`: the inode flag `FS_APPEND_FL`. + pub const APPEND_ONLY: InodeFlags = InodeFlags(1 << 0); + /// `flagImmutable`: the inode flag `FS_IMMUTABLE_FL`. + pub const IMMUTABLE: InodeFlags = InodeFlags(1 << 1); + /// `flagNoAtime`: the inode flag `FS_NOATIME_FL`. + pub const NO_ATIME: InodeFlags = InodeFlags(1 << 2); + /// `flagNoCow`: the inode flag `FS_NOCOW_FL`. + pub const NO_COW: InodeFlags = InodeFlags(1 << 3); + /// `flagNoDump`: the inode flag `FS_NODUMP_FL`. + pub const NO_DUMP: InodeFlags = InodeFlags(1 << 4); + + /// No inode flag. + pub const NONE: InodeFlags = InodeFlags(0); + /// Every inode flag. + pub const ALL: InodeFlags = InodeFlags( + InodeFlags::APPEND_ONLY.0 + | InodeFlags::IMMUTABLE.0 + | InodeFlags::NO_ATIME.0 + | InodeFlags::NO_COW.0 + | InodeFlags::NO_DUMP.0, + ); +} + +impl FlagSet for InodeFlags { + const FIELDS: &'static [(InodeFlags, Field, Features)] = &[ + ( + InodeFlags::APPEND_ONLY, + Field::FlagAppendOnly, + Features::FLAG_APPEND_ONLY, + ), + (InodeFlags::IMMUTABLE, Field::FlagImmutable, Features::FLAG_IMMUTABLE), + (InodeFlags::NO_ATIME, Field::FlagNoAtime, Features::FLAG_NO_ATIME), + (InodeFlags::NO_COW, Field::FlagNoCow, Features::FLAG_NO_COW), + (InodeFlags::NO_DUMP, Field::FlagNoDump, Features::FLAG_NO_DUMP), + ]; +} + +flag_set!(InodeFlags); + +/// What an object says about the flags of one kind, [`DosFlags`] or +/// [`InodeFlags`]: which of them it states, and which of those are set. +/// Nothing is known about the others. +/// +/// ``` +/// use uapi16::{DosFlags, FlagStates}; +/// +/// let mut states = FlagStates::default(); +/// states.put(DosFlags::HIDDEN, Some(true)); +/// states.put(DosFlags::ARCHIVE, Some(false)); +/// assert_eq!(states.get(DosFlags::HIDDEN), Some(true)); +/// assert_eq!(states.get(DosFlags::ARCHIVE), Some(false)); +/// assert_eq!(states.get(DosFlags::SYSTEM), None); +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct FlagStates { + /// The flags the object states. + pub stated: F, + /// Of those, the flags that are set. + pub set: F, +} + +impl FlagStates { + /// Whether `flag` is set, cleared, or not known. + pub fn get(self, flag: F) -> Option { + ((self.stated & flag) == flag).then_some((self.set & flag) == flag) + } + + /// States `flag` as set or cleared, or as not known. + pub fn put(&mut self, flag: F, state: Option) { + self.stated = self.stated & !flag; + self.set = self.set & !flag; + if let Some(set) = state { + self.stated = self.stated | flag; + if set { + self.set = self.set | flag; + } + } + } + + /// The fields of the flags the object states, each with the feature + /// that records it. + pub(crate) fn feature_fields(&self) -> impl Iterator + '_ { + F::FIELDS + .iter() + .filter(move |(flag, _, _)| (self.stated & *flag) == *flag) + .map(|&(_, field, feature)| (field, feature)) + } +} + +/// The fields of an object of a manifest that a reader filled in: the +/// sizes and hashes that follow from other fields, which the record of the +/// object does not have. A writer leaves them out. +/// +/// What is filled in is a size or a hash: the `size` and the `sha256` of a +/// [`FileObject`], and the sizes and hashes of a [`Contents`]. +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct FilledIn(u8); + +impl FilledIn { + /// The fields that can be filled in, in the order of their bits. + const FIELDS: [Field; 6] = [ + Field::Size, + Field::Sha256, + Field::EncodedSize, + Field::EncodedSha256, + Field::OriginalSize, + Field::OriginalSha256, + ]; + + /// The bit of `field`, none for one that cannot be filled in. + fn bit(field: Field) -> u8 { + FilledIn::FIELDS + .iter() + .position(|&fillable| fillable == field) + .map_or(0, |at| 1 << at) + } + + /// Whether `field` was filled in. + pub fn contains(self, field: Field) -> bool { + self.0 & FilledIn::bit(field) != 0 + } + + /// Notes that `field` was filled in, if it is one that can be. + pub fn insert(&mut self, field: Field) { + self.0 |= FilledIn::bit(field); + } + + /// Notes that `field` was not filled in, for a value that was set + /// since. + pub fn remove(&mut self, field: Field) { + self.0 &= !FilledIn::bit(field); + } +} + +impl fmt::Debug for FilledIn { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("FilledIn(")?; + let filled = FilledIn::FIELDS.into_iter().filter(|&field| self.contains(field)); + for (i, field) in filled.enumerate() { + if i > 0 { + f.write_str(" | ")?; + } + f.write_str(field.as_str())?; + } + f.write_str(")") + } +} + +/// The 32-bit volume serial number of a FAT or exFAT file system, the +/// field `fatSerial`. It is written as FAT tools show it: two groups of +/// four hexadecimal digits, the upper 16 bits first, `1234-ABCD`. +/// +/// ``` +/// use uapi16::FatSerial; +/// +/// let serial: FatSerial = "1234-abcd".parse()?; +/// assert_eq!(serial, FatSerial(0x1234_abcd)); +/// assert_eq!(serial.to_string(), "1234-ABCD"); +/// # Ok::<(), uapi16::InvalidFatSerial>(()) +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FatSerial(pub u32); + +/// A string that is not a FAT volume serial number, see [`FatSerial`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidFatSerial(()); + +impl fmt::Display for InvalidFatSerial { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("not a FAT volume serial number") + } +} + +impl std::error::Error for InvalidFatSerial {} + +impl FatSerial { + /// The hexadecimal digits of each group. + const GROUP_DIGITS: usize = 4; + /// The bits of each group. + const GROUP_BITS: u32 = 16; + /// What separates the groups. + const SEPARATOR: char = '-'; + /// The radix of the digits. + const HEX: u32 = 16; + + /// The serial number the specification derives from a file system + /// UUID: its first four bytes. + pub fn from_uuid(uuid: &Uuid) -> FatSerial { + let [a, b, c, d, ..] = *uuid.as_bytes(); + FatSerial(u32::from_be_bytes([a, b, c, d])) + } +} + +impl fmt::Display for FatSerial { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{:04X}{}{:04X}", + self.0 >> FatSerial::GROUP_BITS, + FatSerial::SEPARATOR, + self.0 & u32::from(u16::MAX) + ) + } +} + +impl FromStr for FatSerial { + type Err = InvalidFatSerial; + + fn from_str(text: &str) -> Result { + let group = |digits: &str| { + // from_str_radix would also take a sign. + if digits.len() != FatSerial::GROUP_DIGITS || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(InvalidFatSerial(())); + } + u32::from_str_radix(digits, FatSerial::HEX).map_err(|_| InvalidFatSerial(())) + }; + let (upper, lower) = text.split_once(FatSerial::SEPARATOR).ok_or(InvalidFatSerial(()))?; + Ok(FatSerial((group(upper)? << FatSerial::GROUP_BITS) | group(lower)?)) + } +} + +/// The identity of the file system the file objects of a manifest are +/// placed in: the fields `fsUUID`, `fsLabel` and `fatSerial`, which only +/// the root file object has. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct FileSystemIdentity { + /// `fsUUID`: the UUID of the file system. + pub uuid: Option, + /// `fsLabel`: the label of the file system, see + /// [`FileSystemIdentity::is_valid_label`]. + pub label: Option, + /// `fatSerial`: the volume serial number of a FAT or exFAT file system. + pub fat_serial: Option, +} + +impl FileSystemIdentity { + /// Whether `label` can be the label of a file system in a manifest, + /// in `fsLabel`: a string a manifest can have, without control + /// characters. A file system can take less than that. + /// + /// ``` + /// use uapi16::FileSystemIdentity; + /// + /// assert!(FileSystemIdentity::is_valid_label("ESP")); + /// assert!(FileSystemIdentity::is_valid_label("A.B \u{e9}")); + /// assert!(!FileSystemIdentity::is_valid_label("a\tb")); + /// assert!(!FileSystemIdentity::is_valid_label("a\u{fffe}")); + /// ``` + pub fn is_valid_label(label: &str) -> bool { + STRING_RULES.admits(label) && !label.chars().any(char::is_control) + } + + /// Whether it says nothing. + pub fn is_empty(&self) -> bool { + self.uuid.is_none() && self.label.is_none() && self.fat_serial.is_none() + } + + /// The volume serial number a FAT or exFAT file system takes from the + /// identity, as the specification has it: `fatSerial`, or else the one + /// derived from `fsUUID`, see [`FatSerial::from_uuid`]. Returned with + /// the field it comes from. + /// + /// ``` + /// use uapi16::{FatSerial, Field, FileSystemIdentity}; + /// + /// let mut identity = FileSystemIdentity::default(); + /// identity.uuid = "1234abcd-5678-4ef0-9abc-def012345678".parse().ok(); + /// assert_eq!(identity.volume_serial(), Some((FatSerial(0x1234_abcd), Field::FsUuid))); + /// identity.fat_serial = Some(FatSerial(0x5678_9abc)); + /// assert_eq!(identity.volume_serial(), Some((FatSerial(0x5678_9abc), Field::FatSerial))); + /// ``` + pub fn volume_serial(&self) -> Option<(FatSerial, Field)> { + match (self.fat_serial, &self.uuid) { + (Some(serial), _) => Some((serial, Field::FatSerial)), + (None, Some(uuid)) => Some((FatSerial::from_uuid(uuid), Field::FsUuid)), + (None, None) => None, + } + } +} + +/// Where a contents object says the data is. It names at most one place. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum Location { + /// Neither `file`, `url` nor `literal` is given: the data is in the + /// file of the object's own name, next to the manifest. + #[default] + Implied, + /// `file`: the data is in this file next to the manifest. + File(Name), + /// `url`: the data is at this http or https URL. + Url(String), + /// `literal`: the data is in the manifest, and here. + Literal(Vec), +} + +/// A contents object: one place the data of a file object can be taken +/// from, and how it is stored there. +/// +/// The data can be stored in an encoding, such as gzip. The encoded sizes +/// and hashes are those of the data as it is stored, the original ones +/// those of the decoded data. The file object's data is the part of the +/// decoded data that starts at `offset`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Contents { + /// `file`, `url` or `literal`: where the data is. + pub location: Location, + /// `httpHeaders`: the header fields of the HTTP requests for the data + /// at `url`, by name, in the order the manifest lists them. + pub http_headers: Vec<(String, String)>, + /// `encoding`: the HTTP content coding the data is stored in, in + /// lower case. None is no encoding. + pub encoding: Option, + /// `encodedSize`: the size of the data as it is stored. + pub encoded_size: Option, + /// `encodedSha256`: the hash of the data as it is stored. + pub encoded_sha256: Option, + /// `originalSize`: the size of the decoded data. + pub original_size: Option, + /// `originalSha256`: the hash of the decoded data. + pub original_sha256: Option, + /// `offset`: where the file object's data starts in the decoded data. + pub offset: u64, + /// The sizes and hashes that follow from the other fields, if a reader + /// filled them in. Whoever sets another value takes the field out. + pub filled_in: FilledIn, +} + +impl Contents { + /// A contents object for data in the place `location`, stored as it + /// is. + pub fn new(location: Location) -> Contents { + Contents { + location, + ..Contents::default() + } + } + + /// The data the manifest carries itself, if this is where the data + /// is. + pub fn literal(&self) -> Option<&[u8]> { + match &self.location { + Location::Literal(data) => Some(data), + _ => None, + } + } + + /// The file next to the manifest the data is in, if `file` names one. + pub fn file(&self) -> Option<&Name> { + match &self.location { + Location::File(name) => Some(name), + _ => None, + } + } + + /// The URL the data is at, if this is where the data is. + pub fn url(&self) -> Option<&str> { + match &self.location { + Location::Url(url) => Some(url), + _ => None, + } + } +} + +/// The inode attributes of a file: its access mode, its owner, its +/// modification time and extended attributes, whether it is read-only and +/// its Linux inode flags. +/// +/// They are what a file is as an inode rather than as an entry of a +/// directory. A [`FileObject`] has them for its file and the +/// [`RootObject`] for the root directory. The specification calls them so +/// where a directory is described twice: by the file object of the +/// manifest it is in and by the root file object of a sub-manifest of its +/// own. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct InodeAttributes { + /// `mode`: the access mode. + pub mode: Option, + /// `uid`: the owning user. + pub uid: Option, + /// `gid`: the owning group. + pub gid: Option, + /// `userName`: the name of the owning user. + pub user_name: Option>, + /// `groupName`: the name of the owning group. + pub group_name: Option>, + /// `mTimeNSec`: the modification time in nanoseconds since the epoch, + /// see [`InodeAttributes::mtime`]. + pub mtime_nsec: Option, + /// `extendedAttributes`: the extended attributes of the `user` + /// namespace, by their names without the `user.` in front. None says + /// nothing about them. A map lists them all, so an empty one says the + /// file has none. + pub user_xattrs: Option>>>, + /// `readOnly`: whether the file is read-only, see + /// [`InodeAttributes::is_read_only`]. It stands for the read-only + /// attribute of DOS and for [`GptPartition::FLAG_READ_ONLY`] too. + pub read_only: Option, + /// `flagAppendOnly` and the other fields of the inode flags: the + /// flags the object states. + pub flags: FlagStates, +} + +impl InodeAttributes { + /// The fields of the inode attributes that belong to a feature, each + /// with its feature, in the order of their names. The fields of the + /// inode flags are in [`InodeFlags::FIELDS`]. + const FEATURE_FIELDS: [(Field, Features); 8] = [ + (Field::ExtendedAttributes, Features::USER_XATTR), + (Field::Gid, Features::GID), + (Field::GroupName, Features::GROUP_NAME), + (Field::MTimeNSec, Features::MTIME), + (Field::Mode, Features::MODE), + (Field::ReadOnly, Features::READ_ONLY), + (Field::Uid, Features::UID), + (Field::UserName, Features::USER_NAME), + ]; + + /// Whether the attributes have `field`, one of + /// [`InodeAttributes::FEATURE_FIELDS`]. + fn has_feature_field(&self, field: Field) -> bool { + match field { + Field::ExtendedAttributes => self.user_xattrs.is_some(), + Field::Gid => self.gid.is_some(), + Field::GroupName => self.group_name.is_some(), + Field::MTimeNSec => self.mtime_nsec.is_some(), + Field::Mode => self.mode.is_some(), + Field::ReadOnly => self.read_only.is_some(), + Field::Uid => self.uid.is_some(), + Field::UserName => self.user_name.is_some(), + _ => false, + } + } + + /// The fields the attributes have that belong to a feature, each with + /// its feature. + fn feature_fields(&self) -> impl Iterator + '_ { + InodeAttributes::FEATURE_FIELDS + .into_iter() + .filter(|(field, _)| self.has_feature_field(*field)) + .chain(self.flags.feature_fields()) + } + + /// The modification time, if the attributes have one. + pub fn mtime(&self) -> Option { + self.mtime_nsec.map(|nsec| UNIX_EPOCH + Duration::from_nanos(nsec)) + } + + /// Sets the modification time to `time`. `mTimeNSec` counts + /// nanoseconds since the epoch in 64 bits, which ends in the year + /// 2554. A time it cannot express leaves the attributes without one. + pub fn set_mtime(&mut self, time: SystemTime) { + self.mtime_nsec = time + .duration_since(UNIX_EPOCH) + .ok() + .and_then(|since| u64::try_from(since.as_nanos()).ok()); + } + + /// Whether the file gets the read-only attribute in a file system with + /// DOS attributes, such as FAT: what `readOnly` says, or else whether + /// `mode` gives nobody write permission. Attributes with neither are + /// not read-only. + /// + /// The specification lets `mode` stand in for `readOnly` for the DOS + /// attribute only, and only where the manifest does not list the + /// `read-only` feature. Where it lists it, an object without `readOnly` + /// is not read-only, and a reader fills that in. The read-only flag of + /// a GPT partition, [`GptPartition::FLAG_READ_ONLY`], is `readOnly` + /// alone. + pub fn is_read_only(&self) -> bool { + match (self.read_only, self.mode) { + (Some(read_only), _) => read_only, + (None, Some(mode)) => !mode.is_writable(), + (None, None) => false, + } + } +} + +/// A file object: what a manifest says about one file below its root. +/// +/// Every field but the name and the type is optional. What the file is as +/// an inode, its access mode, owner, time and the like, is in +/// [`FileObject::inode`], as it is for the root directory in the +/// [`RootObject`]. A reader fills in what follows from the other fields: +/// the size 0 for the hash of no data and that hash for the size 0, and +/// the size and the hash of a file whose contents object gives them. It +/// notes them in `filled_in`, and a writer leaves them out. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct FileObject { + /// `name`: the path of the file below the root. + pub name: Name, + /// `type`: the inode type. An object that does not say is a regular + /// file. + pub inode_type: InodeType, + /// `size`: the size of the contents in bytes. For a symbolic link that + /// is the length of its target, for a directory the size of the + /// manifest of its own that `contents` refers to. + pub size: Option, + /// `sha256`: the hash of the contents. + pub sha256: Option, + /// `contents`: where the contents can be taken from. Without any they + /// are in the file of the object's name next to the manifest. + pub contents: Vec, + /// `inodeToken`: the objects that carry the same token are hard links + /// to one file. None is a file of its own. + pub inode_token: Option, + /// `major`: the major number of a device node. + pub major: Option, + /// `minor`: the minor number of a device node. + pub minor: Option, + /// The `gpt` fields, if the object describes a partition. + pub gpt: Option>, + /// `flagHidden`, `flagSystem` and `flagArchive`: the DOS attributes the + /// object states. + pub dos_flags: FlagStates, + /// The inode attributes of the file. + pub inode: InodeAttributes, + /// `validSinceUSec`, `validUntilUSec` and `validity`: when the file may + /// be used. + pub validity: ValidityWindow, + /// The size and the hash, if a reader filled them in. Whoever sets + /// another value takes the field out. + pub filled_in: FilledIn, +} + +impl FileObject { + /// The fields of a file object that belong to a feature, each with its + /// feature, in the order of their names. Those of the DOS attributes + /// are in [`DosFlags::FIELDS`], those of the inode attributes in + /// [`InodeAttributes::FEATURE_FIELDS`]. + const FEATURE_FIELDS: [(Field, Features); 12] = [ + (Field::Contents, Features::SYMLINK), + (Field::GptFlagGrowFileSystem, Features::GPT_FLAG_GROW_FILE_SYSTEM), + (Field::GptFlagNoAuto, Features::GPT_FLAG_NO_AUTO), + (Field::GptFlags, Features::GPT_FLAGS), + (Field::GptLabel, Features::GPT_LABEL), + (Field::GptTypeUuid, Features::GPT_TYPE_UUID), + (Field::GptUuid, Features::GPT_UUID), + (Field::InodeToken, Features::HARDLINK), + (Field::Major, Features::DEVICE), + (Field::Minor, Features::DEVICE), + (Field::Sha256, Features::SHA256), + (Field::Size, Features::SIZE), + ]; + + /// A file object for the regular file `name` that says nothing else + /// about it. + pub fn new(name: Name) -> FileObject { + FileObject { + name, + inode_type: InodeType::Regular, + size: None, + sha256: None, + contents: Vec::new(), + inode_token: None, + major: None, + minor: None, + gpt: None, + dos_flags: FlagStates::default(), + inode: InodeAttributes::default(), + validity: ValidityWindow::default(), + filled_in: FilledIn::default(), + } + } + + /// Whether the object has `field`, one of [`FileObject::FEATURE_FIELDS`], + /// other than one a reader filled in. `contents` belongs to a feature on + /// a symbolic link only. + fn has_feature_field(&self, field: Field) -> bool { + let gpt = self.gpt.as_deref(); + match field { + Field::Contents => self.inode_type == InodeType::Symlink && !self.contents.is_empty(), + Field::GptFlagGrowFileSystem => gpt.is_some_and(|gpt| gpt.grow_file_system.is_some()), + Field::GptFlagNoAuto => gpt.is_some_and(|gpt| gpt.no_auto.is_some()), + Field::GptFlags => gpt.is_some_and(|gpt| gpt.flags.is_some()), + Field::GptLabel => gpt.is_some_and(|gpt| gpt.label.is_some()), + Field::GptTypeUuid => gpt.is_some_and(|gpt| gpt.type_uuid.is_some()), + Field::GptUuid => gpt.is_some_and(|gpt| gpt.uuid.is_some()), + Field::InodeToken => self.inode_token.is_some(), + Field::Major => self.major.is_some(), + Field::Minor => self.minor.is_some(), + Field::Sha256 => self.sha256.is_some() && !self.filled_in.contains(field), + Field::Size => self.size.is_some() && !self.filled_in.contains(field), + _ => false, + } + } + + /// The fields the object has that belong to a feature, each with its + /// feature: the fields a manifest that does not record the feature + /// cannot have. Its own come first, then those of its inode + /// attributes. + pub(crate) fn feature_fields(&self) -> impl Iterator + '_ { + FileObject::FEATURE_FIELDS + .into_iter() + .filter(|(field, _)| self.has_feature_field(*field)) + .chain(self.dos_flags.feature_fields()) + .chain(self.inode.feature_fields()) + } + + /// The features whose fields the object has, see [`Features`]. A + /// manifest records them all or the object is not one of its file + /// objects. The fields a reader filled in do not count. + pub fn stated_features(&self) -> Features { + self.feature_fields() + .fold(Features::NONE, |features, (_, feature)| features | feature) + } + + /// Checks that the object may be used at the time `now_usec`, in + /// microseconds since the epoch: that it is not revoked and that the + /// time is inside its validity window. What is true of a directory is + /// true of everything in it. + pub fn check_validity(&self, now_usec: u64) -> Result<(), Error> { + self.validity + .check(now_usec, self.name.escape_debug()) + .map_err(|e| e.named(self.name.as_str())) + } +} + +/// The root file object: what a manifest says about the root directory of +/// the tree it describes, and about the manifest itself. +/// +/// It is the first object of a manifest. It has no name and is a +/// directory, so neither is a field here. Like a [`FileObject`] it has the +/// inode attributes of its directory and a validity window, which is that +/// of the whole manifest. The other fields only the root file object has: +/// what the manifest records and the order it lists its file objects in, +/// and the identity of the file system or of the partition table the file +/// objects are placed in. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct RootObject { + /// The inode attributes of the root directory. + pub inode: InodeAttributes, + /// `fsUUID`, `fsLabel` and `fatSerial`: the identity of the file + /// system the file objects are placed in. + pub file_system: FileSystemIdentity, + /// `gptDiskUuid`: the disk UUID of the GPT partition table the file + /// objects are placed in as partitions. + pub gpt_disk_uuid: Option, + /// `order`: the order the manifest lists its file objects in. + pub order: Option, + /// `features`: what the manifest records. None is + /// [`Features::DEFAULT`]. + pub features: Option, + /// `validSinceUSec`, `validUntilUSec` and `validity`: when the + /// manifest may be used. + pub validity: ValidityWindow, +} + +impl RootObject { + /// The fields of the root file object that belong to a feature, each + /// with its feature, in the order of their names. Those of the inode + /// attributes are in [`InodeAttributes::FEATURE_FIELDS`]. + const FEATURE_FIELDS: [(Field, Features); 4] = [ + (Field::FatSerial, Features::FAT_SERIAL), + (Field::FsLabel, Features::FS_LABEL), + (Field::FsUuid, Features::FS_UUID), + (Field::GptDiskUuid, Features::GPT_DISK_UUID), + ]; + + /// Whether the object has `field`, one of + /// [`RootObject::FEATURE_FIELDS`]. + fn has_feature_field(&self, field: Field) -> bool { + match field { + Field::FatSerial => self.file_system.fat_serial.is_some(), + Field::FsLabel => self.file_system.label.is_some(), + Field::FsUuid => self.file_system.uuid.is_some(), + Field::GptDiskUuid => self.gpt_disk_uuid.is_some(), + _ => false, + } + } + + /// The fields the object has that belong to a feature, each with its + /// feature: the fields a manifest that does not record the feature + /// cannot have. Its own come first, then those of its inode + /// attributes. + pub(crate) fn feature_fields(&self) -> impl Iterator + '_ { + RootObject::FEATURE_FIELDS + .into_iter() + .filter(|(field, _)| self.has_feature_field(*field)) + .chain(self.inode.feature_fields()) + } + + /// The features whose fields the object has, see [`Features`]. A + /// manifest records them all or this is not its root file object. + pub fn stated_features(&self) -> Features { + self.feature_fields() + .fold(Features::NONE, |features, (_, feature)| features | feature) + } + + /// Checks that the manifest may be used at the time `now_usec`, in + /// microseconds since the epoch: that its root file object is not + /// revoked and that the time is inside its validity window. + pub fn check_validity(&self, now_usec: u64) -> Result<(), Error> { + self.validity.check(now_usec, "the manifest") + } +} + +/// A signature object: a signature over the manifest up to the first +/// signature object. +/// +/// A manifest can carry several. This crate reads them and does not +/// verify them. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Signature { + /// `mechanism`: how the signature was made. The specification has + /// `openpgp` and `pkcs7`. + pub mechanism: String, + /// `key`: what identifies the key, such as its fingerprint. + pub key: Option>, + /// `data`: the signature. + pub data: Option>, +} + +impl Signature { + /// A signature object of the mechanism `mechanism`, without a key + /// and without data. + pub fn new(mechanism: impl Into) -> Signature { + Signature { + mechanism: mechanism.into(), + key: None, + data: None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Digest; + + /// Gives an object a field. + type Give = fn(&mut T); + + #[test] + fn inode_types() { + for (name, inode_type) in [ + ("reg", InodeType::Regular), + ("dir", InodeType::Directory), + ("lnk", InodeType::Symlink), + ("fifo", InodeType::Fifo), + ("chr", InodeType::CharDevice), + ("blk", InodeType::BlockDevice), + ("sock", InodeType::Socket), + ] { + assert_eq!(name.parse(), Ok(inode_type)); + assert_eq!(inode_type.as_str(), name); + assert_eq!(inode_type.to_string(), name); + assert_eq!( + inode_type.has_contents(), + ["reg", "dir", "lnk"].contains(&name), + "{}", + name + ); + assert_eq!(inode_type.is_device(), ["chr", "blk"].contains(&name), "{}", name); + } + for name in ["", "REG", "file", "symlink", "reg "] { + assert!(name.parse::().is_err(), "{:?}", name); + } + } + + #[test] + fn modes() { + for bits in [0, 0o644, 0o755, 0o4755, 0o7777] { + let mode = Mode::new(bits).unwrap(); + assert_eq!(mode.bits(), bits); + assert_eq!(u32::from(mode), bits); + } + assert_eq!(Mode::new(0o10000), None); + assert_eq!(Mode::new(0o100644), None); + assert_eq!(Mode::new(u32::MAX), None); + for (bits, writable) in [ + (0o644, true), + (0o444, false), + (0o020, true), + (0o002, true), + (0o555, false), + (0o7555, false), + (0, false), + ] { + assert_eq!(Mode::new(bits).unwrap().is_writable(), writable, "{:o}", bits); + } + assert_eq!(format!("{:?}", Mode::new(0o644).unwrap()), "Mode(0o644)"); + } + + #[test] + fn uuids() { + let bytes = [ + 0x4f, 0x68, 0xbc, 0xe3, 0xe8, 0xcd, 0x4d, 0xb1, 0x96, 0xe7, 0xfb, 0xca, 0xf9, 0x84, 0xb7, 0x09, + ]; + // The groups of the text form are the whole UUID. + assert_eq!(Uuid::GROUPS.iter().sum::(), Uuid::SIZE); + let uuid = Uuid::new(bytes); + let text = "4f68bce3-e8cd-4db1-96e7-fbcaf984b709"; + assert_eq!(uuid.to_string(), text); + assert_eq!(format!("{:?}", uuid), format!("Uuid({})", text)); + assert_eq!(uuid.as_bytes(), &bytes); + for spelling in [ + text.to_string(), + text.to_uppercase(), + text.replace('-', ""), + format!("urn:uuid:{}", text), + format!("URN:UUID:{}", text.to_uppercase()), + format!("urn:uuid:{}", text.replace('-', "")), + ] { + assert_eq!(spelling.parse(), Ok(uuid), "{}", spelling); + } + for bad in [ + "", + "not-a-uuid", + "4f68bce3-e8cd-4db1-96e7-fbcaf984b70", + "4f68bce3-e8cd-4db1-96e7-fbcaf984b7090", + "4f68bce3e8cd-4db1-96e7-fbcaf984b709", + "4f68bce3-e8cd-4db1-96e7fbcaf984b709-", + "4f68bce3-e8cd-4db1-96e7-fbcaf984b70g", + "4f68bce3 e8cd 4db1 96e7 fbcaf984b709", + "4f68bce3e8cd4db196e7fbcaf984b70 9", + "{4f68bce3-e8cd-4db1-96e7-fbcaf984b709}", + "urn:uuid:", + "uuid:4f68bce3-e8cd-4db1-96e7-fbcaf984b709", + // Whitespace, a sign or a prefix where a digit belongs, at the + // length of a UUID. + "4f68bce3e8cd4db196e7fbcaf984b7 9", + " f68bce3e8cd4db196e7fbcaf984b709", + "4f68bce3-e8cd-4db1-96e7-fbcaf984b70\n", + "4f68bce3-e8cd-4db1-96e7-\tbcaf984b709", + "+f68bce3-e8cd-4db1-96e7-fbcaf984b709", + "0x68bce3e8cd4db196e7fbcaf984b709", + // Characters of more than one byte, where a cut by bytes + // would fall inside one. + "12345678\u{e9}", + "\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}", + "4f68bce3-e8cd-4db1-96e7-fbcaf984b7\u{e9}", + ] { + assert!(bad.parse::().is_err(), "{:?}", bad); + } + } + + #[test] + fn times() { + let mut inode = InodeAttributes::default(); + assert_eq!(inode.mtime(), None); + inode.set_mtime(UNIX_EPOCH); + assert_eq!((inode.mtime_nsec, inode.mtime()), (Some(0), Some(UNIX_EPOCH))); + let time = UNIX_EPOCH + Duration::new(1_700_000_000, 5); + inode.set_mtime(time); + assert_eq!(inode.mtime_nsec, Some(1_700_000_000_000_000_005)); + assert_eq!(inode.mtime(), Some(time)); + // mTimeNSec holds nanoseconds since the epoch in 64 bits: up to the + // year 2554, and nothing before 1970. + let last = UNIX_EPOCH + Duration::from_nanos(u64::MAX); + inode.set_mtime(last); + assert_eq!((inode.mtime_nsec, inode.mtime()), (Some(u64::MAX), Some(last))); + inode.set_mtime(last + Duration::from_nanos(1)); + assert_eq!(inode.mtime_nsec, None); + inode.set_mtime(UNIX_EPOCH - Duration::from_secs(1)); + assert_eq!(inode.mtime_nsec, None); + } + + #[test] + fn read_only() { + let mut inode = InodeAttributes::default(); + assert!(!inode.is_read_only()); + inode.mode = Mode::new(0o444); + assert!(inode.is_read_only()); + inode.mode = Mode::new(0o464); + assert!(!inode.is_read_only()); + inode.read_only = Some(true); + assert!(inode.is_read_only()); + inode.mode = None; + assert!(inode.is_read_only()); + inode.read_only = Some(false); + assert!(!inode.is_read_only()); + // What readOnly says counts, the false a reader fills in too. + inode.mode = Mode::new(0o444); + assert!(!inode.is_read_only()); + } + + #[test] + fn validity() { + assert_eq!( + (Validity::Good.as_str(), Validity::Revoked.as_str()), + ("good", "revoked") + ); + assert_eq!(Validity::Revoked.to_string(), "revoked"); + assert_eq!(ValidityWindow::default().state, Validity::Good); + let kind = |object: &FileObject, now| object.check_validity(now).map_err(|e| e.kind()); + let mut object = FileObject::new(Name::new("d/x").unwrap()); + assert_eq!(kind(&object, 0), Ok(())); + assert_eq!(kind(&object, u64::MAX), Ok(())); + object.validity.since_usec = 10; + object.validity.until_usec = Some(20); + assert_eq!(kind(&object, 9), Err(ErrorKind::NotValid(Invalid::NotYetValid))); + assert_eq!(kind(&object, 10), Ok(())); + assert_eq!(kind(&object, 19), Ok(())); + assert_eq!(kind(&object, 20), Err(ErrorKind::NotValid(Invalid::Expired))); + let e = object.check_validity(20).unwrap_err(); + assert_eq!((e.name(), e.to_string().as_str()), (Some("d/x"), "d/x has expired")); + assert_eq!( + object.check_validity(9).unwrap_err().to_string(), + "d/x is not valid yet" + ); + // Revoked whatever the time is. + object.validity.state = Validity::Revoked; + for now in [9, 15, 20] { + assert_eq!(kind(&object, now), Err(ErrorKind::NotValid(Invalid::Revoked))); + } + assert_eq!(object.check_validity(15).unwrap_err().to_string(), "d/x is revoked"); + // The root file object speaks for the manifest, which has no name. + let mut root = RootObject::default(); + assert_eq!(root.check_validity(u64::MAX).map_err(|e| e.kind()), Ok(())); + root.validity.until_usec = Some(1); + let e = root.check_validity(1).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::NotValid(Invalid::Expired)); + assert_eq!((e.name(), e.to_string().as_str()), (None, "the manifest has expired")); + root.validity.state = Validity::Revoked; + assert_eq!( + root.check_validity(0).unwrap_err().to_string(), + "the manifest is revoked" + ); + } + + #[test] + fn flags() { + // The tables are in the order of the names of the fields, and each + // has every flag of its kind. + let dos: Vec<&str> = DosFlags::FIELDS.iter().map(|(_, field, _)| field.as_str()).collect(); + let inode: Vec<&str> = InodeFlags::FIELDS.iter().map(|(_, field, _)| field.as_str()).collect(); + assert!(dos.windows(2).all(|pair| pair[0] < pair[1]), "{:?}", dos); + assert!(inode.windows(2).all(|pair| pair[0] < pair[1]), "{:?}", inode); + let every_dos = DosFlags::FIELDS + .iter() + .fold(DosFlags::NONE, |every, (flag, _, _)| every | *flag); + let every_inode = InodeFlags::FIELDS + .iter() + .fold(InodeFlags::NONE, |every, (flag, _, _)| every | *flag); + assert_eq!((every_dos, every_inode), (DosFlags::ALL, InodeFlags::ALL)); + // A field is the field of one kind of flags. + assert!(dos.iter().all(|field| !inode.contains(field))); + for &(flag, _, _) in DosFlags::FIELDS { + assert_eq!((!flag & flag, !flag | flag), (DosFlags::NONE, DosFlags::ALL)); + } + for &(flag, _, _) in InodeFlags::FIELDS { + assert_eq!((!flag & flag, !flag | flag), (InodeFlags::NONE, InodeFlags::ALL)); + } + assert_eq!((!DosFlags::NONE, !InodeFlags::ALL), (DosFlags::ALL, InodeFlags::NONE)); + let flags = DosFlags::HIDDEN | DosFlags::ARCHIVE; + assert!(flags.contains(DosFlags::ARCHIVE) && !flags.contains(DosFlags::ALL)); + assert_eq!(flags.without(DosFlags::ARCHIVE), DosFlags::HIDDEN); + assert_eq!(format!("{:?}", flags), "DosFlags(flagArchive | flagHidden)"); + assert_eq!( + format!("{:?}", InodeFlags::NO_COW | InodeFlags::APPEND_ONLY), + "InodeFlags(flagAppendOnly | flagNoCow)" + ); + assert_eq!(format!("{:?}", InodeFlags::NONE), "InodeFlags()"); + // What an object says about the flags of one kind. + let mut states = FlagStates::default(); + assert_eq!(states.get(InodeFlags::IMMUTABLE), None); + states.put(InodeFlags::IMMUTABLE, Some(true)); + states.put(InodeFlags::NO_DUMP, Some(false)); + assert_eq!(states.get(InodeFlags::IMMUTABLE), Some(true)); + assert_eq!(states.get(InodeFlags::NO_DUMP), Some(false)); + assert_eq!(states.get(InodeFlags::NO_COW), None); + assert_eq!(states.stated, InodeFlags::IMMUTABLE | InodeFlags::NO_DUMP); + assert_eq!(states.set, InodeFlags::IMMUTABLE); + states.put(InodeFlags::IMMUTABLE, Some(false)); + assert_eq!(states.get(InodeFlags::IMMUTABLE), Some(false)); + states.put(InodeFlags::IMMUTABLE, None); + states.put(InodeFlags::NO_DUMP, None); + assert_eq!(states, FlagStates::default()); + } + + #[test] + fn features_of_the_fields() { + const UUID: Uuid = Uuid::new([1; Uuid::SIZE]); + // Every feature has a field, of a file object or of the root file + // object, and every table is in the order of the names. + let tables: [&[(Field, Features)]; 3] = [ + &InodeAttributes::FEATURE_FIELDS, + &FileObject::FEATURE_FIELDS, + &RootObject::FEATURE_FIELDS, + ]; + for table in tables { + assert!( + table.windows(2).all(|pair| pair[0].0.as_str() < pair[1].0.as_str()), + "{:?}", + table + ); + } + let dos = DosFlags::FIELDS.iter().map(|&(_, field, feature)| (field, feature)); + let inode = InodeFlags::FIELDS.iter().map(|&(_, field, feature)| (field, feature)); + let every = tables + .iter() + .flat_map(|table| table.iter().copied()) + .chain(dos) + .chain(inode) + .fold(Features::NONE, |every, (_, feature)| every | feature); + assert_eq!(every, Features::ALL); + // A field makes a file object state its feature. + assert_eq!( + FileObject::new(Name::new("f").unwrap()).stated_features(), + Features::NONE + ); + let partition = |set: Give| { + let mut gpt = GptPartition::default(); + set(&mut gpt); + Some(Box::new(gpt)) + }; + let cases: [(Give, Features); 14] = [ + (|o| o.size = Some(1), Features::SIZE), + (|o| o.sha256 = Some(Sha256::EMPTY), Features::SHA256), + (|o| o.inode_token = NonZeroU64::new(1), Features::HARDLINK), + (|o| o.major = Some(1), Features::DEVICE), + (|o| o.minor = Some(1), Features::DEVICE), + ( + |o| o.dos_flags.put(DosFlags::HIDDEN, Some(false)), + Features::FLAG_HIDDEN, + ), + (|o| o.dos_flags.put(DosFlags::SYSTEM, Some(true)), Features::FLAG_SYSTEM), + ( + |o| o.dos_flags.put(DosFlags::ARCHIVE, Some(true)), + Features::FLAG_ARCHIVE, + ), + (|o| o.inode.mode = Mode::new(0o644), Features::MODE), + (|o| o.inode.uid = Some(0), Features::UID), + (|o| o.inode.user_name = Some("u".into()), Features::USER_NAME), + (|o| o.inode.mtime_nsec = Some(0), Features::MTIME), + (|o| o.inode.user_xattrs = Some(Box::default()), Features::USER_XATTR), + (|o| o.inode.read_only = Some(false), Features::READ_ONLY), + ]; + for (set, feature) in cases { + let mut object = FileObject::new(Name::new("f").unwrap()); + set(&mut object); + assert_eq!(object.stated_features(), feature, "{:?}", object); + } + let partitions: [(Give, Features); 6] = [ + (|gpt| gpt.label = Some("l".into()), Features::GPT_LABEL), + (|gpt| gpt.uuid = Some(UUID), Features::GPT_UUID), + (|gpt| gpt.type_uuid = Some(UUID), Features::GPT_TYPE_UUID), + (|gpt| gpt.flags = Some(0), Features::GPT_FLAGS), + (|gpt| gpt.no_auto = Some(false), Features::GPT_FLAG_NO_AUTO), + ( + |gpt| gpt.grow_file_system = Some(true), + Features::GPT_FLAG_GROW_FILE_SYSTEM, + ), + ]; + for (set, feature) in partitions { + let mut object = FileObject::new(Name::new("f").unwrap()); + object.gpt = partition(set); + assert_eq!(object.stated_features(), feature, "{:?}", object); + } + let mut object = FileObject::new(Name::new("f").unwrap()); + (object.inode.gid, object.inode.group_name) = (Some(0), Some("g".into())); + assert_eq!(object.stated_features(), Features::GID | Features::GROUP_NAME); + for &(flag, _, feature) in InodeFlags::FIELDS { + let mut object = FileObject::new(Name::new("f").unwrap()); + object.inode.flags.put(flag, Some(true)); + assert_eq!(object.stated_features(), feature, "{:?}", flag); + } + // The contents of a symbolic link are its target, which a feature + // records. Those of other files are not. + let mut object = FileObject::new(Name::new("f").unwrap()); + object.contents = vec![Contents::new(Location::Literal(b"t".to_vec()))]; + assert_eq!(object.stated_features(), Features::NONE); + object.inode_type = InodeType::Symlink; + assert_eq!(object.stated_features(), Features::SYMLINK); + // What a reader filled in does not count. + let mut object = FileObject::new(Name::new("f").unwrap()); + (object.size, object.sha256) = (Some(0), Some(Sha256::EMPTY)); + object.filled_in.insert(Field::Size); + assert_eq!(object.stated_features(), Features::SHA256); + object.filled_in.insert(Field::Sha256); + assert_eq!(object.stated_features(), Features::NONE); + // The fields of the root file object, its inode attributes among + // them. + assert_eq!(RootObject::default().stated_features(), Features::NONE); + let cases: [(Give, Features); 6] = [ + (|r| r.file_system.uuid = Some(UUID), Features::FS_UUID), + (|r| r.file_system.label = Some("ESP".into()), Features::FS_LABEL), + (|r| r.file_system.fat_serial = Some(FatSerial(1)), Features::FAT_SERIAL), + (|r| r.gpt_disk_uuid = Some(UUID), Features::GPT_DISK_UUID), + (|r| r.inode.mtime_nsec = Some(0), Features::MTIME), + ( + |r| r.inode.flags.put(InodeFlags::NO_COW, Some(false)), + Features::FLAG_NO_COW, + ), + ]; + for (set, feature) in cases { + let mut root = RootObject::default(); + set(&mut root); + assert_eq!(root.stated_features(), feature, "{:?}", root); + } + // order and features describe the manifest, no feature records + // them. + let mut root = RootObject::default(); + (root.order, root.features) = (Some(Order::CodePoint), Some(Features::ALL)); + assert_eq!(root.stated_features(), Features::NONE); + } + + #[test] + fn contents_objects() { + let contents = Contents::default(); + assert_eq!(contents.location, Location::Implied); + assert_eq!( + (contents.literal(), contents.file(), contents.url()), + (None, None, None) + ); + let literal = Contents::new(Location::Literal(b"data".to_vec())); + assert_eq!(literal.literal(), Some(&b"data"[..])); + assert_eq!((literal.file(), literal.url(), literal.offset), (None, None, 0)); + let file = Contents::new(Location::File(Name::new("blob").unwrap())); + assert_eq!(file.file().map(Name::as_str), Some("blob")); + let url = Contents::new(Location::Url("https://example.com/x".to_string())); + assert_eq!(url.url(), Some("https://example.com/x")); + } +} From ca5fa81b95a7771fa36e7e922a493bc2ae8cd41e Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 07/19] uapi16: add the reader Add Decoder and Reader, which read a manifest record by record. Decoder does the reading but no I/O. It is fed the bytes of the manifest with feed() as they come and told with end() that the input ended, and step() says what comes next: Step::Input when it needs more of the manifest, Step::Root with the root file object, Step::Object with a file object or a signature object, and Step::End after the trailer. Reader is a small driver that feeds a Decoder from anything that implements io::Read with BufReader::fill_buf(), Decoder::feed() and consume(). Reader::open() reads the root file object and the reader is then an iterator over the objects that follow, up to the trailer. So an async front end can drive the same decoder later without a second copy of the reader. A manifest can be gigabytes long and come through a pipe, so it is read exactly once and the decoder keeps nothing but the current record and the name of the file object before it. Nothing grows with the manifest and reading takes time in proportion to its size. The decoder splits the records as it is fed. feed() takes bytes up to the next record separator, with the same memchr search that BufRead::skip_until() does. A record may be 4 MiB large, from its record separator up to the next one, which is how the specification counts it. So feed() never takes more than what a record of 4 MiB has behind its separator, plus the separator after it. A record whose separator doesn't come within that is refused as too large, however the manifest is fed. The separator isn't kept and the buffer grows the way a Vec does but never beyond what a record has behind its separator, so the decoder holds less than 4 MiB of one record, like systemd does. A record that has a NUL byte or isn't UTF-8 is refused. Records of nothing but whitespace are skipped, as RFC 7464 suggests, but nothing may follow the trailer, whitespace included, as the specification asks. A record ends where the next one starts. So an object comes out once the separator of the record behind it was fed, and the trailer gives Step::End only after end(). A step reads one record at most. An error of the input ends the reader, with one exception: a WouldBlock from a non-blocking input loses nothing. The record being read is kept and the next call to next() reads on. Reader::open() fails on it like on any other error. Reader::get_mut() hands out the input the way BufReader's does. Decoder::input_error() turns an error of the input into one about the record being read. The first record makes a RootObject and every other one a FileObject. The root can't have a name or a type other than dir, or any of the fields only the other file objects have: size, sha256, contents, inodeToken, major, minor, the gpt fields of a partition and the DOS attributes. Note that systemd's reader takes size, sha256 and contents on the root and we don't. These fields refer to a sub-manifest, and the specification puts them on the dir object of the outer manifest, not on the root file object of the sub-manifest. On a root they have nothing to refer to. Each record is read once with the pull parser, which refuses strings with noncharacters or NUL as the specification asks, and every field goes straight to where it belongs. Whether a record holds a file object is only known once its mediaType has been read, and that can be its last member. So the first error in a field is remembered and only reported once the record turned out to be valid JSON and a file object. The rules are those of the specification, and where it leaves something open those of systemd's reader in src/shared/uapi16-manifest.c: the type of every field, which fields an inode type permits, how the sizes and hashes of an object and of its contents objects have to agree, and what contents objects, extended attributes and signature objects may look like. A null value counts as no value, also for mediaType and for extended attributes and HTTP headers. A size the contents objects give has to agree with every one of them, whichever comes first. A field the reader doesn't know is passed over whatever its value is, as the specification asks, at any depth and with numbers of any size. Where systemd is laxer than the specification we follow the specification: - Integers are JSON numbers written as decimal digits without sign, fraction or exponent, up to 64 bits, and the access mode follows the same rule. systemd also takes integers as decimal strings and an access mode as a string of octal digits (cf. [3]). We refuse those like any other string. -0 is refused too, the json parser reads it as a float. - Base64 and the hex digits of a signature key take no whitespace anywhere, while systemd passes over it in both. The specification wants hex digits and the Base64 of RFC 4648, which has nothing but the digits and the padding, and the clarification in [1] makes refusing whitespace explicit. Base64 takes both alphabets in any mix, as systemd's unbase64mem() does. A uid or gid of 65535 is refused like one of 4294967295. The specification forbids both again since upstream 7ad6521 (cf. [2]), and systemd refuses both as well. The reader also checks where every file object comes. The specification wants them in tree order: every directory comes before the objects below it and these follow it immediately. Since every directory is listed, the directories that can still get entries are the root, the directories the last object is in, and the last object itself if it is a directory. So the name of the last object is all we need to keep. The first byte in which the next name differs from it settles whether the next object may come, and also catches a name that comes twice in a row or again right after the entries of the directory it names. A name that comes again further down could only be found by remembering every name, and we don't. A manifest that declares "order": "codepoint" is checked to have every name sort after the one before it though, which finds every repeated name. A consumer that relies on the order calls RootObject::require_order() and refuses a manifest that doesn't declare it, even if its objects happen to be sorted. The fields of every object are checked against the features the manifest lists, the ones upstream added for readOnly, fsUUID, fsLabel, fatSerial and the gpt fields included, and a symbolic link has to carry its target if the manifest records them. The reader also fills in what the features say about the fields an object doesn't have: a flag the manifest records is cleared, an object without readOnly isn't read-only where the manifest lists read-only, and a file without extended attributes has none if the manifest records them. The sizes and hashes it fills in from other fields and a readOnly it fills in are marked in filled_in, and the checks of an object treat a filled-in readOnly as one that isn't there. So an object read from a manifest passes the same checks again. The gpt fields aren't filled in, as every regular file of a manifest that lists gpt-flags would get a GptPartition otherwise. Instead, gptFlags is checked against gptFlagNoAuto, gptFlagGrowFileSystem and readOnly, which give one of its flags each, and a missing field counts as cleared, gptFlags as 0, where the manifest lists its feature. Only a regular file has gptFlags. Note that systemd doesn't compare readOnly with gptFlags at all. The checks of a single object are kept apart from the filling in so that a writer can run the same ones on what it writes. FileObject::check_permitted_fields() checks the fields against the inode type, and check_consistency() on FileObject, RootObject and Contents checks the fields that have to agree with each other, such as readOnly and mode, a size of 0 and the hash, or httpHeaders and url. The reader fills in what follows from them once they passed. An error about a name says why the name is invalid, such as "name has an empty component". The strings of a manifest that error messages quote go through escape_debug(), so a manifest can't put control characters on a terminal. Signature objects are read but not verified. That takes an OpenPGP or an X.509 implementation. Reader::signed_len() says how much of the manifest they sign so that a caller can verify them. Error grows Problem, what is wrong with a manifest. A record the parser refuses is NotJson, DuplicateKey or InvalidString, after the kind of error the parser reports. Problem::as_str() gives every problem a stable name, the one ufat's Varlink interface uses for it, so a caller can pass it on, and Problem::ALL lists them all, so a caller can check that it knows every name. Problem and ErrorKind are non_exhaustive so that both can grow. src/uapi16/refused.jsonl holds 358 manifests the reader has to refuse, each with one problem or with two of them to show which one is reported. They cover the decoder cases of ufat's own manifest tests in src/fat/manifest/tests.rs as well. For each of them the test checks the problem, the record, the name and the field the error is about, and its message. [1]: https://github.com/uapi-group/specifications/pull/260 [2]: https://github.com/uapi-group/specifications/commit/7ad65217ed10bdbf42047305b5a0cd74280f4321 [3]: https://github.com/systemd/systemd/issues/44897 Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/base64.rs | 301 ++++ src/uapi16/decode.rs | 2920 ++++++++++++++++++++++++++++++++++++++ src/uapi16/error.rs | 385 +++++ src/uapi16/features.rs | 15 + src/uapi16/hex.rs | 90 ++ src/uapi16/lib.rs | 123 +- src/uapi16/name.rs | 32 +- src/uapi16/object.rs | 163 ++- src/uapi16/reader.rs | 1640 +++++++++++++++++++++ src/uapi16/refused.jsonl | 358 +++++ src/uapi16/sequence.rs | 445 ++++++ 11 files changed, 6456 insertions(+), 16 deletions(-) create mode 100644 src/uapi16/base64.rs create mode 100644 src/uapi16/decode.rs create mode 100644 src/uapi16/reader.rs create mode 100644 src/uapi16/refused.jsonl create mode 100644 src/uapi16/sequence.rs diff --git a/src/uapi16/base64.rs b/src/uapi16/base64.rs new file mode 100644 index 0000000..6d1b2ea --- /dev/null +++ b/src/uapi16/base64.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Base64, the way a manifest carries literal contents, the values of +//! extended attributes and the data of a signature. + +use std::fmt; + +/// The digits of one group, and the bytes a group holds. +const GROUP_DIGITS: usize = 4; +const GROUP_BYTES: usize = 3; +/// The bits of one digit. +const DIGIT_BITS: u32 = 6; +/// The digits of the standard alphabet. +const ALPHABET: &[u8; 1 << DIGIT_BITS] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +/// The values of `+` and `/`, the last two digits of the standard +/// alphabet. The URL-safe alphabet spells them `-` and `_`. +const PLUS_VALUE: u8 = 62; +const SLASH_VALUE: u8 = 63; +/// Where the lower case letters and the decimal digits start in the +/// alphabet. +const FIRST_LOWER: u8 = 26; +const FIRST_DECIMAL: u8 = 52; +/// What fills up the last group. +const PAD: u8 = b'='; +/// The most padding a group has: its first two digits are never padding. +const MAX_PADDING: usize = 2; +/// How many groups are formatted at a time. +const CHUNK_GROUPS: usize = 16; + +/// Bytes that print as Base64 in the standard alphabet with padding, the +/// way systemd writes them. +pub(crate) struct Base64<'a>(pub(crate) &'a [u8]); + +impl Base64<'_> { + /// The value of a digit of the standard or of the URL-safe alphabet. + fn value(digit: u8) -> Option { + match digit { + b'A'..=b'Z' => Some(digit - b'A'), + b'a'..=b'z' => Some(digit - b'a' + FIRST_LOWER), + b'0'..=b'9' => Some(digit - b'0' + FIRST_DECIMAL), + b'+' | b'-' => Some(PLUS_VALUE), + b'/' | b'_' => Some(SLASH_VALUE), + _ => None, + } + } + + /// Decodes Base64 the way systemd's unbase64mem() does, but for + /// whitespace: + /// + /// - The digits are those of the standard and of the URL-safe + /// alphabet, in any mix. + /// - The digits come in groups of four. The last group can end in "=" + /// or "==", and then the bits the padding leaves over have to be + /// zero. Nothing may follow the padding. + /// - Any other character is refused, whitespace too, which + /// unbase64mem() passes over. The specification has nothing but the + /// digits and the padding. + pub(crate) fn decode(text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len() / GROUP_DIGITS * GROUP_BYTES); + // The digits of the group so far, how many they are and how many + // of them are padding. + let mut group = 0u32; + let mut digits = 0; + let mut padding = 0; + let mut ended = false; + for &b in text.as_bytes() { + if ended { + return None; + } + let value = if b == PAD { + padding += 1; + 0 + } else if padding > 0 { + return None; + } else { + Base64::value(b)? + }; + group = (group << DIGIT_BITS) | u32::from(value); + digits += 1; + if digits < GROUP_DIGITS { + continue; + } + if padding > MAX_PADDING { + return None; + } + // The three bytes of the group are the low ones. Those the + // padding stands for have to be zero. + let bytes = group.to_be_bytes(); + let (kept, rest) = bytes[size_of::() - GROUP_BYTES..].split_at(GROUP_BYTES - padding); + if rest.iter().any(|&b| b != 0) { + return None; + } + out.extend_from_slice(kept); + ended = padding > 0; + group = 0; + digits = 0; + padding = 0; + } + (digits == 0).then_some(out) + } +} + +impl fmt::Display for Base64<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut text = [PAD; CHUNK_GROUPS * GROUP_DIGITS]; + for chunk in self.0.chunks(CHUNK_GROUPS * GROUP_BYTES) { + let mut len = 0; + for bytes in chunk.chunks(GROUP_BYTES) { + let mut group = [0u8; size_of::()]; + group[size_of::() - GROUP_BYTES..][..bytes.len()].copy_from_slice(bytes); + let group = u32::from_be_bytes(group); + // A group of n bytes has n + 1 digits, padding fills the rest. + for digit in 0..GROUP_DIGITS { + let shift = DIGIT_BITS * (GROUP_DIGITS - 1 - digit) as u32; + text[len] = if digit <= bytes.len() { + ALPHABET[(group >> shift) as usize % ALPHABET.len()] + } else { + PAD + }; + len += 1; + } + } + f.write_str(std::str::from_utf8(&text[..len]).expect("ASCII"))?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test vectors of systemd's unbase64mem() in + /// src/test/test-hexdecoct.c: what it decodes and what it refuses. It + /// passes over whitespace, so the vectors with whitespace are refused + /// here. + #[test] + fn decodes() { + for (text, data) in [ + ("", ""), + ("Zg==", "f"), + ("Zm8=", "fo"), + ("Zm9v", "foo"), + ("Zm9vYg==", "foob"), + ("Zm9vYmE=", "fooba"), + ("Zm9vYmFy", "foobar"), + ] { + assert_eq!(Base64::decode(text).as_deref(), Some(data.as_bytes()), "{:?}", text); + } + for text in [ + " ", + " \n\r ", + " Zg\n== ", + " Zm 8=\r", + " Zm9\n\r\r\nv ", + " Z m9vYg==\n\r", + " Zm 9vYmE= ", + " Z m9v YmFy ", + "aGVs\nbG8 =", + "A", + "A====", + "AAB==", + " A A A B = ", + " Z m 8 = q u u x ", + ] { + assert_eq!(Base64::decode(text), None, "{:?}", text); + } + } + + /// Whitespace is not a digit, wherever it is: neither JSON's, which + /// systemd passes over, nor any other. + #[test] + fn refuses_whitespace() { + let text = "Zm9vYg=="; + for space in [" ", "\t", "\n", "\r", "\x0b", "\x0c"] { + for at in 0..=text.len() { + let mut spaced = text.to_string(); + spaced.insert_str(at, space); + assert_eq!(Base64::decode(&spaced), None, "{:?}", spaced); + } + } + } + + /// Both alphabets, with the values systemd's unbase64char() gives the + /// digits, and its test of the two spellings of the same data. + #[test] + fn alphabets() { + assert_eq!(Base64::decode("AZaz").unwrap(), [1, 150, 179]); + assert_eq!(Base64::decode("09+/").unwrap(), [211, 223, 191]); + assert_eq!(Base64::decode("09-_").unwrap(), [211, 223, 191]); + assert_eq!(Base64::decode("_-8=").unwrap(), [0xff, 0xef]); + let plaintext: &[u8] = &[ + 0xcc, 0xa1, 0x72, 0x22, 0xae, 0xda, 0x66, 0x7e, 0x04, 0xa6, 0xe0, 0x82, 0x9a, 0x97, 0x05, 0xf6, 0x33, 0xe0, + 0x0f, 0xc2, 0x45, 0x13, 0x58, 0x3f, 0xc5, 0xf4, 0xf4, 0x31, 0xab, 0x3c, 0x5f, 0x83, 0x34, 0x5b, 0x27, 0x32, + 0x8a, 0x04, 0x6c, 0x43, 0x82, 0x07, 0xe3, 0x2c, 0xac, 0xb9, 0xfb, 0xac, 0xd0, 0x03, 0x91, 0x42, 0xcb, 0xa4, + 0xde, 0x87, 0x86, 0x85, 0x10, 0xbb, 0xb7, 0x5b, 0x4b, 0xc8, 0xa0, 0xf4, 0x22, 0x1d, 0x15, 0x71, 0x87, 0x9d, + 0xbf, 0x9f, 0xa9, 0xf1, 0xee, 0xa2, 0xb6, 0xaa, 0xc8, 0xc3, 0x37, 0x9c, 0xbb, 0xdf, 0x3e, 0xac, 0xdc, 0x94, + 0x54, 0x38, 0x56, 0x07, 0x34, 0xb4, 0x3c, 0xcc, 0x31, 0x13, + ]; + let standard = "zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g/xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5+p8e6itqrIwzecu98+rNyUVDhWBzS0PMwxEw=="; + let url_safe = "zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g_xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5-p8e6itqrIwzecu98-rNyUVDhWBzS0PMwxEw=="; + for text in [standard, url_safe] { + assert_eq!(Base64::decode(text).as_deref(), Some(plaintext)); + } + // What is written is the standard alphabet. + assert_eq!(Base64(plaintext).to_string(), standard); + } + + /// One text can have digits of both alphabets, as systemd takes it. + #[test] + fn mixed_alphabets() { + for text in ["+_-/", "-/+_", "+/-_"] { + assert_eq!( + Base64::decode(text).as_deref(), + Some(&[0xfb, 0xff, 0xbf][..]), + "{:?}", + text + ); + } + assert_eq!(Base64::decode("Zm9v-_+/").as_deref(), Some(&b"foo\xfb\xff\xbf"[..])); + } + + /// What systemd refuses: a last group without its padding, incomplete + /// padding, padding with nothing to pad, padding that leaves bits set, + /// anything after the padding, and any character that is not a digit, + /// "=" or whitespace. + #[test] + fn refuses() { + for text in [ + "Zg", + "Zm8", + "aGVsbG8", + "Zg=", + "Zm9v=", + "Zm9v==", + "=", + "==", + " = ", + "Zh==", + "Zm9=", + "Zg==Zg==", + "Zg== x", + "Z=g=", + "====", + "Zm9\x0cv", + "Zm9\x0bv", + "!!!!", + "Zm9v\0", + "=AAA", + "A=AA", + "AA=A", + "Zg===", + "Zm9v\u{e9}", + ] { + assert_eq!(Base64::decode(text), None, "{:?}", text); + } + } + + #[test] + fn prints() { + for (data, text) in [ + ("", ""), + ("f", "Zg=="), + ("fo", "Zm8="), + ("foo", "Zm9v"), + ("foob", "Zm9vYg=="), + ("fooba", "Zm9vYmE="), + ("foobar", "Zm9vYmFy"), + ] { + assert_eq!(Base64(data.as_bytes()).to_string(), text); + } + assert_eq!(Base64(&[0xfb, 0xff, 0xbf]).to_string(), "+/+/"); + } + + /// Data of every length up to 300 bytes comes back from what is + /// printed for it. Broken into lines, as systemd's base64mem_full() can + /// write it, it is refused. + #[test] + fn round_trip() { + let mut x = 1u32; + for len in 0..300usize { + let data: Vec = (0..len) + .map(|_| { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + (x >> 16) as u8 + }) + .collect(); + let text = Base64(&data).to_string(); + assert_eq!(text.len(), len.div_ceil(GROUP_BYTES) * GROUP_DIGITS); + assert_eq!(Base64::decode(&text).as_deref(), Some(&data[..]), "{} bytes", len); + let mut lines = Vec::new(); + for line in text.as_bytes().chunks(1 + len % 77) { + lines.extend_from_slice(line); + lines.push(b'\n'); + } + if !lines.is_empty() { + let decoded = Base64::decode(std::str::from_utf8(&lines).unwrap()); + assert_eq!(decoded, None, "{} bytes", len); + } + } + } +} diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs new file mode 100644 index 0000000..c74a470 --- /dev/null +++ b/src/uapi16/decode.rs @@ -0,0 +1,2920 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Reading one record of a manifest into the object it holds, and the +//! rules for the fields of the objects, which the writer checks what it +//! writes against as well. +//! +//! A record is read once, member by member. Whether it is JSON at all is +//! only known at its end, and so is its media type, which says what kind +//! of object it is. So the first error in a field is noted and reported +//! when the record is known to be a file object. The rules are those of +//! the specification, and where it leaves something open those of +//! systemd's reader, src/shared/uapi16-manifest.c. + +use std::borrow::Cow; +use std::collections::{BTreeMap, HashSet}; +use std::fmt; +use std::num::NonZeroU64; + +use json::{ParseError, Parser}; + +use crate::base64::Base64; +use crate::digest::Digest; +use crate::error::{Error, Field, Problem}; +use crate::hex::Hex; +use crate::object::{ + Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FlagSet, GptPartition, InodeAttributes, InodeFlags, + InodeType, Location, Mode, RootObject, Signature, Uuid, Validity, +}; +use crate::{ + Features, Name, Order, Sha256, MAX_CONTENTS, MEDIA_TYPE, SIGNATURE_MEDIA_TYPE, STRING_RULES, TRAILER_MEDIA_TYPE, + USER_NAMESPACE, +}; + +/// The user and group ID that is -1 as an unsigned 32-bit integer, +/// `(uid_t) -1`, which stands for no ID. +const INVALID_ID: u32 = u32::MAX; +/// The user and group ID that is -1 as an unsigned 16-bit integer, which +/// the legacy 16-bit system calls take for no ID. +const INVALID_ID_16: u32 = u16::MAX as u32; +/// The schemes a URL can have. +const URL_SCHEMES: [&str; 2] = ["http://", "https://"]; +/// The symbols an HTTP field name may have besides letters and digits, +/// RFC 9110's tchar. +const TOKEN_SYMBOLS: &[u8] = b"!#$%&'*+-.^_`|~"; +/// What the value of an HTTP header field cannot have. +const LINE_BREAKS: [char; 2] = ['\r', '\n']; +/// The encoding that stands for none in HTTP, which a manifest does not +/// take. +const IDENTITY_ENCODING: &str = "identity"; + +/// What a record holds. +pub(crate) enum DecodedObject { + /// A file object, or what is wrong with it. + File(Result, Error>), + /// A signature object. + Signature(Signature), + /// The trailer object. + Trailer, + /// An object of a media type this crate does not know. + Other, +} + +/// What the `mediaType` of a record says it is. +#[derive(Clone, Copy, PartialEq, Eq)] +enum MediaType { + /// None was given, or null: the record holds a file object. + Absent, + /// The one of a manifest, which the first object of a manifest has to + /// have. + Manifest, + Signature, + Trailer, + Other, +} + +/// A member that has to be a string, as it was found. +enum StringMember<'a> { + /// Not there, or null. + Absent, + String(Cow<'a, str>), + /// There, and not a string. + NotString, +} + +/// What is wrong with a hash and the size of the data it is the hash of: +/// data of size 0 has the hash of no data, and only it has. +enum SizeHashConflict { + /// The hash of no data, with a size that is not 0. + EmptyHashWithSize, + /// The size 0, with a hash that is not the one of no data. + ZeroSizeWithHash, +} + +/// The object a message is about: `manifest object 5`, and with its name +/// `manifest object 5 (EFI/BOOT)`. +#[derive(Clone, Copy)] +pub(crate) struct Subject<'a> { + /// The number of the record the object is in. + record_number: u64, + name: Option<&'a str>, +} + +/// The size of some data and its hash, as far as they are known. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SizeAndHash { + pub(crate) size: Option, + pub(crate) sha256: Option, +} + +/// What a contents object says of its data, as it is stored and as it is +/// once decoded, with what follows from its fields. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ContentsData { + /// The data as it is stored, in its encoding. + pub(crate) encoded: SizeAndHash, + /// The data once it is decoded. + pub(crate) original: SizeAndHash, +} + +impl<'a> Subject<'a> { + /// The file object `object` of the record with the number + /// `record_number`. + pub(crate) fn new(object: &'a FileObject, record_number: u64) -> Subject<'a> { + Subject { + record_number, + name: (!object.name.is_root()).then_some(object.name.as_str()), + } + } + + /// The root file object, which the first record holds. + pub(crate) fn root() -> Subject<'static> { + Subject { + record_number: ROOT_RECORD, + name: Some(ROOT_NAME), + } + } +} + +impl fmt::Display for Subject<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "manifest object {}", self.record_number)?; + match self.name { + Some(name) => write!(f, " ({})", name.escape_debug()), + None => Ok(()), + } + } +} + +impl SizeAndHash { + /// Reconciles the size and the hash: the size 0 gives the hash of no + /// data and the hash of no data the size 0, and the two must not + /// contradict each other. + fn reconcile(&mut self) -> Result<(), SizeHashConflict> { + match (self.sha256, self.size) { + (Some(hash), Some(size)) if hash == Sha256::EMPTY && size != 0 => { + return Err(SizeHashConflict::EmptyHashWithSize) + } + (Some(hash), Some(0)) if hash != Sha256::EMPTY => return Err(SizeHashConflict::ZeroSizeWithHash), + (Some(hash), None) if hash == Sha256::EMPTY => self.size = Some(0), + (None, Some(0)) => self.sha256 = Some(Sha256::EMPTY), + _ => {} + } + Ok(()) + } +} + +impl SizeHashConflict { + /// The error about the object `subject` names, or about a contents + /// object of it, whose hash is the field `hash` and whose size the field + /// `size`. + fn into_error(self, subject: Subject<'_>, hash: Field, size: Field) -> Error { + match self { + SizeHashConflict::EmptyHashWithSize => Error::manifest( + Problem::Contradiction, + format!( + "{}: '{}' is the hash of no data, but '{}' is not 0", + subject, hash, size + ), + ) + .at(hash), + SizeHashConflict::ZeroSizeWithHash => Error::manifest( + Problem::Contradiction, + format!( + "{}: '{}' is 0, but '{}' is not the hash of no data", + subject, size, hash + ), + ) + .at(size), + } + } +} + +impl Field { + /// The fields of a file object this crate reads, the most common + /// first. + const FILE_OBJECT: [Field; 40] = [ + Field::Name, + Field::Size, + Field::Sha256, + Field::MTimeNSec, + Field::Mode, + Field::Type, + Field::Uid, + Field::Gid, + Field::Contents, + Field::MediaType, + Field::UserName, + Field::GroupName, + Field::Major, + Field::Minor, + Field::InodeToken, + Field::ExtendedAttributes, + Field::ReadOnly, + Field::FlagHidden, + Field::FlagSystem, + Field::FlagArchive, + Field::FlagAppendOnly, + Field::FlagImmutable, + Field::FlagNoAtime, + Field::FlagNoCow, + Field::FlagNoDump, + Field::GptLabel, + Field::GptUuid, + Field::GptTypeUuid, + Field::GptDiskUuid, + Field::GptFlags, + Field::GptFlagNoAuto, + Field::GptFlagGrowFileSystem, + Field::FatSerial, + Field::FsUuid, + Field::FsLabel, + Field::Order, + Field::Features, + Field::ValidSinceUSec, + Field::ValidUntilUSec, + Field::Validity, + ]; + /// The fields of a contents object. + const CONTENTS: [Field; 10] = [ + Field::File, + Field::Url, + Field::Literal, + Field::Encoding, + Field::EncodedSize, + Field::EncodedSha256, + Field::OriginalSize, + Field::OriginalSha256, + Field::Offset, + Field::HttpHeaders, + ]; + /// The fields of the value of an extended attribute. + const EXTENDED_ATTRIBUTE: [Field; 2] = [Field::Text, Field::Base64]; + /// The fields of a signature object. + const SIGNATURE: [Field; 3] = [Field::Mechanism, Field::Key, Field::Data]; + + /// The field among `fields` whose name is `name`. + fn find_by_name(fields: &[Field], name: &str) -> Option { + fields.iter().copied().find(|field| field.as_str() == name) + } + + /// The field of a file object the key `key` names, if this crate reads + /// it. + fn from_file_object_key(key: &str) -> Option { + Field::find_by_name(&Field::FILE_OBJECT, key) + } + + /// The field of a contents object the key `key` names, if this crate + /// reads it. + fn from_contents_key(key: &str) -> Option { + Field::find_by_name(&Field::CONTENTS, key) + } + + /// The field of the value of an extended attribute the key `key` + /// names. + fn from_extended_attribute_key(key: &str) -> Option { + Field::find_by_name(&Field::EXTENDED_ATTRIBUTE, key) + } + + /// The field of a signature object the key `key` names, if this crate + /// reads it. + fn from_signature_key(key: &str) -> Option { + Field::find_by_name(&Field::SIGNATURE, key) + } +} + +/// An object as far as its record was read: what does not go into a +/// [`FileObject`] as it is. The fields only the root file object has are +/// kept apart, so that the first record makes a [`RootObject`] of the +/// draft and every other record a [`FileObject`]. +struct Draft { + object: Box, + name: Option, + /// The name as the record has it, when it is not a valid one. + invalid_name: Option, + inode_type: Option, + /// `fsUUID`, `fsLabel` and `fatSerial`. + file_system: FileSystemIdentity, + /// `gptDiskUuid`. + gpt_disk_uuid: Option, + /// `order`. + order: Option, + /// `features`. + features: Option, + /// The first field the record has that only the root file object may + /// have. + root_only: Option, +} + +impl Draft { + /// The draft of a record no member of which was read yet. + fn new() -> Draft { + Draft { + object: Box::new(FileObject::new(Name::ROOT)), + name: None, + invalid_name: None, + inode_type: None, + file_system: FileSystemIdentity::default(), + gpt_disk_uuid: None, + order: None, + features: None, + root_only: None, + } + } + + /// The name the record gives, valid or not. + fn stated_name(&self) -> Option<&str> { + if !self.object.name.is_root() { + return Some(&self.object.name); + } + self.name.as_deref().or(self.invalid_name.as_deref()) + } + + /// The fields of a partition, which are made when the first of them is + /// read. + fn gpt(&mut self) -> &mut GptPartition { + self.object.gpt.get_or_insert_with(Box::default) + } + + /// The first field the draft has that only the file objects after the + /// root file object have: the contents, the size and the hash of a + /// file, its inode token and device numbers, the fields of a partition + /// and the DOS attributes. + fn file_only_field(&self) -> Option { + let object = &*self.object; + [ + (Field::Size, object.size.is_some()), + (Field::Sha256, object.sha256.is_some()), + (Field::Contents, !object.contents.is_empty()), + (Field::InodeToken, object.inode_token.is_some()), + (Field::Major, object.major.is_some()), + (Field::Minor, object.minor.is_some()), + ] + .into_iter() + .find_map(|(field, has)| has.then_some(field)) + .or_else(|| object.gpt.as_deref().and_then(GptPartition::first_field)) + .or_else(|| object.dos_flags.feature_fields().map(|(field, _)| field).next()) + } + + /// Checks the draft of the first record as the root file object: it + /// has no name, is a directory and has none of the fields only the + /// other file objects have. [`RootObject::check_consistency`] checks + /// its fields against each other. + fn check_root(&self) -> Result<(), Error> { + if self.name.is_some() { + return Err(Error::root_has_name()); + } + if !matches!(self.inode_type, None | Some(InodeType::Directory)) { + return Err(Error::root_not_directory()); + } + match self.file_only_field() { + Some(field) => Err(Error::manifest( + Problem::FieldNotPermitted, + format!( + "{}: '{}' is not permitted on the root file object", + Subject::root(), + field + ), + ) + .at(field)), + None => Ok(()), + } + } + + /// The root file object the draft of the first record holds, once + /// [`Draft::check_root`] found nothing wrong with it. + fn into_root(self) -> RootObject { + let object = *self.object; + RootObject { + inode: object.inode, + file_system: self.file_system, + gpt_disk_uuid: self.gpt_disk_uuid, + order: self.order, + features: self.features, + validity: object.validity, + } + } + + /// Makes the draft the file object of the record with the number + /// `record_number`, one after the root file object: checks its fields + /// against its inode type and against each other, and fills in what + /// follows from them. + fn finish(&mut self, record_number: u64) -> Result<(), Error> { + let Some(name) = self.name.take() else { + return Err(Error::no_name(record_number)); + }; + let object = &mut *self.object; + object.name = name; + object.inode_type = self.inode_type.unwrap_or(InodeType::Regular); + let subject = Subject::new(object, record_number); + object.check_permitted_fields(subject)?; + if let Some(field) = self.root_only { + return Err(Error::manifest( + Problem::FieldNotPermitted, + format!("{}: '{}' is only permitted on the root file object", subject, field), + ) + .at(field)); + } + // The contents objects were checked when they were read, and hold + // what follows from their fields. + let data = object.check_consistency(subject, |contents| Ok(contents.data()))?; + // What the record does not give was filled in. + for (field, given, known) in [ + (Field::Size, object.size.is_some(), data.size.is_some()), + (Field::Sha256, object.sha256.is_some(), data.sha256.is_some()), + ] { + if known && !given { + object.filled_in.insert(field); + } + } + (object.size, object.sha256) = (data.size, data.sha256); + Ok(()) + } +} + +// The rules for the fields of the objects, which the reader holds what it +// reads to and the writer what it writes. Each check names the object in +// its error with `subject`. + +impl FileObject { + /// Checks that the object has no field its inode type does not permit: + /// a size, contents objects or a hash on anything but a regular file, a + /// symbolic link or a directory, device numbers on anything but a + /// device, an access mode on a symbolic link, an inode token on a + /// directory, the fields of a partition on anything but a regular file, + /// and flags on anything but a regular file or a directory. + pub(crate) fn check_permitted_fields(&self, subject: Subject<'_>) -> Result<(), Error> { + let inode_type = self.inode_type; + let not_permitted = |message: String| Error::manifest(Problem::FieldNotPermitted, message); + if self.size.is_some() && !inode_type.has_contents() { + return Err( + not_permitted(format!("{}: 'size' is not permitted on a {}", subject, inode_type)).at(Field::Size), + ); + } + if (self.major.is_some() || self.minor.is_some()) && !inode_type.is_device() { + return Err(not_permitted(format!( + "{}: 'major' and 'minor' are not permitted on a {}", + subject, inode_type + )) + .at(Field::Major)); + } + if self.inode.mode.is_some() && inode_type == InodeType::Symlink { + return Err(not_permitted(format!("{}: 'mode' is not permitted on a symlink", subject)).at(Field::Mode)); + } + if self.inode_token.is_some() && inode_type == InodeType::Directory { + return Err( + not_permitted(format!("{}: 'inodeToken' is not permitted on a directory", subject)) + .at(Field::InodeToken), + ); + } + if (!self.contents.is_empty() || self.sha256.is_some()) && !inode_type.has_contents() { + return Err(not_permitted(format!( + "{}: 'contents' and 'sha256' are not permitted on a {}", + subject, inode_type + )) + .at(Field::Contents)); + } + if inode_type != InodeType::Regular { + if let Some(field) = self.gpt.as_deref().and_then(GptPartition::first_field) { + return Err( + not_permitted(format!("{}: '{}' is not permitted on a {}", subject, field, inode_type)).at(field), + ); + } + } + match self.unpermitted_flag() { + Some(field) => Err(Error::unpermitted_flag(self, field, subject)), + None => Ok(()), + } + } + + /// Checks that the fields of the object agree with each other, as the + /// specification requires: `readOnly` and `mode`, and the size and the + /// hash of the object and those of its contents objects. `contents_data` + /// gives what each contents object says of its data: what + /// [`Contents::check_consistency`] returns for it, or what its fields + /// hold once a reader checked and filled it in. Returns the size and the + /// hash of the data of the object: those it gives, and those that follow + /// from its contents objects and from each other. Whether `gptFlags` + /// agrees with the fields that give its flags one by one depends on what + /// the manifest records, see [`FileObject::check_partition_flags`]. + pub(crate) fn check_consistency( + &self, + subject: Subject<'_>, + contents_data: impl Fn(&Contents) -> Result, + ) -> Result { + self.inode.check_read_only(subject)?; + // The size and the hash of the object and those of its contents + // objects have to agree where they are about the same data. A part + // of the data of a contents object, of the size the object gives, + // has to fit into it. Without a size of the object, a contents + // object gives it: the rest of its data from the offset on, and + // every contents object that gives one has to give the same. A + // contents object that is all of the data gives its hash. + let mut data = SizeAndHash { + size: self.size, + sha256: self.sha256, + }; + for contents in &self.contents { + let original = contents_data(contents)?.original; + let Some(total) = original.size else { + continue; + }; + // Contents::check_consistency found the offset inside the data. + let rest = total - contents.offset; + match (self.size, data.size) { + (Some(stated), _) => { + if contents.offset.checked_add(stated).is_none_or(|end| end > total) { + return Err(Error::manifest( + Problem::Contradiction, + format!( + "{}: offset {} plus size {} exceeds the contents size {}", + subject, contents.offset, stated, total + ), + ) + .at(Field::Offset)); + } + } + (None, None) => data.size = Some(rest), + (None, Some(given)) => { + if given != rest { + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: contents objects give the sizes {} and {}", subject, given, rest), + ) + .at(Field::Contents)); + } + } + } + // The size of the object is known from here on. + let whole = contents.offset == 0 && original.size == data.size; + match (original.sha256.filter(|_| whole), data.sha256) { + (Some(hash), Some(known)) if hash != known => { + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: object and contents hashes differ", subject), + ) + .at(Field::Sha256)); + } + (Some(hash), None) => data.sha256 = Some(hash), + _ => {} + } + } + // What the size and the hash were given or follow from has to agree. + data.reconcile() + .map_err(|conflict| conflict.into_error(subject, Field::Sha256, Field::Size))?; + Ok(data) + } + + /// Checks that the attribute flags of the partition the object + /// describes agree where they are given twice: all of them in + /// `gptFlags`, and one each in `gptFlagNoAuto`, `gptFlagGrowFileSystem` + /// and `readOnly`. Where `features`, which the manifest records, has + /// the feature of one of these fields, an object without the field + /// counts as having it cleared, and `gptFlags` as 0. Only a regular + /// file has `gptFlags`. + pub(crate) fn check_partition_flags(&self, features: Features, subject: Subject<'_>) -> Result<(), Error> { + let gpt = self.gpt.as_deref(); + let given = gpt.and_then(|gpt| gpt.flags); + let implied = (self.inode_type == InodeType::Regular && features.contains(Features::GPT_FLAGS)).then_some(0); + let Some(flags) = given.or(implied) else { + return Ok(()); + }; + let one_each = [ + ( + Field::GptFlagNoAuto, + gpt.and_then(|gpt| gpt.no_auto), + Features::GPT_FLAG_NO_AUTO, + GptPartition::FLAG_NO_AUTO, + ), + ( + Field::GptFlagGrowFileSystem, + gpt.and_then(|gpt| gpt.grow_file_system), + Features::GPT_FLAG_GROW_FILE_SYSTEM, + GptPartition::FLAG_GROW_FILE_SYSTEM, + ), + ( + Field::ReadOnly, + self.inode.stated_read_only(), + Features::READ_ONLY, + GptPartition::FLAG_READ_ONLY, + ), + ]; + for (field, stated, feature, flag) in one_each { + let set = stated.or(features.contains(feature).then_some(false)); + if set.is_none_or(|set| set == (flags & flag != 0)) { + continue; + } + // The error is about a field the object has. Where the other + // one is missing, the message says what that stands for. + let (at, missing) = match (given, stated) { + (Some(_), Some(_)) => (Field::GptFlags, None), + (Some(_), None) => (Field::GptFlags, Some((field, feature, "false"))), + (None, _) => (field, Some((Field::GptFlags, Features::GPT_FLAGS, "0"))), + }; + let mut message = format!( + "{}: '{}' and '{}' contradict each other", + subject, + Field::GptFlags, + field + ); + if let Some((missing, feature, value)) = missing { + message = format!( + "{} ('{}' is not there, which means {} as the manifest lists '{}')", + message, + missing, + value, + feature.names().next().unwrap_or_default() + ); + } + return Err(Error::manifest(Problem::Contradiction, message).at(at)); + } + Ok(()) + } + + /// The user or group ID `id`, the value of `field`, if it is one. The + /// two IDs that stand for no ID are none. + pub(crate) fn check_id(field: Field, id: u64, subject: Subject<'_>) -> Result { + match u32::try_from(id) { + Ok(id) if id != INVALID_ID && id != INVALID_ID_16 => Ok(id), + _ => Err(Error::manifest( + Problem::FieldOutOfRange, + format!("{}: {} {} is out of range", subject, field, id), + ) + .at(field)), + } + } + + /// Checks `name`, the value of `field`, as the name of a user or of a + /// group. systemd's relaxed rules take anything that is not obviously + /// broken or a number in disguise. + pub(crate) fn check_owner_name(field: Field, name: &str, subject: Subject<'_>) -> Result<(), Error> { + let digits = name.strip_prefix('-').unwrap_or(name); + if name.is_empty() + || name.starts_with(' ') + || name.ends_with(' ') + || name == "." + || name == ".." + || name.chars().any(|c| c.is_ascii_control() || c == ':' || c == '/') + || digits.bytes().all(|b| b.is_ascii_digit()) + { + return Err(Error::manifest( + Problem::WrongFieldType, + format!("{}: {} '{}' is not a valid name", subject, field, name.escape_debug()), + ) + .at(field)); + } + Ok(()) + } + + /// Checks `name` as the name of an extended attribute: it is not empty + /// and has no control character. + pub(crate) fn check_xattr_name(name: &str, subject: Subject<'_>) -> Result<(), Error> { + if name.is_empty() || name.chars().any(|c| c.is_ascii_control()) { + return Err(Error::manifest( + Problem::InvalidExtendedAttributes, + format!("{}: invalid extended attribute name '{}'", subject, name.escape_debug()), + ) + .at(Field::ExtendedAttributes)); + } + Ok(()) + } +} + +impl RootObject { + /// Checks that the fields of the root file object agree with each + /// other, as the specification requires: `readOnly` and `mode`. + pub(crate) fn check_consistency(&self) -> Result<(), Error> { + self.inode.check_read_only(Subject::root()) + } +} + +impl InodeAttributes { + /// Checks that `readOnly` and `mode` agree where the attributes have + /// both: the file is read-only if nobody has write permission. A + /// `readOnly` a reader filled in is not one the attributes have, see + /// [`FilledIn`](crate::FilledIn). + fn check_read_only(&self, subject: Subject<'_>) -> Result<(), Error> { + match (self.stated_read_only(), self.mode) { + (Some(read_only), Some(mode)) if read_only == mode.is_writable() => Err(Error::manifest( + Problem::Contradiction, + format!("{}: 'readOnly' and 'mode' contradict each other", subject), + ) + .at(Field::ReadOnly)), + _ => Ok(()), + } + } +} + +impl Contents { + /// Checks that the fields of the contents object agree with each + /// other, as the specification requires, and returns what they say of + /// its data with what follows from them: a literal gives the size of + /// the stored data, and without an encoding the stored data is the + /// data. A size of 0 and the hash of no data go together. `httpHeaders` + /// come with a URL only, and the offset is inside the data. `subject` + /// names the file object the contents object belongs to. + pub(crate) fn check_consistency(&self, subject: Subject<'_>) -> Result { + if !self.http_headers.is_empty() && self.url().is_none() { + return Err(Error::manifest( + Problem::InvalidContents, + format!("{}: 'httpHeaders' is only permitted with 'url'", subject), + ) + .at(Field::HttpHeaders)); + } + let mut data = self.data(); + // A literal is as large as the data as it is stored, and without + // an encoding that is the data. + if let Location::Literal(literal) = &self.location { + let len = literal.len() as u64; + let original = data.original.size.filter(|_| self.encoding.is_none()); + if let Some(size) = [data.encoded.size, original] + .into_iter() + .flatten() + .find(|&size| size != len) + { + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: literal contents are {} bytes, not {}", subject, len, size), + ) + .at(Field::Literal)); + } + data.encoded.size = Some(len); + if self.encoding.is_none() { + data.original.size = Some(len); + } + } + data.encoded + .reconcile() + .map_err(|conflict| conflict.into_error(subject, Field::EncodedSha256, Field::EncodedSize))?; + data.original + .reconcile() + .map_err(|conflict| conflict.into_error(subject, Field::OriginalSha256, Field::OriginalSize))?; + if self.encoding.is_none() { + // Without an encoding the encoded and the original data are the same. + let ContentsData { encoded, original } = &mut data; + match (encoded.size, original.size) { + (Some(a), Some(b)) if a != b => { + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: encoded and original size differ without an encoding", subject), + ) + .at(Field::EncodedSize)); + } + (Some(a), None) => original.size = Some(a), + (None, Some(b)) => encoded.size = Some(b), + _ => {} + } + match (encoded.sha256, original.sha256) { + (Some(a), Some(b)) if a != b => { + return Err(Error::manifest( + Problem::Contradiction, + format!("{}: encoded and original hash differ without an encoding", subject), + ) + .at(Field::EncodedSha256)); + } + (Some(a), None) => original.sha256 = Some(a), + (None, Some(b)) => encoded.sha256 = Some(b), + _ => {} + } + } + if let Some(total) = data.original.size { + if self.offset > total { + return Err(Error::manifest( + Problem::InvalidContents, + format!( + "{}: contents offset {} is beyond the data size {}", + subject, self.offset, total + ), + ) + .at(Field::Offset)); + } + } + Ok(data) + } + + /// What the contents object says of its data, as its fields hold it. + fn data(&self) -> ContentsData { + ContentsData { + encoded: SizeAndHash { + size: self.encoded_size, + sha256: self.encoded_sha256, + }, + original: SizeAndHash { + size: self.original_size, + sha256: self.original_sha256, + }, + } + } + + /// Fills in what follows from the fields of the contents object, `data` + /// from [`Contents::check_consistency`], and notes what it filled in. + fn fill_in(&mut self, data: ContentsData) { + let given = [ + self.encoded_size.is_some(), + self.encoded_sha256.is_some(), + self.original_size.is_some(), + self.original_sha256.is_some(), + ]; + let known = [ + (Field::EncodedSize, data.encoded.size.is_some()), + (Field::EncodedSha256, data.encoded.sha256.is_some()), + (Field::OriginalSize, data.original.size.is_some()), + (Field::OriginalSha256, data.original.sha256.is_some()), + ]; + for ((field, known), given) in known.into_iter().zip(given) { + if known && !given { + self.filled_in.insert(field); + } + } + (self.encoded_size, self.encoded_sha256) = (data.encoded.size, data.encoded.sha256); + (self.original_size, self.original_sha256) = (data.original.size, data.original.sha256); + } + + /// Checks `url` as the URL of the data: an http or an https one. + pub(crate) fn check_url(url: &str, subject: Subject<'_>) -> Result<(), Error> { + if !URL_SCHEMES.iter().any(|scheme| url.starts_with(scheme)) { + return Err(Error::manifest( + Problem::InvalidContents, + format!( + "{}: contents URL '{}' is not http or https", + subject, + url.escape_debug() + ), + ) + .at(Field::Url)); + } + Ok(()) + } + + /// Checks `encoding` as the encoding of the data: a content coding of + /// HTTP, which does not tell upper case from lower case, other than the + /// one that stands for none. + pub(crate) fn check_encoding(encoding: &str, subject: Subject<'_>) -> Result<(), Error> { + if encoding.is_empty() || encoding.eq_ignore_ascii_case(IDENTITY_ENCODING) { + return Err(Error::manifest( + Problem::InvalidContents, + format!("{}: encoding '{}' is not permitted", subject, encoding.escape_debug()), + ) + .at(Field::Encoding)); + } + Ok(()) + } + + /// Checks `headers` as the header fields of the requests for the data + /// at a URL: a name is a token as RFC 9110 has it, and none comes twice + /// in any case. A value has no line break. + pub(crate) fn check_headers(headers: &[(String, String)], subject: Subject<'_>) -> Result<(), Error> { + let mut names = HashSet::new(); + for (name, value) in headers { + let token = !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || TOKEN_SYMBOLS.contains(&b)); + let problem = if !token { + format!("'{}' is not the name of an HTTP header field", name.escape_debug()) + } else if value.contains(LINE_BREAKS) { + format!( + "the value of HTTP header field '{}' has a line break", + name.escape_debug() + ) + } else if !names.insert(name.to_ascii_lowercase()) { + format!("HTTP header field '{}' is given twice", name.escape_debug()) + } else { + continue; + }; + return Err( + Error::manifest(Problem::InvalidContents, format!("{}: {}", subject, problem)).at(Field::HttpHeaders), + ); + } + Ok(()) + } +} + +impl GptPartition { + /// The first field of the partition that is set, of `gptLabel`, + /// `gptUuid`, `gptTypeUuid`, `gptFlags`, `gptFlagNoAuto` and + /// `gptFlagGrowFileSystem`. + pub(crate) fn first_field(&self) -> Option { + [ + (Field::GptLabel, self.label.is_some()), + (Field::GptUuid, self.uuid.is_some()), + (Field::GptTypeUuid, self.type_uuid.is_some()), + (Field::GptFlags, self.flags.is_some()), + (Field::GptFlagNoAuto, self.no_auto.is_some()), + (Field::GptFlagGrowFileSystem, self.grow_file_system.is_some()), + ] + .into_iter() + .find_map(|(field, set)| set.then_some(field)) + } + + /// Checks `label` as a partition label: it has no control characters + /// and no more UTF-16 units than the partition table has room for. + pub(crate) fn check_label(label: &str, subject: Subject<'_>) -> Result<(), Error> { + if label.chars().any(char::is_control) || label.encode_utf16().nth(GptPartition::LABEL_MAX).is_some() { + return Err(Error::manifest( + Problem::WrongFieldType, + format!( + "{}: '{}' is not a valid GPT partition label", + subject, + label.escape_debug() + ), + ) + .at(Field::GptLabel)); + } + Ok(()) + } +} + +impl FileSystemIdentity { + /// Checks `label` as the label of a file system, see + /// [`FileSystemIdentity::is_valid_label`]. + pub(crate) fn check_label(label: &str, subject: Subject<'_>) -> Result<(), Error> { + if !FileSystemIdentity::is_valid_label(label) { + return Err(Error::manifest( + Problem::WrongFieldType, + format!( + "{}: '{}' is not a valid file system label", + subject, + label.escape_debug() + ), + ) + .at(Field::FsLabel)); + } + Ok(()) + } +} + +/// The number of the first record of a manifest, the one that holds the +/// root file object. +pub(crate) const ROOT_RECORD: u64 = 0; +/// What a message calls the root file object, which has no name. +const ROOT_NAME: &str = "root"; + +/// Reads one record, member by member, into the object it holds. +pub(crate) struct RecordDecoder<'a> { + json: Parser<'a>, + /// The number of the record, for what is said about it. + record_number: u64, + /// The first error found in a field. + first_error: Option, +} + +/// A record that was read as a file object, before its media type said +/// whether it is one. +struct Candidate { + draft: Draft, + record_number: u64, + first_error: Option, +} + +impl Candidate { + /// The root file object the first record holds, or what is wrong with + /// it. + fn into_root_object(mut self) -> Result { + let checked = match self.first_error.take() { + Some(e) => Err(e), + None => self.draft.check_root(), + }; + checked.map_err(|e| self.annotate(e))?; + let root = self.draft.into_root(); + root.check_consistency().map_err(|e| e.in_record(self.record_number))?; + Ok(root) + } + + /// The file object the record holds, or what is wrong with it. + fn into_file_object(mut self) -> Result, Error> { + let finished = match self.first_error.take() { + Some(e) => Err(e), + None => self.draft.finish(self.record_number), + }; + finished.map_err(|e| self.annotate(e))?; + Ok(self.draft.object) + } + + /// Annotates `e` as an error about the record: with its number, and + /// with the name of the object as the record states it. + fn annotate(&self, e: Error) -> Error { + let e = e.in_record(self.record_number); + match self.draft.stated_name() { + Some(name) => e.named(name), + None => e, + } + } +} + +impl<'a> RecordDecoder<'a> { + /// Reads the record `text`, the one with the number `record_number`, as + /// far as a file object goes, and says what its media type makes it. + fn read(text: &'a str, record_number: u64) -> Result<(MediaType, Candidate), Error> { + let mut decoder = RecordDecoder { + json: Parser::with_rules(text, STRING_RULES), + record_number, + first_error: None, + }; + let not_json = |e| Error::not_json(record_number, e); + if !decoder.json.object().map_err(not_json)? { + decoder.json.skip().map_err(not_json)?; + decoder.json.end().map_err(not_json)?; + return Err(Error::manifest( + Problem::NotObject, + format!("manifest record {} is not a JSON object", record_number), + ) + .in_record(record_number)); + } + let (media_type, draft) = decoder.file_object().map_err(not_json)?; + decoder.json.end().map_err(not_json)?; + let Some(media_type) = media_type else { + return Err(Error::manifest( + Problem::InvalidMediaType, + format!("manifest object {} has a mediaType that is not a string", record_number), + ) + .in_record(record_number)); + }; + let candidate = Candidate { + draft, + record_number, + first_error: decoder.first_error, + }; + Ok((media_type, candidate)) + } + + /// Reads the first record of a manifest, which holds the root file + /// object and says with its media type that this is a manifest. + pub(crate) fn root(text: &'a str) -> Result { + let (media_type, candidate) = RecordDecoder::read(text, ROOT_RECORD)?; + if media_type != MediaType::Manifest { + return Err(Error::manifest( + Problem::InvalidMediaType, + "the first object of the manifest is not of the manifest media type".into(), + ) + .in_record(ROOT_RECORD)); + } + candidate.into_root_object() + } + + /// Reads the record `text`, the one with the number `record_number`, + /// which is not the first. + pub(crate) fn record(text: &'a str, record_number: u64) -> Result { + let (media_type, candidate) = RecordDecoder::read(text, record_number)?; + Ok(match media_type { + MediaType::Trailer => DecodedObject::Trailer, + MediaType::Signature => DecodedObject::Signature(Signature::decode(text, record_number)?), + MediaType::Other => DecodedObject::Other, + MediaType::Absent | MediaType::Manifest => DecodedObject::File(candidate.into_file_object()), + }) + } + + /// Notes the error `problem` in `field`, which `message` describes, + /// unless an error was noted before. + fn note_error(&mut self, problem: Problem, field: Field, message: impl FnOnce() -> String) { + if self.first_error.is_none() { + self.first_error = Some(Error::manifest(problem, message()).at(field)); + } + } + + /// The value `checked` holds, or None after noting its error, unless an + /// error was noted before. + fn note_err(&mut self, checked: Result) -> Option { + checked + .map_err(|e| { + self.first_error.get_or_insert(e); + }) + .ok() + } + + /// The object the record is about, for a message. The first record + /// holds the root file object. + fn subject(&self) -> Subject<'static> { + if self.record_number == ROOT_RECORD { + return Subject::root(); + } + Subject { + record_number: self.record_number, + name: None, + } + } + + /// Reads a string. Any other value is an error, which is noted. + fn string(&mut self, field: Field) -> Result>, ParseError> { + let value = self.json.string()?; + if value.is_none() { + self.json.skip()?; + self.note_error(Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not a string", field) + }); + } + Ok(value) + } + + /// Reads a boolean. Any other value is an error, which is noted. + fn bool(&mut self, field: Field) -> Result, ParseError> { + let value = self.json.bool()?; + if value.is_none() { + self.json.skip()?; + self.note_error(Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not a boolean", field) + }); + } + Ok(value) + } + + /// Reads an unsigned integer of 64 bits: a number written as decimal + /// digits without sign, fraction or exponent, as the specification has + /// it. Any other value is an error, which is noted, a string of digits + /// too. + fn unsigned(&mut self, field: Field) -> Result, ParseError> { + let value = match self.json.number()? { + Some(number) => number.as_u64(), + None => { + self.json.skip()?; + None + } + }; + if value.is_none() { + self.note_error(Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not an unsigned integer", field) + }); + } + Ok(value) + } + + /// Reads a hash. Anything but the hex digits of one is an error, which + /// is noted. + fn digest(&mut self, field: Field) -> Result, ParseError> { + let Some(text) = self.string(field)? else { + return Ok(None); + }; + let digest = text.parse().ok(); + if digest.is_none() { + self.note_error(Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not a SHA-256 hash", field) + }); + } + Ok(digest) + } + + /// Reads an access mode, an unsigned integer like every other one. + fn mode(&mut self, field: Field) -> Result, ParseError> { + let Some(bits) = self.unsigned(field)? else { + return Ok(None); + }; + let mode = u32::try_from(bits).ok().and_then(Mode::new); + if mode.is_none() { + self.note_error(Problem::FieldOutOfRange, field, || { + format!("manifest field '{}' is out of range: {}", field, bits) + }); + } + Ok(mode) + } + + /// Reads a user or group ID. + fn id(&mut self, field: Field) -> Result, ParseError> { + let Some(id) = self.unsigned(field)? else { + return Ok(None); + }; + Ok(self.note_err(FileObject::check_id(field, id, self.subject()))) + } + + /// Reads the name of a user or of a group. + fn user_or_group_name(&mut self, field: Field) -> Result>, ParseError> { + let Some(name) = self.string(field)? else { + return Ok(None); + }; + let checked = FileObject::check_owner_name(field, &name, self.subject()); + Ok(self.note_err(checked).map(|()| name.into())) + } + + /// Reads a UUID. + fn uuid(&mut self, field: Field) -> Result, ParseError> { + let Some(text) = self.string(field)? else { + return Ok(None); + }; + let uuid = text.parse().ok(); + if uuid.is_none() { + let subject = self.subject(); + self.note_error(Problem::WrongFieldType, field, || { + format!("{}: {} '{}' is not a UUID", subject, field, text.escape_debug()) + }); + } + Ok(uuid) + } + + /// Reads a GPT partition label. + fn gpt_label(&mut self, field: Field) -> Result, ParseError> { + let Some(label) = self.string(field)? else { + return Ok(None); + }; + let checked = GptPartition::check_label(&label, self.subject()); + Ok(self.note_err(checked).map(|()| label.into_owned())) + } + + /// Reads a FAT volume serial number, `1234-ABCD`. + fn fat_serial(&mut self, field: Field) -> Result, ParseError> { + let Some(text) = self.string(field)? else { + return Ok(None); + }; + let serial = text.parse().ok(); + if serial.is_none() { + let subject = self.subject(); + self.note_error(Problem::WrongFieldType, field, || { + format!( + "{}: {} '{}' is not a FAT volume serial number", + subject, + field, + text.escape_debug() + ) + }); + } + Ok(serial) + } + + /// Reads a file system label. + fn fs_label(&mut self, field: Field) -> Result, ParseError> { + let Some(label) = self.string(field)? else { + return Ok(None); + }; + let checked = FileSystemIdentity::check_label(&label, self.subject()); + Ok(self.note_err(checked).map(|()| label.into_owned())) + } + + /// Reads `order`. A value the specification does not have declares no + /// order, as it asks. + fn order(&mut self, field: Field) -> Result, ParseError> { + Ok(self.string(field)?.and_then(|value| Order::declared(&value))) + } + + /// Reads `features`: an array of strings, none of them twice. Names + /// the specification does not have are passed over, as it asks. + fn features(&mut self, field: Field) -> Result, ParseError> { + let subject = self.subject(); + if !self.json.array()? { + self.json.skip()?; + self.note_error(Problem::WrongFieldType, field, || { + format!("{}: '{}' is not an array of strings", subject, field) + }); + return Ok(None); + } + let mut features = Features::NONE; + let mut names = HashSet::new(); + while self.json.element()? { + let Some(name) = self.json.string()? else { + self.json.skip()?; + self.note_error(Problem::WrongFieldType, field, || { + format!("{}: '{}' is not an array of strings", subject, field) + }); + continue; + }; + if let Some(feature) = Features::listed(&name) { + features |= feature; + } + if names.contains(&name) { + self.note_error(Problem::FieldOutOfRange, field, || { + format!("{}: '{}' lists '{}' twice", subject, field, name.escape_debug()) + }); + } + names.insert(name); + } + Ok(Some(features)) + } + + /// Reads `httpHeaders`: an object that maps the names of HTTP header + /// fields to their values, see [`Contents::check_headers`]. + fn http_headers(&mut self) -> Result, ParseError> { + let field = Field::HttpHeaders; + let subject = self.subject(); + let mut headers = Vec::new(); + if !self.json.object()? { + self.json.skip()?; + self.note_error(Problem::InvalidContents, field, || { + format!("{}: '{}' is not an object", subject, field) + }); + return Ok(headers); + } + while let Some(name) = self.json.key()? { + // A header field that is null is not there. + if self.json.null()? { + continue; + } + let Some(value) = self.json.string()? else { + self.json.skip()?; + self.note_error(Problem::InvalidContents, field, || { + format!( + "{}: the value of HTTP header field '{}' is not a string", + subject, + name.escape_debug() + ) + }); + continue; + }; + headers.push((name.into_owned(), value.into_owned())); + } + self.note_err(Contents::check_headers(&headers, subject)); + Ok(headers) + } + + /// Reads a member that has to be a string, whatever it is. + fn member(&mut self) -> Result, ParseError> { + if self.json.null()? { + return Ok(StringMember::Absent); + } + Ok(match self.json.string()? { + Some(text) => StringMember::String(text), + None => { + self.json.skip()?; + StringMember::NotString + } + }) + } + + /// What the `mediaType` in front of the parser says the record is. + /// None is a media type that is not a string. + fn media_type(&mut self) -> Result, ParseError> { + Ok(match self.json.string()?.as_deref() { + Some(MEDIA_TYPE) => Some(MediaType::Manifest), + Some(SIGNATURE_MEDIA_TYPE) => Some(MediaType::Signature), + Some(TRAILER_MEDIA_TYPE) => Some(MediaType::Trailer), + Some(_) => Some(MediaType::Other), + None => { + self.json.skip()?; + None + } + }) + } + + /// Reads the members of the object the parser is in as those of a + /// file object or of the root file object, and says what media type + /// the record has. None is a media type that is not a string. + fn file_object(&mut self) -> Result<(Option, Draft), ParseError> { + let mut media_type = Some(MediaType::Absent); + let mut draft = Draft::new(); + while let Some(key) = self.json.key()? { + let Some(field) = Field::from_file_object_key(&key) else { + self.json.skip()?; + continue; + }; + // A field that is null is a field that is not there. + if self.json.null()? { + continue; + } + if field == Field::MediaType { + media_type = self.media_type()?; + continue; + } + let object = &mut *draft.object; + match field { + Field::Name => { + if let Some(name) = self.string(field)? { + match Name::new(name.as_ref()) { + Ok(name) => draft.name = Some(name), + Err(reason) => { + let subject = self.subject(); + self.note_error(Problem::InvalidName, field, || { + format!("{}: {}: '{}'", subject, reason, name.escape_debug()) + }); + draft.invalid_name = Some(name.into_owned()); + } + } + } + } + Field::Type => { + if let Some(name) = self.string(field)? { + draft.inode_type = name.parse().ok(); + if draft.inode_type.is_none() { + let subject = self.subject(); + self.note_error(Problem::UnknownType, field, || { + format!("{}: unknown inode type '{}'", subject, name.escape_debug()) + }); + } + } + } + Field::Size => object.size = self.unsigned(field)?, + Field::Mode => object.inode.mode = self.mode(field)?, + Field::Uid => object.inode.uid = self.id(field)?, + Field::Gid => object.inode.gid = self.id(field)?, + Field::UserName => object.inode.user_name = self.user_or_group_name(field)?, + Field::GroupName => object.inode.group_name = self.user_or_group_name(field)?, + Field::Major => object.major = self.unsigned(field)?, + Field::Minor => object.minor = self.unsigned(field)?, + Field::MTimeNSec => object.inode.mtime_nsec = self.unsigned(field)?, + // The token 0 is that of a file with one name. + Field::InodeToken => object.inode_token = self.unsigned(field)?.and_then(NonZeroU64::new), + Field::ExtendedAttributes => object.inode.user_xattrs = self.extended_attributes()?.map(Box::new), + Field::GptLabel => draft.gpt().label = self.gpt_label(field)?, + Field::GptUuid => draft.gpt().uuid = self.uuid(field)?, + Field::GptTypeUuid => draft.gpt().type_uuid = self.uuid(field)?, + Field::GptFlags => draft.gpt().flags = self.unsigned(field)?, + Field::GptFlagNoAuto => draft.gpt().no_auto = self.bool(field)?, + Field::GptFlagGrowFileSystem => draft.gpt().grow_file_system = self.bool(field)?, + Field::ReadOnly => object.inode.read_only = self.bool(field)?, + Field::FlagHidden | Field::FlagSystem | Field::FlagArchive => { + if let (Some(flag), Some(set)) = (DosFlags::from_field(field), self.bool(field)?) { + object.dos_flags.put(flag, Some(set)); + } + } + Field::FlagAppendOnly + | Field::FlagImmutable + | Field::FlagNoAtime + | Field::FlagNoCow + | Field::FlagNoDump => { + if let (Some(flag), Some(set)) = (InodeFlags::from_field(field), self.bool(field)?) { + object.inode.flags.put(flag, Some(set)); + } + } + Field::FatSerial => { + draft.root_only.get_or_insert(field); + draft.file_system.fat_serial = self.fat_serial(field)?; + } + Field::FsUuid => { + draft.root_only.get_or_insert(field); + draft.file_system.uuid = self.uuid(field)?; + } + Field::FsLabel => { + draft.root_only.get_or_insert(field); + draft.file_system.label = self.fs_label(field)?; + } + Field::GptDiskUuid => { + draft.root_only.get_or_insert(field); + draft.gpt_disk_uuid = self.uuid(field)?; + } + Field::Order => { + draft.root_only.get_or_insert(field); + draft.order = self.order(field)?; + } + Field::Features => { + draft.root_only.get_or_insert(field); + draft.features = self.features(field)?; + } + Field::Contents => object.contents = self.contents()?, + Field::Sha256 => object.sha256 = self.digest(field)?, + Field::ValidSinceUSec => object.validity.since_usec = self.unsigned(field)?.unwrap_or_default(), + Field::ValidUntilUSec => object.validity.until_usec = self.unsigned(field)?, + // A value the specification does not have yet is good. + Field::Validity => { + if self + .string(field)? + .is_some_and(|validity| validity == Validity::Revoked.as_str()) + { + object.validity.state = Validity::Revoked; + } + } + _ => self.json.skip()?, + } + } + Ok((media_type, draft)) + } + + /// Reads the `extendedAttributes` field: namespaces that map names to + /// values, a value being an object with exactly one of `text` and + /// `base64`. Only the `user` namespace is defined. Others are passed + /// over, as systemd passes over them. + fn extended_attributes(&mut self) -> Result>>, ParseError> { + let field = Field::ExtendedAttributes; + let subject = self.subject(); + if !self.json.object()? { + self.json.skip()?; + self.note_error(Problem::InvalidExtendedAttributes, field, || { + format!("{}: 'extendedAttributes' is not an object", subject) + }); + return Ok(None); + } + let mut user = None; + while let Some(namespace) = self.json.key()? { + if namespace != USER_NAMESPACE { + self.json.skip()?; + continue; + } + // A namespace that is null says nothing about its attributes. + if self.json.null()? { + continue; + } + if !self.json.object()? { + self.json.skip()?; + self.note_error(Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: extended attribute namespace '{}' is not an object", + subject, namespace + ) + }); + continue; + } + let attributes = user.insert(BTreeMap::new()); + while let Some(name) = self.json.key()? { + // An attribute that is null is not there. + if self.json.null()? { + continue; + } + if self.note_err(FileObject::check_xattr_name(&name, subject)).is_none() { + self.json.skip()?; + continue; + } + if !self.json.object()? { + self.json.skip()?; + self.note_error(Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: value of extended attribute '{}' is not an object", + subject, + name.escape_debug() + ) + }); + continue; + } + let (mut text, mut base64) = (StringMember::Absent, StringMember::Absent); + while let Some(key) = self.json.key()? { + match Field::from_extended_attribute_key(&key) { + Some(Field::Text) => text = self.member()?, + Some(Field::Base64) => base64 = self.member()?, + _ => self.json.skip()?, + } + } + let value = match (text, base64) { + (StringMember::String(text), StringMember::Absent) => Some(text.into_owned().into_bytes()), + (StringMember::NotString, StringMember::Absent) => { + self.note_error(Problem::WrongFieldType, Field::Text, || { + format!("manifest field '{}' is not a string", Field::Text) + }); + None + } + (StringMember::Absent, StringMember::String(base64)) => { + let value = Base64::decode(&base64); + if value.is_none() { + self.note_error(Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: extended attribute '{}' is not valid Base64", + subject, + name.escape_debug() + ) + }); + } + value + } + (StringMember::Absent, StringMember::NotString) => { + self.note_error(Problem::WrongFieldType, Field::Base64, || { + format!("manifest field '{}' is not a string", Field::Base64) + }); + None + } + _ => { + self.note_error(Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: extended attribute '{}' needs exactly one of 'text' and 'base64'", + subject, + name.escape_debug() + ) + }); + None + } + }; + if let Some(value) = value { + attributes.insert(name.into_owned(), value); + } + } + } + Ok(user) + } + + /// Reads the `contents` field: an array of contents objects. + fn contents(&mut self) -> Result, ParseError> { + let field = Field::Contents; + let mut list = Vec::new(); + if !self.json.array()? { + self.json.skip()?; + self.note_error(Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not an array", field) + }); + return Ok(list); + } + let error_before = self.first_error.is_some(); + let mut count = 0usize; + while self.json.element()? { + let contents = self.contents_object()?; + count += 1; + if count <= MAX_CONTENTS { + list.push(contents); + } + } + // Too many of them is what is wrong with the field, whatever is + // wrong with one of them. + if count > MAX_CONTENTS && !error_before { + self.first_error = Some(Error::too_many_contents(self.subject())); + } + Ok(list) + } + + /// Reads one contents object. + fn contents_object(&mut self) -> Result { + let subject = self.subject(); + let mut contents = Contents::default(); + if !self.json.object()? { + self.json.skip()?; + self.note_error(Problem::InvalidContents, Field::Contents, || { + format!("{}: contents entry is not an object", subject) + }); + return Ok(contents); + } + // How many of file, url and literal the object has. + let mut places = 0; + while let Some(key) = self.json.key()? { + let Some(field) = Field::from_contents_key(&key) else { + self.json.skip()?; + continue; + }; + if self.json.null()? { + continue; + } + match field { + Field::File => { + if let Some(file) = self.string(field)? { + match Name::new(file.as_ref()) { + Ok(file) => { + contents.location = Location::File(file); + places += 1; + } + Err(reason) => self.note_error(Problem::InvalidContents, field, || { + format!( + "{}: contents file reference: {}: '{}'", + subject, + reason, + file.escape_debug() + ) + }), + } + } + } + Field::Url => { + if let Some(url) = self.string(field)? { + if self.note_err(Contents::check_url(&url, subject)).is_some() { + contents.location = Location::Url(url.into_owned()); + places += 1; + } + } + } + Field::Literal => { + if let Some(literal) = self.string(field)? { + match Base64::decode(&literal) { + Some(literal) => { + contents.location = Location::Literal(literal); + places += 1; + } + None => self.note_error(Problem::InvalidContents, field, || { + format!("{}: literal contents are not Base64", subject) + }), + } + } + } + Field::Encoding => { + if let Some(encoding) = self.string(field)? { + let encoding = encoding.to_ascii_lowercase(); + if self.note_err(Contents::check_encoding(&encoding, subject)).is_some() { + contents.encoding = Some(encoding); + } + } + } + Field::EncodedSize => contents.encoded_size = self.unsigned(field)?, + Field::EncodedSha256 => contents.encoded_sha256 = self.digest(field)?, + Field::OriginalSize => contents.original_size = self.unsigned(field)?, + Field::OriginalSha256 => contents.original_sha256 = self.digest(field)?, + Field::Offset => contents.offset = self.unsigned(field)?.unwrap_or_default(), + Field::HttpHeaders => contents.http_headers = self.http_headers()?, + _ => self.json.skip()?, + } + } + // What is wrong with the contents object as a whole counts unless an + // error was noted before. + if self.first_error.is_none() { + let checked = if places > 1 { + Err(Error::manifest( + Problem::InvalidContents, + format!("{}: only one of file, url and literal may be set", subject), + )) + } else { + contents.check_consistency(subject) + }; + match checked { + Ok(data) => contents.fill_in(data), + Err(e) => self.first_error = Some(e), + } + } + Ok(contents) + } +} + +impl Signature { + /// Reads the signature object the record `text` holds, the one with the + /// number `record_number`, which is known to be a JSON object. The + /// signature is not verified, but a manifest whose signature objects + /// are malformed is refused like systemd refuses it. + fn decode(text: &str, record_number: u64) -> Result { + let mut decoder = RecordDecoder { + json: Parser::with_rules(text, STRING_RULES), + record_number, + first_error: None, + }; + decoder + .signature() + .map_err(|e| Error::not_json(record_number, e))? + .map_err(|e| e.in_record(record_number)) + } +} + +impl RecordDecoder<'_> { + /// Reads the members of the record as those of a signature object. + fn signature(&mut self) -> Result, ParseError> { + let record_number = self.record_number; + let (mut mechanism, mut key, mut data) = (StringMember::Absent, StringMember::Absent, StringMember::Absent); + self.json.object()?; + while let Some(member) = self.json.key()? { + match Field::from_signature_key(&member) { + Some(Field::Mechanism) => mechanism = self.member()?, + Some(Field::Key) => key = self.member()?, + Some(Field::Data) => data = self.member()?, + _ => self.json.skip()?, + } + } + self.json.end()?; + let not_a_string = |field: Field| { + Error::manifest( + Problem::WrongFieldType, + format!("manifest field '{}' is not a string", field), + ) + .at(field) + }; + let StringMember::String(mechanism) = mechanism else { + return Ok(Err(Error::manifest( + Problem::InvalidSignature, + format!("manifest signature object {} has no 'mechanism' string", record_number), + ) + .at(Field::Mechanism))); + }; + let key = match key { + StringMember::Absent => None, + StringMember::NotString => return Ok(Err(not_a_string(Field::Key))), + StringMember::String(key) => match Hex::decode(&key) { + Some(key) => Some(key), + None => { + return Ok(Err(Error::manifest( + Problem::InvalidSignature, + format!("manifest signature object {}: 'key' is not hex", record_number), + ) + .at(Field::Key))); + } + }, + }; + let data = match data { + StringMember::Absent => None, + StringMember::NotString => return Ok(Err(not_a_string(Field::Data))), + StringMember::String(data) => match Base64::decode(&data) { + Some(data) => Some(data), + None => { + return Ok(Err(Error::manifest( + Problem::InvalidSignature, + format!("manifest signature object {}: 'data' is not Base64", record_number), + ) + .at(Field::Data))); + } + }, + }; + let mut signature = Signature::new(mechanism); + signature.key = key; + signature.data = data; + Ok(Ok(signature)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::ErrorKind; + use crate::testing::{read_whole, sequence, EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, WORLD}; + + /// The file object of `record`, the record after the root file object. + fn object(record: &str) -> FileObject { + match RecordDecoder::record(record, ROOT_RECORD + 1) { + Ok(DecodedObject::File(Ok(object))) => *object, + Ok(DecodedObject::File(Err(e))) | Err(e) => panic!("{}: {}", record, e), + Ok(_) => panic!("{}: not a file object", record), + } + } + + /// What is wrong with `record`, the record after the root file object. + fn refused(record: &str) -> Error { + match RecordDecoder::record(record, ROOT_RECORD + 1) { + Ok(DecodedObject::File(Err(e))) | Err(e) => e, + Ok(_) => panic!("{} was taken", record), + } + } + + #[test] + fn reads_every_field() { + let o = object(&format!( + concat!( + r#"{{"name":"dir/file","type":"reg","size":5,"mode":420,"uid":1000,"gid":100,"#, + r#""userName":"Domain Users","groupName":"users","mTimeNSec":1700000000000000005,"#, + r#""inodeToken":7,"extendedAttributes":{{"user":{{"b":{{"base64":"AP8="}},"a":{{"text":"x"}}}}}},"#, + r#""gptLabel":"root","gptUuid":"4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709","#, + r#""gptTypeUuid":"urn:uuid:4f68bce3e8cd4db196e7fbcaf984b709","gptFlags":9223372036854775808,"#, + r#""gptFlagNoAuto":true,"gptFlagGrowFileSystem":false,"readOnly":false,"sha256":"{}","#, + r#""contents":[{{"url":"https://example.com/x"}},{{"file":"blob","offset":2,"originalSize":7,"#, + r#""originalSha256":"{}"}}],"validSinceUSec":10,"validUntilUSec":20,"validity":"revoked","#, + r#""xVendorField":{{"anything":[1,2,3]}}}}"# + ), + HELLO, WORLD + )); + assert_eq!(o.name, "dir/file"); + assert_eq!(o.inode_type, InodeType::Regular); + assert_eq!(o.size, Some(5)); + assert_eq!(o.inode.mode, Mode::new(0o644)); + assert_eq!((o.inode.uid, o.inode.gid), (Some(1000), Some(100))); + assert_eq!(o.inode.user_name.as_deref(), Some("Domain Users")); + assert_eq!(o.inode.group_name.as_deref(), Some("users")); + assert_eq!((o.major, o.minor), (None, None)); + assert_eq!(o.inode.mtime_nsec, Some(1_700_000_000_000_000_005)); + assert_eq!(o.inode_token, NonZeroU64::new(7)); + let attributes = o.inode.user_xattrs.as_ref().unwrap(); + let listed: Vec<(&str, &[u8])> = attributes.iter().map(|(k, v)| (k.as_str(), &v[..])).collect(); + assert_eq!(listed, [("a", &b"x"[..]), ("b", &[0, 0xff])]); + let gpt = o.gpt.as_deref().unwrap(); + let uuid: Uuid = "4f68bce3-e8cd-4db1-96e7-fbcaf984b709".parse().unwrap(); + assert_eq!(gpt.label.as_deref(), Some("root")); + assert_eq!((gpt.uuid, gpt.type_uuid), (Some(uuid), Some(uuid))); + assert_eq!(gpt.flags, Some(GptPartition::FLAG_NO_AUTO)); + assert_eq!((gpt.no_auto, gpt.grow_file_system), (Some(true), Some(false))); + assert_eq!(o.inode.read_only, Some(false)); + assert_eq!(o.sha256, HELLO.parse().ok()); + assert_eq!(o.contents.len(), 2); + assert_eq!(o.contents[0].url(), Some("https://example.com/x")); + assert_eq!(o.contents[1].file().map(Name::as_str), Some("blob")); + assert_eq!((o.contents[1].offset, o.contents[1].original_size), (2, Some(7))); + assert_eq!(o.contents[1].original_sha256, WORLD.parse().ok()); + assert_eq!((o.validity.since_usec, o.validity.until_usec), (10, Some(20))); + assert_eq!(o.validity.state, Validity::Revoked); + + // The fields of the other inode types. + let o = object(r#"{"name":"null","type":"chr","major":1,"minor":3,"mode":438}"#); + assert_eq!( + (o.inode_type, o.major, o.minor), + (InodeType::CharDevice, Some(1), Some(3)) + ); + let o = object(r#"{"name":"sda","type":"blk","major":18446744073709551615}"#); + assert_eq!( + (o.inode_type, o.major, o.minor), + (InodeType::BlockDevice, Some(u64::MAX), None) + ); + let o = object(r#"{"contents":[{"literal":"YS50eHQ="}],"name":"link","size":5,"type":"lnk"}"#); + assert_eq!(o.inode_type, InodeType::Symlink); + assert_eq!(o.contents[0].literal(), Some(&b"a.txt"[..])); + for (name, inode_type) in [ + ("fifo", InodeType::Fifo), + ("sock", InodeType::Socket), + ("dir", InodeType::Directory), + ] { + assert_eq!( + object(&format!(r#"{{"name":"x","type":"{}"}}"#, name)).inode_type, + inode_type + ); + } + + // The root file object: a directory, and the one object that can + // have a disk UUID. + let root = RecordDecoder::root(concat!( + r#"{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"#, + r#""mediaType":"application/vnd.uapi.16.manifest","mode":509,"uid":1000,"readOnly":false,"#, + r#""gptDiskUuid":"4f68bce3-e8cd-4db1-96e7-fbcaf984b709","validUntilUSec":20}"# + )) + .unwrap(); + assert_eq!( + root.stated_features(), + Features::USER_XATTR + | Features::GID + | Features::MTIME + | Features::MODE + | Features::UID + | Features::READ_ONLY + | Features::GPT_DISK_UUID + ); + assert_eq!(root.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); + assert_eq!( + (root.inode.uid, root.inode.gid, root.inode.mode), + (Some(1000), Some(1000), Mode::new(0o775)) + ); + assert_eq!(root.inode.read_only, Some(false)); + assert_eq!(root.gpt_disk_uuid, Some(uuid)); + assert_eq!(root.validity.until_usec, Some(20)); + // Saying that it has no name, that it is a directory or that it is + // no hard link says nothing. + let root = r#"{"mediaType":"application/vnd.uapi.16.manifest","type":"dir","name":null,"inodeToken":0}"#; + assert_eq!(RecordDecoder::root(root).unwrap(), RootObject::default()); + } + + /// The root file object has none of the fields only the other file + /// objects have. Those of a sub-manifest in its directory, size, + /// contents and hash, are the fields of the object of that directory + /// in the manifest above. + #[test] + fn what_the_root_cannot_have() { + let root = |field: &str| format!(r#"{{"mediaType":"application/vnd.uapi.16.manifest",{}}}"#, field); + let sha256 = format!(r#""sha256":"{}""#, EMPTY); + for (member, field) in [ + (r#""size":5"#, Field::Size), + (r#""size":0"#, Field::Size), + (sha256.as_str(), Field::Sha256), + (r#""contents":[{"file":"sub"}]"#, Field::Contents), + (r#""inodeToken":3"#, Field::InodeToken), + (r#""major":1"#, Field::Major), + (r#""minor":1"#, Field::Minor), + (r#""gptLabel":"l""#, Field::GptLabel), + (r#""gptUuid":"4f68bce3-e8cd-4db1-96e7-fbcaf984b709""#, Field::GptUuid), + ( + r#""gptTypeUuid":"4f68bce3-e8cd-4db1-96e7-fbcaf984b709""#, + Field::GptTypeUuid, + ), + (r#""gptFlags":0"#, Field::GptFlags), + (r#""gptFlagNoAuto":false"#, Field::GptFlagNoAuto), + (r#""gptFlagGrowFileSystem":true"#, Field::GptFlagGrowFileSystem), + (r#""flagHidden":false"#, Field::FlagHidden), + (r#""flagSystem":true"#, Field::FlagSystem), + (r#""flagArchive":true"#, Field::FlagArchive), + // The first of them is named. + (r#""flagHidden":true,"size":1"#, Field::Size), + ] { + let e = RecordDecoder::root(&root(member)).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number(), e.name(), e.field()), + ( + ErrorKind::Manifest(Problem::FieldNotPermitted), + Some(ROOT_RECORD), + None, + Some(field) + ), + "{}", + member + ); + assert_eq!( + e.to_string(), + format!( + "manifest object 0 (root): '{}' is not permitted on the root file object", + field + ) + ); + } + // An empty list of contents objects is none, and null is no value. + for member in [r#""contents":[]"#, r#""size":null,"flagHidden":null,"gptLabel":null"#] { + assert_eq!( + RecordDecoder::root(&root(member)).unwrap(), + RootObject::default(), + "{}", + member + ); + } + // A name and a type that is not a directory have errors of their + // own, and readOnly has to agree with mode on the root too. + for (member, problem) in [ + (r#""name":"x""#, Problem::RootHasName), + (r#""type":"reg""#, Problem::RootNotDirectory), + (r#""mode":420,"readOnly":true"#, Problem::Contradiction), + ] { + let e = RecordDecoder::root(&root(member)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(problem), "{}", member); + } + } + + #[test] + fn what_a_field_can_look_like() { + // An object says as little as its name. + let o = object(r#"{"name":"x"}"#); + assert_eq!(o, FileObject::new(Name::new("x").unwrap())); + // A field that is null is not there. Fields this crate does not + // know are passed over, whatever they hold. + let nulls = concat!( + r#"{"name":"x","type":null,"size":null,"mode":null,"uid":null,"userName":null,"major":null,"#, + r#""mTimeNSec":null,"inodeToken":null,"extendedAttributes":null,"gptLabel":null,"gptFlags":null,"#, + r#""gptDiskUuid":null,"readOnly":null,"contents":null,"sha256":null,"validSinceUSec":null,"#, + r#""validUntilUSec":null,"validity":null,"xUnknown":null,"xFlagHidden":"x","other":{"a":[{}]}}"# + ); + assert_eq!(object(nulls), o); + assert_eq!( + object(r#"{"name":"x","mediaType":"application/vnd.uapi.16.manifest"}"#), + o + ); + assert_eq!(object(r#"{"name":"x","mediaType":null}"#), o); + // Also a number of any size and nesting of any depth. + let deep = format!("{}1{}", r#"[{"a":"#.repeat(1000), "}]".repeat(1000)); + for value in ["1e400", "-1e400", &"9".repeat(400), &deep] { + assert_eq!(object(&format!(r#"{{"name":"x","xUnknown":{}}}"#, value)), o); + } + // Integers are numbers of up to 64 bits. + for (text, size) in [("5", 5), ("0", 0), ("18446744073709551615", u64::MAX)] { + assert_eq!( + object(&format!(r#"{{"name":"x","size":{}}}"#, text)).size, + Some(size), + "{}", + text + ); + } + // An integer has no sign, not even -0, and is no string of digits. + for text in [ + "-0", + "-1", + r#""-0""#, + r#""5""#, + r#""0005""#, + r#""0""#, + r#""18446744073709551615""#, + ] { + let e = refused(&format!(r#"{{"name":"x","size":{}}}"#, text)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::WrongFieldType), Some(Field::Size)), + "{}", + text + ); + } + // Access modes are numbers in decimal like every other integer, and + // no strings of octal digits. + for (text, mode) in [("420", 0o644), ("4095", 0o7777), ("0", 0)] { + assert_eq!( + object(&format!(r#"{{"name":"x","mode":{}}}"#, text)).inode.mode, + Mode::new(mode), + "{}", + text + ); + } + for text in [r#""644""#, r#""0644""#, r#""7777""#] { + let e = refused(&format!(r#"{{"name":"x","mode":{}}}"#, text)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::WrongFieldType), Some(Field::Mode)), + "{}", + text + ); + } + // The largest ID, and the token of a file with one name. An ID is + // any below (uid_t) -1 but the one that is -1 in 16 bits. + assert_eq!( + object(r#"{"name":"x","uid":4294967294,"gid":65534}"#).inode.uid, + Some(u32::MAX - 1) + ); + assert_eq!(object(r#"{"name":"x","uid":65536,"gid":65534}"#).inode.gid, Some(65534)); + for (record, field) in [ + (r#"{"name":"x","uid":65535}"#, Field::Uid), + (r#"{"name":"x","gid":65535}"#, Field::Gid), + (r#"{"name":"x","uid":4294967295}"#, Field::Uid), + (r#"{"name":"x","gid":4294967295}"#, Field::Gid), + ] { + let e = refused(record); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::FieldOutOfRange), Some(field)), + "{}", + record + ); + } + assert_eq!(object(r#"{"name":"x","inodeToken":0}"#).inode_token, None); + assert_eq!(object(r#"{"name":"x","type":"dir","inodeToken":0}"#).inode_token, None); + // Any validity but revoked is good. + for (text, validity) in [ + ("good", Validity::Good), + ("revoked", Validity::Revoked), + ("REVOKED", Validity::Good), + ("", Validity::Good), + ("later", Validity::Good), + ] { + assert_eq!( + object(&format!(r#"{{"name":"x","validity":"{}"}}"#, text)) + .validity + .state, + validity, + "{:?}", + text + ); + } + // Names of users and groups are taken liberally. + for name in ["root", "Domain Users", "1a", "-a", "\u{e9}", "a\u{85}"] { + let o = object(&format!( + r#"{{"name":"x","userName":"{}","groupName":"{}"}}"#, + name, name + )); + assert_eq!( + (o.inode.user_name.as_deref(), o.inode.group_name.as_deref()), + (Some(name), Some(name)) + ); + } + // A partition label has room for 36 UTF-16 units. + let label = "x".repeat(GptPartition::LABEL_MAX); + let o = object(&format!(r#"{{"name":"x","gptLabel":"{}"}}"#, label)); + assert_eq!(o.gpt.unwrap().label, Some(label)); + let pairs = "\u{1f600}".repeat(GptPartition::LABEL_MAX / 2); + assert!(object(&format!(r#"{{"name":"x","gptLabel":"{}"}}"#, pairs)) + .gpt + .is_some()); + for label in [ + format!("{}x", pairs), + "x".repeat(GptPartition::LABEL_MAX + 1), + "a\tb".into(), + "a\u{85}b".into(), + ] { + let e = refused(&format!( + r#"{{"name":"x","gptLabel":{}}}"#, + json::Value::from(label.as_str()) + )); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::WrongFieldType), "{:?}", label); + } + // The longest name, and one byte more. A component is not limited + // on its own. + let name = "x".repeat(Name::MAX_LEN); + assert_eq!(object(&format!(r#"{{"name":"{}"}}"#, name)).name, name.as_str()); + let e = refused(&format!(r#"{{"name":"{}x"}}"#, name)); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidName)); + assert_eq!( + e.to_string(), + format!("manifest object 1: name is longer than 4095 bytes: '{}x'", name) + ); + } + + /// A `readOnly` the reader filled in is not one the object has: the + /// checks of the object, which a writer runs as well, take it for one + /// that is not there. + #[test] + fn filled_in_read_only() { + let root = r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["mode","read-only"],"mode":365}"#; + let m = read_whole(&sequence(&[root, r#"{"name":"x","mode":292}"#, TRAILER])).unwrap(); + let (root, object) = (&m.root, &m.objects[0]); + for inode in [&root.inode, &object.inode] { + assert_eq!(inode.read_only, Some(false)); + assert!(inode.filled_in.contains(Field::ReadOnly)); + assert!(!inode.is_read_only()); + } + assert!(root.check_consistency().is_ok()); + let subject = Subject::new(object, 1); + assert_eq!( + object + .check_consistency(subject, |contents| contents.check_consistency(subject)) + .unwrap(), + SizeAndHash::default() + ); + assert_eq!( + (root.stated_features(), object.stated_features()), + (Features::MODE, Features::MODE) + ); + // A readOnly the object has is held against its mode. + let mut given = object.clone(); + given.inode.filled_in.remove(Field::ReadOnly); + let e = given + .check_consistency(Subject::new(&given, 1), |contents| Ok(contents.data())) + .unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::Contradiction), Some(Field::ReadOnly)) + ); + } + + /// The checks a writer runs on an object it is handed, whose contents + /// objects no reader checked or filled in, find what a reader finds in + /// the record of that object. + #[test] + fn consistency_of_objects_not_read() { + let check = |object: &FileObject| { + let subject = Subject::new(object, 1); + object.check_consistency(subject, |contents| contents.check_consistency(subject)) + }; + let file = |size: Option, contents: Contents| { + let mut object = FileObject::new(Name::new("x").unwrap()); + object.size = size; + object.contents = vec![contents]; + object + }; + let hello = || Contents::new(Location::Literal(b"hello".to_vec())); + assert_eq!( + check(&file(None, hello())).unwrap(), + SizeAndHash { + size: Some(5), + sha256: None + } + ); + let mut beyond = hello(); + beyond.offset = 7; + let mut headers = Contents::new(Location::File(Name::new("a").unwrap())); + headers.http_headers = vec![("A".to_string(), "b".to_string())]; + let mut empty = file(Some(3), hello()); + empty.contents.clear(); + empty.sha256 = EMPTY.parse().ok(); + let mut read_only = file(None, hello()); + read_only.inode.mode = Mode::new(0o644); + read_only.inode.read_only = Some(true); + for (object, record) in [ + ( + file(None, beyond), + r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":7}]}"#.to_string(), + ), + ( + file(Some(10), hello()), + r#"{"name":"x","size":10,"contents":[{"literal":"aGVsbG8="}]}"#.to_string(), + ), + ( + file(None, headers), + r#"{"name":"x","contents":[{"file":"a","httpHeaders":{"A":"b"}}]}"#.to_string(), + ), + (empty, format!(r#"{{"name":"x","size":3,"sha256":"{}"}}"#, EMPTY)), + ( + read_only, + r#"{"name":"x","mode":420,"readOnly":true,"contents":[{"literal":"aGVsbG8="}]}"#.to_string(), + ), + ] { + let e = check(&object).unwrap_err(); + let read = refused(&record); + assert_eq!((e.kind(), e.field()), (read.kind(), read.field()), "{}", record); + } + } + + /// `gptFlags` holds the flags that `gptFlagNoAuto`, + /// `gptFlagGrowFileSystem` and `readOnly` give one each, and the two + /// agree. Where the manifest lists the feature of a field, an object + /// without the field has its flags cleared. + #[test] + fn partition_flags() { + let (no_auto, grow) = (GptPartition::FLAG_NO_AUTO, GptPartition::FLAG_GROW_FILE_SYSTEM); + let read_only = GptPartition::FLAG_READ_ONLY; + let listed = Features::GPT_FLAGS + | Features::GPT_FLAG_NO_AUTO + | Features::GPT_FLAG_GROW_FILE_SYSTEM + | Features::READ_ONLY; + let check = |features: Features, record: &str| { + let o = object(record); + o.check_partition_flags(features, Subject::new(&o, 1)) + }; + for (features, record) in [ + ( + Features::NONE, + format!(r#"{{"name":"x","gptFlags":{},"gptFlagNoAuto":true}}"#, no_auto), + ), + ( + Features::NONE, + format!( + r#"{{"name":"x","gptFlags":{},"gptFlagGrowFileSystem":true,"gptFlagNoAuto":false}}"#, + grow + ), + ), + ( + Features::NONE, + format!(r#"{{"name":"x","gptFlags":{},"readOnly":true}}"#, read_only), + ), + (Features::NONE, r#"{"name":"x","gptFlags":0,"readOnly":false}"#.into()), + // Without the features nothing is known of a field that is not + // there. + ( + Features::NONE, + format!(r#"{{"name":"x","gptFlags":{}}}"#, no_auto | grow | read_only), + ), + ( + Features::NONE, + r#"{"name":"x","readOnly":true,"gptFlagNoAuto":true}"#.into(), + ), + // With them, it is cleared. + (listed, r#"{"name":"x"}"#.into()), + (listed, r#"{"name":"x","gptFlags":0}"#.into()), + (listed, r#"{"name":"x","readOnly":false,"gptFlagNoAuto":false}"#.into()), + ( + listed, + format!( + r#"{{"name":"x","gptFlags":{},"gptFlagNoAuto":true,"readOnly":true}}"#, + no_auto | read_only + ), + ), + // Only a regular file has gptFlags. + (listed, r#"{"name":"x","type":"dir","readOnly":true}"#.into()), + (listed, r#"{"name":"x","type":"lnk","readOnly":true}"#.into()), + ] { + assert!(check(features, &record).is_ok(), "{:?} {}", features, record); + } + // readOnly true with the read-only flag clear, and false with it + // set, and the same for the fields of the other flags. + for (features, record, field, why) in [ + ( + Features::NONE, + r#"{"name":"x","gptFlags":0,"readOnly":true}"#.to_string(), + Field::ReadOnly, + "", + ), + ( + Features::NONE, + format!(r#"{{"name":"x","gptFlags":{},"readOnly":false}}"#, read_only), + Field::ReadOnly, + "", + ), + ( + listed, + r#"{"name":"x","readOnly":true}"#.to_string(), + Field::ReadOnly, + " ('gptFlags' is not there, which means 0 as the manifest lists 'gpt-flags')", + ), + ( + listed, + format!(r#"{{"name":"x","gptFlags":{}}}"#, read_only), + Field::ReadOnly, + " ('readOnly' is not there, which means false as the manifest lists 'read-only')", + ), + ( + Features::NONE, + format!(r#"{{"name":"x","gptFlags":{},"gptFlagNoAuto":false}}"#, no_auto), + Field::GptFlagNoAuto, + "", + ), + ( + listed, + format!(r#"{{"name":"x","gptFlags":{}}}"#, no_auto), + Field::GptFlagNoAuto, + " ('gptFlagNoAuto' is not there, which means false as the manifest lists 'gpt-flag-no-auto')", + ), + ( + listed, + r#"{"name":"x","gptFlagGrowFileSystem":true}"#.to_string(), + Field::GptFlagGrowFileSystem, + " ('gptFlags' is not there, which means 0 as the manifest lists 'gpt-flags')", + ), + ] { + let e = check(features, &record).unwrap_err(); + // The error is about gptFlags where the object has it. + let at = if record.contains(r#""gptFlags""#) { + Field::GptFlags + } else { + field + }; + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::Contradiction), Some(at)), + "{}", + record + ); + assert_eq!( + e.to_string(), + format!( + "manifest object 1 (x): 'gptFlags' and '{}' contradict each other{}", + field, why + ) + ); + } + } + + #[test] + fn flags_and_the_file_system() { + let o = object(r#"{"name":"x","flagHidden":true,"flagArchive":false,"flagNoCow":null}"#); + assert_eq!(o.dos_flags.get(DosFlags::HIDDEN), Some(true)); + assert_eq!(o.dos_flags.get(DosFlags::ARCHIVE), Some(false)); + assert_eq!(o.inode.flags.get(InodeFlags::NO_COW), None); + let dir = object(r#"{"name":"d","type":"dir","flagImmutable":true,"flagSystem":true}"#); + assert_eq!( + (dir.dos_flags.set, dir.inode.flags.set), + (DosFlags::SYSTEM, InodeFlags::IMMUTABLE) + ); + // Only regular files and directories have flags. The root has no + // DOS attributes, see what_the_root_cannot_have(). + for (record, field) in [ + (r#"{"name":"l","type":"lnk","flagHidden":true}"#, Field::FlagHidden), + (r#"{"name":"f","type":"fifo","flagNoDump":false}"#, Field::FlagNoDump), + ] { + let e = refused(record); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::FieldNotPermitted), Some(field)), + "{}", + record + ); + } + assert_eq!( + refused(r#"{"name":"x","flagHidden":"x"}"#).kind(), + ErrorKind::Manifest(Problem::WrongFieldType) + ); + let root = RecordDecoder::root(concat!( + r#"{"mediaType":"application/vnd.uapi.16.manifest","flagImmutable":true,"fatSerial":"1234-abcd","#, + r#""fsUUID":"11111111-2222-3333-4444-555555555555","fsLabel":"ESP","order":"codepoint","#, + r#""features":["flag-immutable","x-later","size"]}"# + )) + .unwrap(); + assert_eq!(root.inode.flags.get(InodeFlags::IMMUTABLE), Some(true)); + assert_eq!( + root.stated_features(), + Features::FLAG_IMMUTABLE | Features::FAT_SERIAL | Features::FS_UUID | Features::FS_LABEL + ); + let identity = &root.file_system; + assert_eq!(identity.fat_serial, Some(FatSerial(0x1234_abcd))); + assert_eq!(identity.label.as_deref(), Some("ESP")); + assert_eq!(root.order, Some(Order::CodePoint)); + // A feature the specification does not have is passed over. + assert_eq!(root.features, Some(Features::FLAG_IMMUTABLE | Features::SIZE)); + // An order the specification does not have is none. + let root = RecordDecoder::root(r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"later"}"#).unwrap(); + assert_eq!(root.order, None); + for root in [ + r#"{"mediaType":"application/vnd.uapi.16.manifest","flagHidden":true}"#, + r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["size","size"]}"#, + r#"{"mediaType":"application/vnd.uapi.16.manifest","features":"size"}"#, + r#"{"mediaType":"application/vnd.uapi.16.manifest","fatSerial":"1234ABCD"}"#, + r#"{"mediaType":"application/vnd.uapi.16.manifest","fsLabel":"a\u0007"}"#, + ] { + assert!(RecordDecoder::root(root).is_err(), "{}", root); + } + // These belong to the root file object alone. + for (record, field) in [ + (r#"{"name":"x","order":"codepoint"}"#, Field::Order), + (r#"{"name":"x","order":"later"}"#, Field::Order), + (r#"{"name":"x","features":[]}"#, Field::Features), + (r#"{"name":"x","fsLabel":"ESP"}"#, Field::FsLabel), + (r#"{"name":"x","fatSerial":"1234-ABCD"}"#, Field::FatSerial), + ( + r#"{"name":"x","fsUUID":"11111111-2222-3333-4444-555555555555"}"#, + Field::FsUuid, + ), + ( + r#"{"name":"x","gptDiskUuid":"11111111-2222-3333-4444-555555555555"}"#, + Field::GptDiskUuid, + ), + ] { + let e = refused(record); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::FieldNotPermitted), Some(field)), + "{}", + record + ); + } + } + + #[test] + fn extended_attributes() { + let attributes = |text: &str| { + let object = object(&format!(r#"{{"name":"x","extendedAttributes":{}}}"#, text)); + object.inode.user_xattrs.map(|attributes| *attributes) + }; + // Nothing is said about the namespace, or it is empty. + assert_eq!(attributes("{}"), None); + assert_eq!(attributes(r#"{"user":null}"#), None); + assert_eq!(attributes(r#"{"other":{"a":"b"},"USER":5}"#), None); + assert_eq!(attributes(r#"{"user":{}}"#), Some(BTreeMap::new())); + assert_eq!(attributes(r#"{"user":{"k":null}}"#), Some(BTreeMap::new())); + let listed = attributes(concat!( + r#"{"other":5,"user":{"b":{"text":"2"},"a":{"base64":"AAE="},"c":{"text":""},"#, + r#""d":{"text":"t","base64":null,"more":1}}}"# + )) + .unwrap(); + let listed: Vec<(&str, &[u8])> = listed.iter().map(|(k, v)| (k.as_str(), &v[..])).collect(); + assert_eq!(listed, [("a", &[0u8, 1][..]), ("b", b"2"), ("c", b""), ("d", b"t")]); + // A value that holds a NUL has to be written in Base64, and a + // text with a noncharacter is no string of a manifest at all. + for text in [r#"x\u0000y"#, r#"\uffff"#, "\u{fdd0}"] { + let e = refused(&format!( + r#"{{"name":"x","extendedAttributes":{{"user":{{"e":{{"text":"{}"}}}}}}}}"#, + text + )); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidString), "{}", text); + } + } + + #[test] + fn fills_in_what_follows() { + let empty: Sha256 = EMPTY.parse().unwrap(); + let hello: Sha256 = HELLO.parse().unwrap(); + // The size 0 and the hash of no data go together. + let o = object(r#"{"name":"x","size":0}"#); + assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + let o = object(&format!(r#"{{"name":"x","sha256":"{}"}}"#, EMPTY)); + assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + let o = object(&format!(r#"{{"name":"x","type":"dir","sha256":"{}"}}"#, EMPTY)); + assert_eq!(o.size, Some(0)); + // A literal says how long it is. + let o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); + assert_eq!(o.size, Some(5)); + assert_eq!( + (o.contents[0].encoded_size, o.contents[0].original_size), + (Some(5), Some(5)) + ); + let o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":2}]}"#); + assert_eq!(o.size, Some(3)); + let o = object(r#"{"name":"x","contents":[{"literal":""}]}"#); + assert_eq!((o.size, o.sha256), (Some(0), Some(empty))); + // An encoded literal says how long the encoded data is. + let o = object( + r#"{"name":"x","size":5,"contents":[{"literal":"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==","encoding":"GZIP"}]}"#, + ); + let contents = &o.contents[0]; + assert_eq!(contents.encoding.as_deref(), Some("gzip")); + assert_eq!((contents.encoded_size, contents.original_size), (Some(25), None)); + // Without an encoding the encoded data is the original data. + let o = object(&format!( + r#"{{"name":"x","contents":[{{"file":"a","encodedSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + )); + let contents = &o.contents[0]; + assert_eq!((contents.encoded_size, contents.original_size), (Some(5), Some(5))); + assert_eq!( + (contents.encoded_sha256, contents.original_sha256), + (Some(hello), Some(hello)) + ); + // The object is the whole of the contents: their size and hash are + // its own. + assert_eq!((o.size, o.sha256), (Some(5), Some(hello))); + // It is a part of them: the size follows, the hash does not. + let o = object(&format!( + r#"{{"name":"x","contents":[{{"file":"a","offset":2,"originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + )); + assert_eq!((o.size, o.sha256), (Some(3), None)); + let o = object(&format!( + r#"{{"name":"x","size":3,"sha256":"{}","contents":[{{"file":"a","originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO, WORLD + )); + assert_eq!((o.size, o.sha256), (Some(3), Some(hello))); + // Every contents object that gives a size gives the same one, + // whichever comes first. + let o = object( + r#"{"name":"x","contents":[{"file":"a","originalSize":5,"offset":1},{"file":"b","originalSize":4}]}"#, + ); + assert_eq!(o.size, Some(4)); + for contents in [ + [r#"{"file":"a","originalSize":5}"#, r#"{"file":"b","originalSize":4}"#], + [r#"{"literal":"YWJj"}"#, r#"{"literal":"YWJjZA=="}"#], + [ + r#"{"url":"https://example.com/x","originalSize":3}"#, + r#"{"literal":"YWJjZA=="}"#, + ], + ] { + for [first, second] in [contents, [contents[1], contents[0]]] { + let e = refused(&format!(r#"{{"name":"x","contents":[{},{}]}}"#, first, second)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::Contradiction), Some(Field::Contents)), + "{} {}", + first, + second + ); + } + } + // A size that follows from the contents objects is held against + // the hash, as one that is given. + for record in [ + format!(r#"{{"name":"x","sha256":"{}","contents":[{{"literal":""}}]}}"#, HELLO), + format!( + r#"{{"name":"x","contents":[{{"literal":"","originalSha256":"{}"}}]}}"#, + HELLO + ), + format!( + r#"{{"name":"x","sha256":"{}","contents":[{{"literal":"aGVsbG8="}}]}}"#, + EMPTY + ), + ] { + let e = refused(&record); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::Contradiction), "{}", record); + } + } + + #[test] + fn contents_objects() { + let contents = |text: &str| { + object(&format!(r#"{{"name":"x","contents":[{}]}}"#, text)) + .contents + .remove(0) + }; + assert_eq!(contents("{}"), Contents::default()); + assert_eq!( + contents(r#"{"file":null,"url":null,"literal":null,"offset":null,"xHeaders":{"A":"b"}}"#), + Contents::default() + ); + // The header fields of a request for a URL, sorted by nothing but + // the manifest. + let headers = contents(r#"{"url":"https://example.com/x","httpHeaders":{"X-Foo":"bar","Authorization":"t"}}"#); + assert_eq!( + headers.http_headers, + [ + ("X-Foo".to_string(), "bar".to_string()), + ("Authorization".to_string(), "t".to_string()) + ] + ); + let headers = contents(r#"{"url":"https://example.com/x","httpHeaders":{"A":null,"B":"c","b":null}}"#); + assert_eq!(headers.http_headers, [("B".to_string(), "c".to_string())]); + for refused_headers in [ + r#"{"file":"y","httpHeaders":{"A":"b"}}"#, + r#"{"url":"https://example.com/x","httpHeaders":{"A b":"c"}}"#, + r#"{"url":"https://example.com/x","httpHeaders":{"":"c"}}"#, + r#"{"url":"https://example.com/x","httpHeaders":{"A":"b\nc"}}"#, + r#"{"url":"https://example.com/x","httpHeaders":{"A":"b","a":"c"}}"#, + r#"{"url":"https://example.com/x","httpHeaders":{"A":1}}"#, + r#"{"url":"https://example.com/x","httpHeaders":[]}"#, + ] { + let e = refused(&format!(r#"{{"name":"x","contents":[{}]}}"#, refused_headers)); + assert_eq!( + e.kind(), + ErrorKind::Manifest(Problem::InvalidContents), + "{}", + refused_headers + ); + } + assert_eq!( + contents(r#"{"file":"data/y.bin"}"#).file().map(Name::as_str), + Some("data/y.bin") + ); + for url in ["https://example.com/x", "http://example.com/x", "https://"] { + assert_eq!(contents(&format!(r#"{{"url":"{}"}}"#, url)).url(), Some(url)); + } + // Either alphabet of Base64. + for (text, data) in [("aGVsbG8=", &b"hello"[..]), ("_-8=", &[0xff, 0xef]), ("", b"")] { + assert_eq!( + contents(&format!(r#"{{"literal":"{}"}}"#, text)).literal(), + Some(data), + "{:?}", + text + ); + } + // Whitespace is not Base64, wherever it is. + for text in [ + "aGVs bG8=", + " aGVsbG8=", + "aGVsbG8= ", + r"aGVs\nbG8=", + r"aGVsbG8=\r\n", + " ", + ] { + let e = refused(&format!(r#"{{"name":"x","contents":[{{"literal":"{}"}}]}}"#, text)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::InvalidContents), Some(Field::Literal)), + "{:?}", + text + ); + } + assert_eq!( + contents(r#"{"file":"a","encoding":"Zstd"}"#).encoding.as_deref(), + Some("zstd") + ); + assert_eq!(contents(r#"{"file":"a","offset":7}"#).offset, 7); + assert_eq!(contents(r#"{"file":"a","offset":5,"originalSize":5}"#).offset, 5); + // As many as MAX_CONTENTS, and no more. + let many = |n: usize| { + format!( + r#"{{"name":"x","contents":[{}]}}"#, + vec![r#"{"literal":"AA=="}"#; n].join(",") + ) + }; + assert_eq!(object(&many(MAX_CONTENTS)).contents.len(), MAX_CONTENTS); + let e = refused(&many(MAX_CONTENTS + 1)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::InvalidContents), Some(Field::Contents)) + ); + assert_eq!(e.to_string(), "manifest object 1: more than 256 contents entries"); + // Too many is what is wrong, whatever is wrong with one of them, + // unless something was wrong before them. + let bad_one = many(MAX_CONTENTS + 1).replacen("AA==", "!", 1); + assert_eq!( + refused(&bad_one).to_string(), + "manifest object 1: more than 256 contents entries" + ); + let bad_after = many(MAX_CONTENTS + 1).replacen("}]}", r#"}],"size":"x"}"#, 1); + assert_eq!(refused(&bad_after).field(), Some(Field::Contents)); + let bad_before = many(MAX_CONTENTS + 1).replacen(r#""name":"x""#, r#""size":"x","name":"x""#, 1); + assert_eq!(refused(&bad_before).field(), Some(Field::Size)); + } + + #[test] + fn signature_objects() { + let signature = |record: &str| { + let mut m = read_whole(&sequence(&[ROOT, record, TRAILER])).unwrap_or_else(|e| panic!("{}: {}", record, e)); + m.signatures.remove(0) + }; + let s = signature(SIGNATURE); + assert_eq!( + (s.mechanism.as_str(), s.key, s.data.as_deref()), + ("pkcs7", None, Some(&[0u8, 0, 0][..])) + ); + let s = signature(concat!( + r#"{"data":null,"key":"ABcd01","mechanism":"openpgp","other":[1,2,1e400],"#, + r#""mediaType":"application/vnd.uapi.16.signature"}"# + )); + assert_eq!( + (s.mechanism.as_str(), s.key.as_deref(), s.data), + ("openpgp", Some(&[0xab, 0xcd, 1][..]), None) + ); + let s = signature(r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"x","key":"","data":""}"#); + assert_eq!((s.key.as_deref(), s.data.as_deref()), (Some(&[][..]), Some(&[][..]))); + // The key is hex digits and the data Base64, without whitespace. + for (member, field) in [ + (r#""key":"AB cd01""#, Field::Key), + (r#""key":"ABcd01\n""#, Field::Key), + (r#""data":"AAAA AAAA""#, Field::Data), + (r#""data":"AAAA\nAAAA""#, Field::Data), + ] { + let record = format!( + r#"{{"mediaType":"application/vnd.uapi.16.signature","mechanism":"openpgp",{}}}"#, + member + ); + let e = read_whole(&sequence(&[ROOT, &record, TRAILER])).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::InvalidSignature), Some(field)), + "{}", + member + ); + } + } + + /// What an error quotes of a manifest has its control characters + /// escaped, so that it is no control sequence on a terminal and no line + /// of a log of its own. + #[test] + fn errors_escape_what_they_quote() { + // An escape sequence that sets the title of a terminal, and the + // control sequence introducer of C1, which a name can have. + let (esc, csi) = (r"\u001b]0;title\u0007\n", r"\u009b2J"); + let records = [ + format!(r#"{{"name":"a{}"}}"#, esc), + format!(r#"{{"name":"x","type":"{}"}}"#, esc), + format!(r#"{{"name":"x","userName":"{}"}}"#, esc), + format!(r#"{{"name":"x","gptUuid":"{}"}}"#, esc), + format!(r#"{{"name":"x","gptLabel":"{}"}}"#, esc), + format!( + r#"{{"name":"x","extendedAttributes":{{"user":{{"{}":{{"text":"v"}}}}}}}}"#, + esc + ), + format!(r#"{{"name":"x","extendedAttributes":{{"user":{{"a{}":5}}}}}}"#, csi), + format!(r#"{{"name":"x","contents":[{{"file":"{}"}}]}}"#, esc), + format!(r#"{{"name":"x","contents":[{{"url":"{}"}}]}}"#, esc), + format!( + r#"{{"name":"x","contents":[{{"url":"https://x","httpHeaders":{{"{}":5}}}}]}}"#, + esc + ), + format!( + r#"{{"name":"x","contents":[{{"url":"https://x","httpHeaders":{{"{}":"b"}}}}]}}"#, + esc + ), + format!(r#"{{"name":"x{}","type":"fifo","size":1}}"#, csi), + ]; + let mut errors: Vec = records.iter().map(|record| refused(record)).collect(); + let root = |field: &str| format!(r#"{{"mediaType":"application/vnd.uapi.16.manifest",{}}}"#, field); + for root in [ + root(&format!(r#""fatSerial":"{}""#, esc)), + root(&format!(r#""features":["{0}","{0}"]"#, esc)), + root(&format!(r#""fsLabel":"{}""#, esc)), + ] { + errors.push(RecordDecoder::root(&root).unwrap_err()); + } + let ordered = root(r#""order":"codepoint""#); + for records in [ + [format!(r#"{{"name":"b{}"}}"#, csi), r#"{"name":"a"}"#.to_string()], + [ + format!(r#"{{"name":"d{}","type":"dir"}}"#, csi), + format!(r#"{{"name":"e{}/x"}}"#, csi), + ], + ] { + let bytes = sequence(&[&ordered, &records[0], &records[1], TRAILER]); + errors.push(read_whole(&bytes).unwrap_err()); + } + for e in errors { + let message = e.to_string(); + assert!(!message.contains(char::is_control), "{:?}", message); + assert!( + message.contains(r"\u{1b}") || message.contains(r"\u{9b}"), + "{:?}", + message + ); + } + } + + /// The fields of the kind of object `field` is a field of. + fn fields_of(field: Field) -> &'static [Field] { + match field { + Field::Name + | Field::MediaType + | Field::Type + | Field::Size + | Field::Mode + | Field::Uid + | Field::Gid + | Field::UserName + | Field::GroupName + | Field::Major + | Field::Minor + | Field::MTimeNSec + | Field::InodeToken + | Field::ExtendedAttributes + | Field::GptLabel + | Field::GptUuid + | Field::GptTypeUuid + | Field::GptDiskUuid + | Field::GptFlags + | Field::GptFlagNoAuto + | Field::GptFlagGrowFileSystem + | Field::ReadOnly + | Field::FlagHidden + | Field::FlagSystem + | Field::FlagArchive + | Field::FlagAppendOnly + | Field::FlagImmutable + | Field::FlagNoAtime + | Field::FlagNoCow + | Field::FlagNoDump + | Field::FatSerial + | Field::FsUuid + | Field::FsLabel + | Field::Order + | Field::Features + | Field::Contents + | Field::Sha256 + | Field::ValidSinceUSec + | Field::ValidUntilUSec + | Field::Validity => &Field::FILE_OBJECT, + Field::File + | Field::Url + | Field::Literal + | Field::Encoding + | Field::EncodedSize + | Field::EncodedSha256 + | Field::OriginalSize + | Field::OriginalSha256 + | Field::Offset + | Field::HttpHeaders => &Field::CONTENTS, + Field::Text | Field::Base64 => &Field::EXTENDED_ATTRIBUTE, + Field::Mechanism | Field::Key | Field::Data => &Field::SIGNATURE, + } + } + + /// Every field is read by the name it is written with, the one of + /// [`Field::as_str`], in the objects it is a field of. + #[test] + fn fields_are_read_by_their_names() { + /// Finds the field a key is the name of. + type Lookup = fn(&str) -> Option; + let kinds: [(&[Field], Lookup); 4] = [ + (&Field::FILE_OBJECT, Field::from_file_object_key), + (&Field::CONTENTS, Field::from_contents_key), + (&Field::EXTENDED_ATTRIBUTE, Field::from_extended_attribute_key), + (&Field::SIGNATURE, Field::from_signature_key), + ]; + let mut names = HashSet::new(); + for (fields, of) in kinds { + for &field in fields { + assert_eq!(of(field.as_str()), Some(field), "{}", field); + assert_eq!(fields_of(field), fields, "{}", field); + assert!(names.insert(field.as_str()), "{}", field); + } + assert_eq!(of("xUnknown"), None); + } + // Data is the last of the fields. + assert_eq!(names.len(), Field::Data as usize + 1); + } + + /// refused.jsonl holds manifests a reader refuses, one to a line: its + /// records, the problem by the name [`Problem::as_str`] gives it, the + /// number of the record and the name of the object the error is about, + /// the field, and what the error says. The test holds the reader to all + /// of it. + #[test] + fn refuses_what_the_vectors_refuse() { + let vectors = include_str!("refused.jsonl"); + let mut problems = HashSet::new(); + for line in vectors.lines() { + let vector = json::parse(line).unwrap(); + let [records, problem, record_number, name, field, message] = vector.as_array().unwrap() else { + panic!("{}", line); + }; + let records: Vec<&str> = records + .as_array() + .unwrap() + .iter() + .map(|record| match record.as_str().unwrap() { + "@root" => ROOT, + "@trailer" => TRAILER, + "@signature" => SIGNATURE, + record => record, + }) + .collect(); + let e = match read_whole(&sequence(&records)) { + Ok(_) => panic!("{} was taken", line), + Err(e) => e, + }; + let ErrorKind::Manifest(found) = e.kind() else { + panic!("{}: {:?}", line, e); + }; + assert_eq!(Some(found.as_str()), problem.as_str(), "{}", line); + assert_eq!(e.record_number(), record_number.as_u64(), "{}", line); + assert_eq!(e.name(), name.as_str(), "{}", line); + assert_eq!(e.field().map(Field::as_str), field.as_str(), "{}", line); + assert_eq!(Some(e.to_string().as_str()), message.as_str(), "{}", line); + problems.insert(found); + } + // Every problem a manifest can have is among them, but those of + // bytes that are not UTF-8, that come before the first record + // separator or that make a record too large, and the one of an + // order a consumer requires, which error.rs's problem_names test + // pins. A NUL byte in a record is a NUL character in the string a + // vector gives the record in. + let elsewhere = [ + Problem::NotUtf8, + Problem::NoRecordSeparator, + Problem::RecordTooLarge, + Problem::NoOrder, + ]; + for problem in Problem::ALL + .iter() + .copied() + .filter(|problem| !elsewhere.contains(problem)) + { + assert!(problems.contains(&problem), "{:?}", problem); + } + } +} diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index 6b6bdd0..d958653 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -4,6 +4,171 @@ use std::fmt; use std::io; +use crate::decode::Subject; +use crate::object::FileObject; +use crate::{MAX_CONTENTS, MAX_RECORD_SIZE}; + +/// What is wrong with a manifest. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Problem { + /// A record is not valid JSON. + NotJson, + /// An object of a record has a key twice, which the specification does + /// not permit. + DuplicateKey, + /// A string holds what the specification does not permit in strings: a + /// noncharacter or the NUL character, written as it is or with an + /// escape. + InvalidString, + /// A record is not a JSON object. + NotObject, + /// A record is not UTF-8. + NotUtf8, + /// A record contains a NUL byte. + ContainsNulByte, + /// A record does not start with the record separator. + NoRecordSeparator, + /// A record is larger than [`MAX_RECORD_SIZE`], its record separator + /// counted. + RecordTooLarge, + /// The manifest holds no object at all. + NoObjects, + /// The trailer object is missing. + NoTrailer, + /// Data follows the trailer object. + DataAfterTrailer, + /// A file object follows a signature object. + FileAfterSignature, + /// The media type is missing on the first object, is not a string, or + /// is not the one of a manifest where it has to be. + InvalidMediaType, + /// The root file object has a name. + RootHasName, + /// The root file object is not a directory. + RootNotDirectory, + /// The root file object does not declare the order a consumer requires + /// in `order`, see + /// [`RootObject::require_order`](crate::RootObject::require_order). + NoOrder, + /// An object after the first has no name. + NoName, + /// A name is not one a file object can have, for one of the reasons of + /// [`InvalidName`](crate::InvalidName). + InvalidName, + /// Two objects carry the same name. + DuplicateName, + /// A file object does not come right after the file object of its + /// directory: the directory is not listed, or its entries ended. + Misplaced, + /// A file object comes after one it sorts before, in the order the + /// manifest declares. + OutOfOrder, + /// A file object has a field of a feature the manifest does not list in + /// `features`. + UnlistedFeature, + /// A symbolic link has no target in a manifest that records the targets + /// of symbolic links. + NoTarget, + /// An inode type the specification does not have. + UnknownType, + /// A field is of the wrong JSON type or shape. + WrongFieldType, + /// The value of a field is out of range. + FieldOutOfRange, + /// A field the object cannot have: one its inode type does not permit, + /// one only the root file object has on another object, or one only the + /// other file objects have on the root file object. + FieldNotPermitted, + /// Two fields contradict each other. + Contradiction, + /// A contents object is malformed, or there are more than + /// [`MAX_CONTENTS`] of them. + InvalidContents, + /// A signature object is malformed. + InvalidSignature, + /// The `extendedAttributes` field is malformed. + InvalidExtendedAttributes, +} + +impl Problem { + /// Every problem, in the order of the variants. A problem added to the + /// enum is added here too, which a test of this crate checks. + pub const ALL: &'static [Problem] = &[ + Problem::NotJson, + Problem::DuplicateKey, + Problem::InvalidString, + Problem::NotObject, + Problem::NotUtf8, + Problem::ContainsNulByte, + Problem::NoRecordSeparator, + Problem::RecordTooLarge, + Problem::NoObjects, + Problem::NoTrailer, + Problem::DataAfterTrailer, + Problem::FileAfterSignature, + Problem::InvalidMediaType, + Problem::RootHasName, + Problem::RootNotDirectory, + Problem::NoOrder, + Problem::NoName, + Problem::InvalidName, + Problem::DuplicateName, + Problem::Misplaced, + Problem::OutOfOrder, + Problem::UnlistedFeature, + Problem::NoTarget, + Problem::UnknownType, + Problem::WrongFieldType, + Problem::FieldOutOfRange, + Problem::FieldNotPermitted, + Problem::Contradiction, + Problem::InvalidContents, + Problem::InvalidSignature, + Problem::InvalidExtendedAttributes, + ]; + + /// The name of the problem, such as `noTrailer`, for a caller that + /// passes it on, in the errors of an interface for example. The names + /// are stable and do not follow the names of the variants: + /// [`Problem::RootHasName`] is `firstHasName`. + pub const fn as_str(self) -> &'static str { + match self { + Problem::NotJson => "notJson", + Problem::DuplicateKey => "duplicateKey", + Problem::InvalidString => "invalidString", + Problem::NotObject => "notObject", + Problem::NotUtf8 => "notUtf8", + Problem::ContainsNulByte => "nulByte", + Problem::NoRecordSeparator => "recordSeparator", + Problem::RecordTooLarge => "recordTooLarge", + Problem::NoObjects => "empty", + Problem::NoTrailer => "noTrailer", + Problem::DataAfterTrailer => "dataAfterTrailer", + Problem::FileAfterSignature => "fileAfterSignature", + Problem::InvalidMediaType => "mediaType", + Problem::RootHasName => "firstHasName", + Problem::RootNotDirectory => "firstNotDirectory", + Problem::NoOrder => "noOrder", + Problem::NoName => "noName", + Problem::InvalidName => "invalidName", + Problem::DuplicateName => "duplicateName", + Problem::Misplaced => "misplaced", + Problem::OutOfOrder => "outOfOrder", + Problem::UnlistedFeature => "unlistedFeature", + Problem::NoTarget => "noTarget", + Problem::UnknownType => "unknownType", + Problem::WrongFieldType => "fieldType", + Problem::FieldOutOfRange => "fieldRange", + Problem::FieldNotPermitted => "fieldNotPermitted", + Problem::Contradiction => "contradiction", + Problem::InvalidContents => "contents", + Problem::InvalidSignature => "signature", + Problem::InvalidExtendedAttributes => "extendedAttributes", + } + } +} + /// Why a file object must not be used now. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Invalid { @@ -17,7 +182,10 @@ pub enum Invalid { /// What kind of error an [`Error`] is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum ErrorKind { + /// The manifest is malformed. + Manifest(Problem), /// A file object is revoked or outside its validity window. NotValid(Invalid), /// Reading or writing failed. @@ -213,6 +381,7 @@ impl fmt::Display for Field { #[derive(Debug)] enum Cause { Io(io::Error), + Json(json::ParseError), } /// What went wrong reading a manifest, or using one. @@ -249,6 +418,18 @@ impl Error { })) } + /// A manifest that is malformed. + pub(crate) fn manifest(problem: Problem, message: String) -> Error { + Error::new(ErrorKind::Manifest(problem), message) + } + + /// Names the record the error is about, unless one is named. + #[must_use] + pub(crate) fn in_record(mut self, record_number: u64) -> Error { + self.0.record_number.get_or_insert(record_number); + self + } + /// Names the file object the error is about. #[must_use] pub(crate) fn named(mut self, name: impl Into) -> Error { @@ -256,12 +437,118 @@ impl Error { self } + /// Names the field the error is about. + #[must_use] + pub(crate) fn at(mut self, field: Field) -> Error { + self.0.field = Some(field); + self + } + /// Notes the I/O error behind this one. #[must_use] pub(crate) fn caused_by(mut self, error: io::Error) -> Error { self.0.cause = Some(Cause::Io(error)); self } + + /// A record that is not JSON, that has a key twice in an object, or + /// that has a string the specification does not permit. + pub(crate) fn not_json(record_number: u64, error: json::ParseError) -> Error { + let (problem, message) = match error.kind { + json::ParseErrorKind::Syntax => ( + Problem::NotJson, + format!("manifest record {} is not valid JSON: {}", record_number, error), + ), + json::ParseErrorKind::DuplicateKey => ( + Problem::DuplicateKey, + format!( + "manifest record {} has a key twice in an object: {}", + record_number, error + ), + ), + json::ParseErrorKind::StringRule => ( + Problem::InvalidString, + format!("manifest record {} has an invalid string: {}", record_number, error), + ), + }; + let mut e = Error::manifest(problem, message).in_record(record_number); + e.0.cause = Some(Cause::Json(error)); + e + } + + /// The root file object, which has a name. + pub(crate) fn root_has_name() -> Error { + Error::manifest(Problem::RootHasName, "the root file object has a name".into()).at(Field::Name) + } + + /// The root file object, which is not a directory. + pub(crate) fn root_not_directory() -> Error { + Error::manifest( + Problem::RootNotDirectory, + "the root file object is not a directory".into(), + ) + .at(Field::Type) + } + + /// A file object after the root file object, in the record with the + /// number `record_number`, that has no name. + pub(crate) fn no_name(record_number: u64) -> Error { + Error::manifest( + Problem::NoName, + format!("manifest object {} has no name", record_number), + ) + .at(Field::Name) + .in_record(record_number) + } + + /// A file object in the record with the number `record_number`, behind + /// a signature object. + pub(crate) fn file_after_signature(record_number: u64) -> Error { + Error::manifest( + Problem::FileAfterSignature, + "manifest contains a file object after a signature object".into(), + ) + .in_record(record_number) + } + + /// Data in the record with the number `record_number`, behind the + /// trailer object. + pub(crate) fn data_after_trailer(record_number: u64) -> Error { + Error::manifest( + Problem::DataAfterTrailer, + "manifest contains data after the trailer object".into(), + ) + .in_record(record_number) + } + + /// A record larger than [`MAX_RECORD_SIZE`], its record separator + /// counted. + pub(crate) fn record_too_large() -> Error { + Error::manifest( + Problem::RecordTooLarge, + format!("manifest record exceeds {} bytes", MAX_RECORD_SIZE), + ) + } + + /// A file object, which `subject` names, with more than + /// [`MAX_CONTENTS`] contents objects. + pub(crate) fn too_many_contents(subject: Subject<'_>) -> Error { + Error::manifest( + Problem::InvalidContents, + format!("{}: more than {} contents entries", subject, MAX_CONTENTS), + ) + .at(Field::Contents) + } + + /// `object`, which `subject` names, states the flag of the field + /// `field`, which it cannot have, see [`FileObject::unpermitted_flag`]. + pub(crate) fn unpermitted_flag(object: &FileObject, field: Field, subject: Subject<'_>) -> Error { + Error::manifest( + Problem::FieldNotPermitted, + format!("{}: '{}' is not permitted on a {}", subject, field, object.inode_type), + ) + .at(field) + } } impl Error { @@ -308,6 +595,7 @@ impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.0.cause { Some(Cause::Io(e)) => Some(e), + Some(Cause::Json(e)) => Some(e), None => None, } } @@ -333,3 +621,100 @@ impl From for io::Error { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_io_error_passes_through() { + let e = Error::from(io::Error::from_raw_os_error(libc::ENOSPC)); + assert_eq!(e.kind(), ErrorKind::Io); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); + assert_eq!(e.to_string(), io::Error::from_raw_os_error(libc::ENOSPC).to_string()); + assert!(std::error::Error::source(&e).is_some()); + assert_eq!(io::Error::from(e).raw_os_error(), Some(libc::ENOSPC)); + // Any other error is carried by an I/O error. + let e = Error::manifest(Problem::NoTrailer, "incomplete".to_string()); + let io = io::Error::from(e); + assert_eq!(io.kind(), io::ErrorKind::InvalidData); + let inner = io.get_ref().and_then(|e| e.downcast_ref::()).unwrap(); + assert_eq!(inner.kind(), ErrorKind::Manifest(Problem::NoTrailer)); + assert_eq!(io.to_string(), "incomplete"); + } + + /// The names of the problems the vectors of refused.jsonl do not hold: + /// those of the bytes of a manifest that are not UTF-8, that do not + /// start with a record separator or that are too large, and the one of + /// the order a consumer requires. + #[test] + fn problem_names() { + for (problem, name) in [ + (Problem::NotUtf8, "notUtf8"), + (Problem::NoRecordSeparator, "recordSeparator"), + (Problem::RecordTooLarge, "recordTooLarge"), + (Problem::NoOrder, "noOrder"), + ] { + assert_eq!(problem.as_str(), name); + } + } + + /// Where `problem` is in [`Problem::ALL`]. As a constant it does not + /// build for a problem that ALL lacks. + const fn position_in_all(problem: Problem) -> usize { + let mut position = 0; + while position < Problem::ALL.len() { + if Problem::ALL[position] as usize == problem as usize { + return position; + } + position += 1; + } + panic!("Problem::ALL lacks a problem"); + } + + /// ALL holds every problem once, in the order of the variants, and no + /// two problems have the same name. The match names every problem, so + /// a problem added to the enum does not build without an arm here, and + /// its arm, a constant, does not build until ALL has the problem. + #[test] + fn all_problems() { + let position = |problem: Problem| match problem { + Problem::NotJson => const { position_in_all(Problem::NotJson) }, + Problem::DuplicateKey => const { position_in_all(Problem::DuplicateKey) }, + Problem::InvalidString => const { position_in_all(Problem::InvalidString) }, + Problem::NotObject => const { position_in_all(Problem::NotObject) }, + Problem::NotUtf8 => const { position_in_all(Problem::NotUtf8) }, + Problem::ContainsNulByte => const { position_in_all(Problem::ContainsNulByte) }, + Problem::NoRecordSeparator => const { position_in_all(Problem::NoRecordSeparator) }, + Problem::RecordTooLarge => const { position_in_all(Problem::RecordTooLarge) }, + Problem::NoObjects => const { position_in_all(Problem::NoObjects) }, + Problem::NoTrailer => const { position_in_all(Problem::NoTrailer) }, + Problem::DataAfterTrailer => const { position_in_all(Problem::DataAfterTrailer) }, + Problem::FileAfterSignature => const { position_in_all(Problem::FileAfterSignature) }, + Problem::InvalidMediaType => const { position_in_all(Problem::InvalidMediaType) }, + Problem::RootHasName => const { position_in_all(Problem::RootHasName) }, + Problem::RootNotDirectory => const { position_in_all(Problem::RootNotDirectory) }, + Problem::NoOrder => const { position_in_all(Problem::NoOrder) }, + Problem::NoName => const { position_in_all(Problem::NoName) }, + Problem::InvalidName => const { position_in_all(Problem::InvalidName) }, + Problem::DuplicateName => const { position_in_all(Problem::DuplicateName) }, + Problem::Misplaced => const { position_in_all(Problem::Misplaced) }, + Problem::OutOfOrder => const { position_in_all(Problem::OutOfOrder) }, + Problem::UnlistedFeature => const { position_in_all(Problem::UnlistedFeature) }, + Problem::NoTarget => const { position_in_all(Problem::NoTarget) }, + Problem::UnknownType => const { position_in_all(Problem::UnknownType) }, + Problem::WrongFieldType => const { position_in_all(Problem::WrongFieldType) }, + Problem::FieldOutOfRange => const { position_in_all(Problem::FieldOutOfRange) }, + Problem::FieldNotPermitted => const { position_in_all(Problem::FieldNotPermitted) }, + Problem::Contradiction => const { position_in_all(Problem::Contradiction) }, + Problem::InvalidContents => const { position_in_all(Problem::InvalidContents) }, + Problem::InvalidSignature => const { position_in_all(Problem::InvalidSignature) }, + Problem::InvalidExtendedAttributes => const { position_in_all(Problem::InvalidExtendedAttributes) }, + }; + for (i, &problem) in Problem::ALL.iter().enumerate() { + assert_eq!((position(problem), problem as usize), (i, i), "{:?}", problem); + } + let names: std::collections::HashSet<&str> = Problem::ALL.iter().map(|problem| problem.as_str()).collect(); + assert_eq!(names.len(), Problem::ALL.len()); + } +} diff --git a/src/uapi16/features.rs b/src/uapi16/features.rs index 3ab9ada..c2ff73f 100644 --- a/src/uapi16/features.rs +++ b/src/uapi16/features.rs @@ -303,6 +303,12 @@ impl Order { Order::CodePoint => "codepoint", } } + + /// The order a value of `order` declares. A value the specification + /// does not have declares none, as it asks. + pub(crate) fn declared(value: &str) -> Option { + (value == Order::CodePoint.as_str()).then_some(Order::CodePoint) + } } impl fmt::Display for Order { @@ -373,4 +379,13 @@ mod tests { assert_eq!(more, some | Features::MODE); assert_eq!(format!("{:?}", some), "Features(mtime | sha256 | size)"); } + + #[test] + fn orders() { + assert_eq!(Order::declared("codepoint"), Some(Order::CodePoint)); + for value in ["", "CodePoint", "alphabetical", "bytes", "codepoint "] { + assert_eq!(Order::declared(value), None, "{:?}", value); + } + assert_eq!(Order::CodePoint.to_string(), "codepoint"); + } } diff --git a/src/uapi16/hex.rs b/src/uapi16/hex.rs index 77f99b5..35bc310 100644 --- a/src/uapi16/hex.rs +++ b/src/uapi16/hex.rs @@ -28,6 +28,18 @@ impl Hex<'_> { text.bytes().map(Hex::value) } + /// Decodes the bytes `text` spells, two hex digits for each, however + /// many there are. An odd number of digits, or anything that is not a + /// digit, is None. + pub(crate) fn decode(text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len() / DIGITS_PER_BYTE); + let mut values = Hex::values(text); + while let Some(high) = values.next() { + out.push((high? << DIGIT_BITS) | values.next()??); + } + Some(out) + } + /// Decodes the `N` bytes `text` spells, two hex digits for each. Fewer /// or more digits, or anything that is not a digit, are None. pub(crate) fn decode_array(text: &str) -> Option<[u8; N]> { @@ -56,3 +68,81 @@ impl fmt::Display for Hex<'_> { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes() { + assert_eq!(Hex::decode(""), Some(vec![])); + assert_eq!(Hex::decode("00ff"), Some(vec![0, 0xff])); + assert_eq!(Hex::decode("0aF01b2C"), Some(vec![0x0a, 0xf0, 0x1b, 0x2c])); + for text in ["0", "012", "0g", "xyz", "0x10", "1\u{b}0", "\u{e9}\u{e9}", "+1", "-1"] { + assert_eq!(Hex::decode(text), None, "{:?}", text); + } + assert_eq!(Hex::decode_array::<2>("00ff"), Some([0, 0xff])); + assert_eq!(Hex::decode_array::<2>("00FF"), Some([0, 0xff])); + assert_eq!(Hex::decode_array::<2>("00f"), None); + assert_eq!(Hex::decode_array::<2>("00"), None); + assert_eq!(Hex::decode_array::<2>("00ff00"), None); + assert_eq!(Hex::decode_array::<2>("00fg"), None); + assert_eq!(Hex::decode_array::<2>("00\u{e9}"), None); + assert_eq!(Hex::decode_array::<0>(""), Some([])); + assert_eq!(Hex::decode_array::<0>("00"), None); + } + + #[test] + fn refuses_whitespace() { + // Whitespace is not a digit, wherever it is: neither JSON's, which + // systemd passes over, nor any other. + for space in [" ", "\t", "\n", "\r", "\x0c", "\x0b", "\u{a0}", "\u{2028}"] { + for text in [ + format!("00{}ff", space), + format!("{}00ff", space), + format!("00ff{}", space), + ] { + assert_eq!(Hex::decode(&text), None, "{:?}", text); + assert_eq!(Hex::decode_array::<2>(&text), None, "{:?}", text); + } + assert_eq!(Hex::decode_array::<0>(space), None, "{:?}", space); + } + for text in ["0aF0 1b\n2C\t\r", " 0 1 2 3 "] { + assert_eq!(Hex::decode(text), None, "{:?}", text); + } + assert_eq!(Hex::decode_array::<2>("00 FF"), None); + assert_eq!(Hex::decode_array::<3>("0 1 2 3 4 5"), None); + } + + #[test] + fn digits() { + // Every byte is a digit or it is not, and the two ways to decode + // agree on it. + for byte in 0..=u8::MAX { + let value = char::from(byte).to_digit(1 << DIGIT_BITS).map(|value| value as u8); + assert_eq!(Hex::value(byte), value, "{:#x}", byte); + let Ok(text) = String::from_utf8(vec![b'5', byte]) else { + continue; + }; + let expected = value.map(|value| [0x50 | value]); + assert_eq!(Hex::decode_array::<1>(&text), expected, "{:?}", text); + assert_eq!(Hex::decode(&text), expected.map(Vec::from), "{:?}", text); + let text: String = text.chars().rev().collect(); + let expected = value.map(|value| [(value << DIGIT_BITS) | 0x5]); + assert_eq!(Hex::decode_array::<1>(&text), expected, "{:?}", text); + } + } + + #[test] + fn prints() { + assert_eq!(Hex(&[]).to_string(), ""); + assert_eq!(Hex(&[0, 0x0f, 0xf0, 0xff]).to_string(), "000ff0ff"); + // More than is formatted at a time. + let bytes: Vec = (0..=255).collect(); + let text = Hex(&bytes).to_string(); + assert_eq!(text.len(), 512); + assert!(text.starts_with("000102") && text.ends_with("fdfeff")); + assert_eq!(Hex::decode(&text), Some(bytes.clone())); + assert_eq!(Hex::decode(&text.to_uppercase()), Some(bytes)); + } +} diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index d3b2691..e8abd69 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -9,26 +9,64 @@ //! objects can come after the file objects, and a trailer object ends the //! manifest. //! +//! - [`Reader`] reads a manifest record by record from a [`Read`]. It +//! checks every object against the rules of the specification, and +//! where it comes: right after the object of its directory, in the order +//! the manifest declares, and with the fields of the [`Features`] the +//! manifest records. +//! - [`Decoder`] does the same with the bytes it is fed, and does no I/O. //! - [`RootObject`], [`FileObject`], [`Contents`] and [`Signature`] are the //! objects, and [`Name`], [`InodeType`], [`Mode`], [`DosFlags`], //! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What //! the root file object and a file object both have is in //! [`InodeAttributes`] and [`ValidityWindow`]. //! +//! A manifest that does not come through a [`Read`], such as one from an +//! async runtime, goes to a [`Decoder`] as it comes. [`Decoder::step`] says +//! what comes next. When it asks for more of the manifest with +//! [`Step::Input`], [`Decoder::feed`] takes the bytes that came, up to the +//! end of the record it reads, and returns how many it took. The others go +//! in with a later call. [`Decoder::end`] says that there are no more. The +//! other steps hand out the root file object, the objects after it, and +//! the end of the manifest. A record ends where the next one starts, so an +//! object comes once the separator of the record after it was fed, or the +//! input ended, and the end of the manifest once the input ended. A step +//! reads a whole record, of up to [`MAX_RECORD_SIZE`] bytes with its record +//! separator, at once. +//! +//! A manifest is input from outside and can be very large. Reading one +//! takes time in proportion to its size, and keeps one record without its +//! separator and the name of the file object before it in memory: less +//! than [`MAX_RECORD_SIZE`] and at most [`Name::MAX_LEN`] bytes. Nothing +//! grows with the manifest. +//! +//! Signature objects are read and not verified: that takes an OpenPGP or +//! an X.509 implementation. [`Reader::signed_len`] says how much of the +//! manifest they sign. +//! +//! The reader takes every field the specification has. A field it does +//! not know is passed over, whatever its value is, as the specification +//! asks. +//! //! [UAPI.16 file manifest]: https://uapi-group.org/specifications/specs/file_manifest/ +//! [`Read`]: std::io::Read #![deny(unsafe_code)] #![warn(missing_docs)] +mod base64; +mod decode; mod digest; mod error; mod features; mod hex; mod name; mod object; +mod reader; +mod sequence; pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; -pub use error::{Error, ErrorKind, Field, Invalid}; +pub use error::{Error, ErrorKind, Field, Invalid, Problem}; pub use features::{Features, Order, UnknownFeature}; pub use name::{InvalidName, Name}; pub use object::{ @@ -36,12 +74,32 @@ pub use object::{ InodeFlags, InodeType, InvalidFatSerial, InvalidUuid, Location, Mode, RootObject, Signature, UnknownInodeType, Uuid, Validity, ValidityWindow, }; +pub use reader::{Decoder, Object, Reader, Step}; +/// The media type of a manifest, which its first object carries. +pub const MEDIA_TYPE: &str = "application/vnd.uapi.16.manifest"; +/// The media type of a signature object. +pub const SIGNATURE_MEDIA_TYPE: &str = "application/vnd.uapi.16.signature"; +/// The media type of the trailer object. +pub const TRAILER_MEDIA_TYPE: &str = "application/vnd.uapi.16.trailer"; /// The name of a manifest that is stored in the tree it describes. pub const FILENAME: &str = "Uapi16Manifest"; /// What the name of a manifest ends in that is stored next to what it /// describes. pub const SUFFIX: &str = ".Uapi16Manifest"; +/// The byte every record starts with, the ASCII record separator. +pub const RECORD_SEPARATOR: u8 = 0x1E; +/// The byte that ends a record behind its JSON text, a newline. +pub(crate) const RECORD_END: u8 = b'\n'; +/// The namespace of the extended attributes of a file object, the one the +/// specification defines. +pub(crate) const USER_NAMESPACE: &str = "user"; +/// The largest record a reader takes, from its record separator up to the +/// next one as the specification counts it, the same as systemd's. +pub const MAX_RECORD_SIZE: usize = 4 * 1024 * 1024; +/// The most contents objects a file object can have, the same as for +/// systemd. +pub const MAX_CONTENTS: usize = 256; /// What the strings of a manifest may not hold beyond what JSON forbids: /// noncharacters and the NUL character, escaped or not. @@ -50,7 +108,68 @@ pub(crate) const STRING_RULES: json::StringRules = json::StringRules::NO_NONCHAR /// What the tests of this crate build manifests from. #[cfg(test)] pub(crate) mod testing { - use super::Name; + use super::{Error, FileObject, Name, Object, Reader, RootObject, Signature, RECORD_END, RECORD_SEPARATOR}; + + /// The root file object that says nothing but that this is a manifest. + pub(crate) const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#; + /// The trailer object. + pub(crate) const TRAILER: &str = r#"{"mediaType":"application/vnd.uapi.16.trailer"}"#; + /// A signature object. + pub(crate) const SIGNATURE: &str = + r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"AAAA"}"#; + /// The hash of "hello", in hex. + pub(crate) const HELLO: &str = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + /// The hash of "world", in hex. + pub(crate) const WORLD: &str = "486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7"; + /// The hash of no data, in hex. + pub(crate) const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// The JSON text sequence of `records`. + pub(crate) fn sequence(records: &[&str]) -> Vec { + let mut out = Vec::new(); + for record in records { + out.push(RECORD_SEPARATOR); + out.extend_from_slice(record.as_bytes()); + out.push(RECORD_END); + } + out + } + + /// The manifest with the file objects `records` between the root file + /// object and the trailer. + pub(crate) fn manifest(records: &[&str]) -> Vec { + sequence(&[&[ROOT][..], records, &[TRAILER]].concat()) + } + + /// A manifest read to its end: what the tests look at. + #[derive(Clone, Debug, PartialEq, Eq)] + pub(crate) struct Whole { + pub(crate) root: RootObject, + pub(crate) objects: Vec, + pub(crate) signatures: Vec, + } + + /// Reads the manifest `bytes` to its end. + pub(crate) fn read_whole(bytes: &[u8]) -> Result { + read_whole_from(bytes) + } + + /// Reads the manifest that `input` holds to its end. + pub(crate) fn read_whole_from(input: impl std::io::Read) -> Result { + let mut reader = Reader::open(input)?; + let mut whole = Whole { + root: reader.root().clone(), + objects: Vec::new(), + signatures: Vec::new(), + }; + for object in &mut reader { + match object? { + Object::File(object) => whole.objects.push(*object), + Object::Signature(signature) => whole.signatures.push(signature), + } + } + Ok(whole) + } /// The names of the full tree in which every directory has an entry /// for each of `pieces`, down to `depth` components: every name of at diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index a761a11..b592008 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -9,7 +9,7 @@ use std::str::FromStr; use json::StringRules; -use crate::{FILENAME, STRING_RULES}; +use crate::{InodeType, FILENAME, STRING_RULES}; /// What separates the components of a name. const SEPARATOR: char = '/'; @@ -257,8 +257,9 @@ impl Ord for Name { /// The names are the same in all bytes before that one, so the bytes from /// there on settle both how the names are ordered and whether the second /// one may follow the first in a manifest. That is why one pass over the -/// bytes the names share answers all of it. The root's empty name is a -/// name here, too. +/// bytes the names share answers all the questions +/// [`SequenceCheck`](crate::sequence::SequenceCheck) asks of a file object +/// and the one before it. The root's empty name is a name here, too. pub(crate) struct NamePair<'a> { /// The bytes of the first name from the first byte in which the names /// differ on, and those of the second one. @@ -297,6 +298,31 @@ impl<'a> NamePair<'a> { let rank = |rest: &[u8]| rest.first().map(|&b| (b != SEPARATOR_BYTE, b)); rank(self.first).cmp(&rank(self.second)) } + + /// Whether the second name is that of a file in a directory that can + /// still have entries after the first file, the last one so far: the + /// root, a directory the first file is in, or the first file itself if + /// its type, `first_type`, is a directory. + /// + /// The directory of the second file is the root or one the first file + /// is in if every separator of the second name comes before the first + /// byte in which the names differ, where the first name has the same + /// separators. It is the first file itself if the first name ends there + /// and the second name has its last separator right there. + pub(crate) fn second_is_in_open_directory(&self, first_type: InodeType) -> bool { + let first_is_directory = first_type == InodeType::Directory; + let rest = match self.second.split_first() { + Some((&SEPARATOR_BYTE, inside)) if first_is_directory && self.first.is_empty() => inside, + _ => self.second, + }; + !rest.contains(&SEPARATOR_BYTE) + } + + /// Whether the second name is the first one, or that of a directory + /// the first file is in. + pub(crate) fn second_is_first_or_above(&self) -> bool { + self.second.is_empty() && self.first.first().is_none_or(|&b| b == SEPARATOR_BYTE) + } } impl PartialOrd for Name { diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index f6b7218..d7a3369 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -8,7 +8,8 @@ use std::ops::{BitAnd, BitOr, Not}; use std::str::FromStr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use crate::error::{Error, ErrorKind, Field, Invalid}; +use crate::decode::ROOT_RECORD; +use crate::error::{Error, ErrorKind, Field, Invalid, Problem}; use crate::hex::Hex; use crate::{Features, Name, Order, Sha256, STRING_RULES}; @@ -334,6 +335,14 @@ impl FromStr for Uuid { /// The `gpt` fields of a file object that describe a regular file as a /// partition of a GPT partition table: those of its entry in the table. +/// +/// `gptFlags` holds all attribute flags of the entry. `gptFlagNoAuto`, +/// `gptFlagGrowFileSystem` and `readOnly` give one of them each, and where +/// a flag is given both ways the two agree. Where the manifest lists the +/// feature of one of these fields, a regular file without the field has the +/// flags it gives cleared. A reader checks the fields against each other +/// that way and leaves them as the manifest has them: a regular file +/// without any `gpt` field has no `GptPartition`. #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct GptPartition { @@ -389,11 +398,38 @@ impl GptPartition { /// The crate does not export it, so no other crate can name or implement /// it. pub trait FlagSet: - Copy + PartialEq + BitAnd + BitOr + Not + 'static + Copy + Default + PartialEq + BitAnd + BitOr + Not + 'static { /// Every single flag with its field and the feature that records it, in /// the order of the names of the fields. const FIELDS: &'static [(Self, Field, Features)]; + + /// The flag `field` is the field of. + fn from_field(field: Field) -> Option { + Self::FIELDS + .iter() + .find(|&&(_, of, _)| of == field) + .map(|&(flag, _, _)| flag) + } + + /// The flags an object of the type `inode_type` may have: every one on + /// a regular file or a directory, none on any other file. + fn permitted(inode_type: InodeType) -> Self { + // The default is no flag, so its complement is every flag. + let none = Self::default(); + match inode_type { + InodeType::Regular | InodeType::Directory => !none, + _ => none, + } + } + + /// The flags `features` records. + fn recorded_by(features: Features) -> Self { + Self::FIELDS + .iter() + .filter(|&&(_, _, feature)| features.contains(feature)) + .fold(Self::default(), |flags, &(flag, _, _)| flags | flag) + } } /// What [`DosFlags`] and [`InodeFlags`] both have besides their flags: @@ -586,26 +622,52 @@ impl FlagStates { .filter(move |(flag, _, _)| (self.stated & *flag) == *flag) .map(|&(_, field, feature)| (field, feature)) } + + /// The field of the first flag stated that an object of the type + /// `inode_type` cannot have. The flags stated are held against those + /// the type permits all at once, and the fields are only looked through + /// to name the first flag that is not permitted. + pub(crate) fn unpermitted_field(&self, inode_type: InodeType) -> Option { + let unpermitted = self.stated & !F::permitted(inode_type); + if unpermitted == F::default() { + return None; + } + F::FIELDS + .iter() + .find(|&&(flag, _, _)| (unpermitted & flag) == flag) + .map(|&(_, field, _)| field) + } + + /// Fills in what `features`, which a manifest records, say about the + /// flags an object of the type `inode_type` does not state: a flag the + /// manifest records is cleared. + pub(crate) fn fill_in(&mut self, features: Features, inode_type: InodeType) { + self.stated = self.stated | (F::recorded_by(features) & F::permitted(inode_type)); + } } -/// The fields of an object of a manifest that a reader filled in: the -/// sizes and hashes that follow from other fields, which the record of the -/// object does not have. A writer leaves them out. +/// The fields of an object of a manifest that a reader filled in, which +/// the record of the object does not have: the sizes and hashes that +/// follow from other fields, and `readOnly`, which is false where the +/// manifest lists `read-only`. A writer leaves them out, and the checks of +/// an object take a filled-in `readOnly` for one that is not there. /// -/// What is filled in is a size or a hash: the `size` and the `sha256` of a -/// [`FileObject`], and the sizes and hashes of a [`Contents`]. +/// The `size` and the `sha256` of a [`FileObject`], the sizes and hashes +/// of a [`Contents`] and the `readOnly` of [`InodeAttributes`] can be +/// filled in. Each of them notes it in its own `filled_in`. #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct FilledIn(u8); impl FilledIn { /// The fields that can be filled in, in the order of their bits. - const FIELDS: [Field; 6] = [ + const FIELDS: [Field; 7] = [ Field::Size, Field::Sha256, Field::EncodedSize, Field::EncodedSha256, Field::OriginalSize, Field::OriginalSha256, + Field::ReadOnly, ]; /// The bit of `field`, none for one that cannot be filled in. @@ -902,6 +964,9 @@ pub struct InodeAttributes { /// `flagAppendOnly` and the other fields of the inode flags: the /// flags the object states. pub flags: FlagStates, + /// `readOnly`, if a reader filled it in. Whoever sets another value + /// takes the field out. + pub filled_in: FilledIn, } impl InodeAttributes { @@ -928,7 +993,7 @@ impl InodeAttributes { Field::GroupName => self.group_name.is_some(), Field::MTimeNSec => self.mtime_nsec.is_some(), Field::Mode => self.mode.is_some(), - Field::ReadOnly => self.read_only.is_some(), + Field::ReadOnly => self.stated_read_only().is_some(), Field::Uid => self.uid.is_some(), Field::UserName => self.user_name.is_some(), _ => false, @@ -944,6 +1009,28 @@ impl InodeAttributes { .chain(self.flags.feature_fields()) } + /// `readOnly` as the record of the object has it: None where a reader + /// filled it in. + pub(crate) fn stated_read_only(&self) -> Option { + self.read_only.filter(|_| !self.filled_in.contains(Field::ReadOnly)) + } + + /// Fills in what `features`, which the manifest records, say about the + /// attributes a file of the type `inode_type` does not have: an inode + /// flag the manifest records is cleared, the file is not read-only if + /// the manifest records `readOnly`, which is noted in `filled_in`, and + /// it has no extended attributes if the manifest records them. + fn fill_in(&mut self, features: Features, inode_type: InodeType) { + self.flags.fill_in(features, inode_type); + if features.contains(Features::READ_ONLY) && self.read_only.is_none() { + self.read_only = Some(false); + self.filled_in.insert(Field::ReadOnly); + } + if features.contains(Features::USER_XATTR) && self.user_xattrs.is_none() { + self.user_xattrs = Some(Box::default()); + } + } + /// The modification time, if the attributes have one. pub fn mtime(&self) -> Option { self.mtime_nsec.map(|nsec| UNIX_EPOCH + Duration::from_nanos(nsec)) @@ -1103,12 +1190,31 @@ impl FileObject { /// The features whose fields the object has, see [`Features`]. A /// manifest records them all or the object is not one of its file - /// objects. The fields a reader filled in do not count. + /// objects. What a reader filled in, see [`FilledIn`], does not count. pub fn stated_features(&self) -> Features { self.feature_fields() .fold(Features::NONE, |features, (_, feature)| features | feature) } + /// Fills in what `features`, which its manifest records, say about the + /// fields the object does not have: a flag the manifest records is + /// cleared, the file is not read-only if the manifest records + /// `readOnly`, and it has no extended attributes if the manifest + /// records them. The `gpt` fields are not filled in, see + /// [`GptPartition`]. + pub(crate) fn fill_in(&mut self, features: Features) { + self.dos_flags.fill_in(features, self.inode_type); + self.inode.fill_in(features, self.inode_type); + } + + /// The field of the first flag the object states that it cannot have: + /// only regular files and directories have flags. + pub(crate) fn unpermitted_flag(&self) -> Option { + self.dos_flags + .unpermitted_field(self.inode_type) + .or_else(|| self.inode.flags.unpermitted_field(self.inode_type)) + } + /// Checks that the object may be used at the time `now_usec`, in /// microseconds since the epoch: that it is not revoked and that the /// time is inside its validity window. What is true of a directory is @@ -1186,12 +1292,47 @@ impl RootObject { } /// The features whose fields the object has, see [`Features`]. A - /// manifest records them all or this is not its root file object. + /// manifest records them all or this is not its root file object. A + /// `readOnly` a reader filled in, see [`FilledIn`], does not count. pub fn stated_features(&self) -> Features { self.feature_fields() .fold(Features::NONE, |features, (_, feature)| features | feature) } + /// What the manifest records: the features the root file object lists + /// in `features`, or [`Features::DEFAULT`] if it lists none. + pub fn recorded_features(&self) -> Features { + self.features.unwrap_or(Features::DEFAULT) + } + + /// Requires the manifest to declare `order` in its root file object, as + /// a consumer does that relies on the order: a manifest that does not is + /// [`Problem::NoOrder`], even if its file objects are in that order. A + /// reader checks the file objects against the order the manifest + /// declares while it reads them. + pub fn require_order(&self, order: Order) -> Result<(), Error> { + if self.order == Some(order) { + return Ok(()); + } + Err(Error::manifest( + Problem::NoOrder, + format!( + "the manifest does not declare \"{}\": \"{}\" in its root file object", + Field::Order, + order + ), + ) + .at(Field::Order) + .in_record(ROOT_RECORD)) + } + + /// Fills in what `features`, which the manifest records, say about the + /// fields of the root directory the object does not have, as + /// [`FileObject::fill_in`] does for a file object. + pub(crate) fn fill_in(&mut self, features: Features) { + self.inode.fill_in(features, InodeType::Directory); + } + /// Checks that the manifest may be used at the time `now_usec`, in /// microseconds since the epoch: that its root file object is not /// revoked and that the time is inside its validity window. diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs new file mode 100644 index 0000000..bb4b6fa --- /dev/null +++ b/src/uapi16/reader.rs @@ -0,0 +1,1640 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Reading a manifest record by record. + +use std::fmt; +use std::io::{self, BufRead, BufReader, Read}; +use std::iter::FusedIterator; + +use json::is_whitespace; + +use crate::decode::{DecodedObject, RecordDecoder, ROOT_RECORD}; +use crate::error::{Error, Problem}; +use crate::object::{FileObject, RootObject, Signature}; +use crate::sequence::SequenceCheck; +use crate::{MAX_RECORD_SIZE, RECORD_END, RECORD_SEPARATOR}; + +/// How much is read from the input at a time. +const READ_SIZE: usize = 64 * 1024; +/// The most bytes a record has behind its record separator, which counts +/// as a part of the record. +const MAX_RECORD_TEXT: usize = MAX_RECORD_SIZE - size_of_val(&RECORD_SEPARATOR); +/// The most the read of one record takes from the input: the bytes of a +/// record as large as a record can be behind its separator, and the +/// separator behind them. +const READ_LIMIT: usize = MAX_RECORD_TEXT + size_of_val(&RECORD_SEPARATOR); +/// The byte no record may have. +const NUL: u8 = 0; + +/// Where the read of a record ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RecordEnd { + /// At a record separator, where the next record starts. + Separator, + /// At the end of the input. + Input, + /// At [`READ_LIMIT`], without a separator: the record is too large. + Limit, +} + +/// What [`RecordSplitter::next_record`] has. +enum NextRecord<'a> { + /// The text of the next record that is more than whitespace. + Text(&'a str), + /// Nothing yet: the next record goes on in input that was not fed. + Input, + /// Nothing: the input ended. + End, +} + +/// Splits the input into the records of a JSON text sequence as it is +/// fed: each one starts with a record separator and goes up to the next +/// one. It holds one record without its separator, at most +/// [`MAX_RECORD_TEXT`] bytes, and takes no more of the input for it than +/// [`READ_LIMIT`]. +#[derive(Default)] +struct RecordSplitter { + /// The record being read, or the one handed out last, without its + /// separators. A record too large is kept up to the limit. + record: Vec, + /// How many bytes of the input the read of the record took, its + /// separator included. + taken: usize, + /// Where the read of the record ended, once it did. + end: Option, + /// Whether the record was handed out, so that the next one is read. + handed_out: bool, + /// Whether the input ended. + input_ended: bool, + /// How many bytes of the input went into the records read so far. + pos: u64, + /// Where in the input the record that was handed out last starts. + offset: u64, +} + +impl RecordSplitter { + /// Takes bytes from the start of `input` into the record being read, + /// up to the separator behind it, and no more than [`READ_LIMIT`] for + /// the record. Returns how many it took. Once the read ended it takes + /// none, until the record was handed out and the next read started. + #[inline] + fn feed(&mut self, input: &[u8]) -> usize { + if self.end.is_some() { + return 0; + } + let window = &input[..input.len().min(READ_LIMIT - self.taken)]; + // Reading a slice does no I/O and cannot fail. The search is the + // one BufRead::skip_until() does in a BufReader. + let mut rest = window; + let took = rest.skip_until(RECORD_SEPARATOR).unwrap_or_default(); + let separated = window[..took].last() == Some(&RECORD_SEPARATOR); + // The separator is not kept, and neither is the byte of a record + // too large that reaches the limit. + let kept = took - usize::from(separated); + let kept = &window[..kept.min(MAX_RECORD_TEXT - self.record.len())]; + // The buffer grows the way a Vec grows, but not beyond the largest + // record. + let len = self.record.len() + kept.len(); + if len > self.record.capacity() { + let capacity = (2 * self.record.capacity()).max(len).min(MAX_RECORD_TEXT); + self.record.reserve_exact(capacity - self.record.len()); + } + self.record.extend_from_slice(kept); + self.taken += took; + if separated { + self.end = Some(RecordEnd::Separator); + } else if self.taken == READ_LIMIT { + self.end = Some(RecordEnd::Limit); + } + took + } + + /// Notes that the input ended: the read of the record ends there, and + /// so does every read after it. + #[inline] + fn end_input(&mut self) { + self.input_ended = true; + self.end.get_or_insert(RecordEnd::Input); + } + + /// Starts the read of the next record. + #[inline] + fn restart(&mut self) { + self.record.clear(); + self.taken = 0; + self.end = self.input_ended.then_some(RecordEnd::Input); + } + + /// Moves on to the read of the next record once the record read last + /// was handed out. + #[inline] + fn advance(&mut self) { + if std::mem::take(&mut self.handed_out) { + self.restart(); + } + } + + /// Whether the record being read goes on in input that was not fed + /// yet. + #[inline] + fn wants_input(&self) -> bool { + self.end.is_none() + } + + /// Whether the record that was handed out last, which holds the + /// trailer object, is the end of the input: nothing comes behind the + /// object but whitespace up to the newline that ends the record. + fn ends_with_trailer(&self) -> bool { + // The record was read as JSON, so behind the object there is only + // JSON's whitespace, which is ASCII whitespace. + let behind = &self.record[self.record.trim_ascii_end().len()..]; + let newline = behind.iter().position(|&b| b == RECORD_END); + self.end == Some(RecordEnd::Input) && newline.is_none_or(|at| at + 1 == behind.len()) + } + + /// The next record that is more than whitespace, once it was read up to + /// its end. Its text stays as it is until the next call. + #[inline] + fn next_record(&mut self) -> Result, Error> { + self.advance(); + if self.wants_input() { + return Ok(NextRecord::Input); + } + loop { + let Some(end) = self.end else { + return Ok(NextRecord::Input); + }; + let start = self.pos; + self.pos += self.taken as u64; + // Nothing may come before the first separator. + if start == 0 { + if self.taken == 0 { + return Ok(NextRecord::End); + } + if let Some(&first) = self.record.first() { + return Err(Error::manifest( + Problem::NoRecordSeparator, + format!( + "manifest record does not start with a record separator but with byte 0x{:02x}", + first + ), + )); + } + self.restart(); + continue; + } + if self.taken == 0 { + return Ok(NextRecord::End); + } + if end == RecordEnd::Limit { + return Err(Error::record_too_large()); + } + if self.record.contains(&NUL) { + return Err(Error::manifest( + Problem::ContainsNulByte, + "manifest record contains a NUL byte".into(), + )); + } + self.offset = start - size_of_val(&RECORD_SEPARATOR) as u64; + // Empty records are skipped, as RFC 7464 suggests. Only JSON's + // whitespace counts as empty. + if !self.record.iter().all(|&b| is_whitespace(b)) { + self.handed_out = true; + return match std::str::from_utf8(&self.record) { + Ok(text) => Ok(NextRecord::Text(text)), + Err(_) => Err(Error::manifest(Problem::NotUtf8, "manifest record is not UTF-8".into())), + }; + } + self.restart(); + } + } +} + +impl fmt::Debug for RecordSplitter { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RecordSplitter") + .field( + "record", + &format_args!("{}/{}", self.record.len(), self.record.capacity()), + ) + .field("taken", &self.taken) + .field("end", &self.end) + .field("handed_out", &self.handed_out) + .field("input_ended", &self.input_ended) + .field("pos", &self.pos) + .field("offset", &self.offset) + .finish() + } +} + +/// An object of a manifest after its root file object, as a [`Reader`] +/// and a [`Decoder`] hand it out. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Object { + /// A file object. + File(Box), + /// A signature object. It comes after the last file object. + Signature(Signature), +} + +/// How far a decoder has got in the manifest. +#[derive(Debug)] +enum Stage { + /// The root file object comes. + Root, + /// File objects come, each checked against the ones before it. + Files(SequenceCheck), + /// A signature object was read. File objects cannot follow. + Signatures, + /// The manifest is decoded to its end, or decoding it failed. + Done, +} + +/// What a [`Decoder`] has for its caller next. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Step { + /// More of the manifest: [`Decoder::feed`] takes it, and + /// [`Decoder::end`] says that the input ended. + Input, + /// The root file object. It comes first, once. + Root(Box), + /// A file object or a signature object. + Object(Object), + /// The end of the manifest, after its trailer object. Once + /// [`Decoder::step`] returned an error, it returns this as well. + End, +} + +/// Reads a manifest from the bytes it is fed, and does no I/O itself. +/// +/// [`Decoder::step`] says what comes next. [`Step::Input`] asks for more +/// of the manifest: [`Decoder::feed`] takes the bytes that come next, and +/// [`Decoder::end`] says that there are no more. [`Step::Root`] is the root +/// file object, [`Step::Object`] each object after it, and [`Step::End`] +/// the end of the manifest. +/// +/// A record ends where the next one starts, so an object comes once the +/// separator of the record after it was fed, or [`Decoder::end`] was +/// called. Nothing may follow the trailer object, so [`Step::End`] comes +/// only after [`Decoder::end`]. [`Decoder::step`] reads a whole record, of +/// up to [`MAX_RECORD_SIZE`] bytes with its record separator, in one call. +/// +/// A decoder checks and fills in what a [`Reader`] does, which is a +/// decoder fed from a [`Read`]. It takes the bytes of one record at a time, +/// up to the record separator behind it, and keeps one record without its +/// separator and the name of the last file object in memory: less than +/// [`MAX_RECORD_SIZE`] and at most [`Name::MAX_LEN`](crate::Name::MAX_LEN) +/// bytes, in whatever pieces the manifest comes. +/// +/// ``` +/// use uapi16::{Decoder, Object, Step}; +/// +/// let manifest = concat!( +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", +/// "\x1e{\"name\":\"a\",\"size\":3}\n", +/// "\x1e{\"name\":\"b\",\"type\":\"dir\"}\n", +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", +/// ); +/// let mut input = manifest.as_bytes(); +/// let mut decoder = Decoder::new(); +/// let mut names = Vec::new(); +/// loop { +/// match decoder.step()? { +/// Step::Input if input.is_empty() => decoder.end(), +/// // The manifest comes in pieces of at most five bytes. +/// Step::Input => { +/// let taken = decoder.feed(&input[..input.len().min(5)]); +/// input = &input[taken..]; +/// } +/// Step::Object(Object::File(object)) => names.push(object.name), +/// Step::End => break, +/// _ => {} +/// } +/// } +/// assert_eq!(names, ["a", "b"]); +/// # Ok::<(), uapi16::Error>(()) +/// ``` +#[derive(Debug)] +pub struct Decoder { + splitter: RecordSplitter, + /// The number of the record that is read next. + next_record: u64, + /// The number of the record the object handed out last came from. + last_record: u64, + stage: Stage, + /// Where in the input the first signature object starts. + signed: Option, +} + +impl Default for Decoder { + fn default() -> Decoder { + Decoder::new() + } +} + +impl Decoder { + /// A decoder at the start of a manifest. + pub fn new() -> Decoder { + Decoder { + splitter: RecordSplitter::default(), + next_record: ROOT_RECORD, + last_record: ROOT_RECORD, + stage: Stage::Root, + signed: None, + } + } + + /// Takes bytes from the start of `input`, after [`Step::Input`], up to + /// the end of the record it reads. It takes one at least where `input` + /// has any, and returns how many it took. The others are for a later + /// call, after the next step. + #[inline] + #[must_use] + pub fn feed(&mut self, input: &[u8]) -> usize { + self.splitter.feed(input) + } + + /// Says that the input ended, after [`Step::Input`]. + #[inline] + pub fn end(&mut self) { + self.splitter.end_input(); + } + + /// What comes next. Once it returned an error, it returns + /// [`Step::End`]. + #[inline] + pub fn step(&mut self) -> Result { + if !matches!(self.stage, Stage::Done) { + // The next record goes on in input that was not fed yet, as it + // does right after every object that was handed out. + self.splitter.advance(); + if self.splitter.wants_input() { + return Ok(Step::Input); + } + } + let step = match self.stage { + Stage::Root => self.root(), + Stage::Files(_) | Stage::Signatures => self.object(), + Stage::Done => return Ok(Step::End), + }; + if matches!(step, Ok(Step::End) | Err(_)) { + self.stage = Stage::Done; + } + step + } + + /// The number of the record the object handed out last came from. The + /// record of the root file object is number 0. Records that are empty + /// do not count. + pub fn record_number(&self) -> u64 { + self.last_record + } + + /// How many bytes at the start of the manifest its signature objects + /// sign, see [`Reader::signed_len`]. + pub fn signed_len(&self) -> Option { + self.signed + } + + /// An error `e` of the input the manifest is read from, as an error + /// about the record the decoder reads. + pub fn input_error(&self, e: io::Error) -> Error { + Error::from(e).in_record(self.next_record) + } + + /// Reads the root file object. + fn root(&mut self) -> Result { + let text = match self.splitter.next_record().map_err(|e| e.in_record(ROOT_RECORD))? { + NextRecord::Input => return Ok(Step::Input), + NextRecord::End => { + return Err(Error::manifest( + Problem::NoObjects, + "manifest contains no objects".into(), + )) + } + NextRecord::Text(text) => text, + }; + let mut root = RecordDecoder::root(text)?; + let features = root.recorded_features(); + let sequence_check = SequenceCheck::new(features, root.order); + sequence_check + .check_root_fields(&root) + .map_err(|e| e.in_record(ROOT_RECORD))?; + root.fill_in(features); + self.stage = Stage::Files(sequence_check); + self.next_record = ROOT_RECORD + 1; + Ok(Step::Root(Box::new(root))) + } + + /// Reads on to the next file or signature object. + fn object(&mut self) -> Result { + loop { + let number = self.next_record; + let text = match self.splitter.next_record().map_err(|e| e.in_record(number))? { + NextRecord::Input => return Ok(Step::Input), + NextRecord::End => { + return Err(Error::manifest( + Problem::NoTrailer, + "manifest lacks the trailer object, it is incomplete".into(), + )) + } + NextRecord::Text(text) => text, + }; + let decoded = RecordDecoder::record(text, number)?; + self.next_record += 1; + match decoded { + // Nothing may come behind the trailer, not even an empty + // record or whitespace. + DecodedObject::Trailer if self.splitter.ends_with_trailer() => return Ok(Step::End), + DecodedObject::Trailer => return Err(Error::data_after_trailer(self.next_record)), + DecodedObject::Other => {} + DecodedObject::Signature(signature) => { + self.stage = Stage::Signatures; + self.signed.get_or_insert(self.splitter.offset); + self.last_record = number; + return Ok(Step::Object(Object::Signature(signature))); + } + DecodedObject::File(object) => { + // A file object behind a signature is one the signature + // does not cover. + let Stage::Files(sequence_check) = &mut self.stage else { + return Err(Error::file_after_signature(number)); + }; + let mut object = object?; + let checked = sequence_check + .check_fields(&object, number) + .and_then(|()| sequence_check.admit(&object, number)); + checked.map_err(|e| e.in_record(number).named(object.name.as_str()))?; + object.fill_in(sequence_check.features()); + self.last_record = number; + return Ok(Step::Object(Object::File(object))); + } + } + } + } +} + +/// Reads a manifest record by record. +/// +/// [`Reader::open`] reads the root file object, the first object of +/// every manifest. The reader is then an iterator over the file objects +/// and the signature objects that follow. It ends after the trailer +/// object. Objects of a media type the specification does not have are +/// passed over, as it asks. +/// +/// The reader keeps one record and the name of the last file object in +/// memory. It checks every object against the rules of the specification, +/// and the order of the objects: the file objects in tree order, each +/// right after the object of its directory, then signature objects, then +/// the trailer, and nothing behind it. A file object has no field of a +/// feature the manifest does not record, and the reader fills in what the +/// features say about the fields it does not have, see +/// [`Features`](crate::Features): a +/// flag the manifest records is cleared, a file is not read-only and has +/// no extended attributes. It leaves the `gpt` fields as they are, see +/// [`GptPartition`](crate::GptPartition). +/// +/// A name that comes again right after the entries of the directory it +/// names is an error, a name that comes again later only if the manifest +/// declares an order in `order`. Then every name has to come after the one +/// before it, and none can come twice. A consumer that relies on the order +/// requires the manifest to declare it with +/// [`RootObject::require_order`]. +/// +/// Once the reader returned an error it returns nothing more. An error of +/// the kind [`WouldBlock`](io::ErrorKind::WouldBlock) from the input is +/// the exception: the reader lost nothing, and reads on when it is asked +/// again. +/// +/// A manifest comes from outside and may be anything. No record is larger +/// than [`MAX_RECORD_SIZE`] with its record separator, and reading takes +/// time in proportion to the size of the input. +/// +/// ``` +/// use uapi16::{Object, Reader}; +/// +/// let manifest = concat!( +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", +/// "\x1e{\"name\":\"a\",\"size\":3}\n", +/// "\x1e{\"name\":\"b\",\"type\":\"dir\"}\n", +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", +/// ); +/// let mut names = Vec::new(); +/// for object in Reader::open(manifest.as_bytes())? { +/// if let Object::File(object) = object? { +/// names.push(object.name); +/// } +/// } +/// assert_eq!(names, ["a", "b"]); +/// # Ok::<(), uapi16::Error>(()) +/// ``` +#[derive(Debug)] +pub struct Reader { + input: BufReader, + decoder: Decoder, + root: RootObject, + /// Whether an error ended the reading. + failed: bool, +} + +impl Reader { + /// Starts to read a manifest from `input`, with its root file object. + /// An error of the input fails it, one of the kind + /// [`WouldBlock`](io::ErrorKind::WouldBlock) as well. The input is + /// dropped then, with what was read of it. + pub fn open(input: R) -> Result, Error> { + let mut reader = Reader { + input: BufReader::with_capacity(READ_SIZE, input), + decoder: Decoder::new(), + root: RootObject::default(), + failed: false, + }; + let Step::Root(root) = reader.pull()? else { + unreachable!("a decoder hands out the root file object first"); + }; + reader.root = *root; + Ok(reader) + } + + /// The root file object of the manifest. + pub fn root(&self) -> &RootObject { + &self.root + } + + /// What the manifest is read from. The reader reads ahead of the + /// objects it returned. It has read the input to its end once it + /// returned None after the last of them, which it does when it read + /// the trailer object. + pub fn get_ref(&self) -> &R { + self.input.get_ref() + } + + /// What the manifest is read from, to change it. Reading from it + /// directly takes bytes away from the reader, which reads ahead of the + /// objects it returned. + pub fn get_mut(&mut self) -> &mut R { + self.input.get_mut() + } + + /// The number of the record the object returned last came from. The + /// record of the root file object is number 0. Records that are empty + /// do not count. + pub fn record_number(&self) -> u64 { + self.decoder.record_number() + } + + /// How many bytes at the start of the manifest its signature objects + /// sign: all that comes before the record of the first of them, up to + /// its record separator. None as long as no signature object was read. + /// + /// This crate does not verify signatures. With this number and the + /// [`Signature`] objects a caller can. + pub fn signed_len(&self) -> Option { + self.decoder.signed_len() + } + + /// Feeds the decoder until it takes a step other than [`Step::Input`]. + fn pull(&mut self) -> Result { + loop { + match self.decoder.step()? { + Step::Input => self.fill()?, + step => return Ok(step), + } + } + } + + /// Feeds the decoder what the input has next, or tells it that the + /// input ended. An error of the input is one about the record being + /// read. + fn fill(&mut self) -> Result<(), Error> { + let input = loop { + match self.input.fill_buf() { + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + result => break result, + } + }; + let input = input.map_err(|e| self.decoder.input_error(e))?; + if input.is_empty() { + self.decoder.end(); + } else { + let taken = self.decoder.feed(input); + self.input.consume(taken); + } + Ok(()) + } +} + +impl Iterator for Reader { + type Item = Result; + + fn next(&mut self) -> Option> { + if self.failed { + return None; + } + match self.pull() { + Ok(Step::Object(object)) => Some(Ok(object)), + Ok(Step::End) => None, + // pull() feeds the decoder what it asks for, and the root file + // object came when the reader was opened. + Ok(Step::Input | Step::Root(_)) => unreachable!("a decoder hands out the root file object once"), + Err(e) => { + // An input that has nothing right now gave the decoder + // nothing, and it reads on from where it was. + self.failed = e.io_error().map(io::Error::kind) != Some(io::ErrorKind::WouldBlock); + Some(Err(e)) + } + } + } +} + +impl FusedIterator for Reader {} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::{ErrorKind, Field}; + use crate::testing::{manifest, sequence, ROOT, SIGNATURE, TRAILER}; + use crate::testing::{read_whole, read_whole_from, Whole, HELLO}; + use crate::{Digest, DosFlags, Features, FlagStates, InodeFlags, InodeType, Name, Order, RootObject, Sha256}; + use std::collections::BTreeMap; + + /// Reads `bytes` to the end and returns the names of the file objects + /// and the number of signature objects. + fn read(bytes: &[u8]) -> Result<(Vec, usize), Error> { + let mut names = Vec::new(); + let mut signatures = 0; + for object in Reader::open(bytes)? { + match object? { + Object::File(object) => names.push(object.name.to_string()), + Object::Signature(_) => signatures += 1, + } + } + Ok((names, signatures)) + } + + /// The problem with `bytes` and the record it is in. + fn problem(bytes: &[u8]) -> (Problem, Option) { + let e = read(bytes).expect_err("the manifest was taken"); + match e.kind() { + ErrorKind::Manifest(problem) => (problem, e.record_number()), + other => panic!("{:?}: {}", other, e), + } + } + + #[test] + fn reads_a_manifest() { + let file = format!( + r#"{{"mTimeNSec":1700000000000000000,"mode":420,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"{}","size":5}}"#, + HELLO + ); + let m = read_whole(&sequence(&[ + concat!( + r#"{"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid"],"#, + r#""mTimeNSec":7,"mediaType":"application/vnd.uapi.16.manifest","mode":509}"# + ), + r#"{"mode":493,"name":"EFI","type":"dir","uid":0,"gid":0}"#, + r#"{"name":"EFI/BOOT","type":"dir"}"#, + &file, + r#"{"name":"empty","size":0}"#, + r#"{"contents":[{"literal":"aGVsbG8="}],"name":"literal.txt","mode":420}"#, + r#"{"contents":[{"literal":"aGVsbG8="}],"name":"link","type":"lnk"}"#, + SIGNATURE, + r#"{"mediaType":"application/x-unknown","whatever":1}"#, + TRAILER, + ])) + .unwrap(); + assert_eq!( + (m.root.inode.mtime_nsec, m.root.inode.mode.map(crate::Mode::bits)), + (Some(7), Some(0o775)) + ); + let names: Vec<&str> = m.objects.iter().map(|object| object.name.as_str()).collect(); + assert_eq!( + names, + [ + "EFI", + "EFI/BOOT", + "EFI/BOOT/BOOTX64.EFI", + "empty", + "literal.txt", + "link" + ] + ); + assert_eq!(m.objects[2].sha256, Some(Sha256::digest(b"hello"))); + assert_eq!(m.objects[3].sha256, Some(Sha256::EMPTY)); + assert_eq!(m.objects[4].size, Some(5)); + assert_eq!(m.objects[5].inode_type, InodeType::Symlink); + assert_eq!(m.signatures.len(), 1); + assert_eq!(m.signatures[0].mechanism, "pkcs7"); + assert_eq!(m.signatures[0].data.as_deref(), Some(&[0u8, 0, 0][..])); + // The least a manifest is. + let least = read_whole(&sequence(&[ROOT, TRAILER])).unwrap(); + assert_eq!((least.root, least.objects.len()), (RootObject::default(), 0)); + } + + #[test] + fn tree_order() { + let dir = |name: &str| format!(r#"{{"name":"{}","type":"dir"}}"#, name); + let file = |name: &str| format!(r#"{{"name":"{}","size":0}}"#, name); + let read_names = |records: &[String]| { + let records: Vec<&str> = records.iter().map(String::as_str).collect(); + read(&manifest(&records)) + }; + let good = [dir("a"), dir("a/b"), file("a/b/c"), file("a/d"), file("e")]; + assert_eq!(read_names(&good).unwrap().0.len(), 5); + for (records, record) in [ + (vec![file("a/x")], 1), + (vec![dir("a"), file("b"), file("a/x")], 3), + (vec![file("a"), file("a/x")], 2), + ] { + let records: Vec<&str> = records.iter().map(String::as_str).collect(); + assert_eq!( + problem(&manifest(&records)), + (Problem::Misplaced, Some(record)), + "{:?}", + records + ); + } + } + + #[test] + fn repeated_names() { + // A name right after itself, or right after the entries of the + // directory it names, is found in any order. + for records in [ + &[r#"{"name":"a"}"#, r#"{"name":"a"}"#][..], + &[ + r#"{"name":"d","type":"dir"}"#, + r#"{"name":"d/x"}"#, + r#"{"name":"d","type":"dir"}"#, + ], + ] { + assert_eq!(problem(&manifest(records)).0, Problem::DuplicateName, "{:?}", records); + } + // A name that comes again later is only found if the manifest + // declares an order. + let later = manifest(&[r#"{"name":"a"}"#, r#"{"name":"b"}"#, r#"{"name":"a"}"#]); + assert_eq!(read(&later).unwrap().0, ["a", "b", "a"]); + let declared = sequence(&[ + r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"#, + r#"{"name":"a"}"#, + r#"{"name":"b"}"#, + r#"{"name":"a"}"#, + TRAILER, + ]); + assert_eq!(problem(&declared), (Problem::OutOfOrder, Some(3))); + // Names that differ by case, by a byte or by a prefix are not the + // same. + let m = read_whole(&manifest(&[r#"{"name":"A"}"#, r#"{"name":"a"}"#, r#"{"name":"a."}"#])).unwrap(); + assert_eq!(m.objects.len(), 3); + } + + #[test] + fn requires_the_declared_order() { + // A consumer that relies on the order requires the manifest to + // declare it. File objects that are in it are not enough. + let sorted = manifest(&[r#"{"name":"a"}"#, r#"{"name":"b"}"#]); + let reader = Reader::open(&sorted[..]).unwrap(); + assert_eq!(reader.root().order, None); + let e = reader.root().require_order(Order::CodePoint).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number(), e.field()), + (ErrorKind::Manifest(Problem::NoOrder), Some(0), Some(Field::Order)) + ); + assert_eq!( + e.to_string(), + r#"the manifest does not declare "order": "codepoint" in its root file object"# + ); + // An order the specification does not have, or null, declares none. + for order in [r#""later""#, r#""CodePoint""#, "null"] { + let root = format!( + r#"{{"mediaType":"application/vnd.uapi.16.manifest","order":{}}}"#, + order + ); + let bytes = sequence(&[&root, TRAILER]); + let reader = Reader::open(&bytes[..]).unwrap(); + let e = reader.root().require_order(Order::CodePoint).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoOrder), "{}", order); + } + let declared = sequence(&[ + r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"#, + r#"{"name":"a"}"#, + TRAILER, + ]); + let reader = Reader::open(&declared[..]).unwrap(); + assert_eq!(reader.root().order, Some(Order::CodePoint)); + assert!(reader.root().require_order(Order::CodePoint).is_ok()); + } + + #[test] + fn features() { + let with = |root: &str, records: &[&str]| sequence(&[&[root][..], records, &[TRAILER]].concat()); + // A field of a feature the manifest does not record, on any file + // object, the root's too. + assert_eq!( + problem(&manifest(&[r#"{"name":"a","mTimeNSec":5}"#])), + (Problem::UnlistedFeature, Some(1)) + ); + let root = r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["size"]}"#; + assert_eq!( + problem(&with(root, &[r#"{"name":"a","mode":420}"#])), + (Problem::UnlistedFeature, Some(1)) + ); + let e = Reader::open( + &with( + r#"{"mediaType":"application/vnd.uapi.16.manifest","uid":0,"features":[]}"#, + &[], + )[..], + ) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::UnlistedFeature)); + // The error names the field and the record. + assert_eq!((e.record_number(), e.field()), (Some(0), Some(Field::Uid))); + let e = read(&manifest(&[r#"{"name":"a","mTimeNSec":5}"#])).unwrap_err(); + assert_eq!( + (e.record_number(), e.name(), e.field()), + (Some(1), Some("a"), Some(Field::MTimeNSec)) + ); + // The fields of the file system and of partitions belong to + // features too. + for (root, records, field) in [ + ( + r#"{"mediaType":"application/vnd.uapi.16.manifest","readOnly":true}"#, + &[][..], + Field::ReadOnly, + ), + ( + r#"{"mediaType":"application/vnd.uapi.16.manifest","fsLabel":"ESP"}"#, + &[], + Field::FsLabel, + ), + ( + r#"{"mediaType":"application/vnd.uapi.16.manifest","fsUUID":"11111111-2222-3333-4444-555555555555"}"#, + &[], + Field::FsUuid, + ), + ( + r#"{"mediaType":"application/vnd.uapi.16.manifest","fatSerial":"1234-ABCD"}"#, + &[], + Field::FatSerial, + ), + ( + r#"{"mediaType":"application/vnd.uapi.16.manifest","gptDiskUuid":"11111111-2222-3333-4444-555555555555"}"#, + &[], + Field::GptDiskUuid, + ), + (ROOT, &[r#"{"name":"a","readOnly":false}"#], Field::ReadOnly), + (ROOT, &[r#"{"name":"a","gptLabel":"l"}"#], Field::GptLabel), + (ROOT, &[r#"{"name":"a","gptFlags":0}"#], Field::GptFlags), + (ROOT, &[r#"{"name":"a","gptFlagNoAuto":false}"#], Field::GptFlagNoAuto), + ] { + let e = read(&with(root, records)).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::UnlistedFeature), Some(field)), + "{} {:?}", + root, + records + ); + } + // A size of 0 that the hash of no data follows from names the size, + // not the hash it gives. + let sized = with( + r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["sha256"]}"#, + &[r#"{"name":"a","size":0}"#], + ); + assert_eq!(read(&sized).unwrap_err().field(), Some(Field::Size)); + // A symbolic link without its target in a manifest that records + // them. + assert_eq!( + problem(&manifest(&[r#"{"name":"l","type":"lnk"}"#])), + (Problem::NoTarget, Some(1)) + ); + let quiet = r#"{"mediaType":"application/vnd.uapi.16.manifest","features":["size"]}"#; + assert!(read(&with(quiet, &[r#"{"name":"l","type":"lnk"}"#])).is_ok()); + // What the features say about the fields an object does not have. + let root = concat!( + r#"{"mediaType":"application/vnd.uapi.16.manifest","#, + r#""features":["flag-hidden","flag-no-cow","gpt-flags","gpt-label","read-only","user-xattr"]}"# + ); + let read_only = format!( + r#"{{"name":"b","readOnly":true,"gptFlags":{}}}"#, + crate::GptPartition::FLAG_READ_ONLY + ); + let bytes = with( + root, + &[ + r#"{"name":"a","flagHidden":true,"gptLabel":"l"}"#, + &read_only, + r#"{"name":"c"}"#, + r#"{"name":"l","type":"lnk"}"#, + ], + ); + let reader = Reader::open(&bytes[..]).unwrap(); + assert_eq!( + reader.root().recorded_features(), + Features::FLAG_HIDDEN + | Features::FLAG_NO_COW + | Features::GPT_FLAGS + | Features::GPT_LABEL + | Features::READ_ONLY + | Features::USER_XATTR + ); + // The root has the inode flags. It has no DOS attributes at all. + let root = reader.root(); + assert_eq!(root.inode.flags.get(InodeFlags::NO_COW), Some(false)); + assert_eq!(root.inode.read_only, Some(false)); + assert_eq!(root.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); + let m = read_whole(&bytes).unwrap(); + let a = &m.objects[0]; + assert_eq!(a.dos_flags.get(DosFlags::HIDDEN), Some(true)); + assert_eq!(a.dos_flags.get(DosFlags::SYSTEM), None); + assert_eq!(a.inode.flags.get(InodeFlags::NO_COW), Some(false)); + assert_eq!(a.inode.read_only, Some(false)); + assert_eq!(a.inode.user_xattrs.as_deref().map(BTreeMap::len), Some(0)); + assert_eq!(m.objects[1].inode.read_only, Some(true)); + // The gpt fields are as the records have them: a missing gptFlags + // is 0, but nothing fills it in, and a regular file without any + // gpt field has no GptPartition. + assert_eq!(a.gpt.as_deref().map(|gpt| gpt.flags), Some(None)); + assert_eq!(m.objects[2].gpt, None); + // A symbolic link has no flags. + let link = &m.objects[3]; + assert_eq!( + (link.dos_flags, link.inode.flags), + (FlagStates::default(), FlagStates::default()) + ); + // Without the features nothing is known about them. + let m = read_whole(&manifest(&[r#"{"name":"a"}"#])).unwrap(); + let a = &m.objects[0]; + assert_eq!( + (a.dos_flags, a.inode.flags), + (FlagStates::default(), FlagStates::default()) + ); + assert_eq!((a.inode.user_xattrs.as_deref(), a.inode.read_only), (None, None)); + assert_eq!(m.root, RootObject::default()); + } + + #[test] + fn records() { + let files = [r#"{"name":"a","size":0}"#, r#"{"name":"b","type":"dir"}"#]; + let plain = manifest(&files); + assert_eq!(read(&plain).unwrap(), (vec!["a".to_string(), "b".to_string()], 0)); + // Records of nothing but whitespace are passed over, up to the + // trailer. A newline at the end of a record is not needed. + let mut spaced = vec![RECORD_SEPARATOR, RECORD_SEPARATOR, b' ', RECORD_SEPARATOR, b'\n', b'\t']; + spaced.extend(sequence(&[ROOT])); + spaced.extend([RECORD_SEPARATOR, b'\r', b'\n', RECORD_SEPARATOR, b'\t']); + spaced.extend(sequence(&files)); + spaced.extend([RECORD_SEPARATOR, b' ', RECORD_SEPARATOR]); + spaced.push(RECORD_SEPARATOR); + spaced.extend(TRAILER.as_bytes()); + assert_eq!(read(&spaced).unwrap(), read(&plain).unwrap()); + // Behind the trailer object there is the newline that ends its + // record, and nothing else: no empty record and no whitespace. + for behind in [&b" "[..], b"\r", b" \r\n", b"\t\n"] { + let mut bytes = sequence(&[ROOT, TRAILER]); + bytes.pop(); + bytes.extend(behind); + assert!(read(&bytes).is_ok(), "{:?}", behind); + } + for behind in [ + &[RECORD_SEPARATOR][..], + &[RECORD_SEPARATOR, b'\n'], + &[RECORD_SEPARATOR, RECORD_SEPARATOR], + b"\n", + b" ", + b"\r\n", + b"\t", + ] { + let mut bytes = sequence(&[ROOT, TRAILER]); + bytes.extend(behind); + assert_eq!(problem(&bytes), (Problem::DataAfterTrailer, Some(2)), "{:?}", behind); + } + let crlf: Vec = String::from_utf8(plain.clone()) + .unwrap() + .replace('\n', "\r\n") + .into_bytes(); + assert_eq!(read(&crlf).unwrap(), read(&plain).unwrap()); + // Whitespace is JSON's, as systemd has it: whitespace beyond ASCII + // is not nothing, and neither is a form feed or a vertical tab, on + // its own or next to whitespace. + for odd in ["\u{2028}", "\u{a0}", "\u{b}", "\u{c}", " \u{c}\n"] { + let mut bytes = sequence(&[ROOT]); + bytes.push(RECORD_SEPARATOR); + bytes.extend(odd.as_bytes()); + bytes.extend(sequence(&[TRAILER])); + assert_eq!(problem(&bytes), (Problem::NotJson, Some(1)), "{:?}", odd); + } + } + + #[test] + fn what_is_no_sequence_of_records() { + assert_eq!(problem(b""), (Problem::NoObjects, None)); + assert_eq!( + problem(&[RECORD_SEPARATOR, b'\n', RECORD_SEPARATOR]), + (Problem::NoObjects, None) + ); + // Every record starts with a record separator. + assert_eq!(problem(ROOT.as_bytes()), (Problem::NoRecordSeparator, Some(0))); + assert_eq!(problem(b"garbage"), (Problem::NoRecordSeparator, Some(0))); + let mut bom = b"\xef\xbb\xbf".to_vec(); + bom.extend(manifest(&[])); + let e = read(&bom).unwrap_err(); + assert_eq!( + e.to_string(), + "manifest record does not start with a record separator but with byte 0xef" + ); + // What comes after a record belongs to it up to the next separator. + let mut junk = sequence(&[ROOT]); + junk.extend(b"junk"); + junk.extend(sequence(&[TRAILER])); + assert_eq!(problem(&junk), (Problem::NotJson, Some(0))); + let mut junk = manifest(&[]); + junk.extend(b"junk"); + assert_eq!(problem(&junk), (Problem::NotJson, Some(1))); + // A NUL byte and bytes that are not UTF-8. Behind the trailer they + // are data behind the trailer like any other. + for (bad, expected) in [(&b"\0"[..], Problem::ContainsNulByte), (&b"\xff"[..], Problem::NotUtf8)] { + let mut bytes = sequence(&[ROOT]); + bytes.push(RECORD_SEPARATOR); + bytes.extend(br#"{"name":"a"#); + bytes.extend(bad); + bytes.extend(br#""}"#); + bytes.extend(sequence(&[TRAILER])); + assert_eq!(problem(&bytes), (expected, Some(1))); + let mut bytes = manifest(&[]); + bytes.push(RECORD_SEPARATOR); + bytes.extend(bad); + assert_eq!(problem(&bytes), (Problem::DataAfterTrailer, Some(2))); + } + let mut bytes = sequence(&[ROOT]); + bytes.extend([RECORD_SEPARATOR, b' ', 0, b' ']); + bytes.extend(sequence(&[TRAILER])); + assert_eq!(problem(&bytes), (Problem::ContainsNulByte, Some(1))); + } + + #[test] + fn the_largest_record() { + // A record is its bytes from its separator up to the next one, the + // newline at its end included. + let record = |len: usize| { + let frame = "\x1e{\"name\":\"x\",\"size\":0,\"pad\":\"\"}\n"; + let pad = "p".repeat(len - frame.len()); + format!(r#"{{"name":"x","size":0,"pad":"{}"}}"#, pad) + }; + let fits = record(MAX_RECORD_SIZE); + assert_eq!(sequence(&[&fits]).len(), MAX_RECORD_SIZE); + assert_eq!(read(&manifest(&[&fits])).unwrap().0, ["x"]); + let too_large = record(MAX_RECORD_SIZE + 1); + let bytes = manifest(&[&too_large]); + assert_eq!(problem(&bytes), (Problem::RecordTooLarge, Some(1))); + assert_eq!( + read(&bytes).unwrap_err().to_string(), + format!("manifest record exceeds {} bytes", MAX_RECORD_SIZE) + ); + // A record that is too large is that before it is anything else, + // and before its end was seen. + let mut bytes = sequence(&[ROOT]); + bytes.push(RECORD_SEPARATOR); + bytes.resize(bytes.len() + MAX_RECORD_SIZE, 0); + bytes.extend(sequence(&[TRAILER])); + assert_eq!(problem(&bytes), (Problem::RecordTooLarge, Some(1))); + let mut bytes = sequence(&[ROOT]); + bytes.push(RECORD_SEPARATOR); + bytes.resize(bytes.len() + MAX_RECORD_SIZE + 2 * READ_SIZE, b'x'); + assert_eq!(problem(&bytes), (Problem::RecordTooLarge, Some(1))); + } + + #[test] + fn the_order_of_the_objects() { + let file = r#"{"name":"x"}"#; + let other = r#"{"mediaType":"application/x-other","name":5,"contents":7}"#; + assert_eq!(problem(&sequence(&[ROOT])), (Problem::NoTrailer, None)); + assert_eq!(problem(&sequence(&[ROOT, file])), (Problem::NoTrailer, None)); + for behind in [file, "{", TRAILER, other, "5"] { + assert_eq!( + problem(&sequence(&[ROOT, TRAILER, behind])), + (Problem::DataAfterTrailer, Some(2)), + "{}", + behind + ); + } + // Signature objects come after the file objects. An object of an + // unknown media type can be anywhere and is passed over. + let read_all = |records: &[&str]| read(&sequence(records)); + assert_eq!(read_all(&[ROOT, SIGNATURE, TRAILER]).unwrap(), (vec![], 1)); + assert_eq!( + read_all(&[ROOT, other, file, other, SIGNATURE, other, SIGNATURE, other, TRAILER]).unwrap(), + (vec!["x".to_string()], 2) + ); + assert_eq!( + problem(&sequence(&[ROOT, SIGNATURE, file, TRAILER])), + (Problem::FileAfterSignature, Some(2)) + ); + // That it is a file object after a signature comes before what is + // wrong with it. That it is no object comes before both. + assert_eq!( + problem(&sequence(&[ROOT, SIGNATURE, r#"{"name":"/x","size":"y"}"#, TRAILER])), + (Problem::FileAfterSignature, Some(2)) + ); + assert_eq!( + problem(&sequence(&[ROOT, SIGNATURE, r#"{"name":"x","mediaType":5}"#, TRAILER])), + (Problem::InvalidMediaType, Some(2)) + ); + // The first object is the root file object, and says so with its + // media type. + for first in [file, TRAILER, SIGNATURE, other, r#"{"type":"dir"}"#] { + let e = read(&sequence(&[first, TRAILER])).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::InvalidMediaType), "{}", first); + assert_eq!(e.record_number(), Some(0)); + assert_eq!( + e.to_string(), + "the first object of the manifest is not of the manifest media type" + ); + } + } + + #[test] + fn the_reader_as_an_iterator() { + let bytes = sequence(&[ + ROOT, + " ", + r#"{"name":"a","size":0}"#, + "\n\n", + r#"{"mediaType":"application/x-other"}"#, + r#"{"name":"b","type":"dir"}"#, + SIGNATURE, + TRAILER, + ]); + let mut reader = Reader::open(&bytes[..]).unwrap(); + assert_eq!(reader.root(), &RootObject::default()); + assert_eq!(reader.record_number(), 0); + // Records of whitespace do not count, objects that are passed over + // do. + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == "a")); + assert_eq!(reader.record_number(), 1); + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == "b")); + assert_eq!(reader.record_number(), 3); + assert_eq!(reader.signed_len(), None); + assert!(matches!(reader.next(), Some(Ok(Object::Signature(signature))) if signature.mechanism == "pkcs7")); + assert_eq!(reader.record_number(), 4); + assert!(reader.next().is_none()); + assert!(reader.next().is_none()); + assert_eq!(reader.record_number(), 4); + // The input is read to its end once None was returned. + assert!(reader.get_ref().is_empty()); + // What is signed ends in front of the first signature object. + let signed = sequence(&[ + ROOT, + " ", + r#"{"name":"a","size":0}"#, + "\n\n", + r#"{"mediaType":"application/x-other"}"#, + r#"{"name":"b","type":"dir"}"#, + ]); + assert_eq!(reader.signed_len(), Some(signed.len() as u64)); + assert_eq!( + &bytes[signed.len()..][..1 + SIGNATURE.len()], + [&[RECORD_SEPARATOR][..], SIGNATURE.as_bytes()].concat() + ); + // After an error there is nothing more. + let bytes = manifest(&[r#"{"name":"a"}"#, r#"{"name":"b","size":"x"}"#, r#"{"name":"c"}"#]); + let mut reader = Reader::open(&bytes[..]).unwrap(); + assert!(matches!(reader.next(), Some(Ok(_)))); + let e = reader.next().unwrap().unwrap_err(); + assert_eq!((e.record_number(), e.name()), (Some(2), Some("b"))); + assert!(reader.next().is_none()); + assert!(reader.next().is_none()); + } + + /// Hands out the bytes of a manifest a few at a time, and says now + /// and then that a signal interrupted the read. + #[derive(Debug)] + struct Trickle<'a> { + bytes: &'a [u8], + step: usize, + calls: usize, + } + + impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.calls += 1; + if self.calls % 3 == 0 { + return Err(io::ErrorKind::Interrupted.into()); + } + let n = self.step.min(buf.len()).min(self.bytes.len()); + buf[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + Ok(n) + } + } + + #[test] + fn input_in_pieces() { + let long = format!(r#"{{"name":"long","size":0,"pad":"{}"}}"#, "p".repeat(3 * READ_SIZE)); + let bytes = manifest(&[r#"{"name":"a","size":0}"#, &long, r#"{"name":"é","type":"dir"}"#]); + let whole = read_whole(&bytes).unwrap(); + assert_eq!(whole.objects.len(), 3); + assert_eq!(whole.objects[2].name, Name::new("\u{e9}").unwrap()); + // The pieces end anywhere: inside a record, inside a character, + // right in front of a separator. + for step in PIECES { + let trickle = Trickle { + bytes: &bytes, + step, + calls: 0, + }; + assert_eq!(read_whole_from(trickle).unwrap(), whole, "{} at a time", step); + } + // A NUL byte spoils the record it is in and none before it, and + // where the signed part ends does not depend on the pieces. + let mut bytes = sequence(&[ROOT, r#"{"name":"a"}"#, &long, r#"{"name":"b"}"#, SIGNATURE, SIGNATURE]); + let signed = bytes.len() - 2 * (SIGNATURE.len() + 2); + bytes.push(RECORD_SEPARATOR); + bytes.extend(b"{\"mediaType\":\"application/x-other\0\"}\n"); + bytes.extend(sequence(&[TRAILER])); + for step in [1, 7, READ_SIZE, 5 * READ_SIZE] { + let mut reader = Reader::open(Trickle { + bytes: &bytes, + step, + calls: 0, + }) + .unwrap(); + for name in ["a", "long", "b"] { + assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if object.name == name)); + } + assert_eq!(reader.signed_len(), None); + for _ in 0..2 { + assert!(matches!(reader.next(), Some(Ok(Object::Signature(_))))); + assert_eq!(reader.signed_len(), Some(signed as u64), "{} at a time", step); + } + let e = reader.next().unwrap().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::ContainsNulByte)); + assert_eq!(e.record_number(), Some(6)); + assert!(reader.next().is_none()); + } + } + + /// Fails every read. + #[derive(Debug)] + struct FaultyInput; + + impl Read for FaultyInput { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::from_raw_os_error(libc::EIO)) + } + } + + #[test] + fn a_read_that_fails() { + let e = Reader::open(FaultyInput).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Io); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EIO)); + // Later on too. A record ends where the next one starts, so the + // first one is read whole when the second one begins. + let bytes = sequence(&[ROOT, r#"{"name":"a"}"#]); + let mut reader = Reader::open(bytes.chain(FaultyInput)).unwrap(); + let e = reader.next().unwrap().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Io); + assert!(reader.next().is_none()); + } + + /// How many bytes the tests feed a decoder at a time. The pieces end + /// anywhere: inside a record, inside a character, right in front of a + /// separator, and around the size a reader reads at a time. + const PIECES: [usize; 8] = [1, 2, 3, 7, 4096, READ_SIZE - 1, READ_SIZE, READ_SIZE + 1]; + + /// Reads the manifest `bytes` to its end with a decoder that is fed + /// `size` bytes at a time. Returns the manifest, the number of the + /// record of every object after the root file object, and how much the + /// signature objects sign. + fn decode(bytes: &[u8], size: usize) -> Result<(Whole, Vec, Option), Error> { + let mut pieces = bytes.chunks(size); + let mut piece: &[u8] = &[]; + let mut decoder = Decoder::new(); + let mut whole = None; + let mut numbers = Vec::new(); + loop { + match decoder.step()? { + Step::Input => { + if piece.is_empty() { + let Some(next) = pieces.next() else { + decoder.end(); + continue; + }; + piece = next; + } + // A decoder that asks for input takes some of it. + let taken = decoder.feed(piece); + assert_ne!(taken, 0, "{} at a time", size); + piece = &piece[taken..]; + } + Step::Root(root) => { + assert!(whole.is_none(), "a second root file object"); + whole = Some(Whole { + root: *root, + objects: Vec::new(), + signatures: Vec::new(), + }); + } + Step::Object(object) => { + let whole = whole.as_mut().expect("an object before the root file object"); + match object { + Object::File(object) => whole.objects.push(*object), + Object::Signature(signature) => whole.signatures.push(signature), + } + numbers.push(decoder.record_number()); + } + Step::End => { + let whole = whole.expect("the end before the root file object"); + return Ok((whole, numbers, decoder.signed_len())); + } + } + } + } + + /// What the tests compare of an error. + fn described(e: &Error) -> (ErrorKind, Option, Option<&str>, Option, String) { + (e.kind(), e.record_number(), e.name(), e.field(), e.to_string()) + } + + #[test] + fn decoding_in_pieces() { + let long = format!(r#"{{"name":"long","size":0,"pad":"{}"}}"#, "p".repeat(3 * READ_SIZE)); + let signed = sequence(&[ + ROOT, + " ", + r#"{"name":"a","size":0}"#, + &long, + "\n\n", + r#"{"mediaType":"application/x-other"}"#, + r#"{"name":"é","type":"dir"}"#, + ]); + let mut bytes = signed.clone(); + bytes.extend(sequence(&[SIGNATURE, SIGNATURE, TRAILER])); + let (whole, numbers, signed_len) = decode(&bytes, bytes.len()).unwrap(); + assert_eq!(whole, read_whole(&bytes).unwrap()); + assert_eq!((whole.objects.len(), whole.signatures.len()), (3, 2)); + // Records of whitespace do not count, objects that are passed over + // do. + assert_eq!(numbers, [1, 2, 4, 5, 6]); + assert_eq!(signed_len, Some(signed.len() as u64)); + let decoded = (whole, numbers, signed_len); + for size in PIECES { + assert_eq!(decode(&bytes, size).unwrap(), decoded, "{} at a time", size); + } + // Behind the trailer object there may be whitespace up to the + // newline that ends its record. + for behind in [&b" "[..], b"\r", b" \r\n", b"\t\n"] { + let mut bytes = sequence(&[ROOT, r#"{"name":"a"}"#, TRAILER]); + bytes.pop(); + bytes.extend(behind); + let whole = read_whole(&bytes).unwrap(); + for size in PIECES { + assert_eq!( + decode(&bytes, size).unwrap().0, + whole, + "{:?} {} at a time", + behind, + size + ); + } + } + } + + /// A record as large as a record can be, with the separator of the + /// next one right behind it, is taken in any pieces, and the decoder + /// holds no more than the record. + #[test] + fn the_largest_record_in_pieces() { + // The separator in front of the record and the newline at its end + // count. + let frame = "\x1e{\"name\":\"x\",\"size\":0,\"pad\":\"\"}\n"; + let pad = "p".repeat(MAX_RECORD_SIZE - frame.len()); + let largest = format!(r#"{{"name":"x","size":0,"pad":"{}"}}"#, pad); + assert_eq!(sequence(&[&largest]).len(), MAX_RECORD_SIZE); + let bytes = manifest(&[&largest]); + let whole = read_whole(&bytes).unwrap(); + for size in PIECES.into_iter().chain([bytes.len()]) { + assert_eq!(decode(&bytes, size).unwrap().0, whole, "{} at a time", size); + let mut decoder = Decoder::new(); + let mut taken = 0; + loop { + match decoder.step().unwrap() { + Step::Input if taken == bytes.len() => decoder.end(), + Step::Input => taken += decoder.feed(&bytes[taken..][..size.min(bytes.len() - taken)]), + Step::Object(_) => assert_eq!(decoder.splitter.record.len(), MAX_RECORD_TEXT), + Step::Root(_) => {} + Step::End => break, + } + assert!( + decoder.splitter.record.capacity() <= MAX_RECORD_TEXT, + "{} at a time", + size + ); + } + } + } + + #[test] + fn failing_in_pieces() { + let too_large = format!(r#"{{"name":"x","pad":"{}"}}"#, "p".repeat(MAX_RECORD_SIZE)); + let root_too_large = format!( + r#"{{"mediaType":"application/vnd.uapi.16.manifest","pad":"{}"}}"#, + "p".repeat(MAX_RECORD_SIZE) + ); + // More than the read of a record takes before the first separator. + let mut unseparated = vec![b'x'; READ_LIMIT + READ_SIZE]; + unseparated.extend(manifest(&[])); + let mut bom = b"\xef\xbb\xbf".to_vec(); + bom.extend(manifest(&[])); + let mut behind = manifest(&[]); + behind.push(RECORD_SEPARATOR); + let mut nul = sequence(&[ROOT]); + nul.extend([RECORD_SEPARATOR, b' ', NUL, b' ']); + nul.extend(sequence(&[TRAILER])); + let mut not_utf8 = sequence(&[ROOT]); + not_utf8.extend([RECORD_SEPARATOR, b'"', 0xff, b'"']); + not_utf8.extend(sequence(&[TRAILER])); + let mut junk = sequence(&[ROOT]); + junk.extend(b"junk"); + junk.extend(sequence(&[TRAILER])); + let cases = [ + Vec::new(), + vec![RECORD_SEPARATOR, b'\n', RECORD_SEPARATOR], + ROOT.as_bytes().to_vec(), + unseparated, + bom, + sequence(&[ROOT]), + sequence(&[ROOT, r#"{"name":"x"}"#]), + manifest(&[&too_large]), + sequence(&[&root_too_large, TRAILER]), + behind, + nul, + not_utf8, + junk, + manifest(&[r#"{"name":"b"}"#, r#"{"name":"a"}"#, r#"{"name":"a/x"}"#]), + manifest(&[r#"{"name":"a"}"#, r#"{"name":"b","size":"x"}"#]), + manifest(&[r#"{"name":"a","mTimeNSec":5}"#]), + sequence(&[ROOT, SIGNATURE, r#"{"name":"x"}"#, TRAILER]), + ]; + for bytes in &cases { + let expected = read_whole(bytes).unwrap_err(); + let e = decode(bytes, bytes.len().max(1)).unwrap_err(); + assert_eq!(described(&e), described(&expected)); + for size in PIECES { + let e = decode(bytes, size).unwrap_err(); + assert_eq!(described(&e), described(&expected), "{} at a time", size); + } + } + } + + #[test] + fn a_record_over_the_limit() { + // The record after the root file object has more bytes than a + // record can have: behind them come more bytes, a separator, or + // the end of the input. + let mut start = sequence(&[ROOT]); + start.push(RECORD_SEPARATOR); + let mut endless = start.clone(); + endless.resize(start.len() + MAX_RECORD_SIZE + 2 * READ_SIZE, b'x'); + let mut separated = start.clone(); + separated.resize(start.len() + READ_LIMIT, b'x'); + separated.extend(sequence(&[TRAILER])); + let mut ended = start.clone(); + ended.resize(start.len() + READ_LIMIT, b'x'); + for bytes in [&endless, &separated, &ended] { + for size in PIECES.into_iter().chain([bytes.len()]) { + let mut decoder = Decoder::new(); + let mut taken = 0; + let e = loop { + match decoder.step() { + Ok(Step::Input) if taken == bytes.len() => decoder.end(), + Ok(Step::Input) => taken += decoder.feed(&bytes[taken..][..size.min(bytes.len() - taken)]), + Ok(Step::Root(_)) => {} + Ok(step) => panic!("{} at a time: {:?}", size, step), + Err(e) => break e, + } + }; + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::RecordTooLarge), Some(1)), + "{} at a time", + size + ); + // The decoder took the record up to the limit and nothing + // behind it, and takes nothing once it refused it. It holds + // no more than the largest record, and does not print it. + assert_eq!(taken, start.len() + READ_LIMIT, "{} at a time", size); + assert_eq!(decoder.feed(&bytes[taken..]), 0); + assert_eq!(decoder.step().unwrap(), Step::End); + assert!( + decoder.splitter.record.capacity() <= MAX_RECORD_TEXT, + "{} at a time", + size + ); + let debug = format!("{:?}", decoder); + assert!(debug.len() < READ_SIZE, "{} at a time: {}", size, debug.len()); + } + } + } + + /// Hands out the bytes of a manifest `step` at a time. With `blocking` + /// it says before every piece that it has nothing yet, as a pipe that + /// does not block does while its writer is slow. + #[derive(Debug)] + struct Hiccups<'a> { + bytes: &'a [u8], + step: usize, + blocking: bool, + /// Whether it said so before the next piece. + said: bool, + } + + impl Read for Hiccups<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.blocking && !self.said { + self.said = true; + return Err(io::ErrorKind::WouldBlock.into()); + } + self.said = false; + let n = self.step.min(buf.len()).min(self.bytes.len()); + buf[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + Ok(n) + } + } + + #[test] + fn reading_on_after_would_block() { + let long = format!(r#"{{"name":"long","size":0,"pad":"{}"}}"#, "p".repeat(3 * READ_SIZE)); + let bytes = sequence(&[ + ROOT, + r#"{"name":"a","size":0}"#, + &long, + r#"{"name":"é","type":"dir"}"#, + SIGNATURE, + TRAILER, + ]); + let whole = read_whole(&bytes).unwrap(); + // The number of the record of every object, and how much is signed + // after it, as a reader says that never sees a WouldBlock. + let mut unblocked = Vec::new(); + let mut reader = Reader::open(&bytes[..]).unwrap(); + while let Some(object) = reader.next() { + object.unwrap(); + unblocked.push((reader.record_number(), reader.signed_len())); + } + let would_block = |e: &Error| e.io_error().map(io::Error::kind) == Some(io::ErrorKind::WouldBlock); + for step in [1, 7, 4096, READ_SIZE + 1] { + let hiccups = Hiccups { + bytes: &bytes, + step, + blocking: false, + said: false, + }; + let mut reader = Reader::open(hiccups).unwrap(); + // From here on the input has nothing every other time it is + // read, in the middle of records as well. + reader.get_mut().blocking = true; + let mut read = Whole { + root: reader.root().clone(), + objects: Vec::new(), + signatures: Vec::new(), + }; + let mut blocked = 0; + let mut numbers = Vec::new(); + let mut last = (reader.record_number(), reader.signed_len()); + while let Some(object) = reader.next() { + let now = (reader.record_number(), reader.signed_len()); + match object { + Ok(Object::File(object)) => read.objects.push(*object), + Ok(Object::Signature(signature)) => read.signatures.push(signature), + // The error is about the record being read, and the + // reader says what it said before it. + Err(e) if would_block(&e) => { + assert_eq!(e.record_number(), Some(last.0 + 1), "{} at a time", step); + assert_eq!(now, last, "{} at a time", step); + blocked += 1; + continue; + } + Err(e) => panic!("{} at a time: {}", step, e), + } + numbers.push(now); + last = now; + } + assert_eq!(read, whole, "{} at a time", step); + assert_eq!(numbers, unblocked, "{} at a time", step); + assert!(blocked > 0, "{} at a time", step); + assert!(reader.next().is_none()); + } + // Reader::open() has no reader to go on with. + let hiccups = Hiccups { + bytes: &bytes, + step: 7, + blocking: true, + said: false, + }; + assert!(would_block(&Reader::open(hiccups).unwrap_err())); + } +} diff --git a/src/uapi16/refused.jsonl b/src/uapi16/refused.jsonl new file mode 100644 index 0000000..7ea3329 --- /dev/null +++ b/src/uapi16/refused.jsonl @@ -0,0 +1,358 @@ +[[],"empty",null,null,null,"manifest contains no objects"] +[["@root"],"noTrailer",null,null,null,"manifest lacks the trailer object, it is incomplete"] +[["@root","{\"name\":\"x\"}"],"noTrailer",null,null,null,"manifest lacks the trailer object, it is incomplete"] +[["@root","@trailer","{\"name\":\"x\"}"],"dataAfterTrailer",2,null,null,"manifest contains data after the trailer object"] +[["@root","@trailer","{"],"dataAfterTrailer",2,null,null,"manifest contains data after the trailer object"] +[["@root","@trailer","@trailer"],"dataAfterTrailer",2,null,null,"manifest contains data after the trailer object"] +[["@root","{\"name\":\"x\"","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: expected ',' or '}' at byte 12"] +[["@root","{\"name\":\"x\",}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: expected a string key at byte 12"] +[["@root","{\"name\":\"x\",\"name\":\"y\"}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 18"] +[["@root","{\"name\":\"x\",\"n\\u0061me\":\"y\"}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 23"] +[["@root","{\"name\":\"x\",\"xExt\":{\"a\":1,\"a\":2}}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 29"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"user-xattr\"]}","{\"name\":\"x\",\"extendedAttributes\":{\"user\":{\"a\":{\"text\":\"1\"},\"a\":{\"text\":\"2\"}}}}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 62"] +[["@root","{\"name\":\"x\",\"extendedAttributes\":{\"other\":{\"a\":1,\"a\":2}}}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 52"] +[["@root","[1,2]","@trailer"],"notObject",1,null,null,"manifest record 1 is not a JSON object"] +[["@root","5","@trailer"],"notObject",1,null,null,"manifest record 1 is not a JSON object"] +[["@root","\"x\"","@trailer"],"notObject",1,null,null,"manifest record 1 is not a JSON object"] +[["@root","null","@trailer"],"notObject",1,null,null,"manifest record 1 is not a JSON object"] +[["@root","{\"name\":\"x\"} x","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: trailing characters at byte 13"] +[["@root","{\"name\":\"x\"}{\"name\":\"y\"}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: trailing characters at byte 12"] +[["@root","{\"name\":5,\"size\":}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: unexpected character at byte 17"] +[["@root","{\"size\":\"x\",\"name\":\"a\",\"name\":\"b\"}","@trailer"],"duplicateKey",1,null,null,"manifest record 1 has a key twice in an object: duplicate key at byte 29"] +[["@root","{\"name\":\"a\\u0000b\"}","@trailer"],"invalidString",1,null,null,"manifest record 1 has an invalid string: NUL in string at byte 18"] +[["@root","{\"name\":\"a\u0000b\"}","@trailer"],"nulByte",1,null,null,"manifest record contains a NUL byte"] +[["{\"type\":\"dir\"}","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["@trailer","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["@signature","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["{\"mediaType\":\"application/x-other\"}","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["{\"mediaType\":5}","@trailer"],"mediaType",0,null,null,"manifest object 0 has a mediaType that is not a string"] +[["{\"mediaType\":null}","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"name\":\"x\"}","@trailer"],"firstHasName",0,"x","name","the root file object has a name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"name\":\"/x\"}","@trailer"],"invalidName",0,"/x","name","manifest object 0 (root): name has an empty component: '/x'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"type\":\"reg\"}","@trailer"],"firstNotDirectory",0,null,"type","the root file object is not a directory"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"inodeToken\":3}","@trailer"],"fieldNotPermitted",0,null,"inodeToken","manifest object 0 (root): 'inodeToken' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"],\"gptLabel\":\"x\"}","@trailer"],"fieldNotPermitted",0,null,"gptLabel","manifest object 0 (root): 'gptLabel' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"major\":1}","@trailer"],"fieldNotPermitted",0,null,"major","manifest object 0 (root): 'major' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"size\":5}","@trailer"],"fieldNotPermitted",0,null,"size","manifest object 0 (root): 'size' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"contents\":[{\"file\":\"sub\"}]}","@trailer"],"fieldNotPermitted",0,null,"contents","manifest object 0 (root): 'contents' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"sha256\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}","@trailer"],"fieldNotPermitted",0,null,"sha256","manifest object 0 (root): 'sha256' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"flag-hidden\"],\"flagHidden\":false}","@trailer"],"fieldNotPermitted",0,null,"flagHidden","manifest object 0 (root): 'flagHidden' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\"],\"gptFlags\":0}","@trailer"],"fieldNotPermitted",0,null,"gptFlags","manifest object 0 (root): 'gptFlags' is not permitted on the root file object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"mode\":\"x\"}","@trailer"],"fieldType",0,null,"mode","manifest field 'mode' is not an unsigned integer"] +[["{\"mediaType\":\"application/x-other\",\"size\":\"x\"}","@trailer"],"mediaType",0,null,null,"the first object of the manifest is not of the manifest media type"] +[["@root","{\"name\":\"x\",\"mediaType\":5}","@trailer"],"mediaType",1,null,null,"manifest object 1 has a mediaType that is not a string"] +[["@root","{\"size\":\"x\",\"name\":\"y\",\"mediaType\":[]}","@trailer"],"mediaType",1,null,null,"manifest object 1 has a mediaType that is not a string"] +[["@root","{\"mediaType\":\"application/x-unknown\",\"name\":}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: unexpected character at byte 44"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"data\":\"AAAA\"}","@trailer"],"signature",2,null,"mechanism","manifest signature object 2 has no 'mechanism' string"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":null}","@trailer"],"signature",2,null,"mechanism","manifest signature object 2 has no 'mechanism' string"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":5,\"key\":5}","@trailer"],"signature",2,null,"mechanism","manifest signature object 2 has no 'mechanism' string"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"key\":\"xyz\"}","@trailer"],"signature",2,null,"key","manifest signature object 2: 'key' is not hex"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"key\":\"abc\"}","@trailer"],"signature",2,null,"key","manifest signature object 2: 'key' is not hex"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"key\":5,\"data\":5}","@trailer"],"fieldType",2,null,"key","manifest field 'key' is not a string"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"data\":\"!!\"}","@trailer"],"signature",2,null,"data","manifest signature object 2: 'data' is not Base64"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"data\":\"AA=\"}","@trailer"],"signature",2,null,"data","manifest signature object 2: 'data' is not Base64"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"mediaType\":\"application/vnd.uapi.16.signature\",\"mechanism\":\"pkcs7\",\"data\":5}","@trailer"],"fieldType",2,null,"data","manifest field 'data' is not a string"] +[["@root","{\"name\":\"x\",\"size\":0}","{\"data\":\"!!\",\"key\":\"xyz\",\"mechanism\":\"pkcs7\",\"mediaType\":\"application/vnd.uapi.16.signature\"}","@trailer"],"signature",2,null,"key","manifest signature object 2: 'key' is not hex"] +[["@root","@signature","{\"name\":\"x\"}","@trailer"],"fileAfterSignature",2,null,null,"manifest contains a file object after a signature object"] +[["@root","@signature","{\"name\":\"/x\",\"size\":\"y\"}","@trailer"],"fileAfterSignature",2,null,null,"manifest contains a file object after a signature object"] +[["@root","@signature","{\"name\":\"x\",\"mediaType\":5}","@trailer"],"mediaType",2,null,null,"manifest object 2 has a mediaType that is not a string"] +[["@root","{\"name\":\"x\"}","{\"name\":\"x\"}","@trailer"],"duplicateName",2,"x",null,"manifest object 2 (x): the name is listed twice"] +[["@root","{\"name\":\"a/x\"}","@trailer"],"misplaced",1,"a/x",null,"manifest object 1 (a/x): does not come right after the object of its directory 'a'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}","{\"name\":\"b\"}","{\"name\":\"a\"}","@trailer"],"outOfOrder",2,"a",null,"manifest object 2 (a): comes after 'b', which it sorts before in the code point ordering"] +[["@root","{\"name\":\"l\",\"type\":\"lnk\"}","@trailer"],"noTarget",1,"l",null,"manifest object 1 (l): the manifest records the targets of symbolic links, but this one has none"] +[["@root","{\"name\":\"x\",\"mTimeNSec\":1}","@trailer"],"unlistedFeature",1,"x","mTimeNSec","manifest object 1 (x): 'mTimeNSec' is a field of the feature 'mtime', which the manifest does not record"] +[["@root","{\"name\":\"x\",\"userName\":\"u\"}","@trailer"],"unlistedFeature",1,"x","userName","manifest object 1 (x): 'userName' is a field of the feature 'user-name', which the manifest does not record"] +[["@root","{\"name\":\"x\",\"extendedAttributes\":{\"user\":{}}}","@trailer"],"unlistedFeature",1,"x","extendedAttributes","manifest object 1 (x): 'extendedAttributes' is a field of the feature 'user-xattr', which the manifest does not record"] +[["@root","{\"name\":\"x\",\"gptFlagNoAuto\":true}","@trailer"],"unlistedFeature",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is a field of the feature 'gpt-flag-no-auto', which the manifest does not record"] +[["@root","{\"name\":\"/abs\",\"size\":0}","@trailer"],"invalidName",1,"/abs","name","manifest object 1: name has an empty component: '/abs'"] +[["@root","{\"name\":\"a/../b\",\"size\":0}","@trailer"],"invalidName",1,"a/../b","name","manifest object 1: name contains a '.' or '..' component: 'a/../b'"] +[["@root","{\"name\":\"a/./b\",\"size\":0}","@trailer"],"invalidName",1,"a/./b","name","manifest object 1: name contains a '.' or '..' component: 'a/./b'"] +[["@root","{\"name\":\"a//b\",\"size\":0}","@trailer"],"invalidName",1,"a//b","name","manifest object 1: name has an empty component: 'a//b'"] +[["@root","{\"name\":\"a/\",\"size\":0}","@trailer"],"invalidName",1,"a/","name","manifest object 1: name has an empty component: 'a/'"] +[["@root","{\"name\":\"\",\"size\":0}","@trailer"],"invalidName",1,"","name","manifest object 1: name is empty: ''"] +[["@root","{\"name\":\".\",\"size\":0}","@trailer"],"invalidName",1,".","name","manifest object 1: name contains a '.' or '..' component: '.'"] +[["@root","{\"name\":\"..\",\"size\":0}","@trailer"],"invalidName",1,"..","name","manifest object 1: name contains a '.' or '..' component: '..'"] +[["@root","{\"name\":\"Uapi16Manifest\",\"size\":0}","@trailer"],"invalidName",1,"Uapi16Manifest","name","manifest object 1: name is reserved for the manifest: 'Uapi16Manifest'"] +[["@root","{\"name\":\"Uapi16Manifest.sig\",\"size\":0}","@trailer"],"invalidName",1,"Uapi16Manifest.sig","name","manifest object 1: name is reserved for the manifest: 'Uapi16Manifest.sig'"] +[["@root","{\"name\":\"Uapi16Manifest.d/x\",\"size\":0}","@trailer"],"invalidName",1,"Uapi16Manifest.d/x","name","manifest object 1: name is reserved for the manifest: 'Uapi16Manifest.d/x'"] +[["@root","{\"name\":\"a\\nb\",\"size\":0}","@trailer"],"invalidName",1,"a\nb","name","manifest object 1: name contains a control character: 'a\\nb'"] +[["@root","{\"name\":\"a\\u007fb\",\"size\":0}","@trailer"],"invalidName",1,"a\u007fb","name","manifest object 1: name contains a control character: 'a\\u{7f}b'"] +[["@root","{\"name\":5,\"size\":0}","@trailer"],"fieldType",1,null,"name","manifest field 'name' is not a string"] +[["@root","{\"name\":null,\"size\":0}","@trailer"],"noName",1,null,"name","manifest object 1 has no name"] +[["@root","{\"size\":0}","@trailer"],"noName",1,null,"name","manifest object 1 has no name"] +[["@root","{\"size\":\"x\"}","@trailer"],"fieldType",1,null,"size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"/x\",\"size\":\"y\"}","@trailer"],"invalidName",1,"/x","name","manifest object 1: name has an empty component: '/x'"] +[["@root","{\"size\":\"y\",\"name\":\"/x\"}","@trailer"],"fieldType",1,"/x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"size\":\"y\",\"name\":\"x\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"size\":\"y\",\"name\":7}","@trailer"],"fieldType",1,null,"size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"reg\",\"major\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a reg"] +[["@root","{\"name\":\"x\",\"type\":\"reg\",\"minor\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a reg"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"reg\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"dir\",\"major\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a dir"] +[["@root","{\"name\":\"x\",\"type\":\"dir\",\"minor\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a dir"] +[["@root","{\"name\":\"x\",\"type\":\"dir\",\"inodeToken\":7}","@trailer"],"fieldNotPermitted",1,"x","inodeToken","manifest object 1 (x): 'inodeToken' is not permitted on a directory"] +[["@root","{\"name\":\"x\",\"type\":\"dir\",\"size\":1,\"inodeToken\":1}","@trailer"],"fieldNotPermitted",1,"x","inodeToken","manifest object 1 (x): 'inodeToken' is not permitted on a directory"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"type\":\"dir\",\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a dir"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"name\":\"x\",\"type\":\"dir\",\"gptFlagNoAuto\":false}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a dir"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"dir\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"lnk\",\"major\":1,\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a lnk"] +[["@root","{\"name\":\"x\",\"type\":\"lnk\",\"minor\":1,\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a lnk"] +[["@root","{\"name\":\"x\",\"type\":\"lnk\",\"mode\":420,\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","mode","manifest object 1 (x): 'mode' is not permitted on a symlink"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\",\"symlink\"]}","{\"name\":\"x\",\"type\":\"lnk\",\"gptLabel\":\"l\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a lnk"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\",\"symlink\"]}","{\"name\":\"x\",\"type\":\"lnk\",\"gptFlagNoAuto\":false,\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a lnk"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\",\"symlink\"]}","{\"name\":\"x\",\"type\":\"lnk\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"size\":1}","@trailer"],"fieldNotPermitted",1,"x","size","manifest object 1 (x): 'size' is not permitted on a fifo"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"major\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a fifo"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"minor\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a fifo"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a fifo"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a fifo"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"type\":\"fifo\",\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a fifo"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"name\":\"x\",\"type\":\"fifo\",\"gptFlagNoAuto\":false}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a fifo"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"fifo\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"size\":1}","@trailer"],"fieldNotPermitted",1,"x","size","manifest object 1 (x): 'size' is not permitted on a chr"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a chr"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a chr"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"type\":\"chr\",\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a chr"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"name\":\"x\",\"type\":\"chr\",\"gptFlagNoAuto\":false}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a chr"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"chr\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"blk\",\"size\":1}","@trailer"],"fieldNotPermitted",1,"x","size","manifest object 1 (x): 'size' is not permitted on a blk"] +[["@root","{\"name\":\"x\",\"type\":\"blk\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a blk"] +[["@root","{\"name\":\"x\",\"type\":\"blk\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a blk"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"type\":\"blk\",\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a blk"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"name\":\"x\",\"type\":\"blk\",\"gptFlagNoAuto\":false}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a blk"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"blk\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"sock\",\"size\":1}","@trailer"],"fieldNotPermitted",1,"x","size","manifest object 1 (x): 'size' is not permitted on a sock"] +[["@root","{\"name\":\"x\",\"type\":\"sock\",\"major\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a sock"] +[["@root","{\"name\":\"x\",\"type\":\"sock\",\"minor\":1}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a sock"] +[["@root","{\"name\":\"x\",\"type\":\"sock\",\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a sock"] +[["@root","{\"name\":\"x\",\"type\":\"sock\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}","@trailer"],"fieldNotPermitted",1,"x","contents","manifest object 1 (x): 'contents' and 'sha256' are not permitted on a sock"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"type\":\"sock\",\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","gptLabel","manifest object 1 (x): 'gptLabel' is not permitted on a sock"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"name\":\"x\",\"type\":\"sock\",\"gptFlagNoAuto\":false}","@trailer"],"fieldNotPermitted",1,"x","gptFlagNoAuto","manifest object 1 (x): 'gptFlagNoAuto' is not permitted on a sock"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"type\":\"sock\",\"gptDiskUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","gptDiskUuid","manifest object 1 (x): 'gptDiskUuid' is only permitted on the root file object"] +[["@root","{\"name\":\"x\",\"type\":\"weird\"}","@trailer"],"unknownType",1,"x","type","manifest object 1: unknown inode type 'weird'"] +[["@root","{\"name\":\"x\",\"type\":5}","@trailer"],"fieldType",1,"x","type","manifest field 'type' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"device\",\"gpt-disk-uuid\",\"gpt-label\",\"sha256\",\"size\"]}","{\"name\":\"x\",\"type\":\"fifo\",\"size\":1,\"major\":1,\"contents\":[],\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"gptLabel\":\"l\",\"gptDiskUuid\":\"4f68bce3e8cd4db196e7fbcaf984b709\"}","@trailer"],"fieldNotPermitted",1,"x","size","manifest object 1 (x): 'size' is not permitted on a fifo"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"device\",\"gpt-label\",\"hardlink\"]}","{\"name\":\"x\",\"type\":\"dir\",\"major\":1,\"inodeToken\":1,\"gptLabel\":\"l\"}","@trailer"],"fieldNotPermitted",1,"x","major","manifest object 1 (x): 'major' and 'minor' are not permitted on a dir"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\",\"mode\",\"symlink\"]}","{\"name\":\"x\",\"type\":\"lnk\",\"gptLabel\":\"l\",\"mode\":1,\"contents\":[{\"literal\":\"eA==\"}]}","@trailer"],"fieldNotPermitted",1,"x","mode","manifest object 1 (x): 'mode' is not permitted on a symlink"] +[["@root","{\"name\":\"x\",\"size\":18446744073709551616}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"18446744073709551616\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":-1}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":-0}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":1.0}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":1e2}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\" 5\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"5 \"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"+5\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"0x5\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"5\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"0\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"18446744073709551615\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":true}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":[]}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":{}}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":\"\u096b\"}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":5.5}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":123456789012345678901234567890123456789012345678901234567890}","@trailer"],"fieldType",1,"x","size","manifest field 'size' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"mtime\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"mTimeNSec\":true}","@trailer"],"fieldType",1,"x","mTimeNSec","manifest field 'mTimeNSec' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"inodeToken\":true}","@trailer"],"fieldType",1,"x","inodeToken","manifest field 'inodeToken' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"validSinceUSec\":true}","@trailer"],"fieldType",1,"x","validSinceUSec","manifest field 'validSinceUSec' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"validUntilUSec\":true}","@trailer"],"fieldType",1,"x","validUntilUSec","manifest field 'validUntilUSec' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"mtime\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"mTimeNSec\":\"1700000000000000000\"}","@trailer"],"fieldType",1,"x","mTimeNSec","manifest field 'mTimeNSec' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"inodeToken\":\"7\"}","@trailer"],"fieldType",1,"x","inodeToken","manifest field 'inodeToken' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"validSinceUSec\":\"1\"}","@trailer"],"fieldType",1,"x","validSinceUSec","manifest field 'validSinceUSec' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"validUntilUSec\":\"18446744073709551615\"}","@trailer"],"fieldType",1,"x","validUntilUSec","manifest field 'validUntilUSec' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"gptFlags\":\"0\"}","@trailer"],"fieldType",1,"x","gptFlags","manifest field 'gptFlags' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"major\":\"x\"}","@trailer"],"fieldType",1,"x","major","manifest field 'major' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"minor\":\"x\"}","@trailer"],"fieldType",1,"x","minor","manifest field 'minor' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"chr\",\"major\":\"1\"}","@trailer"],"fieldType",1,"x","major","manifest field 'major' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"blk\",\"minor\":\"1\"}","@trailer"],"fieldType",1,"x","minor","manifest field 'minor' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":4096}","@trailer"],"fieldRange",1,"x","mode","manifest field 'mode' is out of range: 4096"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"10000\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"8\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"9\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"0o644\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"-1\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":-1}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":5000}","@trailer"],"fieldRange",1,"x","mode","manifest field 'mode' is out of range: 5000"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"77777777777777777777777777\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":true}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":1.5}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"644 \"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":18446744073709551615}","@trailer"],"fieldRange",1,"x","mode","manifest field 'mode' is out of range: 18446744073709551615"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":4294967296}","@trailer"],"fieldRange",1,"x","mode","manifest field 'mode' is out of range: 4294967296"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":4294967295}","@trailer"],"fieldRange",1,"x","mode","manifest field 'mode' is out of range: 4294967295"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"37777777777\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"mode\":\"40000000000\"}","@trailer"],"fieldType",1,"x","mode","manifest field 'mode' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"mode\",\"read-only\"]}","{\"name\":\"x\",\"mode\":420,\"readOnly\":true}","@trailer"],"contradiction",1,"x","readOnly","manifest object 1 (x): 'readOnly' and 'mode' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"mode\",\"read-only\"]}","{\"name\":\"x\",\"mode\":292,\"readOnly\":false}","@trailer"],"contradiction",1,"x","readOnly","manifest object 1 (x): 'readOnly' and 'mode' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"mode\",\"read-only\"]}","{\"name\":\"x\",\"mode\":2,\"readOnly\":true}","@trailer"],"contradiction",1,"x","readOnly","manifest object 1 (x): 'readOnly' and 'mode' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"read-only\"]}","{\"name\":\"x\",\"readOnly\":\"yes\"}","@trailer"],"fieldType",1,"x","readOnly","manifest field 'readOnly' is not a boolean"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":4294967295}","@trailer"],"fieldRange",1,"x","uid","manifest object 1: uid 4294967295 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":\"4294967295\"}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":4294967296}","@trailer"],"fieldRange",1,"x","uid","manifest object 1: uid 4294967296 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":18446744073709551615}","@trailer"],"fieldRange",1,"x","uid","manifest object 1: uid 18446744073709551615 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":-1}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":true}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":65535}","@trailer"],"fieldRange",1,"x","uid","manifest object 1: uid 65535 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"uid\":\"0\"}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"uid\":65535}","@trailer"],"fieldRange",0,null,"uid","manifest object 0 (root): uid 65535 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":4294967295}","@trailer"],"fieldRange",1,"x","gid","manifest object 1: gid 4294967295 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":\"4294967295\"}","@trailer"],"fieldType",1,"x","gid","manifest field 'gid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":4294967296}","@trailer"],"fieldRange",1,"x","gid","manifest object 1: gid 4294967296 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":18446744073709551615}","@trailer"],"fieldRange",1,"x","gid","manifest object 1: gid 18446744073709551615 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":-1}","@trailer"],"fieldType",1,"x","gid","manifest field 'gid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":true}","@trailer"],"fieldType",1,"x","gid","manifest field 'gid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":65535}","@trailer"],"fieldRange",1,"x","gid","manifest object 1: gid 65535 is out of range"] +[["@root","{\"name\":\"x\",\"size\":0,\"gid\":\"65534\"}","@trailer"],"fieldType",1,"x","gid","manifest field 'gid' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"123\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '123' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"-123\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '-123' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"-\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '-' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"a:b\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName 'a:b' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"a/b\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName 'a/b' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\" g\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName ' g' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"g \"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName 'g ' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\".\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '.' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"..\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName '..' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"a\\nb\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName 'a\\nb' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":5}","@trailer"],"fieldType",1,"x","userName","manifest field 'userName' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-name\"]}","{\"name\":\"x\",\"size\":0,\"userName\":\"a\\u007f\"}","@trailer"],"fieldType",1,"x","userName","manifest object 1: userName 'a\\u{7f}' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"123\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '123' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"-123\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '-123' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"-\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '-' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"a:b\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName 'a:b' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"a/b\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName 'a/b' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\" g\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName ' g' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"g \"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName 'g ' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\".\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '.' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"..\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName '..' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"a\\nb\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName 'a\\nb' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":5}","@trailer"],"fieldType",1,"x","groupName","manifest field 'groupName' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"group-name\",\"size\"]}","{\"name\":\"x\",\"size\":0,\"groupName\":\"a\\u007f\"}","@trailer"],"fieldType",1,"x","groupName","manifest object 1: groupName 'a\\u{7f}' is not a valid name"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}","@trailer"],"fieldType",1,"x","gptLabel","manifest object 1: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' is not a valid GPT partition label"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":\"\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00\\ud83d\\ude00x\"}","@trailer"],"fieldType",1,"x","gptLabel","manifest object 1: '\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00x' is not a valid GPT partition label"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":\"a\\tb\"}","@trailer"],"fieldType",1,"x","gptLabel","manifest object 1: 'a\\tb' is not a valid GPT partition label"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":\"a\\u007fb\"}","@trailer"],"fieldType",1,"x","gptLabel","manifest object 1: 'a\\u{7f}b' is not a valid GPT partition label"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":\"a\\u0085b\"}","@trailer"],"fieldType",1,"x","gptLabel","manifest object 1: 'a\\u{85}b' is not a valid GPT partition label"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-label\"]}","{\"name\":\"x\",\"gptLabel\":5}","@trailer"],"fieldType",1,"x","gptLabel","manifest field 'gptLabel' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"not-a-uuid\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid 'not-a-uuid' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"12345678\\u00e9\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '12345678\u00e9' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"\\u00e9\\u00e9\\u00e9\\u00e9\\u00e9\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '\u00e9\u00e9\u00e9\u00e9\u00e9' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b70\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '4f68bce3-e8cd-4db1-96e7-fbcaf984b70' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"4f68bce3e8cd-4db1-96e7-fbcaf984b709-\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '4f68bce3e8cd-4db1-96e7-fbcaf984b709-' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"4f68bce3 e8cd4db196e7fbcaf984b709\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '4f68bce3 e8cd4db196e7fbcaf984b709' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":5}","@trailer"],"fieldType",1,"x","gptUuid","manifest field 'gptUuid' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"urn:uuid:\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid 'urn:uuid:' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-uuid\"]}","{\"name\":\"x\",\"gptUuid\":\"{4f68bce3-e8cd-4db1-96e7-fbcaf984b709}\"}","@trailer"],"fieldType",1,"x","gptUuid","manifest object 1: gptUuid '{4f68bce3-e8cd-4db1-96e7-fbcaf984b709}' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"not-a-uuid\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid 'not-a-uuid' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"12345678\\u00e9\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '12345678\u00e9' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"\\u00e9\\u00e9\\u00e9\\u00e9\\u00e9\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '\u00e9\u00e9\u00e9\u00e9\u00e9' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"4f68bce3-e8cd-4db1-96e7-fbcaf984b70\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '4f68bce3-e8cd-4db1-96e7-fbcaf984b70' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"4f68bce3e8cd-4db1-96e7-fbcaf984b709-\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '4f68bce3e8cd-4db1-96e7-fbcaf984b709-' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"4f68bce3 e8cd4db196e7fbcaf984b709\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '4f68bce3 e8cd4db196e7fbcaf984b709' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":5}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest field 'gptTypeUuid' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"urn:uuid:\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid 'urn:uuid:' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-type-uuid\"]}","{\"name\":\"x\",\"gptTypeUuid\":\"{4f68bce3-e8cd-4db1-96e7-fbcaf984b709}\"}","@trailer"],"fieldType",1,"x","gptTypeUuid","manifest object 1: gptTypeUuid '{4f68bce3-e8cd-4db1-96e7-fbcaf984b709}' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"]}","{\"name\":\"x\",\"gptDiskUuid\":\"zz\"}","@trailer"],"fieldType",1,"x","gptDiskUuid","manifest object 1: gptDiskUuid 'zz' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-disk-uuid\"],\"gptDiskUuid\":\"zz\"}","@trailer"],"fieldType",0,null,"gptDiskUuid","manifest object 0 (root): gptDiskUuid 'zz' is not a UUID"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-grow-file-system\",\"gpt-flag-no-auto\",\"gpt-flags\"]}","{\"gptFlags\":0,\"gptFlagNoAuto\":true,\"name\":\"x\"}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'gptFlagNoAuto' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-grow-file-system\",\"gpt-flag-no-auto\",\"gpt-flags\"]}","{\"gptFlags\":9223372036854775808,\"gptFlagNoAuto\":false,\"name\":\"x\"}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'gptFlagNoAuto' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-grow-file-system\",\"gpt-flag-no-auto\",\"gpt-flags\"]}","{\"gptFlags\":576460752303423488,\"gptFlagGrowFileSystem\":false,\"name\":\"x\"}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'gptFlagGrowFileSystem' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-grow-file-system\",\"gpt-flag-no-auto\",\"gpt-flags\"]}","{\"gptFlags\":0,\"gptFlagGrowFileSystem\":true,\"name\":\"x\"}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'gptFlagGrowFileSystem' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\",\"read-only\"]}","{\"name\":\"x\",\"gptFlags\":0,\"readOnly\":true}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'readOnly' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\",\"read-only\"]}","{\"name\":\"x\",\"gptFlags\":1152921504606846976,\"readOnly\":false}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'readOnly' contradict each other"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\",\"read-only\"]}","{\"name\":\"x\",\"readOnly\":true}","@trailer"],"contradiction",1,"x","readOnly","manifest object 1 (x): 'gptFlags' and 'readOnly' contradict each other ('gptFlags' is not there, which means 0 as the manifest lists 'gpt-flags')"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\",\"read-only\"]}","{\"name\":\"x\",\"gptFlags\":1152921504606846976}","@trailer"],"contradiction",1,"x","gptFlags","manifest object 1 (x): 'gptFlags' and 'readOnly' contradict each other ('readOnly' is not there, which means false as the manifest lists 'read-only')"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flags\"]}","{\"gptFlags\":\"x\",\"name\":\"x\"}","@trailer"],"fieldType",1,"x","gptFlags","manifest field 'gptFlags' is not an unsigned integer"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-no-auto\"]}","{\"gptFlagNoAuto\":1,\"name\":\"x\"}","@trailer"],"fieldType",1,"x","gptFlagNoAuto","manifest field 'gptFlagNoAuto' is not a boolean"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"gpt-flag-grow-file-system\"]}","{\"gptFlagGrowFileSystem\":\"true\",\"name\":\"x\"}","@trailer"],"fieldType",1,"x","gptFlagGrowFileSystem","manifest field 'gptFlagGrowFileSystem' is not a boolean"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b98\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982400\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b982\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"sha256\":\"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"sha256\":5}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a string"] +[["@root","{\"name\":\"x\",\"sha256\":\"\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"sha256\":\"2cf2 4dba 5fb0 a30e 26e8 3b2a c5b9 e29e 1b16 1e5c 1fa7 425e 7304 3362 938b 9824\"}","@trailer"],"fieldType",1,"x","sha256","manifest field 'sha256' is not a SHA-256 hash"] +[["@root","{\"name\":\"x\",\"size\":3,\"sha256\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"}","@trailer"],"contradiction",1,"x","sha256","manifest object 1 (x): 'sha256' is the hash of no data, but 'size' is not 0"] +[["@root","{\"name\":\"x\",\"size\":0,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\"}","@trailer"],"contradiction",1,"x","size","manifest object 1 (x): 'size' is 0, but 'sha256' is not the hash of no data"] +[["@root","{\"name\":\"x\",\"contents\":{}}","@trailer"],"fieldType",1,"x","contents","manifest field 'contents' is not an array"] +[["@root","{\"name\":\"x\",\"contents\":[5]}","@trailer"],"contents",1,"x","contents","manifest object 1: contents entry is not an object"] +[["@root","{\"name\":\"x\",\"contents\":[null]}","@trailer"],"contents",1,"x","contents","manifest object 1: contents entry is not an object"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"/abs\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/abs'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a/../b\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name contains a '.' or '..' component: 'a/../b'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name is empty: ''"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"Uapi16Manifest\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name is reserved for the manifest: 'Uapi16Manifest'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\\nb\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name contains a control character: 'a\\nb'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":5}]}","@trailer"],"fieldType",1,"x","file","manifest field 'file' is not a string"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":\"ftp://example.com/x\"}]}","@trailer"],"contents",1,"x","url","manifest object 1: contents URL 'ftp://example.com/x' is not http or https"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":\"HTTPS://example.com/x\"}]}","@trailer"],"contents",1,"x","url","manifest object 1: contents URL 'HTTPS://example.com/x' is not http or https"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":\"\"}]}","@trailer"],"contents",1,"x","url","manifest object 1: contents URL '' is not http or https"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":\"example.com\"}]}","@trailer"],"contents",1,"x","url","manifest object 1: contents URL 'example.com' is not http or https"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":5}]}","@trailer"],"fieldType",1,"x","url","manifest field 'url' is not a string"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8\"}]}","@trailer"],"contents",1,"x","literal","manifest object 1: literal contents are not Base64"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVs bG8=\"}]}","@trailer"],"contents",1,"x","literal","manifest object 1: literal contents are not Base64"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"!\"}]}","@trailer"],"contents",1,"x","literal","manifest object 1: literal contents are not Base64"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"====\"}]}","@trailer"],"contents",1,"x","literal","manifest object 1: literal contents are not Base64"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":5}]}","@trailer"],"fieldType",1,"x","literal","manifest field 'literal' is not a string"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encoding\":\"identity\"}]}","@trailer"],"contents",1,"x","encoding","manifest object 1: encoding 'identity' is not permitted"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encoding\":\"IDENTITY\"}]}","@trailer"],"contents",1,"x","encoding","manifest object 1: encoding 'identity' is not permitted"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encoding\":\"\"}]}","@trailer"],"contents",1,"x","encoding","manifest object 1: encoding '' is not permitted"] +[["@root","{\"name\":\"x\",\"contents\":[{\"encoding\":5}]}","@trailer"],"fieldType",1,"x","encoding","manifest field 'encoding' is not a string"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"literal\":\"AA==\"}]}","@trailer"],"contents",1,"x",null,"manifest object 1: only one of file, url and literal may be set"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"url\":\"https://e/x\"}]}","@trailer"],"contents",1,"x",null,"manifest object 1: only one of file, url and literal may be set"] +[["@root","{\"name\":\"x\",\"contents\":[{\"url\":\"https://e/x\",\"literal\":\"AA==\"}]}","@trailer"],"contents",1,"x",null,"manifest object 1: only one of file, url and literal may be set"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"url\":\"https://e/x\",\"literal\":\"AA==\"}]}","@trailer"],"contents",1,"x",null,"manifest object 1: only one of file, url and literal may be set"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encodedSize\":5,\"originalSize\":6}]}","@trailer"],"contradiction",1,"x","encodedSize","manifest object 1: encoded and original size differ without an encoding"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encodedSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","encodedSha256","manifest object 1: encoded and original hash differ without an encoding"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encodedSha256\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\",\"encodedSize\":3}]}","@trailer"],"contradiction",1,"x","encodedSha256","manifest object 1: 'encodedSha256' is the hash of no data, but 'encodedSize' is not 0"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encodedSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"encodedSize\":0}]}","@trailer"],"contradiction",1,"x","encodedSize","manifest object 1: 'encodedSize' is 0, but 'encodedSha256' is not the hash of no data"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"originalSha256\":\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\",\"originalSize\":3}]}","@trailer"],"contradiction",1,"x","originalSha256","manifest object 1: 'originalSha256' is the hash of no data, but 'originalSize' is not 0"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"originalSha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"originalSize\":0}]}","@trailer"],"contradiction",1,"x","originalSize","manifest object 1: 'originalSize' is 0, but 'originalSha256' is not the hash of no data"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"encodedSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 5 bytes, not 4"] +[["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"literal\":\"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==\",\"encoding\":\"gzip\",\"encodedSize\":24}]}","@trailer"],"contradiction",1,"x","literal","manifest object 1: literal contents are 25 bytes, not 24"] +[["@root","{\"name\":\"x\",\"size\":3,\"contents\":[{\"file\":\"a\",\"offset\":-2}]}","@trailer"],"fieldType",1,"x","offset","manifest field 'offset' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"offset\":6,\"originalSize\":5}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] +[["@root","{\"name\":\"x\",\"contents\":[{\"literal\":\"aGVsbG8=\",\"offset\":6}]}","@trailer"],"contents",1,"x","offset","manifest object 1: contents offset 6 is beyond the data size 5"] +[["@root","{\"name\":\"x\",\"size\":4,\"contents\":[{\"file\":\"a\",\"offset\":2,\"originalSize\":5}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 2 plus size 4 exceeds the contents size 5"] +[["@root","{\"name\":\"x\",\"size\":18446744073709551615,\"contents\":[{\"file\":\"a\",\"offset\":2,\"originalSize\":18446744073709551615}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 2 plus size 18446744073709551615 exceeds the contents size 18446744073709551615"] +[["@root","{\"name\":\"x\",\"size\":5,\"contents\":[{\"originalSize\":4}]}","@trailer"],"contradiction",1,"x","offset","manifest object 1 (x): offset 0 plus size 5 exceeds the contents size 4"] +[["@root","{\"name\":\"x\",\"size\":5,\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"contents\":[{\"file\":\"a\",\"originalSize\":5,\"originalSha256\":\"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7\"}]}","@trailer"],"contradiction",1,"x","sha256","manifest object 1 (x): object and contents hashes differ"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\"},{\"file\":\"/b\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/b'"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"/a\"},{\"file\":\"b\",\"encoding\":\"identity\"}]}","@trailer"],"contents",1,"x","file","manifest object 1: contents file reference: name has an empty component: '/a'"] +[["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":[]}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: 'extendedAttributes' is not an object"] +[["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":5}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: 'extendedAttributes' is not an object"] +[["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":[]}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute namespace 'user' is not an object"] +[["@root","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":5}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute namespace 'user' is not an object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":\"b\"}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: value of extended attribute 'a' is not an object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"\":{\"text\":\"b\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: invalid extended attribute name ''"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\\nb\":{\"text\":\"b\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: invalid extended attribute name 'a\\nb'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"text\":\"b\",\"base64\":\"Yg==\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' needs exactly one of 'text' and 'base64'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' needs exactly one of 'text' and 'base64'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"text\":null,\"base64\":null}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' needs exactly one of 'text' and 'base64'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"text\":5}}}}","@trailer"],"fieldType",1,"x","text","manifest field 'text' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"base64\":5}}}}","@trailer"],"fieldType",1,"x","base64","manifest field 'base64' is not a string"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"base64\":\"!\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' is not valid Base64"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"base64\":\"Yg\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' is not valid Base64"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"text\":5,\"base64\":5}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' needs exactly one of 'text' and 'base64'"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"base64\":\"!\"},\"\":{\"text\":\"x\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' is not valid Base64"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":[],\"b\":{\"text\":5}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: value of extended attribute 'a' is not an object"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"size\":0,\"extendedAttributes\":{\"user\":{\"a\":{\"TEXT\":\"b\"}}}}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: extended attribute 'a' needs exactly one of 'text' and 'base64'"] +[["@root","{\"name\":\"x\",\"size\":0,\"validity\":5}","@trailer"],"fieldType",1,"x","validity","manifest field 'validity' is not a string"] +[["@root","{\"name\":\"x\",\"uid\":\"a\",\"gid\":\"b\"}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"gid\":\"b\",\"uid\":\"a\"}","@trailer"],"fieldType",1,"x","gid","manifest field 'gid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"type\":\"fifo\",\"size\":1,\"uid\":4294967295}","@trailer"],"fieldRange",1,"x","uid","manifest object 1: uid 4294967295 is out of range"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"literal\":\"AA==\"}],\"uid\":\"x\"}","@trailer"],"contents",1,"x",null,"manifest object 1: only one of file, url and literal may be set"] +[["@root","{\"name\":\"x\",\"uid\":\"x\",\"contents\":[{\"file\":\"a\",\"literal\":\"AA==\"}]}","@trailer"],"fieldType",1,"x","uid","manifest field 'uid' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"encodedSize\":1,\"originalSize\":2,\"offset\":\"x\"}]}","@trailer"],"fieldType",1,"x","offset","manifest field 'offset' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"offset\":\"7\"}]}","@trailer"],"fieldType",1,"x","offset","manifest field 'offset' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"encodedSize\":\"5\"}]}","@trailer"],"fieldType",1,"x","encodedSize","manifest field 'encodedSize' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"file\":\"a\",\"originalSize\":\"5\"}]}","@trailer"],"fieldType",1,"x","originalSize","manifest field 'originalSize' is not an unsigned integer"] +[["@root","{\"name\":\"x\",\"contents\":[{\"encodedSize\":1,\"originalSize\":2},{\"file\":\"/x\"}]}","@trailer"],"contradiction",1,"x","encodedSize","manifest object 1: encoded and original size differ without an encoding"] +[["{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"features\":[\"size\",\"user-xattr\"]}","{\"name\":\"x\",\"extendedAttributes\":{\"user\":{\"a\":5}},\"size\":\"x\"}","@trailer"],"extendedAttributes",1,"x","extendedAttributes","manifest object 1: value of extended attribute 'a' is not an object"] +[["@root","{\"name\":\"a\",\"size\":0}","{\"name\":\"b\",\"size\":\"x\"}","@trailer"],"fieldType",2,"b","size","manifest field 'size' is not an unsigned integer"] diff --git a/src/uapi16/sequence.rs b/src/uapi16/sequence.rs new file mode 100644 index 0000000..fac282b --- /dev/null +++ b/src/uapi16/sequence.rs @@ -0,0 +1,445 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The rules for the file objects of a manifest one after the other: which +//! fields each of them may have, and where it may come. + +use crate::decode::Subject; +use crate::error::{Error, Field, Problem}; +use crate::name::NamePair; +use crate::{Features, FileObject, InodeType, Order, RootObject}; + +/// The check of the file objects of a manifest one after the other: what +/// it keeps of the objects up to the last one to check the next one +/// against. +/// +/// The file objects of a manifest are in tree order: a directory comes +/// before the objects below it, and these come right after it. So the +/// directories more objects may still be in are the root, the directories +/// the last object is in, and the last object if it is a directory. The +/// name of the last object is all that has to be kept, at most +/// [`Name::MAX_LEN`](crate::Name::MAX_LEN) bytes. That also finds a name +/// that comes again right after the entries of the directory it names, +/// and with the code point ordering every name that comes twice. +#[derive(Debug)] +pub(crate) struct SequenceCheck { + /// What the manifest records. + features: Features, + /// The order the manifest declares, which the objects have to be in. + order: Option, + /// The name of the last file object. The root file object's is empty. + last: String, + /// The inode type of the last file object. The root file object is a + /// directory. + last_type: InodeType, +} + +impl SequenceCheck { + /// The check of the file objects of a manifest that records `features` + /// and lists its file objects in `order`, after its root file object. + pub(crate) fn new(features: Features, order: Option) -> SequenceCheck { + SequenceCheck { + features, + order, + last: String::new(), + last_type: InodeType::Directory, + } + } + + /// What the manifest records. + pub(crate) fn features(&self) -> Features { + self.features + } + + /// Checks the fields of the root file object `root`: they have to be of + /// features the manifest records. The error names the first field of a + /// feature the manifest does not record. + pub(crate) fn check_root_fields(&self, root: &RootObject) -> Result<(), Error> { + self.check_features_listed(root.feature_fields(), Subject::root()) + } + + /// Checks the fields of `object`, the one of the record with the number + /// `record_number`, against what the manifest records: they have to be + /// of features the manifest records, the fields a reader filled in + /// aside, a symbolic link has its target in a manifest that records + /// them, and the flags of a partition agree, see + /// [`FileObject::check_partition_flags`]. The error names the first + /// field of a feature the manifest does not record. + pub(crate) fn check_fields(&self, object: &FileObject, record_number: u64) -> Result<(), Error> { + let subject = Subject::new(object, record_number); + self.check_features_listed(object.feature_fields(), subject)?; + let target = object.contents.iter().any(|contents| contents.literal().is_some()); + if self.features.contains(Features::SYMLINK) && object.inode_type == InodeType::Symlink && !target { + return Err(Error::manifest( + Problem::NoTarget, + format!( + "{}: the manifest records the targets of symbolic links, but this one has none", + subject + ), + )); + } + object.check_partition_flags(self.features, subject) + } + + /// Checks that the manifest records the feature of every one of + /// `fields`, the fields of the object `subject` names that belong to a + /// feature, each with its feature. The error names the first one it + /// does not record. + fn check_features_listed( + &self, + mut fields: impl Iterator, + subject: Subject<'_>, + ) -> Result<(), Error> { + let Some((field, feature)) = fields.find(|(_, feature)| !self.features.contains(*feature)) else { + return Ok(()); + }; + Err(Error::manifest( + Problem::UnlistedFeature, + format!( + "{}: '{}' is a field of the feature '{}', which the manifest does not record", + subject, + field, + feature.names().next().unwrap_or_default() + ), + ) + .at(field)) + } + + /// Checks that `object`, the file object of the record with the number + /// `record_number`, which comes after the root file object, may come + /// next, and makes it the last one. + pub(crate) fn admit(&mut self, object: &FileObject, record_number: u64) -> Result<(), Error> { + let name = object.name.as_str(); + if object.name.is_root() { + return Ok(()); + } + let subject = Subject::new(object, record_number); + // The first byte in which the name differs from that of the last + // object settles each of the checks, so the two names are looked + // at once. + let pair = NamePair::new(&self.last, name); + if !pair.second_is_in_open_directory(self.last_type) { + let directory = object.name.parent().unwrap_or_default(); + return Err(Error::manifest( + Problem::Misplaced, + format!( + "{}: does not come right after the object of its directory '{}'", + subject, + directory.escape_debug() + ), + )); + } + // The entry of the directory of this object that came last is the + // last object or a directory it is in. If that is this object, its + // name comes twice. + if pair.second_is_first_or_above() { + return Err(Error::manifest( + Problem::DuplicateName, + format!("{}: the name is listed twice", subject), + )); + } + if self.order == Some(Order::CodePoint) && pair.ordering().is_ge() { + return Err(Error::manifest( + Problem::OutOfOrder, + format!( + "{}: comes after '{}', which it sorts before in the code point ordering", + subject, + self.last.escape_debug() + ), + )); + } + self.last.clear(); + self.last.push_str(name); + self.last_type = object.inode_type; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::ErrorKind; + use crate::testing::full_tree_names; + use crate::{Contents, DosFlags, FatSerial, InodeFlags, Location, Mode, Name, Uuid}; + use std::num::NonZeroU64; + + /// Gives an object a field. + type Give = fn(&mut T); + + fn object(name: &str, inode_type: InodeType) -> FileObject { + let mut object = FileObject::new(Name::new(name).unwrap()); + object.inode_type = inode_type; + object + } + + /// Admits the objects `names`, directories where they end in a slash, + /// and returns the problem of the first one that is not admitted. + fn first_problem(order: Option, names: &[&str]) -> Option<(usize, Problem)> { + let mut check = SequenceCheck::new(Features::DEFAULT, order); + for (i, name) in names.iter().enumerate() { + let object = match name.strip_suffix('/') { + Some(dir) => object(dir, InodeType::Directory), + None => object(name, InodeType::Regular), + }; + if let Err(e) = check.admit(&object, i as u64 + 1) { + let ErrorKind::Manifest(problem) = e.kind() else { + panic!("{}", e); + }; + return Some((i, problem)); + } + } + None + } + + #[test] + fn tree_order() { + for names in [ + &["a/", "a/b/", "a/b/c", "a/d", "e"][..], + &["a", "b", "c"], + &["z/", "z/y/", "z/y/x/", "z/y/x/w", "a"], + &["a-b", "a/", "a/x"], + ] { + assert_eq!(first_problem(None, names), None, "{:?}", names); + } + for (names, at) in [ + // A directory that is not listed, or whose entries ended. + (&["a/x"][..], 0), + (&["a/", "b", "a/x"], 2), + (&["a/", "a/b/", "a/b/c", "a/d", "a/b/e"], 4), + // A file is no directory. + (&["a", "a/x"], 1), + ] { + assert_eq!( + first_problem(None, names), + Some((at, Problem::Misplaced)), + "{:?}", + names + ); + } + } + + #[test] + fn repeated_names() { + // The previous entry of the directory is found also after the + // entries of a directory. + for (names, at) in [ + (&["a", "a"][..], 1), + (&["a/", "a/b/", "a/b/c", "a/b/"], 3), + (&["d/", "d/x", "d/"], 2), + ] { + assert_eq!( + first_problem(None, names), + Some((at, Problem::DuplicateName)), + "{:?}", + names + ); + } + // Without an order a name that comes again later is not found. + assert_eq!(first_problem(None, &["a", "b", "a"]), None); + assert_eq!( + first_problem(Some(Order::CodePoint), &["a", "b", "a"]), + Some((2, Problem::OutOfOrder)) + ); + } + + #[test] + fn code_point_order() { + let order = Some(Order::CodePoint); + assert_eq!(first_problem(order, &["a/", "a/x", "a-b", "a0", "b/", "b/c"]), None); + assert_eq!( + first_problem(order, &["a-b", "a/", "a/x"]), + Some((1, Problem::OutOfOrder)) + ); + assert_eq!(first_problem(order, &["b", "a"]), Some((1, Problem::OutOfOrder))); + assert_eq!(first_problem(order, &["\u{ff61}", "\u{1f600}"]), None); + assert_eq!( + first_problem(order, &["\u{1f600}", "\u{ff61}"]), + Some((1, Problem::OutOfOrder)) + ); + } + + /// What the specification says of an object of the name `name` right + /// after one of the name `last` and the type `last_type`, with the + /// components of the names compared one by one. + fn by_the_definition(last: &Name, last_type: InodeType, name: &Name, order: Option) -> Option { + let last: Vec<&str> = last.components().collect(); + let name: Vec<&str> = name.components().collect(); + let directory = &name[..name.len() - 1]; + // The directories that are open: the root, those the last object + // is in, and the last object itself if it is a directory. + if !(last.starts_with(directory) && (last_type == InodeType::Directory || directory.len() < last.len())) { + return Some(Problem::Misplaced); + } + // The name of the last object, or of a directory it is in. + if last.starts_with(&name) { + return Some(Problem::DuplicateName); + } + (order == Some(Order::CodePoint) && last >= name).then_some(Problem::OutOfOrder) + } + + /// Every object of a name of a few components may come after every + /// other one where the specification says so, and only there. + #[test] + fn checks_by_the_definition() { + let names = full_tree_names(&["a", "ab", "a b", "a-b", "a.b", "\u{e9}"], 3); + for order in [None, Some(Order::CodePoint)] { + for last in &names { + for last_type in [InodeType::Regular, InodeType::Directory] { + // The root is a directory. + if last.is_root() && last_type != InodeType::Directory { + continue; + } + for name in names.iter().filter(|name| !name.is_root()) { + let mut check = SequenceCheck::new(Features::DEFAULT, order); + check.last = last.to_string(); + check.last_type = last_type; + let object = FileObject::new(name.clone()); + let problem = check.admit(&object, 1).err().map(|e| e.kind()); + let expected = by_the_definition(last, last_type, name, order).map(ErrorKind::Manifest); + assert_eq!(problem, expected, "{:?} {:?} {:?} {:?}", last, last_type, name, order); + } + } + } + } + } + + #[test] + fn fields() { + let check = SequenceCheck::new(Features::SIZE | Features::SYMLINK, None); + let mut file = object("f", InodeType::Regular); + file.size = Some(1); + assert!(check.check_fields(&file, 1).is_ok()); + // A field of a feature the manifest does not record is named. + file.inode.mtime_nsec = Some(1); + let e = check.check_fields(&file, 1).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::UnlistedFeature), Some(Field::MTimeNSec)) + ); + assert_eq!( + e.to_string(), + "manifest object 1 (f): 'mTimeNSec' is a field of the feature 'mtime', which the manifest does not record" + ); + // The field the feature has: for the device numbers the one of the + // two the object has, for symbolic links the target in `contents`. + let none = SequenceCheck::new(Features::NONE, None); + let cases: [(InodeType, Give, Field); 8] = [ + (InodeType::Regular, |o| o.inode.mode = Mode::new(0o644), Field::Mode), + (InodeType::CharDevice, |o| o.major = Some(1), Field::Major), + (InodeType::BlockDevice, |o| o.minor = Some(1), Field::Minor), + ( + InodeType::Regular, + |o| o.inode.user_xattrs = Some(Box::default()), + Field::ExtendedAttributes, + ), + ( + InodeType::Regular, + |o| o.dos_flags.put(DosFlags::HIDDEN, Some(false)), + Field::FlagHidden, + ), + ( + InodeType::Regular, + |o| o.inode_token = NonZeroU64::new(1), + Field::InodeToken, + ), + ( + InodeType::Directory, + |o| o.inode.group_name = Some("g".into()), + Field::GroupName, + ), + ( + InodeType::Symlink, + |o| o.contents = vec![Contents::new(Location::Literal(b"t".to_vec()))], + Field::Contents, + ), + ]; + for (inode_type, set, field) in cases { + let mut o = object("o", inode_type); + set(&mut o); + let e = none.check_fields(&o, 1).unwrap_err(); + assert_eq!(e.field(), Some(field), "{:?}", o); + } + let link = object("l", InodeType::Symlink); + let e = check.check_fields(&link, 2).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoTarget)); + assert!(e.to_string().starts_with("manifest object 2 (l): "), "{}", e); + let quiet = SequenceCheck::new(Features::SIZE, None); + assert!(quiet.check_fields(&link, 2).is_ok()); + // The root file object has the fields of features too. + let mut root = RootObject::default(); + assert!(none.check_root_fields(&root).is_ok()); + root.inode.uid = Some(0); + let e = none.check_root_fields(&root).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::UnlistedFeature), Some(Field::Uid)) + ); + assert_eq!( + e.to_string(), + "manifest object 0 (root): 'uid' is a field of the feature 'uid', which the manifest does not record" + ); + } + + /// Of several fields of features the manifest does not record, the + /// error names the first: those of the object itself in the order of + /// their names, then the DOS attributes, then the inode attributes and + /// last the inode flags. Each field given here comes before those given + /// before it. + #[test] + fn the_first_unlisted_field() { + let none = SequenceCheck::new(Features::NONE, None); + let mut object = object("o", InodeType::Regular); + let fields: [(Give, Field); 14] = [ + ( + |o| o.inode.flags.put(InodeFlags::NO_DUMP, Some(true)), + Field::FlagNoDump, + ), + ( + |o| o.inode.flags.put(InodeFlags::APPEND_ONLY, Some(false)), + Field::FlagAppendOnly, + ), + (|o| o.inode.user_name = Some("u".into()), Field::UserName), + (|o| o.inode.read_only = Some(true), Field::ReadOnly), + (|o| o.inode.mode = Mode::new(0o444), Field::Mode), + ( + |o| o.inode.user_xattrs = Some(Box::default()), + Field::ExtendedAttributes, + ), + (|o| o.dos_flags.put(DosFlags::SYSTEM, Some(true)), Field::FlagSystem), + (|o| o.dos_flags.put(DosFlags::ARCHIVE, Some(false)), Field::FlagArchive), + (|o| o.size = Some(1), Field::Size), + (|o| o.major = Some(1), Field::Major), + (|o| o.inode_token = NonZeroU64::new(1), Field::InodeToken), + ( + |o| o.gpt.get_or_insert_with(Box::default).label = Some("l".into()), + Field::GptLabel, + ), + ( + |o| o.gpt.get_or_insert_with(Box::default).flags = Some(0), + Field::GptFlags, + ), + ( + |o| o.gpt.get_or_insert_with(Box::default).grow_file_system = Some(false), + Field::GptFlagGrowFileSystem, + ), + ]; + for (give, field) in fields { + give(&mut object); + assert_eq!(none.check_fields(&object, 1).unwrap_err().field(), Some(field)); + } + let mut root = RootObject::default(); + let fields: [(Give, Field); 6] = [ + (|r| r.inode.flags.put(InodeFlags::NO_COW, Some(true)), Field::FlagNoCow), + (|r| r.inode.uid = Some(0), Field::Uid), + (|r| r.inode.read_only = Some(false), Field::ReadOnly), + ( + |r| r.gpt_disk_uuid = Some(Uuid::new([1; Uuid::SIZE])), + Field::GptDiskUuid, + ), + (|r| r.file_system.label = Some("ESP".into()), Field::FsLabel), + (|r| r.file_system.fat_serial = Some(FatSerial(1)), Field::FatSerial), + ]; + for (give, field) in fields { + give(&mut root); + assert_eq!(none.check_root_fields(&root).unwrap_err().field(), Some(field)); + } + } +} From 244d2b5a60a57ea7a1e153f5722d162363050e7f Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 08/19] uapi16: add the writer Add a writer for manifests. Writer::begin() writes the root file object, file() a file object, signature() a signature object and finish() the trailer object. A writer that is dropped before finish() leaves a manifest without a trailer, which a reader refuses as incomplete. The writer is split up the same way the reader is. An Encoder puts the manifest together record by record and does no I/O: its begin(), file(), signature() and finish() append the record of their object to a string, and whoever calls them sends the records on, one at a time or many at once. Writer drives an Encoder and writes every record out in a single write. So a front end for an async runtime can drive the same encoder later, the way it can drive the reader's Decoder, without a copy of the checks of its own. Every object is one record: the record separator, the object with its keys sorted and without whitespace, and a newline, which is what systemd-manifest writes. The record is put together with the writers of the json crate in a buffer that the writer keeps from one record to the next. Once a record larger than 64 KiB went out, the buffer gives back what it took beyond that. The specification limits a record to 4 MiB, its record separator included, and a reader takes no more than 256 contents objects for a file object, so the encoder refuses both. A record that turns out to be too large is taken back before anything of it is written. The writer checks every object against the root file object the same way the reader does, with the same code: an object has no field of a feature the manifest doesn't list, readOnly and fatSerial among them, it comes right after the object of its directory, and it keeps to the order the manifest declares. The value of every field has to be one the reader takes. Strings keep to the rules the reader applies, and names, labels, URLs, encodings, HTTP headers, user and group IDs and the names of extended attributes are checked by the same functions. The writer also runs the checks the reader does on an object as a whole, which the reader keeps apart from what it fills in: the fields an inode type permits, readOnly against mode and against bit 60 of gptFlags, gptFlags against the gptFlag* fields, a size of 0 against the hash, httpHeaders only next to a url, and a part that has to fit into the data it is taken from. Otherwise a bug in a caller produces a manifest that no reader takes, and only the consumer finds out. An object with more than one fault is refused for the one a reader reports, so the writer checks in the reader's order: a record that is too large, a string the JSON parser refuses or a key it sees twice in an object, such as two header fields of the same name, a file object after a signature object, the values of the fields in the order of their keys, a missing name, a field the inode type doesn't permit, fields that contradict each other, a field of a feature the manifest doesn't list, a symbolic link without its target, gptFlags against the fields of its flags, and where the object comes. That is why the record is put together before the object is checked. The specification wants the encoding in lower case. A reader lowers the case of what it reads first, as systemd does, but the writer writes what it is given. So the check the two share refuses any other encoding. That's the one fault the writer refuses where a reader of the same record finds none. An object the writer refuses is not written, and the writer goes on as if it hadn't been given it. Every error carries the number of the record it is about, record 0 for those of begin(). begin() takes a RootObject, so the root file object can't have a name or be anything but a directory. Writer::get_ref() hands out what the manifest is written to, so that a caller can hash what was written before the first signature object for its data. The specification asks generators not to write fields that are set to their default, so that file objects describing the same file compare as equivalent. So the writer leaves out the type of regular files, a validSinceUSec of 0, a validity of good and an offset of 0. The specification also recommends leaving out the hash of no data next to a size of 0, and the writer does that too. So an empty file goes out with a size of 0 and no hash, and a reader fills the hash in again. For data without an encoding the specification says that the encoded size and hash shouldn't be there at all. The writer leaves them out next to the original ones, which say the same, and writes one that is the only statement of the size or the hash. Written as the original size or hash it would come back as another field, and left out it would be lost. The writer also leaves out what the features of the manifest imply without the field: a flag that is cleared, a readOnly of false, a gptFlags of 0 and extended attributes when there are none. An object only has these fields where the manifest records their features. The features field itself is only written if it isn't the default. A field that FilledIn marks as filled in by a reader isn't written at all, whichever field it is. So what a reader returns can be written back with the root file object it read. The value of an extended attribute goes out as text if it is a string a manifest can hold and as Base64 otherwise, as the specification asks. Note that a record close to 4 MiB can grow past the limit on the way back. The writer writes some values in another form than a manifest may carry them in, a UUID with its hyphens and the value of an extended attribute as text where it can, and refuses such a record. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/decode.rs | 30 +- src/uapi16/lib.rs | 34 +- src/uapi16/object.rs | 6 + src/uapi16/writer.rs | 2311 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 2366 insertions(+), 15 deletions(-) create mode 100644 src/uapi16/writer.rs diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index c74a470..c8e8626 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -846,23 +846,31 @@ impl Contents { } /// Checks `encoding` as the encoding of the data: a content coding of - /// HTTP, which does not tell upper case from lower case, other than the - /// one that stands for none. + /// HTTP other than the one that stands for none, in lower case. HTTP + /// does not tell upper case from lower case, so a reader lowers the case + /// of what it reads first. pub(crate) fn check_encoding(encoding: &str, subject: Subject<'_>) -> Result<(), Error> { - if encoding.is_empty() || encoding.eq_ignore_ascii_case(IDENTITY_ENCODING) { - return Err(Error::manifest( - Problem::InvalidContents, - format!("{}: encoding '{}' is not permitted", subject, encoding.escape_debug()), - ) - .at(Field::Encoding)); - } - Ok(()) + let wrong = if encoding.is_empty() || encoding.eq_ignore_ascii_case(IDENTITY_ENCODING) { + "is not permitted" + } else if encoding.bytes().any(|b| b.is_ascii_uppercase()) { + "is not in lower case" + } else { + return Ok(()); + }; + Err(Error::manifest( + Problem::InvalidContents, + format!("{}: encoding '{}' {}", subject, encoding.escape_debug(), wrong), + ) + .at(Field::Encoding)) } /// Checks `headers` as the header fields of the requests for the data /// at a URL: a name is a token as RFC 9110 has it, and none comes twice /// in any case. A value has no line break. - pub(crate) fn check_headers(headers: &[(String, String)], subject: Subject<'_>) -> Result<(), Error> { + pub(crate) fn check_headers<'h>( + headers: impl IntoIterator, + subject: Subject<'_>, + ) -> Result<(), Error> { let mut names = HashSet::new(); for (name, value) in headers { let token = !name.is_empty() diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index e8abd69..8e12c23 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -15,6 +15,10 @@ //! the manifest declares, and with the fields of the [`Features`] the //! manifest records. //! - [`Decoder`] does the same with the bytes it is fed, and does no I/O. +//! - [`Writer`] writes a manifest record by record to a [`Write`], and +//! checks it the way the reader does. [`Encoder`] does the same into a +//! string, and does no I/O. [`Sha256Context`] computes the hash of a file +//! while it is read, and [`Finalize::finalize`] returns it. //! - [`RootObject`], [`FileObject`], [`Contents`] and [`Signature`] are the //! objects, and [`Name`], [`InodeType`], [`Mode`], [`DosFlags`], //! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What @@ -34,11 +38,17 @@ //! reads a whole record, of up to [`MAX_RECORD_SIZE`] bytes with its record //! separator, at once. //! +//! A manifest that does not go to a [`Write`] is put together by an +//! [`Encoder`]: [`Encoder::begin`], [`Encoder::file`], +//! [`Encoder::signature`] and [`Encoder::finish`] append its records to a +//! string, and the caller sends them on. +//! //! A manifest is input from outside and can be very large. Reading one //! takes time in proportion to its size, and keeps one record without its //! separator and the name of the file object before it in memory: less //! than [`MAX_RECORD_SIZE`] and at most [`Name::MAX_LEN`] bytes. Nothing -//! grows with the manifest. +//! grows with the manifest. Writing one keeps the record it puts together, +//! its separator included, and the name of the file object before it. //! //! Signature objects are read and not verified: that takes an OpenPGP or //! an X.509 implementation. [`Reader::signed_len`] says how much of the @@ -50,6 +60,7 @@ //! //! [UAPI.16 file manifest]: https://uapi-group.org/specifications/specs/file_manifest/ //! [`Read`]: std::io::Read +//! [`Write`]: std::io::Write #![deny(unsafe_code)] #![warn(missing_docs)] @@ -64,6 +75,7 @@ mod name; mod object; mod reader; mod sequence; +mod writer; pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; pub use error::{Error, ErrorKind, Field, Invalid, Problem}; @@ -75,6 +87,7 @@ pub use object::{ Uuid, Validity, ValidityWindow, }; pub use reader::{Decoder, Object, Reader, Step}; +pub use writer::{Encoder, Writer}; /// The media type of a manifest, which its first object carries. pub const MEDIA_TYPE: &str = "application/vnd.uapi.16.manifest"; @@ -94,8 +107,9 @@ pub(crate) const RECORD_END: u8 = b'\n'; /// The namespace of the extended attributes of a file object, the one the /// specification defines. pub(crate) const USER_NAMESPACE: &str = "user"; -/// The largest record a reader takes, from its record separator up to the -/// next one as the specification counts it, the same as systemd's. +/// The largest record a reader takes and a writer writes, from its record +/// separator up to the next one as the specification counts it, the same +/// as systemd's. pub const MAX_RECORD_SIZE: usize = 4 * 1024 * 1024; /// The most contents objects a file object can have, the same as for /// systemd. @@ -108,7 +122,7 @@ pub(crate) const STRING_RULES: json::StringRules = json::StringRules::NO_NONCHAR /// What the tests of this crate build manifests from. #[cfg(test)] pub(crate) mod testing { - use super::{Error, FileObject, Name, Object, Reader, RootObject, Signature, RECORD_END, RECORD_SEPARATOR}; + use super::{Error, FileObject, Name, Object, Reader, RootObject, Signature, Writer, RECORD_END, RECORD_SEPARATOR}; /// The root file object that says nothing but that this is a manifest. pub(crate) const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#; @@ -186,4 +200,16 @@ pub(crate) mod testing { } names } + + /// Writes the manifest `whole`. + pub(crate) fn write_whole(whole: &Whole) -> Result, Error> { + let mut writer = Writer::begin(Vec::new(), &whole.root)?; + for object in &whole.objects { + writer.file(object)?; + } + for signature in &whole.signatures { + writer.signature(signature)?; + } + writer.finish() + } } diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index d7a3369..26b3a17 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -693,6 +693,12 @@ impl FilledIn { pub fn remove(&mut self, field: Field) { self.0 &= !FilledIn::bit(field); } + + /// The fields that either this or `other` notes, such as those of an + /// object and those of its inode attributes. + pub(crate) const fn union(self, other: FilledIn) -> FilledIn { + FilledIn(self.0 | other.0) + } } impl fmt::Debug for FilledIn { diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs new file mode 100644 index 0000000..65b112c --- /dev/null +++ b/src/uapi16/writer.rs @@ -0,0 +1,2311 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Writing a manifest record by record: an [`Encoder`] puts the records +//! together, and a [`Writer`] writes them out. + +use std::fmt; +use std::io::Write; +use std::num::NonZeroU64; + +use json::{ObjectWriter, ValueWriter}; + +use crate::base64::Base64; +use crate::decode::{Subject, ROOT_RECORD}; +use crate::digest::Digest; +use crate::error::{Error, Field, Problem}; +use crate::hex::Hex; +use crate::object::{ + Contents, FileObject, FileSystemIdentity, FilledIn, FlagSet, FlagStates, GptPartition, InodeAttributes, InodeType, + RootObject, Signature, Validity, ValidityWindow, +}; +use crate::sequence::SequenceCheck; +use crate::{ + Features, Name, Order, Sha256, MAX_CONTENTS, MAX_RECORD_SIZE, MEDIA_TYPE, RECORD_END, RECORD_SEPARATOR, + SIGNATURE_MEDIA_TYPE, STRING_RULES, TRAILER_MEDIA_TYPE, USER_NAMESPACE, +}; + +/// The most room for the text of a record that a [`Writer`] keeps from one +/// record to the next. A larger record takes more, and gives it back once +/// it went out. +const TEXT_CAPACITY: usize = 64 * 1024; + +/// How far an encoder has got in the manifest. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Stage { + /// File objects can follow. + Files, + /// A signature object was appended. File objects cannot follow. + Signatures, + /// The trailer object was appended. Nothing can follow. + Done, +} + +/// Writes a manifest record by record. +/// +/// [`Writer::begin`] writes the root file object, [`Writer::file`] the +/// file objects, [`Writer::signature`] the signature objects after them +/// and [`Writer::finish`] the trailer object. A manifest without its +/// trailer is one a reader takes as incomplete, so a writer that is +/// dropped before it finished leaves nothing that passes for a manifest. +/// +/// Every object is one record of the JSON text sequence: a record +/// separator, the object with its keys sorted and without whitespace, and +/// a newline, the way `systemd-manifest` writes it. A field that says +/// nothing is left out. So is the inode type where the specification +/// implies it, on the root file object and on regular files. An +/// [`Encoder`] puts each record together, and it goes out in one write, so +/// a file wants a `BufWriter` around it. +/// +/// The root file object says what the manifest records in `features` and +/// which order it lists its file objects in in `order`. The writer checks +/// every object against them as a [`Reader`](crate::Reader) does: an object +/// has no fields of features the manifest does not record, it comes right +/// after the object of its directory, and it keeps to the order. It checks +/// what an object is itself as a reader does too: the fields its inode +/// type permits, the value of every field and every string it writes, and +/// the fields against each other. An object with more than one fault is +/// refused for the one a reader finds first. The one fault a reader does +/// not find is an encoding that is not in lower case: a reader lowers its +/// case, and the writer refuses it. No record is larger than +/// [`MAX_RECORD_SIZE`], its record separator included, and no file object +/// has more than [`MAX_CONTENTS`] contents objects. An object the writer +/// refuses is not written, and the writer goes on as if it had not been +/// given it. +/// +/// The writer leaves out what the manifest says without it: where the +/// manifest records them, a flag that is cleared, `readOnly` of false, +/// `gptFlags` of 0 and extended attributes there are none of, and +/// `features` if they are the default ones. It leaves out the hash of no +/// data next to the size 0, as the specification recommends. Without an +/// encoding the specification says that the encoded size and hash should +/// not be there. The writer leaves them out next to the original ones, and +/// writes one that is the only statement of the size or the hash: written +/// as the original size or hash it would come back as another field, and +/// left out it would be lost. The writer also leaves out every field a +/// [`Reader`](crate::Reader) filled in, see [`FilledIn`]. So what a reader +/// returns can be written back with the root file object it read. A record +/// close to [`MAX_RECORD_SIZE`] can grow past it on the way back, as the +/// writer writes some values in another form than a manifest may have them +/// in: a UUID with its hyphens, and the value of an extended attribute as +/// text where it can. The writer refuses such a record. +/// +/// ``` +/// use uapi16::{FileObject, Name, Object, Order, Reader, RootObject, Writer}; +/// +/// let mut root = RootObject::default(); +/// root.order = Some(Order::CodePoint); +/// let mut file = FileObject::new(Name::new("a")?); +/// file.size = Some(3); +/// let mut writer = Writer::begin(Vec::new(), &root)?; +/// writer.file(&file)?; +/// let bytes = writer.finish()?; +/// assert_eq!( +/// String::from_utf8_lossy(&bytes), +/// concat!( +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", +/// "\x1e{\"name\":\"a\",\"size\":3}\n", +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", +/// ) +/// ); +/// let mut reader = Reader::open(&bytes[..])?; +/// assert!(matches!(reader.next(), Some(Ok(Object::File(object))) if *object == file)); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct Writer { + out: W, + /// The text of the record that goes out next. The room for it is kept + /// from one record to the next. + text: String, + encoder: Encoder, +} + +impl Writer { + /// Starts a manifest in `out` with the root file object `root`. + pub fn begin(out: W, root: &RootObject) -> Result, Error> { + let mut text = String::new(); + let encoder = Encoder::begin(root, &mut text)?; + let mut writer = Writer { out, text, encoder }; + writer.write_out(ROOT_RECORD)?; + Ok(writer) + } + + /// Writes the file object `file`. + pub fn file(&mut self, file: &FileObject) -> Result<(), Error> { + self.send_record(|encoder, text| encoder.file(file, text)) + } + + /// Writes a signature object. No file object can follow it: it would + /// be one the signature does not cover. + pub fn signature(&mut self, signature: &Signature) -> Result<(), Error> { + self.send_record(|encoder, text| encoder.signature(signature, text)) + } + + /// Ends the manifest with the trailer object, flushes what it was + /// written to and returns it. + pub fn finish(mut self) -> Result { + let record_number = self.encoder.next_record; + self.send_record(|encoder, text| encoder.finish(text))?; + self.out.flush().map_err(|e| Error::from(e).in_record(record_number))?; + Ok(self.out) + } + + /// What the manifest is written to. Every method writes its record to + /// it before it returns, so it has the manifest up to the last record. + /// Before the first signature object, that is what the signature + /// objects sign. + pub fn get_ref(&self) -> &W { + &self.out + } + + /// Writes out the record that `encode` has the encoder append to the + /// text. When the encoder took it back as too large, the text gives + /// back the room it took. + fn send_record( + &mut self, + encode: impl FnOnce(&mut Encoder, &mut String) -> Result<(), Error>, + ) -> Result<(), Error> { + let record_number = self.encoder.next_record; + match encode(&mut self.encoder, &mut self.text) { + Ok(()) => self.write_out(record_number), + Err(e) => { + self.text.shrink_to(TEXT_CAPACITY); + Err(e) + } + } + } + + /// Writes out the text, the record with the number `record_number`, in + /// one write, and empties it for the next record. A record larger than + /// [`TEXT_CAPACITY`] gives back the room it took beyond that. + fn write_out(&mut self, record_number: u64) -> Result<(), Error> { + let written = self.out.write_all(self.text.as_bytes()); + self.text.clear(); + self.text.shrink_to(TEXT_CAPACITY); + written.map_err(|e| Error::from(e).in_record(record_number)) + } +} + +/// Puts a manifest together record by record, and does no I/O. +/// +/// [`Encoder::begin`] appends the record of the root file object to a +/// string, [`Encoder::file`] the record of a file object, +/// [`Encoder::signature`] that of a signature object and +/// [`Encoder::finish`] that of the trailer object. Whoever calls them sends +/// the records on, each one as it comes or many at once. A [`Writer`] is +/// an encoder whose records go to a [`Write`] one at a time. +/// +/// An encoder checks every object the way a [`Reader`](crate::Reader) +/// does, see [`Writer`], and keeps the name of the last file object for +/// that: at most [`Name::MAX_LEN`] bytes. A method that fails appends +/// nothing, and the encoder goes on as if it had not been called. Nothing +/// can follow the trailer object, so after [`Encoder::finish`] every +/// method fails. +/// +/// ``` +/// use uapi16::{Encoder, FileObject, Name, RootObject}; +/// +/// let mut text = String::new(); +/// let mut encoder = Encoder::begin(&RootObject::default(), &mut text)?; +/// for name in ["a", "b"] { +/// encoder.file(&FileObject::new(Name::new(name)?), &mut text)?; +/// } +/// encoder.finish(&mut text)?; +/// assert_eq!( +/// text, +/// concat!( +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", +/// "\x1e{\"name\":\"a\"}\n", +/// "\x1e{\"name\":\"b\"}\n", +/// "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", +/// ) +/// ); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct Encoder { + /// The number of the record that is appended next. + next_record: u64, + stage: Stage, + /// The check of the file objects so far, which the next one is checked + /// against. + sequence_check: SequenceCheck, +} + +impl Encoder { + /// Starts a manifest with the root file object `root`: appends its + /// record to `text`. + pub fn begin(root: &RootObject, text: &mut String) -> Result { + let sequence_check = SequenceCheck::new(root.recorded_features(), root.order); + let start = text.len(); + // In the order a reader finds what is wrong with the record, see + // Encoder::file(). + Encoder::write_record(text, |object| root.write(object)) + .and_then(|()| root.check_strings()) + .and_then(|()| root.check()) + .and_then(|()| sequence_check.check_root_fields(root)) + .map_err(|e| { + text.truncate(start); + e.in_record(ROOT_RECORD) + })?; + Ok(Encoder { + next_record: ROOT_RECORD + 1, + stage: Stage::Files, + sequence_check, + }) + } + + /// Appends the record of the file object `file` to `text`. + pub fn file(&mut self, file: &FileObject, text: &mut String) -> Result<(), Error> { + let record_number = self.next_record; + if self.stage == Stage::Done { + return Err(Error::data_after_trailer(record_number)); + } + // An object with more than one fault is refused for the one a + // reader finds first in its record: a record too large before it + // is read, then a string its JSON parser refuses or a key it sees + // twice in an object, a file object after a signature, the values + // of the fields in the order of their keys, a missing name, a field + // its inode type does not permit, fields that contradict each + // other, a field of a feature the manifest does not record, a + // symbolic link without its target, gptFlags against the fields of + // its flags, and where it comes. So the record is put together + // first. Admitting the object makes it the one the next one is + // checked against, which comes last. + let start = text.len(); + let appended = Encoder::write_record(text, |object| file.write(object)) + .and_then(|()| file.check_strings(record_number)) + .and_then(|()| match self.stage { + Stage::Signatures => Err(Error::file_after_signature(record_number)), + _ => Ok(()), + }) + .and_then(|()| file.check(record_number)) + .and_then(|()| self.sequence_check.check_fields(file, record_number)) + .and_then(|()| self.sequence_check.admit(file, record_number)); + if let Err(e) = appended { + text.truncate(start); + let e = e.in_record(record_number); + return Err(if file.name.is_root() { + e + } else { + e.named(file.name.as_str()) + }); + } + self.next_record += 1; + Ok(()) + } + + /// Appends the record of the signature object `signature` to `text`. + /// No file object can follow it: it would be one the signature does + /// not cover. + pub fn signature(&mut self, signature: &Signature, text: &mut String) -> Result<(), Error> { + let record_number = self.next_record; + if self.stage == Stage::Done { + return Err(Error::data_after_trailer(record_number)); + } + let start = text.len(); + Encoder::write_record(text, |object| signature.write(object)) + .and_then(|()| { + Field::Mechanism.check_string( + &signature.mechanism, + format_args!("manifest signature object {}", record_number), + ) + }) + .map_err(|e| { + text.truncate(start); + e.in_record(record_number) + })?; + self.stage = Stage::Signatures; + self.next_record += 1; + Ok(()) + } + + /// Ends the manifest: appends the record of the trailer object to + /// `text`. + pub fn finish(&mut self, text: &mut String) -> Result<(), Error> { + let record_number = self.next_record; + if self.stage == Stage::Done { + return Err(Error::data_after_trailer(record_number)); + } + Encoder::write_record(text, |object| { + FieldWriter::new(object, FilledIn::default()).string(Field::MediaType, Some(TRAILER_MEDIA_TYPE)); + }) + .map_err(|e| e.in_record(record_number))?; + self.stage = Stage::Done; + self.next_record += 1; + Ok(()) + } + + /// Appends a record to `text`, the members of whose object `members` + /// writes. A record larger than [`MAX_RECORD_SIZE`], its record + /// separator included, is refused and taken back. + fn write_record(text: &mut String, members: impl FnOnce(&mut ObjectWriter<'_>)) -> Result<(), Error> { + let start = text.len(); + text.push(char::from(RECORD_SEPARATOR)); + members(&mut ObjectWriter::new(text)); + text.push(char::from(RECORD_END)); + if text.len() - start > MAX_RECORD_SIZE { + text.truncate(start); + return Err(Error::record_too_large()); + } + Ok(()) + } +} + +/// Writes the fields of an object of a manifest in the order they come, +/// and leaves out every field a reader filled in, whatever the field. +struct FieldWriter<'w, 'o> { + object: &'w mut ObjectWriter<'o>, + /// The fields a reader filled in, of the object and of the parts it + /// has, such as its inode attributes. + filled_in: FilledIn, +} + +impl<'w, 'o> FieldWriter<'w, 'o> { + /// Writes the fields of an object into `object`, but none of those of + /// `filled_in`. + fn new(object: &'w mut ObjectWriter<'o>, filled_in: FilledIn) -> FieldWriter<'w, 'o> { + FieldWriter { object, filled_in } + } + + /// Starts the member of the field `field`, unless a reader filled the + /// field in. + fn field(&mut self, field: Field) -> Option> { + (!self.filled_in.contains(field)).then(|| self.object.key(field.as_str())) + } + + /// What is written of `value`, the value of `field`: nothing where a + /// reader filled the field in. + fn written(&self, field: Field, value: Option) -> Option { + value.filter(|_| !self.filled_in.contains(field)) + } + + /// Writes `value`, if there is one, with `write` as the field `field`. + fn put(&mut self, field: Field, value: Option, write: impl FnOnce(ValueWriter<'_>, T)) { + if let Some(value) = value { + if let Some(member) = self.field(field) { + write(member, value); + } + } + } + + /// Writes the integer `value`, if there is one, as the field `field`. + fn unsigned(&mut self, field: Field, value: Option) { + self.put(field, value, |member, value| member.unsigned(value)); + } + + /// Writes the boolean `value`, if there is one, as the field `field`. + fn bool(&mut self, field: Field, value: Option) { + self.put(field, value, |member, value| member.bool(value)); + } + + /// Writes the string `value`, if there is one, as the field `field`. + fn string(&mut self, field: Field, value: Option<&str>) { + self.put(field, value, |member, value| member.string(value)); + } + + /// Writes what `value` prints, if there is a value, as the field + /// `field`. + fn display(&mut self, field: Field, value: Option) { + self.put(field, value, |member, value| member.display(value)); + } +} + +impl Field { + /// Checks `value`, a string in this field of the object `subject` + /// names: it has none of what the strings of a manifest may not have. + fn check_string(self, value: &str, subject: impl fmt::Display) -> Result<(), Error> { + if STRING_RULES.admits(value) { + return Ok(()); + } + Err(Error::manifest( + Problem::InvalidString, + format!("{}: '{}' has a NUL or a noncharacter in a string", subject, self), + ) + .at(self)) + } +} + +// The specification asks generators to leave out a field that is set to +// its default, so that file objects that describe the same file compare +// as equivalent. It recommends leaving out the hash of no data next to +// the size 0, and says that without an encoding the encoded size and +// hash should not be there. They are left out next to the original ones, +// and one that is the only statement of the size or the hash goes out. +// Where a manifest records the feature of a field, +// which it does where an object has the field, an object without it has a +// flag cleared, is not read-only, has a `gptFlags` of 0 and no extended +// attributes. So these go out only where they say more. + +impl RootObject { + /// Checks every string the record of the root file object has, in the + /// order of the keys, for what the strings of a manifest may not hold. + fn check_strings(&self) -> Result<(), Error> { + let subject = Subject::root(); + self.inode.check_xattr_strings(subject)?; + if let Some(label) = &self.file_system.label { + Field::FsLabel.check_string(label, subject)?; + } + self.inode.check_owner_strings(subject) + } + + /// Checks the root file object as a reader does: the value of every + /// field, in the order of the keys, and the fields against each other. + fn check(&self) -> Result<(), Error> { + let subject = Subject::root(); + let inode = &self.inode; + inode.check_xattr_names(subject)?; + if let Some(label) = &self.file_system.label { + FileSystemIdentity::check_label(label, subject)?; + } + if let Some(gid) = inode.gid { + FileObject::check_id(Field::Gid, u64::from(gid), subject)?; + } + if let Some(name) = &inode.group_name { + FileObject::check_owner_name(Field::GroupName, name, subject)?; + } + if let Some(uid) = inode.uid { + FileObject::check_id(Field::Uid, u64::from(uid), subject)?; + } + if let Some(name) = &inode.user_name { + FileObject::check_owner_name(Field::UserName, name, subject)?; + } + self.check_consistency() + } + + /// Writes the fields of the root file object in the order of their + /// names. It has the media type of a manifest, and neither a name nor a + /// type: it is a directory. + fn write(&self, object: &mut ObjectWriter<'_>) { + let mut fields = FieldWriter::new(object, self.inode.filled_in); + let inode = &self.inode; + let identity = &self.file_system; + inode.write_xattrs(&mut fields); + fields.display(Field::FatSerial, identity.fat_serial); + if let Some(listed) = self.features.filter(|listed| *listed != Features::DEFAULT) { + if let Some(member) = fields.field(Field::Features) { + let mut array = member.array(); + for name in listed.names() { + array.element().string(name); + } + } + } + for field in inode.flags.set_fields() { + fields.bool(field, Some(true)); + } + fields.string(Field::FsLabel, identity.label.as_deref()); + fields.display(Field::FsUuid, identity.uuid); + fields.unsigned(Field::Gid, inode.gid.map(u64::from)); + fields.display(Field::GptDiskUuid, self.gpt_disk_uuid); + fields.string(Field::GroupName, inode.group_name.as_deref()); + fields.unsigned(Field::MTimeNSec, inode.mtime_nsec); + fields.string(Field::MediaType, Some(MEDIA_TYPE)); + fields.unsigned(Field::Mode, inode.mode.map(|mode| u64::from(mode.bits()))); + fields.string(Field::Order, self.order.map(Order::as_str)); + fields.bool(Field::ReadOnly, inode.read_only.filter(|&read_only| read_only)); + fields.unsigned(Field::Uid, inode.uid.map(u64::from)); + fields.string(Field::UserName, inode.user_name.as_deref()); + self.validity.write(&mut fields); + } +} + +impl FileObject { + /// Checks every string the record of the object, the one with the + /// number `record_number`, has, in the order of the keys, for what the + /// strings of a manifest may not hold. + fn check_strings(&self, record_number: u64) -> Result<(), Error> { + let subject = Subject::new(self, record_number); + for contents in &self.contents { + contents.check_strings(subject)?; + } + self.inode.check_xattr_strings(subject)?; + if let Some(label) = self.gpt.as_deref().and_then(|gpt| gpt.label.as_deref()) { + Field::GptLabel.check_string(label, subject)?; + } + self.inode.check_owner_strings(subject) + } + + /// Checks the object, the one of the record with the number + /// `record_number`, as a reader does: the value of every field in the + /// order of the keys, each contents object's fields against each other + /// right after its values, the name, the fields its inode type permits + /// and the fields against each other. Unlike a reader it fills nothing + /// in. + fn check(&self, record_number: u64) -> Result<(), Error> { + let subject = Subject::new(self, record_number); + if self.contents.len() > MAX_CONTENTS { + return Err(Error::too_many_contents(subject)); + } + for contents in &self.contents { + contents.check(subject)?; + contents.check_consistency(subject)?; + } + let inode = &self.inode; + inode.check_xattr_names(subject)?; + if let Some(gid) = inode.gid { + FileObject::check_id(Field::Gid, u64::from(gid), subject)?; + } + if let Some(label) = self.gpt.as_deref().and_then(|gpt| gpt.label.as_deref()) { + GptPartition::check_label(label, subject)?; + } + if let Some(name) = &inode.group_name { + FileObject::check_owner_name(Field::GroupName, name, subject)?; + } + if let Some(uid) = inode.uid { + FileObject::check_id(Field::Uid, u64::from(uid), subject)?; + } + if let Some(name) = &inode.user_name { + FileObject::check_owner_name(Field::UserName, name, subject)?; + } + if self.name.is_root() { + return Err(Error::no_name(record_number)); + } + self.check_permitted_fields(subject)?; + // The contents objects were checked above. This is for what + // follows from them. + self.check_consistency(subject, |contents| contents.check_consistency(subject))?; + Ok(()) + } + + /// Writes the fields of the object in the order of their names. + fn write(&self, object: &mut ObjectWriter<'_>) { + let mut fields = FieldWriter::new(object, self.filled_in.union(self.inode.filled_in)); + let inode = &self.inode; + let gpt = self.gpt.as_deref(); + if !self.contents.is_empty() { + if let Some(member) = fields.field(Field::Contents) { + let mut array = member.array(); + for contents in &self.contents { + contents.write(array.element()); + } + } + } + inode.write_xattrs(&mut fields); + self.write_flags(&mut fields); + fields.unsigned(Field::Gid, inode.gid.map(u64::from)); + fields.bool( + Field::GptFlagGrowFileSystem, + gpt.and_then(|gpt| gpt.grow_file_system).filter(|&set| set), + ); + fields.bool(Field::GptFlagNoAuto, gpt.and_then(|gpt| gpt.no_auto).filter(|&set| set)); + fields.unsigned( + Field::GptFlags, + gpt.and_then(|gpt| gpt.flags).filter(|&flags| flags != 0), + ); + fields.string(Field::GptLabel, gpt.and_then(|gpt| gpt.label.as_deref())); + fields.display(Field::GptTypeUuid, gpt.and_then(|gpt| gpt.type_uuid)); + fields.display(Field::GptUuid, gpt.and_then(|gpt| gpt.uuid)); + fields.string(Field::GroupName, inode.group_name.as_deref()); + fields.unsigned(Field::InodeToken, self.inode_token.map(NonZeroU64::get)); + fields.unsigned(Field::MTimeNSec, inode.mtime_nsec); + fields.unsigned(Field::Major, self.major); + fields.unsigned(Field::Minor, self.minor); + fields.unsigned(Field::Mode, inode.mode.map(|mode| u64::from(mode.bits()))); + fields.string(Field::Name, (!self.name.is_root()).then_some(self.name.as_str())); + fields.bool(Field::ReadOnly, inode.read_only.filter(|&read_only| read_only)); + let size = fields.written(Field::Size, self.size); + let sha256 = fields.written(Field::Sha256, self.sha256.as_ref()); + fields.display(Field::Sha256, sha256.filter(|sha256| !sha256.implied_by(size))); + fields.unsigned(Field::Size, size); + // The specification implies the type of a regular file. + let inode_type = Some(self.inode_type).filter(|&inode_type| inode_type != InodeType::Regular); + fields.string(Field::Type, inode_type.map(InodeType::as_str)); + fields.unsigned(Field::Uid, inode.uid.map(u64::from)); + fields.string(Field::UserName, inode.user_name.as_deref()); + self.validity.write(&mut fields); + } + + /// Writes the fields of the flags that are set, of the DOS attributes + /// and of the inode flags. In the order of their names the two kinds + /// mix, so the fields of the two, each kind in that order, are merged. + fn write_flags(&self, fields: &mut FieldWriter<'_, '_>) { + let mut dos = self.dos_flags.set_fields(); + let mut inode = self.inode.flags.set_fields(); + let (mut next_dos, mut next_inode) = (dos.next(), inode.next()); + loop { + let field = match (next_dos, next_inode) { + (Some(first), Some(second)) if second.as_str() < first.as_str() => { + next_inode = inode.next(); + second + } + (Some(first), _) => { + next_dos = dos.next(); + first + } + (None, Some(second)) => { + next_inode = inode.next(); + second + } + (None, None) => break, + }; + fields.bool(field, Some(true)); + } + } +} + +impl InodeAttributes { + /// The names of the extended attributes, in the order they are + /// written. + fn xattr_names(&self) -> impl Iterator { + self.user_xattrs.iter().flat_map(|attributes| attributes.keys()) + } + + /// Checks the names of the extended attributes of the object `subject` + /// names for what the strings of a manifest may not hold. + fn check_xattr_strings(&self, subject: Subject<'_>) -> Result<(), Error> { + self.xattr_names() + .try_for_each(|name| Field::ExtendedAttributes.check_string(name, subject)) + } + + /// Checks `groupName` and `userName`, in that order, for what the + /// strings of a manifest may not hold. + fn check_owner_strings(&self, subject: Subject<'_>) -> Result<(), Error> { + if let Some(name) = &self.group_name { + Field::GroupName.check_string(name, subject)?; + } + if let Some(name) = &self.user_name { + Field::UserName.check_string(name, subject)?; + } + Ok(()) + } + + /// Checks the names of the extended attributes as a reader does. + fn check_xattr_names(&self, subject: Subject<'_>) -> Result<(), Error> { + self.xattr_names() + .try_for_each(|name| FileObject::check_xattr_name(name, subject)) + } + + /// Writes `extendedAttributes`, unless there are none. A value goes out + /// as text if it is a string a manifest can have, and as Base64 + /// otherwise. + fn write_xattrs(&self, fields: &mut FieldWriter<'_, '_>) { + let Some(attributes) = self.user_xattrs.as_deref().filter(|attributes| !attributes.is_empty()) else { + return; + }; + let Some(member) = fields.field(Field::ExtendedAttributes) else { + return; + }; + let mut namespaces = member.object(); + let mut user = namespaces.key(USER_NAMESPACE).object(); + for (name, value) in attributes { + let mut value_object = user.key(name).object(); + match std::str::from_utf8(value) { + Ok(text) if STRING_RULES.admits(text) => value_object.key(Field::Text.as_str()).string(text), + _ => value_object.key(Field::Base64.as_str()).display(Base64(value)), + } + } + } +} + +impl FlagStates { + /// The fields of the flags that are set, in the order of their names. + fn set_fields(self) -> impl Iterator { + F::FIELDS + .iter() + .filter(move |&&(flag, _, _)| self.get(flag) == Some(true)) + .map(|&(_, field, _)| field) + } +} + +impl ValidityWindow { + /// Writes the fields of the window in the order of their names, which + /// are the last ones of the root file object and of a file object. A + /// `validSinceUSec` of 0 and a `validity` of good are what the + /// specification implies. + fn write(&self, fields: &mut FieldWriter<'_, '_>) { + fields.unsigned(Field::ValidSinceUSec, Some(self.since_usec).filter(|&since| since != 0)); + fields.unsigned(Field::ValidUntilUSec, self.until_usec); + let state = Some(self.state).filter(|&state| state != Validity::Good); + fields.string(Field::Validity, state.map(Validity::as_str)); + } +} + +impl Contents { + /// Checks every string of the contents object, one of those of the + /// file object `subject` names, in the order of the keys, for what the + /// strings of a manifest may not hold, and its header fields for two of + /// the same name, which a JSON parser refuses as a key given twice. + fn check_strings(&self, subject: Subject<'_>) -> Result<(), Error> { + if let Some(encoding) = &self.encoding { + Field::Encoding.check_string(encoding, subject)?; + } + // The header fields go out in the order of their names, and a JSON + // parser refuses a name it saw before in the same object. + let mut previous: Option<&str> = None; + for (name, value) in self.sorted_headers() { + Field::HttpHeaders.check_string(name, subject)?; + if previous == Some(name) { + return Err(Error::manifest( + Problem::DuplicateKey, + format!( + "{}: HTTP header field '{}' is given twice", + subject, + name.escape_debug() + ), + ) + .at(Field::HttpHeaders)); + } + Field::HttpHeaders.check_string(value, subject)?; + previous = Some(name); + } + match self.url() { + Some(url) => Field::Url.check_string(url, subject), + None => Ok(()), + } + } + + /// Checks the contents object, one of those of the file object + /// `subject` names, as a reader does: the value of every field, in the + /// order of the keys. [`Contents::check_consistency`] checks the fields + /// against each other. + fn check(&self, subject: Subject<'_>) -> Result<(), Error> { + if let Some(encoding) = &self.encoding { + Contents::check_encoding(encoding, subject)?; + } + // A reader checks the header fields in the order they are written. + if !self.http_headers.is_empty() { + Contents::check_headers(self.sorted_headers(), subject)?; + } + match self.url() { + Some(url) => Contents::check_url(url, subject), + None => Ok(()), + } + } + + /// The header fields in the order of their names, which is the order + /// they are written in. + fn sorted_headers(&self) -> Vec<&(String, String)> { + let mut headers: Vec<&(String, String)> = self.http_headers.iter().collect(); + headers.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); + headers + } + + /// Writes the contents object, its fields in the order of their names. + /// Of the sizes and hashes it leaves out what a reader filled in, the + /// hash of no data next to the size 0, and without an encoding the + /// encoded size and hash where the original ones say the same. A reader + /// fills them in again. + fn write(&self, value: ValueWriter<'_>) { + let mut object = value.object(); + let mut fields = FieldWriter::new(&mut object, self.filled_in); + let original_size = fields.written(Field::OriginalSize, self.original_size); + let original_sha256 = fields + .written(Field::OriginalSha256, self.original_sha256.as_ref()) + .filter(|sha256| !sha256.implied_by(original_size)); + let mut encoded_size = fields.written(Field::EncodedSize, self.encoded_size); + let mut encoded_sha256 = fields + .written(Field::EncodedSha256, self.encoded_sha256.as_ref()) + .filter(|sha256| !sha256.implied_by(encoded_size)); + if self.encoding.is_none() { + // The data is stored as it is, so the original size and hash + // are the encoded ones. The size 0 says the hash too. + if original_size.is_some() { + encoded_size = None; + } + if original_sha256.is_some() || original_size == Some(0) { + encoded_sha256 = None; + } + } + fields.display(Field::EncodedSha256, encoded_sha256); + fields.unsigned(Field::EncodedSize, encoded_size); + fields.string(Field::Encoding, self.encoding.as_deref()); + fields.string(Field::File, self.file().map(Name::as_str)); + if !self.http_headers.is_empty() { + if let Some(member) = fields.field(Field::HttpHeaders) { + let mut members = member.object(); + for (name, value) in self.sorted_headers() { + members.key(name).string(value); + } + } + } + fields.display(Field::Literal, self.literal().map(Base64)); + // The specification implies an offset of 0. + fields.unsigned(Field::Offset, Some(self.offset).filter(|&offset| offset != 0)); + fields.display(Field::OriginalSha256, original_sha256); + fields.unsigned(Field::OriginalSize, original_size); + fields.string(Field::Url, self.url()); + } +} + +impl Sha256 { + /// Whether the size `size` says the hash: it is 0, and the hash is + /// the hash of no data. + fn implied_by(&self, size: Option) -> bool { + size == Some(0) && *self == Sha256::EMPTY + } +} + +impl Signature { + /// Writes the fields of the signature object in the order of their + /// names. + fn write(&self, object: &mut ObjectWriter<'_>) { + let mut fields = FieldWriter::new(object, FilledIn::default()); + fields.display(Field::Data, self.data.as_deref().map(Base64)); + fields.display(Field::Key, self.key.as_deref().map(Hex)); + fields.string(Field::Mechanism, Some(&self.mechanism)); + fields.string(Field::MediaType, Some(SIGNATURE_MEDIA_TYPE)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::ErrorKind; + use crate::object::{DosFlags, FatSerial, InodeFlags, Location, Mode, Uuid}; + use crate::testing::{read_whole, sequence, write_whole, Whole, EMPTY, HELLO, ROOT, SIGNATURE, TRAILER}; + use crate::{Reader, Sha256}; + use std::collections::BTreeMap; + use std::io; + + fn name(name: &str) -> Name { + Name::new(name).unwrap() + } + + /// The records `writer` wrote after `root`, without the frame of + /// each: the separator in front and the newline behind. + fn written(root: &RootObject, write: impl FnOnce(&mut Writer>)) -> Vec { + let mut writer = Writer::begin(Vec::new(), root).unwrap(); + write(&mut writer); + let text = String::from_utf8(writer.finish().unwrap()).unwrap(); + let separator = char::from(RECORD_SEPARATOR); + assert!(text.starts_with(separator)); + text.split(separator) + .skip(1) + .map(|record| record.strip_suffix(char::from(RECORD_END)).unwrap().to_string()) + .collect() + } + + /// The root file object of a manifest that records every feature, and + /// its record. + fn recording_all() -> (RootObject, String) { + let root = RootObject { + features: Some(Features::ALL), + ..RootObject::default() + }; + let names: Vec = Features::ALL.names().map(|name| format!("\"{}\"", name)).collect(); + let text = format!( + r#"{{"features":[{}],"mediaType":"application/vnd.uapi.16.manifest"}}"#, + names.join(",") + ); + (root, text) + } + + /// A directory that says nothing else about itself. + fn directory(name_of: &str) -> FileObject { + let mut directory = FileObject::new(name(name_of)); + directory.inode_type = InodeType::Directory; + directory + } + + /// The record the writer writes for `object`, in a manifest that + /// records every feature, after the objects of the directories it is + /// in. + fn record(object: &FileObject) -> String { + let (root, root_text) = recording_all(); + let directories: Vec = object + .name + .match_indices('/') + .map(|(end, _)| directory(&object.name[..end])) + .collect(); + let mut records = written(&root, |writer| { + for directory in &directories { + writer.file(directory).unwrap(); + } + writer.file(object).unwrap(); + }); + assert_eq!(records.len(), directories.len() + 3); + assert_eq!(records[0], root_text); + assert_eq!(records.pop().as_deref(), Some(TRAILER)); + records.pop().unwrap() + } + + /// What `systemd-manifest` writes, see the manifests in tests/fixtures: + /// the same objects give the same records. + #[test] + fn writes_records_the_way_systemd_does() { + // What systemd-manifest writes with --field=default,+mtime, with + // the features and the order the specification has since: compact, + // keys sorted, numbers in decimal. A manifest that records extended + // attributes needs no empty namespace for a file that has none. + let mut root = RootObject { + features: Some( + Features::from_names([ + "device", + "gid", + "hardlink", + "mode", + "mtime", + "sha256", + "size", + "symlink", + "uid", + "user-xattr", + ]) + .unwrap(), + ), + order: Some(Order::CodePoint), + ..RootObject::default() + }; + root.inode.user_xattrs = Some(Box::default()); + root.inode.gid = Some(1000); + root.inode.mtime_nsec = Some(1_699_999_000_000_000_000); + root.inode.mode = Mode::new(0o775); + root.inode.uid = Some(1000); + let owned_directory = |name_of: &str| { + let mut owned = directory(name_of); + owned.inode.user_xattrs = Some(Box::default()); + owned.inode.gid = Some(1000); + owned.inode.mtime_nsec = Some(1_699_999_000_000_000_000); + owned.inode.mode = Mode::new(0o775); + owned.inode.uid = Some(1000); + owned + }; + let mut file = FileObject::new(name("EFI/BOOT/BOOTX64.EFI")); + file.inode.user_xattrs = Some(Box::default()); + file.inode.gid = Some(1000); + file.inode.mtime_nsec = Some(1_700_000_000_000_000_000); + file.inode.mode = Mode::new(0o664); + file.sha256 = "608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b" + .parse() + .ok(); + file.size = Some(4096); + file.inode.uid = Some(1000); + let records = written(&root, |writer| { + writer.file(&owned_directory("EFI")).unwrap(); + writer.file(&owned_directory("EFI/BOOT")).unwrap(); + writer.file(&file).unwrap(); + }); + assert_eq!( + records, + [ + concat!( + r#"{"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","#, + r#""user-xattr"],"gid":1000,"mTimeNSec":1699999000000000000,"#, + r#""mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000}"# + ), + r#"{"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI","type":"dir","uid":1000}"#, + concat!( + r#"{"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/BOOT","type":"dir","#, + r#""uid":1000}"# + ), + concat!( + r#"{"gid":1000,"mTimeNSec":1700000000000000000,"#, + r#""mode":436,"name":"EFI/BOOT/BOOTX64.EFI","#, + r#""sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","#, + r#""size":4096,"uid":1000}"# + ), + TRAILER, + ] + ); + // A symbolic link with its target, a file with an attribute, the + // names of one hard-linked file. + let mut link = FileObject::new(name("link")); + link.inode_type = InodeType::Symlink; + link.contents = vec![Contents::new(Location::Literal(b"a.txt".to_vec()))]; + link.inode.gid = Some(1000); + link.inode.group_name = Some("brauner".into()); + link.size = Some(5); + link.inode.user_name = Some("brauner".into()); + assert_eq!( + record(&link), + concat!( + r#"{"contents":[{"literal":"YS50eHQ="}],"gid":1000,"groupName":"brauner","name":"link","#, + r#""size":5,"type":"lnk","userName":"brauner"}"# + ) + ); + let mut noted = FileObject::new(name("a.txt")); + noted.inode.user_xattrs = Some(Box::new(BTreeMap::from([( + "comment".to_string(), + b"set by make-fixtures".to_vec(), + )]))); + assert_eq!( + record(¬ed), + r#"{"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"name":"a.txt"}"# + ); + let mut linked = FileObject::new(name("sub/hl_a")); + linked.inode_token = NonZeroU64::new(1); + linked.size = Some(11); + assert_eq!(record(&linked), r#"{"inodeToken":1,"name":"sub/hl_a","size":11}"#); + let mut fifo = FileObject::new(name("sub/fifo")); + fifo.inode_type = InodeType::Fifo; + assert_eq!(record(&fifo), r#"{"name":"sub/fifo","type":"fifo"}"#); + // The least a manifest and an object are. + assert_eq!(record(&FileObject::new(name("x"))), r#"{"name":"x"}"#); + let empty = Writer::begin(Vec::new(), &RootObject::default()) + .unwrap() + .finish() + .unwrap(); + assert_eq!(empty, sequence(&[ROOT, TRAILER])); + } + + /// Where a manifest records the feature of a field, an object without + /// the field says what the field's default is. The writer leaves those + /// fields out, and a reader reads back what they said. + #[test] + fn leaves_out_what_the_features_imply() { + let mut object = FileObject::new(name("x")); + object.dos_flags.put(DosFlags::HIDDEN, Some(false)); + object.inode.flags.put(InodeFlags::NO_DUMP, Some(false)); + object.inode.read_only = Some(false); + object.inode.user_xattrs = Some(Box::default()); + object.gpt = Some(Box::new(GptPartition { + flags: Some(0), + no_auto: Some(false), + grow_file_system: Some(false), + ..GptPartition::default() + })); + assert_eq!(record(&object), r#"{"name":"x"}"#); + let (root, _) = recording_all(); + let whole = Whole { + root, + objects: vec![object.clone()], + signatures: Vec::new(), + }; + let read = read_whole(&write_whole(&whole).unwrap()).unwrap().objects.remove(0); + assert_eq!(read.dos_flags.get(DosFlags::HIDDEN), Some(false)); + assert_eq!(read.inode.flags.get(InodeFlags::NO_DUMP), Some(false)); + assert_eq!(read.inode.read_only, Some(false)); + assert_eq!(read.inode.user_xattrs.as_deref(), Some(&BTreeMap::new())); + // A reader leaves the fields of a partition as they are: a regular + // file without any is no partition, whose flags the manifest says + // are cleared. + assert_eq!(read.gpt, None); + // What a manifest does not record, an object cannot have, whatever + // it says. + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.file(&object).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::UnlistedFeature)); + } + + /// An object with every field there is, and one of its contents + /// objects with every field. + fn everything() -> FileObject { + let uuid = |last: u8| { + let mut bytes = [0x11; Uuid::SIZE]; + bytes[Uuid::SIZE - 1] = last; + Uuid::new(bytes) + }; + let mut encoded = Contents::new(Location::File(name("blob.gz"))); + encoded.encoding = Some("gzip".into()); + encoded.encoded_size = Some(3); + encoded.encoded_sha256 = Some(Sha256::digest(b"gz")); + encoded.original_size = Some(9); + encoded.original_sha256 = Some(Sha256::digest(b"original")); + encoded.offset = 4; + let mut object = FileObject::new(name("a/\u{e9} \"quoted\"\\")); + object.size = Some(5); + object.inode.mode = Mode::new(0o440); + object.inode.uid = Some(1); + object.inode.gid = Some(2); + object.inode.user_name = Some("user".into()); + object.inode.group_name = Some("group".into()); + object.inode.mtime_nsec = Some(u64::MAX); + object.inode_token = NonZeroU64::new(3); + object.inode.user_xattrs = Some(Box::new(BTreeMap::from([ + ("text".to_string(), b"value".to_vec()), + ("empty".to_string(), Vec::new()), + ("binary".to_string(), vec![0xff, 0x00]), + ("nul".to_string(), b"a\0b".to_vec()), + ("noncharacter".to_string(), "a\u{fffe}".as_bytes().to_vec()), + ]))); + // Flags of both kinds, which mix in the order of their names. + object.inode.flags.put(InodeFlags::APPEND_ONLY, Some(true)); + object.dos_flags.put(DosFlags::ARCHIVE, Some(false)); + object.dos_flags.put(DosFlags::HIDDEN, Some(true)); + object.inode.flags.put(InodeFlags::IMMUTABLE, Some(true)); + object.inode.flags.put(InodeFlags::NO_COW, Some(false)); + object.dos_flags.put(DosFlags::SYSTEM, Some(true)); + // The partition is read-only, which gptFlags says as well where the + // manifest records both. + object.gpt = Some(Box::new(GptPartition { + label: Some("label".into()), + uuid: Some(uuid(1)), + type_uuid: Some(uuid(2)), + flags: Some( + GptPartition::FLAG_NO_AUTO | GptPartition::FLAG_GROW_FILE_SYSTEM | GptPartition::FLAG_READ_ONLY, + ), + no_auto: Some(true), + grow_file_system: Some(true), + })); + object.inode.read_only = Some(true); + object.contents = vec![ + encoded, + Contents { + http_headers: vec![ + ("X-Foo".into(), "bar".into()), + ("Authorization".into(), "Bearer x".into()), + ], + ..Contents::new(Location::Url("https://example.com/blob".into())) + }, + Contents::new(Location::Literal(b"hello".to_vec())), + Contents::default(), + ]; + object.sha256 = HELLO.parse().ok(); + object.validity.since_usec = 6; + object.validity.until_usec = Some(7); + object.validity.state = Validity::Revoked; + object + } + + /// Checks that the keys of every object in `value` are in the order of + /// their bytes. + fn sorted(value: &json::Value) { + match value { + json::Value::Object(object) => { + let keys: Vec<&str> = object.keys().collect(); + assert!( + keys.windows(2).all(|pair| pair[0].as_bytes() < pair[1].as_bytes()), + "{:?}", + keys + ); + object.iter().for_each(|(_, value)| sorted(value)); + } + json::Value::Array(items) => items.iter().for_each(sorted), + _ => {} + } + } + + #[test] + fn keys_are_sorted_and_nothing_is_lost() { + let object = everything(); + let mut device = FileObject::new(name("dev/null")); + device.inode_type = InodeType::CharDevice; + device.major = Some(1); + device.minor = Some(3); + let (mut root, _) = recording_all(); + root.order = Some(Order::CodePoint); + root.gpt_disk_uuid = Some(Uuid::new([0xab; Uuid::SIZE])); + root.file_system = FileSystemIdentity { + uuid: Some(Uuid::new([0xcd; Uuid::SIZE])), + label: Some("ESP".into()), + fat_serial: Some(FatSerial(0x1234_abcd)), + }; + root.inode.mtime_nsec = Some(0); + let mut signature = Signature::new("pkcs7"); + signature.key = Some(vec![0xde, 0xad]); + signature.data = Some(vec![1, 2, 3, 4]); + let objects = [directory("a"), object.clone(), directory("dev"), device.clone()]; + let records = written(&root, |writer| { + for object in &objects { + writer.file(object).unwrap(); + } + writer.signature(&signature).unwrap(); + writer.signature(&Signature::new("openpgp")).unwrap(); + }); + // No whitespace but the one in the name and in a header, and every + // key in its place. + for record in &records { + assert!( + !record + .replace("a/\u{e9} \\\"quoted", "") + .replace("Bearer x", "") + .contains(char::is_whitespace), + "{}", + record + ); + sorted(&json::parse(record).unwrap()); + } + let whole = json::parse(&records[2]).unwrap(); + let keys: Vec<&str> = whole.as_object().unwrap().keys().collect(); + assert_eq!( + keys, + [ + "contents", + "extendedAttributes", + "flagAppendOnly", + "flagHidden", + "flagImmutable", + "flagSystem", + "gid", + "gptFlagGrowFileSystem", + "gptFlagNoAuto", + "gptFlags", + "gptLabel", + "gptTypeUuid", + "gptUuid", + "groupName", + "inodeToken", + "mTimeNSec", + "mode", + "name", + "readOnly", + "sha256", + "size", + "uid", + "userName", + "validSinceUSec", + "validUntilUSec", + "validity", + ] + ); + // A flag that is set goes out as true. One that is cleared needs + // no field in a manifest that records it. + assert_eq!(whole.get("flagHidden"), Some(&json::Value::Bool(true))); + let contents = whole.get("contents").unwrap().as_array().unwrap(); + let keys: Vec<&str> = contents[0].as_object().unwrap().keys().collect(); + assert_eq!( + keys, + [ + "encodedSha256", + "encodedSize", + "encoding", + "file", + "offset", + "originalSha256", + "originalSize" + ] + ); + assert_eq!( + contents[1].to_string(), + r#"{"httpHeaders":{"Authorization":"Bearer x","X-Foo":"bar"},"url":"https://example.com/blob"}"# + ); + assert_eq!(contents[2].to_string(), r#"{"literal":"aGVsbG8="}"#); + assert_eq!(contents[3].to_string(), "{}"); + let (_, recording) = recording_all(); + let listed = recording + .split_once(r#","mediaType""#) + .unwrap() + .0 + .trim_start_matches('{'); + assert_eq!( + records[0], + format!( + concat!( + r#"{{"fatSerial":"1234-ABCD",{},"fsLabel":"ESP","fsUUID":"cdcdcdcd-cdcd-cdcd-cdcd-cdcdcdcdcdcd","#, + r#""gptDiskUuid":"abababab-abab-abab-abab-abababababab","mTimeNSec":0,"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}}"# + ), + listed + ) + ); + assert_eq!(records[4], r#"{"major":1,"minor":3,"name":"dev/null","type":"chr"}"#); + assert_eq!( + records[5], + r#"{"data":"AQIDBA==","key":"dead","mechanism":"pkcs7","mediaType":"application/vnd.uapi.16.signature"}"# + ); + assert_eq!( + records[6], + r#"{"mechanism":"openpgp","mediaType":"application/vnd.uapi.16.signature"}"# + ); + // A value that is a string of a manifest goes out as text, any + // other as Base64: a NUL or a noncharacter makes it binary. + assert!(records[2].contains(concat!( + r#""extendedAttributes":{"user":{"binary":{"base64":"/wA="},"empty":{"text":""},"#, + r#""noncharacter":{"base64":"Ye+/vg=="},"nul":{"base64":"YQBi"},"text":{"text":"value"}}}"# + ))); + // What was written reads back as what was there, with what the + // features of the manifest say about the fields that are not. + let text: Vec<&str> = records.iter().map(String::as_str).collect(); + let m = read_whole(&sequence(&text)).unwrap(); + let mut expected_root = root.clone(); + expected_root.fill_in(Features::ALL); + assert_eq!(m.root, expected_root); + let mut expected: Vec = objects.to_vec(); + // The reader fills in what follows from a literal: how long it is. + // The header fields went out in the order of their names. + let literal = &mut expected[1].contents[2]; + (literal.encoded_size, literal.original_size) = (Some(5), Some(5)); + literal.filled_in.insert(Field::EncodedSize); + literal.filled_in.insert(Field::OriginalSize); + expected[1].contents[1].http_headers.sort(); + for object in &mut expected { + object.fill_in(Features::ALL); + } + assert_eq!(m.objects, expected); + assert_eq!(m.signatures, [signature, Signature::new("openpgp")]); + assert_eq!(read_whole(&write_whole(&m).unwrap()).unwrap(), m); + } + + #[test] + fn the_order_of_the_objects() { + let kind = |e: Error| match e.kind() { + ErrorKind::Manifest(problem) => (problem, e.record_number(), e.field()), + other => panic!("{:?}", other), + }; + // An object has no flag its inode type does not have: the reader + // says the same. + let mut link = FileObject::new(name("l")); + link.inode_type = InodeType::Symlink; + link.inode.flags.put(InodeFlags::NO_DUMP, Some(false)); + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.file(&link).unwrap_err(); + assert_eq!( + e.to_string(), + "manifest object 1 (l): 'flagNoDump' is not permitted on a lnk" + ); + assert_eq!(kind(e), (Problem::FieldNotPermitted, Some(1), Some(Field::FlagNoDump))); + // Every other file object has a name, and comes before the + // signatures. + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); + assert_eq!(kind(e), (Problem::NoName, Some(1), Some(Field::Name))); + writer.file(&FileObject::new(name("a"))).unwrap(); + writer.signature(&Signature::new("pkcs7")).unwrap(); + let e = writer.file(&FileObject::new(name("b"))).unwrap_err(); + assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); + // As for a reader, that comes before a missing name. + let e = writer.file(&FileObject::new(Name::ROOT)).unwrap_err(); + assert_eq!(kind(e), (Problem::FileAfterSignature, Some(3), None)); + writer.signature(&Signature::new("openpgp")).unwrap(); + let bytes = writer.finish().unwrap(); + let m = read_whole(&bytes).unwrap(); + assert_eq!((m.objects.len(), m.signatures.len()), (1, 2)); + // An object comes right after the object of its directory and in + // the order the manifest declares. One that does not is not + // written, and the next one is checked against the one before it. + let root = RootObject { + order: Some(Order::CodePoint), + ..RootObject::default() + }; + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + writer.file(&FileObject::new(name("b"))).unwrap(); + let e = writer.file(&FileObject::new(name("a"))).unwrap_err(); + assert_eq!(kind(e), (Problem::OutOfOrder, Some(2), None)); + let e = writer.file(&FileObject::new(name("c/d"))).unwrap_err(); + assert_eq!(kind(e), (Problem::Misplaced, Some(2), None)); + writer.file(&directory("c")).unwrap(); + writer.file(&FileObject::new(name("c/d"))).unwrap(); + let m = read_whole(&writer.finish().unwrap()).unwrap(); + let names: Vec<&str> = m.objects.iter().map(|object| object.name.as_str()).collect(); + assert_eq!(names, ["b", "c", "c/d"]); + // What a writer leaves that did not finish is no manifest. + let mut unfinished = Vec::new(); + let mut writer = Writer::begin(&mut unfinished, &RootObject::default()).unwrap(); + writer.file(&FileObject::new(name("a"))).unwrap(); + drop(writer); + let e = read_whole(&unfinished).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NoTrailer)); + } + + /// What is wrong with the root file object is wrong with record 0, as + /// a reader has it. A root file object has neither a name nor another + /// type than a directory, so neither can be wrong. + #[test] + fn errors_of_the_root_file_object() { + let refused = |root: &RootObject| { + let e = Writer::begin(Vec::new(), root).unwrap_err(); + let ErrorKind::Manifest(problem) = e.kind() else { + panic!("{}", e); + }; + (problem, e.record_number(), e.field(), e.to_string()) + }; + let mut root = RootObject::default(); + root.inode.uid = Some(u32::MAX); + assert_eq!( + refused(&root), + ( + Problem::FieldOutOfRange, + Some(0), + Some(Field::Uid), + "manifest object 0 (root): uid 4294967295 is out of range".to_string() + ) + ); + // The fields of the features the specification has had the + // longest and of those it has had the shortest. + let mut root = RootObject::default(); + root.inode.mtime_nsec = Some(1); + assert_eq!(refused(&root).0, Problem::UnlistedFeature); + let mut root = RootObject::default(); + root.file_system.fat_serial = Some(FatSerial(0x1234_abcd)); + assert_eq!( + refused(&root), + ( + Problem::UnlistedFeature, + Some(0), + Some(Field::FatSerial), + concat!( + "manifest object 0 (root): 'fatSerial' is a field of the feature 'fat-serial', ", + "which the manifest does not record" + ) + .to_string() + ) + ); + // readOnly against mode. + let mut root = RootObject { + features: Some(Features::DEFAULT | Features::READ_ONLY), + ..RootObject::default() + }; + root.inode.read_only = Some(true); + root.inode.mode = Mode::new(0o755); + assert_eq!( + refused(&root), + ( + Problem::Contradiction, + Some(0), + Some(Field::ReadOnly), + "manifest object 0 (root): 'readOnly' and 'mode' contradict each other".to_string() + ) + ); + } + + /// What a reader returned goes out as it came in, also where the + /// reader filled in a field of a feature the manifest does not record. + #[test] + fn writes_what_it_read() { + let hello = format!(r#""originalSha256":"{}""#, HELLO); + for (features, record) in [ + // The size 0 follows from the hash of no data, and the other way + // around. + ("sha256", format!(r#"{{"name":"x","sha256":"{}"}}"#, EMPTY)), + ("size", r#"{"name":"x","size":0}"#.to_string()), + // The size of a symbolic link is the length of its target, and + // so are the sizes of its contents object. + ( + "symlink", + r#"{"contents":[{"literal":"YS50eHQ="}],"name":"l","type":"lnk"}"#.to_string(), + ), + // The size of a part follows from the size of the data, and the + // encoded data is the data without an encoding. + ( + "", + r#"{"contents":[{"file":"a","offset":2,"originalSize":7}],"name":"x"}"#.to_string(), + ), + ( + "", + r#"{"contents":[{"encodedSize":5,"file":"a"}],"name":"x"}"#.to_string(), + ), + // The hash of all of the data is the hash of the object. + ( + "size", + format!( + r#"{{"contents":[{{"file":"a",{},"originalSize":5}}],"name":"x","size":5}}"#, + hello + ), + ), + // What a manifest says without the fields of the features it + // records. + ( + r#"flag-hidden","flag-immutable","read-only","user-xattr"#, + r#"{"name":"x"}"#.to_string(), + ), + ] { + let root = format!( + r#"{{"features":[{}],"mediaType":"application/vnd.uapi.16.manifest"}}"#, + Some(features) + .filter(|name| !name.is_empty()) + .map(|name| format!("\"{}\"", name)) + .unwrap_or_default() + ); + let bytes = sequence(&[&root, &record, TRAILER]); + let m = read_whole(&bytes).unwrap(); + assert_eq!( + String::from_utf8(write_whole(&m).unwrap()).unwrap(), + String::from_utf8(bytes).unwrap() + ); + } + // The root file object too. + let root = concat!( + r#"{"features":["flag-immutable","mode","read-only","user-xattr"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","mode":365}"# + ); + let bytes = sequence(&[root, TRAILER]); + let m = read_whole(&bytes).unwrap(); + assert_eq!(m.root.inode.read_only, Some(false)); + assert_eq!(write_whole(&m).unwrap(), bytes); + } + + /// A readOnly a reader filled in is left out like every field a reader + /// fills in, also next to a mode that nobody may write. One the + /// manifest gives would contradict that mode, for the reader and for + /// the writer. + #[test] + fn writes_back_a_read_only_a_reader_filled_in() { + let root = r#"{"features":["mode","read-only"],"mediaType":"application/vnd.uapi.16.manifest","mode":365}"#; + let bytes = sequence(&[root, r#"{"mode":292,"name":"x"}"#, TRAILER]); + let m = read_whole(&bytes).unwrap(); + for inode in [&m.root.inode, &m.objects[0].inode] { + assert_eq!(inode.read_only, Some(false)); + assert!(inode.filled_in.contains(Field::ReadOnly)); + } + assert_eq!(write_whole(&m).unwrap(), bytes); + // Given, it is refused. + let contradiction = |e: Error| (e.kind(), e.field(), e.record_number(), e.to_string()); + let given = sequence(&[root, r#"{"mode":292,"name":"x","readOnly":false}"#, TRAILER]); + let expected = ( + ErrorKind::Manifest(Problem::Contradiction), + Some(Field::ReadOnly), + Some(1), + "manifest object 1 (x): 'readOnly' and 'mode' contradict each other".to_string(), + ); + assert_eq!(contradiction(read_whole(&given).unwrap_err()), expected); + let mut object = m.objects[0].clone(); + object.inode.filled_in.remove(Field::ReadOnly); + let mut writer = Writer::begin(Vec::new(), &m.root).unwrap(); + assert_eq!(contradiction(writer.file(&object).unwrap_err()), expected); + // The root file object too. + let given = concat!( + r#"{"features":["mode","read-only"],"mediaType":"application/vnd.uapi.16.manifest","mode":365,"#, + r#""readOnly":false}"# + ); + let expected = ( + ErrorKind::Manifest(Problem::Contradiction), + Some(Field::ReadOnly), + Some(0), + "manifest object 0 (root): 'readOnly' and 'mode' contradict each other".to_string(), + ); + assert_eq!( + contradiction(read_whole(&sequence(&[given, TRAILER])).unwrap_err()), + expected + ); + let mut root = m.root.clone(); + root.inode.filled_in.remove(Field::ReadOnly); + assert_eq!(contradiction(Writer::begin(Vec::new(), &root).unwrap_err()), expected); + } + + /// The writer leaves out what the specification recommends to leave + /// out where it says nothing more, and a reader fills it in again. + #[test] + fn leaves_out_what_the_specification_recommends() { + let empty: Sha256 = EMPTY.parse().unwrap(); + // The hash of no data next to the size 0. + let mut object = FileObject::new(name("x")); + (object.size, object.sha256) = (Some(0), Some(empty)); + // With an encoding, that of the encoded and of the original data. + let mut encoded = Contents::new(Location::File(name("x.gz"))); + encoded.encoding = Some("gzip".into()); + (encoded.encoded_size, encoded.encoded_sha256) = (Some(0), Some(empty)); + (encoded.original_size, encoded.original_sha256) = (Some(0), Some(empty)); + // Without an encoding, the encoded size and hash next to the + // original ones, which say the same. + let mut plain = Contents::new(Location::File(name("x"))); + (plain.encoded_size, plain.encoded_sha256) = (Some(0), Some(empty)); + (plain.original_size, plain.original_sha256) = (Some(0), Some(empty)); + object.contents = vec![encoded, plain]; + let written = record(&object); + assert_eq!( + written, + concat!( + r#"{"contents":[{"encodedSize":0,"encoding":"gzip","file":"x.gz","originalSize":0},"#, + r#"{"file":"x","originalSize":0}],"name":"x","size":0}"# + ) + ); + let (_, root) = recording_all(); + let m = read_whole(&sequence(&[&root, &written, TRAILER])).unwrap(); + let read = &m.objects[0]; + assert_eq!((read.size, read.sha256), (Some(0), Some(empty))); + for contents in &read.contents { + let data = (contents.encoded_size, contents.encoded_sha256); + assert_eq!(data, (Some(0), Some(empty))); + let data = (contents.original_size, contents.original_sha256); + assert_eq!(data, (Some(0), Some(empty))); + } + // Where only the encoded size says it, it stays. + let mut only = FileObject::new(name("y")); + only.contents = vec![Contents { + encoded_size: Some(5), + ..Contents::new(Location::File(name("y"))) + }]; + assert_eq!( + record(&only), + r#"{"contents":[{"encodedSize":5,"file":"y"}],"name":"y"}"# + ); + } + + /// What a reader read in another form than the one the writer writes + /// can grow on the way back. A record close to MAX_RECORD_SIZE grows + /// past it then, and the writer refuses it. + #[test] + fn a_record_that_grows_past_the_limit() { + let root = r#"{"features":["gpt-uuid","user-xattr"],"mediaType":"application/vnd.uapi.16.manifest"}"#; + // A UUID without its hyphens, which the writer writes with them. + let uuid = "11".repeat(Uuid::SIZE); + let record = |pad: usize| { + format!( + r#"{{"extendedAttributes":{{"user":{{"p":{{"text":"{}"}}}}}},"gptUuid":"{}","name":"a"}}"#, + "p".repeat(pad), + uuid + ) + }; + let frame = sequence(&[&record(0)]).len(); + let largest = record(MAX_RECORD_SIZE - frame); + assert_eq!(sequence(&[&largest]).len(), MAX_RECORD_SIZE); + let m = read_whole(&sequence(&[root, &largest, TRAILER])).unwrap(); + let e = write_whole(&m).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number(), e.name()), + (ErrorKind::Manifest(Problem::RecordTooLarge), Some(1), Some("a")) + ); + } + + /// An object with two faults is refused for the one a reader finds + /// first in its record, by a reader and by the writer. The one fault + /// they do not share is an encoding that is not in lower case, which a + /// reader lowers the case of and the writer refuses. + #[test] + fn the_first_of_two_faults() { + /// Gives an object fields. + type Give = fn(&mut FileObject); + /// A character that no string of a manifest may hold. + fn noncharacter() -> char { + char::from_u32(0xfdd0).unwrap() + } + let root = RootObject { + features: Some(Features::DEFAULT | Features::READ_ONLY | Features::USER_NAME | Features::FS_LABEL), + ..RootObject::default() + }; + let root_text = concat!( + r#"{"features":["device","fs-label","gid","hardlink","mode","read-only","sha256","size","symlink","#, + r#""uid","user-name"],"mediaType":"application/vnd.uapi.16.manifest"}"# + ); + let cases: Vec<(String, Give, Problem)> = vec![ + // A record too large, before a string the JSON parser refuses. + ( + format!( + r#"{{"contents":[{{"literal":"{}"}}],"name":"x","userName":"u{}"}}"#, + "AAAA".repeat(MAX_RECORD_SIZE / 4), + noncharacter() + ), + |o| { + o.contents = vec![Contents::new(Location::Literal(vec![0; MAX_RECORD_SIZE / 4 * 3]))]; + o.inode.user_name = Some(format!("u{}", noncharacter()).into()); + }, + Problem::RecordTooLarge, + ), + // A string the JSON parser refuses, before any value. + ( + "{\"name\":\"x\",\"uid\":65535,\"userName\":\"u\u{fdd0}\"}".into(), + |o| (o.inode.uid, o.inode.user_name) = (Some(65535), Some("u\u{fdd0}".into())), + Problem::InvalidString, + ), + // A key the JSON parser finds twice in an object, header fields + // of the same name, before any value. + ( + r#"{"contents":[{"httpHeaders":{"A":"b","A":"c"},"url":"https://example.com/x"}],"name":"x","uid":65535}"# + .into(), + |o| { + o.contents = vec![Contents { + http_headers: vec![("A".into(), "b".into()), ("A".into(), "c".into())], + ..Contents::new(Location::Url("https://example.com/x".into())) + }]; + o.inode.uid = Some(65535); + }, + Problem::DuplicateKey, + ), + // Too many contents objects, before what is wrong with one of + // them. + ( + format!( + r#"{{"contents":[{{"literal":"YQ==","originalSize":5}}{}],"name":"x"}}"#, + r#",{"literal":"YQ=="}"#.repeat(MAX_CONTENTS) + ), + |o| { + o.contents = (0..=MAX_CONTENTS) + .map(|_| Contents::new(Location::Literal(b"a".to_vec()))) + .collect(); + o.contents[0].original_size = Some(5); + }, + Problem::InvalidContents, + ), + // The fields of a contents object against each other, before + // the value of a field behind it. + ( + r#"{"contents":[{"file":"a","httpHeaders":{"A":"b"}}],"name":"x","uid":65535}"#.into(), + |o| { + o.contents = vec![Contents { + http_headers: vec![("A".into(), "b".into())], + ..Contents::new(Location::File(name("a"))) + }]; + o.inode.uid = Some(65535); + }, + Problem::InvalidContents, + ), + // A value, before a missing name. + ( + r#"{"uid":65535}"#.into(), + |o| (o.name, o.inode.uid) = (Name::ROOT, Some(65535)), + Problem::FieldOutOfRange, + ), + // A value, before a field the inode type does not permit. + ( + r#"{"name":"x","size":1,"type":"fifo","uid":65535}"#.into(), + |o| (o.inode_type, o.size, o.inode.uid) = (InodeType::Fifo, Some(1), Some(65535)), + Problem::FieldOutOfRange, + ), + // A field the inode type does not permit, before fields that + // contradict each other. + ( + r#"{"mode":420,"name":"x","readOnly":true,"size":1,"type":"fifo"}"#.into(), + |o| { + (o.inode_type, o.size) = (InodeType::Fifo, Some(1)); + (o.inode.mode, o.inode.read_only) = (Mode::new(0o644), Some(true)); + }, + Problem::FieldNotPermitted, + ), + // Fields that contradict each other, before a field of a + // feature the manifest does not record. + ( + r#"{"mTimeNSec":1,"mode":420,"name":"x","readOnly":true}"#.into(), + |o| (o.inode.mtime_nsec, o.inode.mode, o.inode.read_only) = (Some(1), Mode::new(0o644), Some(true)), + Problem::Contradiction, + ), + // A value, before a field of a feature the manifest does not + // record. + ( + r#"{"mTimeNSec":1,"name":"x","uid":65535}"#.into(), + |o| (o.inode.mtime_nsec, o.inode.uid) = (Some(1), Some(65535)), + Problem::FieldOutOfRange, + ), + ]; + for (record, give, problem) in cases { + let label: String = record.chars().take(100).collect(); + let e = read_whole(&sequence(&[root_text, &record, TRAILER])).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(problem), Some(1)), + "{}", + label + ); + let mut object = FileObject::new(name("x")); + give(&mut object); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + let w = writer.file(&object).unwrap_err(); + assert_eq!( + (w.kind(), w.record_number()), + (e.kind(), e.record_number()), + "{}", + label + ); + } + // A string the JSON parser refuses, before a file object after a + // signature object. + let record = format!(r#"{{"name":"x","userName":"u{}"}}"#, noncharacter()); + let e = read_whole(&sequence(&[root_text, SIGNATURE, &record, TRAILER])).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::InvalidString), Some(2)) + ); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + writer.signature(&Signature::new("pkcs7")).unwrap(); + let mut object = FileObject::new(name("x")); + object.inode.user_name = Some(format!("u{}", noncharacter()).into()); + let w = writer.file(&object).unwrap_err(); + assert_eq!((w.kind(), w.record_number()), (e.kind(), e.record_number())); + // A file object after a signature object, before a missing name. + let e = read_whole(&sequence(&[root_text, SIGNATURE, r#"{"uid":65535}"#, TRAILER])).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::FileAfterSignature)); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + writer.signature(&Signature::new("pkcs7")).unwrap(); + let mut nameless = FileObject::new(Name::ROOT); + nameless.inode.uid = Some(65535); + let w = writer.file(&nameless).unwrap_err(); + assert_eq!((w.kind(), w.record_number()), (e.kind(), e.record_number())); + // The root file object: the label of the file system comes before + // the user ID. + let given = concat!( + r#"{"features":["fs-label"],"fsLabel":"a\tb","mediaType":"application/vnd.uapi.16.manifest","#, + r#""uid":65535}"# + ); + let e = read_whole(&sequence(&[given, TRAILER])).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::WrongFieldType), Some(Field::FsLabel)) + ); + let mut root = RootObject { + features: Some(Features::FS_LABEL), + ..RootObject::default() + }; + root.file_system.label = Some("a\tb".into()); + root.inode.uid = Some(65535); + let w = Writer::begin(Vec::new(), &root).unwrap_err(); + assert_eq!( + (w.kind(), w.field(), w.record_number()), + (e.kind(), e.field(), e.record_number()) + ); + } + + /// What the writer writes has values the reader takes: a string has + /// no NUL and no noncharacter, and the value of a field keeps to its + /// rules. + #[test] + fn checks_what_it_writes() { + /// Gives an object a value. + type Give = fn(&mut FileObject); + /// Contents at a URL, with the header fields `headers`. + fn headers(headers: &[(&str, &str)]) -> Contents { + Contents { + http_headers: headers + .iter() + .map(|&(name, value)| (name.into(), value.into())) + .collect(), + ..Contents::new(Location::Url("https://example.com/x".into())) + } + } + /// Contents in the encoding `encoding`. + fn encoded(encoding: &str) -> Contents { + Contents { + encoding: Some(encoding.into()), + ..Contents::new(Location::File(name("x.gz"))) + } + } + /// Gives `object` the extended attribute `name`, without a value. + fn xattr(object: &mut FileObject, name: &str) { + object.inode.user_xattrs = Some(Box::new(BTreeMap::from([(name.to_string(), Vec::new())]))); + } + /// The partition label `label`. + fn gpt(label: &str) -> Option> { + Some(Box::new(GptPartition { + label: Some(label.into()), + ..GptPartition::default() + })) + } + let cases: [(Give, Problem, Field); 19] = [ + (|o| o.inode.uid = Some(u32::MAX), Problem::FieldOutOfRange, Field::Uid), + (|o| o.inode.gid = Some(u32::MAX), Problem::FieldOutOfRange, Field::Gid), + // -1 as a 16-bit ID is no ID either. + (|o| o.inode.uid = Some(65535), Problem::FieldOutOfRange, Field::Uid), + (|o| o.inode.gid = Some(65535), Problem::FieldOutOfRange, Field::Gid), + ( + |o| o.inode.user_name = Some("u\u{fdd0}".into()), + Problem::InvalidString, + Field::UserName, + ), + ( + |o| o.inode.user_name = Some("u\0".into()), + Problem::InvalidString, + Field::UserName, + ), + ( + |o| o.inode.group_name = Some("a:b".into()), + Problem::WrongFieldType, + Field::GroupName, + ), + (|o| xattr(o, "a\0b"), Problem::InvalidString, Field::ExtendedAttributes), + ( + |o| xattr(o, ""), + Problem::InvalidExtendedAttributes, + Field::ExtendedAttributes, + ), + (|o| o.gpt = gpt("x\0"), Problem::InvalidString, Field::GptLabel), + (|o| o.gpt = gpt("a\tb"), Problem::WrongFieldType, Field::GptLabel), + ( + |o| o.contents = vec![Contents::new(Location::Url("ftp://example.com/x".into()))], + Problem::InvalidContents, + Field::Url, + ), + ( + |o| o.contents = vec![encoded("Identity")], + Problem::InvalidContents, + Field::Encoding, + ), + // A reader lowers the case of an encoding, a manifest has it in + // lower case. + ( + |o| o.contents = vec![encoded("GZIP")], + Problem::InvalidContents, + Field::Encoding, + ), + ( + |o| o.contents = vec![encoded("gzip\u{ffff}")], + Problem::InvalidString, + Field::Encoding, + ), + ( + |o| o.contents = vec![headers(&[("bad name", "b")])], + Problem::InvalidContents, + Field::HttpHeaders, + ), + ( + |o| o.contents = vec![headers(&[("A", "b"), ("a", "c")])], + Problem::InvalidContents, + Field::HttpHeaders, + ), + ( + |o| o.contents = vec![headers(&[("A", "b\nc")])], + Problem::InvalidContents, + Field::HttpHeaders, + ), + ( + |o| o.contents = vec![Contents::default(); MAX_CONTENTS + 1], + Problem::InvalidContents, + Field::Contents, + ), + ]; + let (root, _) = recording_all(); + for (give, problem, field) in cases { + let mut object = FileObject::new(name("x")); + give(&mut object); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + let e = writer.file(&object).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.record_number(), e.name()), + (ErrorKind::Manifest(problem), Some(field), Some(1), Some("x")), + "{:?}", + object + ); + } + // A field of a feature the manifest does not record, also one of + // those the specification added last. + let mut object = FileObject::new(name("x")); + object.inode.read_only = Some(true); + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.file(&object).unwrap_err(); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::UnlistedFeature), Some(Field::ReadOnly)) + ); + // The label of the file system, which only the root has. + for (label, problem) in [ + ("a\u{ffff}", Problem::InvalidString), + ("a\0b", Problem::InvalidString), + ("a\u{1}b", Problem::WrongFieldType), + ] { + let mut root = RootObject { + features: Some(Features::DEFAULT | Features::FS_LABEL), + ..RootObject::default() + }; + root.file_system.label = Some(label.into()); + let e = Writer::begin(Vec::new(), &root).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.record_number()), + (ErrorKind::Manifest(problem), Some(Field::FsLabel), Some(0)), + "{:?}", + label + ); + } + // The mechanism of a signature. + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + let e = writer.signature(&Signature::new("pkcs7\u{fffe}")).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.record_number()), + ( + ErrorKind::Manifest(Problem::InvalidString), + Some(Field::Mechanism), + Some(1) + ) + ); + // What the reader takes, the writer takes. + let mut object = FileObject::new(name("x")); + (object.inode.uid, object.inode.gid) = (Some(65534), Some(u32::MAX - 1)); + object.inode.user_name = Some("Domain Users".into()); + object.contents = vec![headers(&[("A", "b"), ("B", "")]); MAX_CONTENTS]; + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + writer.file(&object).unwrap(); + let m = read_whole(&writer.finish().unwrap()).unwrap(); + let read = &m.objects[0]; + assert_eq!( + (read.inode.uid, read.inode.user_name.as_deref(), read.contents.len()), + (Some(65534), Some("Domain Users"), MAX_CONTENTS) + ); + } + + /// The writer refuses what a reader refuses of the fields of an object + /// against its inode type and against each other. + #[test] + fn checks_the_fields_against_each_other() { + /// Gives an object fields. + type Give = fn(&mut FileObject); + /// The fields of a partition with the attribute flags `flags`. + fn partition(flags: u64) -> Option> { + Some(Box::new(GptPartition { + flags: Some(flags), + ..GptPartition::default() + })) + } + /// Contents in the file "x". + fn file() -> Contents { + Contents::new(Location::File(name("x"))) + } + let cases: [(Give, Problem, Option); 17] = [ + // Fields the inode type does not permit. + ( + |o| (o.inode_type, o.size) = (InodeType::Fifo, Some(1)), + Problem::FieldNotPermitted, + Some(Field::Size), + ), + ( + |o| (o.inode_type, o.contents) = (InodeType::CharDevice, vec![file()]), + Problem::FieldNotPermitted, + Some(Field::Contents), + ), + ( + |o| (o.inode_type, o.sha256) = (InodeType::Socket, EMPTY.parse().ok()), + Problem::FieldNotPermitted, + Some(Field::Contents), + ), + (|o| o.major = Some(1), Problem::FieldNotPermitted, Some(Field::Major)), + ( + |o| (o.inode_type, o.inode.mode) = (InodeType::Symlink, Mode::new(0o777)), + Problem::FieldNotPermitted, + Some(Field::Mode), + ), + ( + |o| (o.inode_type, o.inode_token) = (InodeType::Directory, NonZeroU64::new(1)), + Problem::FieldNotPermitted, + Some(Field::InodeToken), + ), + ( + |o| (o.inode_type, o.gpt) = (InodeType::Directory, partition(0)), + Problem::FieldNotPermitted, + Some(Field::GptFlags), + ), + ( + |o| { + o.inode_type = InodeType::Symlink; + o.dos_flags.put(DosFlags::HIDDEN, Some(true)); + }, + Problem::FieldNotPermitted, + Some(Field::FlagHidden), + ), + // readOnly against mode and against gptFlags, both ways, and + // gptFlags against the field of one of its flags. + ( + |o| (o.inode.read_only, o.inode.mode) = (Some(true), Mode::new(0o644)), + Problem::Contradiction, + Some(Field::ReadOnly), + ), + ( + |o| (o.inode.read_only, o.gpt) = (Some(true), partition(0)), + Problem::Contradiction, + Some(Field::GptFlags), + ), + ( + |o| (o.inode.read_only, o.gpt) = (Some(false), partition(GptPartition::FLAG_READ_ONLY)), + Problem::Contradiction, + Some(Field::GptFlags), + ), + // The manifest records gptFlags, so none is 0. + ( + |o| o.inode.read_only = Some(true), + Problem::Contradiction, + Some(Field::ReadOnly), + ), + ( + |o| { + o.gpt = partition(GptPartition::FLAG_NO_AUTO); + o.gpt.as_mut().unwrap().no_auto = Some(false); + }, + Problem::Contradiction, + Some(Field::GptFlags), + ), + // The size 0 against the hash, and the other way around. + ( + |o| (o.size, o.sha256) = (Some(0), HELLO.parse().ok()), + Problem::Contradiction, + Some(Field::Size), + ), + ( + |o| (o.size, o.sha256) = (Some(5), EMPTY.parse().ok()), + Problem::Contradiction, + Some(Field::Sha256), + ), + // httpHeaders without a URL, and a part beyond the data. + ( + |o| { + o.contents = vec![Contents { + http_headers: vec![("A".into(), "b".into())], + ..file() + }]; + }, + Problem::InvalidContents, + Some(Field::HttpHeaders), + ), + ( + |o| { + o.size = Some(5); + o.contents = vec![Contents { + original_size: Some(6), + offset: 2, + ..file() + }]; + }, + Problem::Contradiction, + Some(Field::Offset), + ), + ]; + let (root, _) = recording_all(); + for (give, problem, field) in cases { + let mut object = FileObject::new(name("x")); + give(&mut object); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + let e = writer.file(&object).unwrap_err(); + assert_eq!( + (e.kind(), e.field(), e.record_number(), e.name()), + (ErrorKind::Manifest(problem), field, Some(1), Some("x")), + "{:?}: {}", + object, + e + ); + // Nothing of it was written. + assert_eq!(writer.finish().unwrap(), sequence(&[&recording_all().1, TRAILER])); + } + } + + /// No record is larger than MAX_RECORD_SIZE, its record separator + /// included, which is how a reader counts it too. A larger one is not + /// written, and the writer goes on. + #[test] + fn the_largest_record() { + // An object whose record is as large as one with the name `name_of` + // and an extended attribute, plus `pad` bytes. + let padded = |name_of: &str, pad: usize| { + let mut object = FileObject::new(name(name_of)); + object.inode.user_xattrs = Some(Box::new(BTreeMap::from([("p".to_string(), vec![b'x'; pad])]))); + object + }; + // The separator and the newline are not in what record() returns. + let frame = record(&padded("a", 0)).len() + 2; + let (root, _) = recording_all(); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + let before = writer.get_ref().len(); + let e = writer.file(&padded("a", MAX_RECORD_SIZE - frame + 1)).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number(), e.name()), + (ErrorKind::Manifest(Problem::RecordTooLarge), Some(1), Some("a")) + ); + assert_eq!( + e.to_string(), + format!("manifest record exceeds {} bytes", MAX_RECORD_SIZE) + ); + assert_eq!(writer.get_ref().len(), before); + assert!(writer.text.capacity() <= TEXT_CAPACITY); + // A directory that is not written is not the directory of what + // comes next. + let mut large = padded("d", MAX_RECORD_SIZE); + large.inode_type = InodeType::Directory; + let e = writer.file(&large).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::RecordTooLarge)); + let e = writer.file(&FileObject::new(name("d/x"))).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::Misplaced)); + // The largest one, which a reader takes. + let largest = padded("a", MAX_RECORD_SIZE - frame); + writer.file(&largest).unwrap(); + assert_eq!(writer.get_ref().len() - before, MAX_RECORD_SIZE); + assert!(writer.text.capacity() <= TEXT_CAPACITY); + let mut signature = Signature::new("pkcs7"); + signature.data = Some(vec![0; MAX_RECORD_SIZE]); + let e = writer.signature(&signature).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::RecordTooLarge), Some(2)) + ); + let bytes = writer.finish().unwrap(); + let m = read_whole(&bytes).unwrap(); + assert_eq!(m.objects.len(), 1); + assert_eq!(m.objects[0].inode.user_xattrs, largest.inode.user_xattrs); + // What a reader read, the writer writes back. + assert_eq!(write_whole(&m).unwrap(), bytes); + // The root file object's record is record 0. + let mut root = recording_all().0; + root.inode.user_xattrs = padded("a", MAX_RECORD_SIZE).inode.user_xattrs; + let e = Writer::begin(Vec::new(), &root).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::RecordTooLarge), Some(0)) + ); + } + + /// An encoder appends what a writer writes, and nothing where it fails. + #[test] + fn encodes_what_a_writer_writes() { + let (root, _) = recording_all(); + let whole = Whole { + root: root.clone(), + objects: vec![directory("a"), everything()], + signatures: vec![Signature::new("pkcs7")], + }; + let mut text = String::new(); + let mut encoder = Encoder::begin(&root, &mut text).unwrap(); + for object in &whole.objects { + encoder.file(object, &mut text).unwrap(); + } + // A name that came before is refused once the record was put + // together, and taken back. + let appended = text.clone(); + let e = encoder.file(&directory("a"), &mut text).unwrap_err(); + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::DuplicateName), Some(3)) + ); + assert_eq!(text, appended); + for signature in &whole.signatures { + encoder.signature(signature, &mut text).unwrap(); + } + encoder.finish(&mut text).unwrap(); + assert_eq!(text.as_bytes(), write_whole(&whole).unwrap()); + // Nothing follows the trailer. + let appended = text.len(); + for e in [ + encoder.file(&FileObject::new(name("z")), &mut text).unwrap_err(), + encoder.file(&FileObject::new(Name::ROOT), &mut text).unwrap_err(), + encoder.signature(&Signature::new("pkcs7"), &mut text).unwrap_err(), + encoder.finish(&mut text).unwrap_err(), + ] { + assert_eq!( + (e.kind(), e.record_number()), + (ErrorKind::Manifest(Problem::DataAfterTrailer), Some(5)) + ); + } + assert_eq!(text.len(), appended); + } + + /// What was written so far is there to be signed: the signature + /// objects sign what comes before the first of them. + #[test] + fn what_was_written_can_be_signed() { + let mut writer = Writer::begin(Vec::new(), &RootObject::default()).unwrap(); + writer.file(&FileObject::new(name("a"))).unwrap(); + let signed = writer.get_ref().len(); + let hash = Sha256::digest(writer.get_ref()); + let mut signature = Signature::new("pkcs7"); + signature.data = Some(hash.as_bytes().to_vec()); + writer.signature(&signature).unwrap(); + let bytes = writer.finish().unwrap(); + let mut reader = Reader::open(&bytes[..]).unwrap(); + let objects: Vec<_> = reader.by_ref().collect::>().unwrap(); + assert_eq!(objects.len(), 2); + assert_eq!(reader.signed_len(), u64::try_from(signed).ok()); + assert_eq!(Sha256::digest(&bytes[..signed]), hash); + } + + /// Notes every write and every flush, and fails the write `fail_at`. + #[derive(Debug, Default)] + struct Calls { + writes: Vec, + flushes: usize, + fail_at: Option, + } + + impl Write for Calls { + fn write(&mut self, data: &[u8]) -> io::Result { + if self.fail_at == Some(self.writes.len()) { + return Err(io::Error::from_raw_os_error(libc::ENOSPC)); + } + self.writes.push(data.len()); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.flushes += 1; + Ok(()) + } + } + + #[test] + fn a_record_is_one_write() { + let mut calls = Calls::default(); + let (root, root_text) = recording_all(); + let mut writer = Writer::begin(&mut calls, &root).unwrap(); + writer.file(&directory("a")).unwrap(); + writer.file(&everything()).unwrap(); + let mut empty = FileObject::new(name("empty")); + empty.sha256 = EMPTY.parse().ok(); + writer.file(&empty).unwrap(); + writer.finish().unwrap(); + assert_eq!(calls.writes.len(), 5); + assert_eq!(calls.writes[0], sequence(&[root_text.as_str()]).len()); + assert_eq!(calls.writes[4], sequence(&[TRAILER]).len()); + assert_eq!(calls.flushes, 1); + // An error of what is written to is the writer's, about the record + // it wrote. + for (fail_at, record_number) in [(0, 0), (1, 1)] { + let mut calls = Calls { + fail_at: Some(fail_at), + ..Calls::default() + }; + let e = Writer::begin(&mut calls, &RootObject::default()) + .and_then(|mut writer| writer.file(&FileObject::new(name("a")))) + .unwrap_err(); + assert_eq!((e.kind(), e.record_number()), (ErrorKind::Io, Some(record_number))); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); + } + } +} From 22dbfe5760aa7c13d4a99d7e21e9073d55676304 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:18:51 +0100 Subject: [PATCH 09/19] uapi16: add the sources of file contents A manifest says where the contents of a file are: in the manifest itself as a literal, in a file next to the manifest, or at a URL, possibly in an encoding such as gzip. Add what it takes to get at them when a manifest is applied. FileObject::data() finds the data of a regular file, the target of a symbolic link or the manifest of its own that a directory refers to. A literal is taken first, as the specification suggests, since the manifest carries the data already. Otherwise it's the file the first contents object without an encoding names. The specification implies a contents object only for a regular file. So a regular file without contents objects has its data in the file of its own name, and any other object without them has no data at all. Data that would have to be decoded or fetched from a URL isn't taken. An object that has its data only that way fails with UnsupportedContent::UrlOrEncoding, and one without data with UnsupportedContent::Absent. A ContentSource hands out the data that isn't in the manifest: - DirectorySource takes it from the files next to the manifest. A manifest can't be trusted to stay inside of that directory and a symbolic link can lead out of it, so resolving a name below the directory and nowhere else is up to the caller, through the Directory trait. - StreamSource takes it from one stream that has the data of all files back to back, in the order of the manifest. Its end() is called after the last file object, also when none of them had data on the stream, and fails if the stream goes on. The stream holds the data of a file object and nothing else of its file. So the object needs a size, and a missing one is UnsupportedContent::NoSize. The size is optional in the specification, so that's a limit of the stream and not a malformed manifest. A consumer hands every file object whose data it doesn't take to ContentSource::skip(). StreamSource reads past the data there with the checks of a copy, and DirectorySource does nothing. So only the source knows what the stream carries, and a consumer that leaves an object out doesn't have to know whether its data is on the stream. FileObject::copy_contents() copies the data of a file to a sink and checks its size and its hash on the way with a ContentCheck. A ContentCheck counts and hashes what it is given in update(), refuses anything beyond the size of the object, and holds the data against the size and the hash in finish(). It checks what the file object says of its data, which the specification asks of every file. What the contents objects say of the files the data is in is for the sources to check. A ContentCheck isn't tied to Write. So a caller that copies the data some other way, in an async runtime for example, can check it with the same code. The copies themselves stay blocking. The data of a file object is the part of its file that starts at the offset and is as long as the object says, whatever else the file holds. That's how the specification has it. A file that is too short for the data fails, and so does one of another size than the originalSize the manifest gives. A file can hold the data of several file objects, each of them a part of it, and the manifest can give the size and the hash of the whole file with every one of them. Currently src/fat/manifest/assemble.rs reads such a file from its very beginning for each of its parts, and all of it whenever the hash of the whole file is given. With many parts that's quadratic. Instead, seek to the part. A part whose file object has a sha256 of its own is checked against that while it is copied, and the specification lets a consumer that only takes a part of a file skip the checks of the whole file. So originalSha256 is checked for a part only when its object has no sha256, and for all of a file only when it isn't the object's own sha256. No byte is hashed twice for an object whose sha256 is the hash of its whole file. In a stream a part without a sha256 is taken unchecked, which the specification allows as well: the stream doesn't have the rest of the file. For a part without a sha256 a DirectorySource reads the file once and keeps the hash of every piece of it. Every piece a later part is copied from is then checked against the hash kept for it. A piece is 1 MiB, and larger in a file of more than about 32 GiB, so that the hashes of a file of any size fit into the 1 MiB that the hashes a source keeps take at most. So in the common case, one large file that holds the data of many file objects, every part is checked and the file is read once. A file of about 32 GiB or more takes all of the 1 MiB, and the hashes of a split file are kept while they fit into what is left of it. The parts of a file whose hashes don't fit aren't checked against its originalSha256, which step 8 of acquiring a file in the specification allows. Parts with a sha256 of their own are always checked against that, as step 16 asks. The source doesn't drop the hashes of one file for those of another. If it did, parts of two such files that take turns would each read their file whole again, which is the parts times size this is meant to get rid of. So while copies succeed, a file of more than one piece is read whole once at most for its parts, and the memory a source takes doesn't grow with the manifest. For 1024 parts of 64 KiB of a 33 GiB file, none of them with a sha256, a source reads 34.1 GiB. Reading all of the file for every part came to 33 TiB. Of a 66 GiB file it reads 68.2 GiB. A file is read up to the size it had when it was opened. One that ends before that while it is read, or that is read whole for its hash and has a byte more, changed in the meantime, and that's ContentProblem::SourceChanged. That also keeps a file that is cut short and written again while it is read from adding pieces beyond those the source made room for. Error grows the kinds for all of this: SourceProblem for a file that isn't there the way the manifest says or a file or a stream that can't be read, ContentProblem for data that doesn't match the manifest, and UnsupportedContent for what this crate can't take. A size mismatch and a stream that ended early also carry the size that was found, where it's known, and the one that was expected. A read that fails names the object and the file or the stream, and an error of the sink comes back as it was. Data, SourceProblem, ContentProblem and UnsupportedContent are non_exhaustive as they gain variants once URLs or encodings are supported. DirectorySource and StreamSource print the size of their buffers in Debug, the way BufReader does, but not the buffers. Signed-off-by: Christian Brauner (Amutable) --- src/uapi16/content.rs | 2550 +++++++++++++++++++++++++++++++++++++++++ src/uapi16/error.rs | 137 +++ src/uapi16/lib.rs | 17 +- 3 files changed, 2702 insertions(+), 2 deletions(-) create mode 100644 src/uapi16/content.rs diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs new file mode 100644 index 0000000..4e84df7 --- /dev/null +++ b/src/uapi16/content.rs @@ -0,0 +1,2550 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The contents of the files a manifest describes: where they are, and +//! copying them from there with the sizes and hashes of the manifest +//! checked. + +use std::collections::HashMap; +use std::fmt; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::ops::Range; + +use crate::digest::{Finalize, Sha256Context}; +use crate::error::{ContentProblem, Error, ErrorKind, Field, SourceProblem, UnsupportedContent}; +use crate::object::{Contents, FileObject, InodeType, Location}; +use crate::{Name, Sha256}; + +/// How much a source copies at a time. It is also the smallest piece a +/// file is hashed in. +const COPY_SIZE: usize = 1024 * 1024; +/// How many bytes the hashes a [`DirectorySource`] keeps of the pieces of +/// files take at most: 32 bytes for every piece of a file, and what the +/// file takes besides, see [`PieceHashes::stored_bytes`]. The map that +/// holds them adds up to about half a MiB, with many small files, which +/// does not grow with the manifest either. +const PIECE_HASH_BYTES: usize = 1024 * 1024; +/// What a file takes in [`PieceHashes`] besides the hashes of its pieces: +/// its hash and its length, which it is known by, and the pointer to the +/// hashes of its pieces. +const FILE_ENTRY_BYTES: usize = size_of::<(Sha256, u64)>() + size_of::>(); +/// The most pieces a file is hashed in, so that the hashes of a file of +/// any length fit into [`PIECE_HASH_BYTES`]. +const MAX_PIECES: u64 = ((PIECE_HASH_BYTES - FILE_ENTRY_BYTES) / size_of::()) as u64; + +/// Where the data of a file object is, as [`FileObject::data`] finds it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Data<'a> { + /// In the manifest itself. This is the data. + Literal(&'a [u8]), + /// Outside of the manifest. A [`ContentSource`] has it. + External(Reference<'a>), +} + +/// The file a file object has its data in, next to the manifest. +/// +/// The file can hold more than the data of the one file object: several +/// file objects can each be a part of the same file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Reference<'a> { + /// The file: the one a contents object names, or else the one of the + /// object's own name. + pub file: &'a Name, + /// Where the data starts in the file. + pub offset: u64, + /// The size of the whole file, if the manifest gives it. + pub original_size: Option, + /// The hash of the whole file, if the manifest gives it. + pub original_sha256: Option, +} + +/// How much of its file the data of a file object is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DataExtent { + /// All of the file. + WholeFile, + /// A part of it. + PartOfFile, +} + +impl<'a> Reference<'a> { + /// The reference of an object to the file `file`, by way of the + /// contents object `contents` if one names it. + fn new(file: &'a Name, contents: Option<&'a Contents>) -> Reference<'a> { + Reference { + file, + offset: contents.map_or(0, |contents| contents.offset), + original_size: contents.and_then(|contents| contents.original_size), + original_sha256: contents.and_then(|contents| contents.original_sha256), + } + } + + /// Checks the length `len` of the file against what the manifest says + /// of it and of the data of `object` in it. Returns the size of that + /// data: the rest of the file from the offset on when the object gives + /// none. A length that does not fit is a + /// [`ContentProblem::SizeMismatch`]. + /// + /// The data is the part of the file that starts at the offset and is + /// as long as the object says, whatever else the file holds. So the + /// file has to be long enough for it, and as long as `originalSize` + /// where the manifest gives that. + fn check_len(&self, object: &FileObject, len: u64) -> Result { + let name = &object.name; + let mismatch = |message: String| { + Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message).named(name.as_str()) + }; + if let Some(total) = self.original_size.filter(|&total| total != len) { + let message = format!( + "{}: {} is {} bytes, the manifest says {}", + name.escape_debug(), + self.file.escape_debug(), + len, + total + ); + return Err(mismatch(message).sizes(Some(len), Some(total))); + } + let size = object.size.unwrap_or(len.saturating_sub(self.offset)); + let end = self.offset.checked_add(size); + if end.is_none_or(|end| end > len) { + let message = format!( + "{}: {} is too short for offset {} and size {}", + name.escape_debug(), + self.file.escape_debug(), + self.offset, + size + ); + return Err(mismatch(message).sizes(Some(len), end)); + } + Ok(size) + } + + /// The error for the file of the reference that `object` cannot be + /// taken from. + fn unavailable(&self, object: &FileObject, error: OpenError) -> Error { + let name = &object.name; + let error = match error { + OpenError::NotRegular => { + let message = format!( + "{}: {} is not a regular file", + name.escape_debug(), + self.file.escape_debug() + ); + return Error::new(ErrorKind::Source(SourceProblem::NotRegular), message).named(name.as_str()); + } + OpenError::Io(error) => error, + }; + let problem = match error.kind() { + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => SourceProblem::Missing, + io::ErrorKind::InvalidInput => SourceProblem::NotRegular, + _ => SourceProblem::Unreadable, + }; + let message = format!( + "{}: failed to open {}: {}", + name.escape_debug(), + self.file.escape_debug(), + error + ); + Error::new(ErrorKind::Source(problem), message) + .named(name.as_str()) + .caused_by(error) + } +} + +impl FileObject { + /// Where the data of the file is: the contents of a regular file, the + /// target of a symbolic link, or the manifest of its own that a + /// directory refers to. + /// + /// A literal is taken first, as the specification suggests: the + /// manifest carries the data itself. Otherwise the data is in the file + /// next to the manifest that the first contents object without an + /// encoding names, or in the file of the object's own name where that + /// contents object names no place. A regular file without contents + /// objects has it in the file of its own name too. Data that has to be + /// decoded or fetched from a URL is not taken: an object whose every + /// contents object gives it that way fails with + /// [`UnsupportedContent::UrlOrEncoding`]. Any other object without + /// contents objects has no data and fails with + /// [`UnsupportedContent::Absent`]. + pub fn data(&self) -> Result, Error> { + self.unencoded_data() + .map(|(data, _)| data) + .ok_or_else(|| self.unsupported()) + } + + /// The error of an object whose data this crate cannot take. + fn unsupported(&self) -> Error { + if self.contents.is_empty() { + let message = format!( + "'{}' is a {} without contents objects, which has no data", + self.name.escape_debug(), + self.inode_type + ); + return Error::new(ErrorKind::Unsupported(UnsupportedContent::Absent), message).named(self.name.as_str()); + } + let mut ways: Vec = self + .contents + .iter() + .map(|contents| match &contents.encoding { + Some(encoding) => format!("'{}' encoding", encoding.escape_debug()), + None => "a URL".to_string(), + }) + .collect(); + ways.sort(); + ways.dedup(); + let ways = ways.join(" or "); + let message = format!( + "'{}' is only available through {}, which is not supported", + self.name.escape_debug(), + ways + ); + Error::new(ErrorKind::Unsupported(UnsupportedContent::UrlOrEncoding), message) + .named(self.name.as_str()) + .valued(ways) + } + + /// Where the data of the file is if it is somewhere without an + /// encoding, with the contents object that says so: in the first + /// literal, else in the file of the first contents object that names + /// one. The specification implies a contents object for a regular file + /// that has none, with the file of its own name. + fn unencoded_data(&self) -> Option<(Data<'_>, Option<&Contents>)> { + if self.contents.is_empty() { + let implied = Data::External(Reference::new(&self.name, None)); + return (self.inode_type == InodeType::Regular).then_some((implied, None)); + } + let mut file = None; + for contents in self.contents.iter().filter(|contents| contents.encoding.is_none()) { + match &contents.location { + Location::Literal(literal) => { + let data = self.data_in_literal(literal, contents.offset); + return Some((Data::Literal(data), Some(contents))); + } + Location::File(name) => { + file.get_or_insert((name, contents)); + } + Location::Implied => { + file.get_or_insert((&self.name, contents)); + } + Location::Url(_) => {} + } + } + file.map(|(name, contents)| (Data::External(Reference::new(name, Some(contents))), Some(contents))) + } + + /// The data of the file in the literal `literal`: from `offset` on, as + /// many bytes as the object says it has. An offset or a size beyond the + /// literal takes all there is, which the size of the object then finds. + fn data_in_literal<'a>(&self, literal: &'a [u8], offset: u64) -> &'a [u8] { + let offset = usize::try_from(offset).unwrap_or(usize::MAX); + let data = literal.get(offset..).unwrap_or(&[]); + match self.size.map(usize::try_from) { + Some(Ok(size)) => data.get(..size).unwrap_or(data), + _ => data, + } + } + + /// Whether the data of the file is outside of the manifest, where a + /// [`ContentSource`] has it. + pub fn has_external_data(&self) -> bool { + matches!(self.unencoded_data(), Some((Data::External(_), _))) + } + + /// The hash the manifest gives for all of the file the data is in, + /// `original_sha256`, if the data is to be checked against it. Where + /// the data is all of the file, that is unless it is the hash the + /// object gives. Where it is a part, that is unless the object gives a + /// hash: what is copied is checked against that, and the specification + /// lets a consumer that takes a part of a file skip the checks of all + /// of it. + fn original_sha256_to_check(&self, original_sha256: Option, extent: DataExtent) -> Option { + original_sha256.filter(|&sha256| match (self.sha256, extent) { + (None, _) => true, + (Some(own), DataExtent::WholeFile) => own != sha256, + (Some(_), DataExtent::PartOfFile) => false, + }) + } + + /// Writes the data of the file to `sink`: the literal of the manifest, + /// or what `source` has. Checks the data against the size and the hash + /// the object gives with a [`ContentCheck`], and returns how many bytes + /// it is. An object whose data this crate cannot take fails as + /// [`FileObject::data`] does, and the source is not asked for it. An + /// error of the sink comes back as it was. + /// + /// What was written to the sink when this fails is not the data of + /// the file. + pub fn copy_contents(&self, source: &mut dyn ContentSource, sink: &mut dyn Write) -> Result { + let (data, contents) = self.unencoded_data().ok_or_else(|| self.unsupported())?; + let mut checked = CheckedSink { + sink, + check: ContentCheck::new(self), + failure: None, + }; + let copied = match data { + Data::Literal(data) => contents + .map_or(Ok(()), |contents| contents.check_literal(self, data)) + .and_then(|()| checked.write_all(data).map_err(Error::from)), + Data::External(reference) => source.copy(self, &reference, &mut checked), + }; + let CheckedSink { check, failure, .. } = checked; + // What the check refused and what the sink failed to take reached + // the source as I/O errors. These are the errors to report. + if let Some(failure) = failure { + return Err(failure); + } + copied?; + check.finish() + } +} + +impl Contents { + /// Checks the literal of the contents object, which `data`, the data + /// of `object`, is all of or a part of, against the hash the manifest + /// gives for all of it, where the data is to be checked against that. + /// A literal is no larger than a record and is hashed whole. + fn check_literal(&self, object: &FileObject, data: &[u8]) -> Result<(), Error> { + let Some(literal) = self.literal() else { + return Ok(()); + }; + let extent = if data.len() == literal.len() { + DataExtent::WholeFile + } else { + DataExtent::PartOfFile + }; + let Some(sha256) = object.original_sha256_to_check(self.original_sha256, extent) else { + return Ok(()); + }; + if Sha256::digest(literal) == sha256 { + return Ok(()); + } + let message = format!( + "'{}' is a part of literal contents that do not match the hash in the manifest", + object.name.escape_debug() + ); + Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(object.name.as_str())) + } +} + +/// Holds the data of a file object against the size and the hash the +/// object gives, as the data passes: it counts the bytes and hashes them. +/// +/// It checks what the object says of its data, the check the +/// specification has for the data of every file. What its contents +/// objects say of the files the data is in, their sizes and hashes, is +/// for whoever reads those files to check, such as a [`DirectorySource`]. +/// +/// [`FileObject::copy_contents`] checks what it copies with one. A caller +/// that moves the data itself, such as a copy in an async runtime, hands +/// every piece of it to [`ContentCheck::update`] before it writes it on, +/// and calls [`ContentCheck::finish`] after the last one. +/// +/// ``` +/// use uapi16::{ContentCheck, FileObject, Name, Sha256}; +/// +/// let mut object = FileObject::new(Name::new("hello.txt")?); +/// object.size = Some(5); +/// object.sha256 = Some(Sha256::digest(b"hello")); +/// let mut check = ContentCheck::new(&object); +/// check.update(b"hel")?; +/// check.update(b"lo")?; +/// assert_eq!(check.finish()?, 5); +/// +/// let mut check = ContentCheck::new(&object); +/// check.update(b"hello")?; +/// assert!(check.update(b"!").is_err()); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug)] +pub struct ContentCheck<'a> { + /// The name of the object, which an error carries. + name: &'a Name, + /// The size the object gives. + size: Option, + /// The hash the object gives. + sha256: Option, + /// The hash of the data so far, if the object gives one. + context: Option, + /// How many bytes the data has so far. + len: u64, +} + +impl<'a> ContentCheck<'a> { + /// A check of the data of `object`, of which nothing has passed yet. + pub fn new(object: &'a FileObject) -> ContentCheck<'a> { + ContentCheck { + name: &object.name, + size: object.size, + sha256: object.sha256, + context: object.sha256.map(|_| Sha256Context::default()), + len: 0, + } + } + + /// Takes `data`, the next bytes of the data. Fails, and takes none of + /// them, when they would make the data larger than the size the object + /// gives. + pub fn update(&mut self, data: &[u8]) -> Result<(), Error> { + let added = data.len() as u64; + if let Some(size) = self.size.filter(|&size| added > size.saturating_sub(self.len)) { + let message = format!( + "'{}' has more than the {} bytes the manifest says", + self.name.escape_debug(), + size + ); + return Err(Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message) + .named(self.name.as_str()) + .sizes(None, Some(size))); + } + if let Some(context) = &mut self.context { + context.update(data); + } + self.len = self.len.saturating_add(added); + Ok(()) + } + + /// Checks the data that passed against the size and the hash the + /// object gives, and returns how many bytes it is. + pub fn finish(self) -> Result { + if let Some(size) = self.size.filter(|&size| size != self.len) { + let message = format!( + "'{}' is {} bytes, the manifest says {}", + self.name.escape_debug(), + self.len, + size + ); + return Err(Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), message) + .named(self.name.as_str()) + .sizes(Some(self.len), Some(size))); + } + if self.context.map(Finalize::finalize) != self.sha256 { + let message = format!("'{}' does not match the hash in the manifest", self.name.escape_debug()); + return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(self.name.as_str())); + } + Ok(self.len) + } +} + +/// A sink that hands what is written to it to a [`ContentCheck`] before it +/// passes it on. +struct CheckedSink<'a, 'b> { + sink: &'a mut dyn Write, + check: ContentCheck<'b>, + /// Why what was written did not go through, if it did not: the check + /// refused it, or the sink failed to take it. The writer is told with + /// an I/O error of that kind, and this is the error to report. Nothing + /// written after it goes through. + failure: Option, +} + +impl Write for CheckedSink<'_, '_> { + fn write(&mut self, data: &[u8]) -> io::Result { + if self.failure.is_some() { + return Err(io::ErrorKind::InvalidData.into()); + } + if let Err(e) = self.check.update(data) { + self.failure = Some(e); + return Err(io::ErrorKind::InvalidData.into()); + } + if let Err(e) = self.sink.write_all(data) { + let kind = e.kind(); + self.failure = Some(Error::from(e)); + return Err(kind.into()); + } + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.sink.flush() + } +} + +/// Has the data of the file objects whose data is outside of the +/// manifest. +/// +/// [`DirectorySource`] takes it from the files next to the manifest and +/// [`StreamSource`] from one stream that carries it all, in the order of +/// the manifest. A consumer hands a source every file object, in the +/// order of the manifest: those whose data it takes to +/// [`FileObject::copy_contents`], which calls [`ContentSource::copy`], and +/// the others to [`ContentSource::skip`]. After the last one it calls +/// [`ContentSource::end`]. +pub trait ContentSource { + /// Writes the data of `object` to `sink`, which `reference` says + /// where to find: exactly `object.size` bytes when the object has a + /// size. An error of the sink comes back as it was, and one of the + /// source names the object. + fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error>; + + /// Passes over the data of `object`, which the consumer does not take. + /// A source that hands out the data in the order of the manifest reads + /// past it, and fails where a copy of it would. + fn skip(&mut self, _object: &FileObject) -> Result<(), Error> { + Ok(()) + } + + /// Called after the last file object of the manifest, whether the + /// source had the data of any or not. A source that has data the file + /// objects do not account for fails here. + fn end(&mut self) -> Result<(), Error> { + Ok(()) + } +} + +/// Why a [`Directory`] does not hand out a file. +#[derive(Debug)] +pub enum OpenError { + /// What the name names is not a regular file. + NotRegular, + /// The file could not be reached. An error of the kind `NotFound` or + /// `NotADirectory` says the file is not there. + Io(io::Error), +} + +impl From for OpenError { + fn from(e: io::Error) -> OpenError { + OpenError::Io(e) + } +} + +/// A place that holds the files a manifest refers to: the directory the +/// manifest is in. +/// +/// A manifest is not to be trusted to stay inside that directory. The +/// names it gives are normalized relative paths, see [`Name`], but a +/// symbolic link in the directory can still lead out of it. It is on the +/// implementation to resolve a name below the directory and nowhere else. +pub trait Directory { + /// A file of the directory, open for reading. + type File: Read + Seek; + + /// Opens the regular file `file` names, and returns it with its + /// size. + fn open(&self, file: &Name) -> Result<(Self::File, u64), OpenError>; +} + +/// Takes the data of file objects from the files next to the manifest, +/// in a [`Directory`]. +/// +/// The data of an object is the part of its file that starts at the +/// offset its contents object gives and is as long as the object says, +/// whatever else the file holds, as the specification has it. A file is +/// read as long as it was when it was opened. One that ends before the +/// data does, or that goes on where it is read whole for its hash, changed +/// in the meantime and fails. +/// +/// A file can hold the data of many file objects, each a part of it, and +/// the manifest can give the hash of the whole file with every one of +/// them. A part whose object gives a hash of its own is checked against +/// that one, as every object is, and the specification lets a consumer +/// that takes a part of a file skip the checks of all of it. So only a +/// part without a hash of its own is checked against the hash of the whole +/// file. The source reads the file whole for the first of these parts and +/// keeps the hash of every piece of it, if they fit into what is left of +/// the 1 MiB the hashes it keeps take at most. The parts after that are +/// checked against those, and only the pieces they are in are read. A +/// piece is 1 MiB, or larger in a file of more than about 32 GiB, so that +/// the hashes of a file of any size fit into 1 MiB, and those of a file of +/// about 32 GiB or more take all of it. A part of a file whose hashes do +/// not fit is not checked against the hash of the whole file, as the +/// specification allows. So the memory the source takes does not grow +/// with the manifest, and while copies succeed, a file of more than one +/// piece is read whole once at most for its parts. +pub struct DirectorySource { + directory: D, + /// What a copy goes through, made when the first file is copied. + buffer: Vec, + /// The hashes of the pieces of the files read whole for a part. + hashes: PieceHashes, +} + +impl DirectorySource { + /// A source that takes the files from `directory`. + pub fn new(directory: D) -> DirectorySource { + DirectorySource { + directory, + buffer: Vec::new(), + hashes: PieceHashes::default(), + } + } +} + +impl fmt::Debug for DirectorySource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DirectorySource") + .field("directory", &self.directory) + .field( + "buffer", + &format_args!("{}/{}", self.buffer.len(), self.buffer.capacity()), + ) + .field("hashes", &self.hashes) + .finish() + } +} + +/// The files a [`DirectorySource`] read whole for a part of them, which +/// have the hash the manifest gives for them, with the hash of every piece +/// of each. A file is known by its hash and its length: a part of it is +/// checked against the hashes of the pieces of the file of that hash, +/// whatever its name is. +/// +/// Nothing is dropped. The hashes of a file are kept while they fit into +/// what is left of [`PIECE_HASH_BYTES`], and those of a file of about +/// 32 GiB or more take all of it. The parts of a file whose hashes do not +/// fit are not checked against the hash of the whole file, which the +/// specification allows for a file that is taken only in part. A part that +/// gives a hash of its own is checked against that one in any case. +#[derive(Default)] +struct PieceHashes { + /// The hashes of the pieces of each file, by its hash and its length. + files: HashMap<(Sha256, u64), Box<[Sha256]>>, + /// How many bytes they take, at most [`PIECE_HASH_BYTES`]. + bytes: usize, +} + +impl PieceHashes { + /// The size of the pieces a file of the length `len` is hashed in: + /// [`COPY_SIZE`], or more for a file that would have more than + /// [`MAX_PIECES`] pieces of that size. The last piece is what is left. + fn piece_size(len: u64) -> u64 { + len.div_ceil(MAX_PIECES).max(COPY_SIZE as u64) + } + + /// How many pieces a file of the length `len` has, [`MAX_PIECES`] at + /// most. + fn piece_count(len: u64) -> u64 { + len.div_ceil(PieceHashes::piece_size(len)) + } + + /// How many bytes a file of `pieces` pieces takes when it is kept: the + /// hashes of its pieces and [`FILE_ENTRY_BYTES`]. + fn stored_bytes(pieces: u64) -> usize { + usize::try_from(pieces) + .unwrap_or(usize::MAX) + .saturating_mul(size_of::()) + .saturating_add(FILE_ENTRY_BYTES) + } + + /// Whether the hashes of the pieces of a file of the length `len` are + /// kept when it is read whole for a part of it: those of a file of more + /// than one piece, while they fit into what is left of + /// [`PIECE_HASH_BYTES`]. A part of a file of one piece is checked by + /// reading that piece, all of the file. + fn is_keepable(&self, len: u64) -> bool { + let pieces = PieceHashes::piece_count(len); + pieces > 1 && PieceHashes::stored_bytes(pieces) <= PIECE_HASH_BYTES.saturating_sub(self.bytes) + } + + /// The hashes of the pieces of the file of the length `len` with the + /// hash `sha256`, if it was read whole. + fn get(&self, sha256: Sha256, len: u64) -> Option<&[Sha256]> { + self.files.get(&(sha256, len)).map(|pieces| &**pieces) + } + + /// Keeps `pieces`, the hashes of the pieces of the file of the length + /// `len` with the hash `sha256`, as [`PieceHashes::is_keepable`] allows. + fn keep(&mut self, sha256: Sha256, len: u64, pieces: Box<[Sha256]>) { + self.bytes = self + .bytes + .saturating_add(PieceHashes::stored_bytes(pieces.len() as u64)); + self.files.insert((sha256, len), pieces); + } +} + +impl fmt::Debug for PieceHashes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PieceHashes") + .field("files", &self.files.len()) + .field("bytes", &format_args!("{}/{}", self.bytes, PIECE_HASH_BYTES)) + .finish() + } +} + +/// Why a copy from a file or a stream did not go through. +#[derive(Debug)] +enum CopyFailure { + /// Reading the file or the stream failed. + ReadFailed(io::Error), + /// The sink did not take what was read. + WriteFailed(io::Error), + /// The file does not have the hash it is checked against. + HashMismatch, + /// The file is not as long as it was when it was opened, or longer: + /// it changed while it was read. + SourceChanged, +} + +impl CopyFailure { + /// The error of a copy of the data of `object` from `place`, its file + /// or the stream, that failed so. + fn into_error(self, object: &FileObject, place: &str) -> Error { + let name = &object.name; + let (problem, what) = match self { + CopyFailure::ReadFailed(error) => { + let message = format!("{}: failed to read {}: {}", name.escape_debug(), place, error); + return Error::new(ErrorKind::Source(SourceProblem::Unreadable), message) + .named(name.as_str()) + .caused_by(error); + } + // The error of the sink comes back as it was. + CopyFailure::WriteFailed(error) => return Error::from(error), + CopyFailure::HashMismatch => (ContentProblem::HashMismatch, "does not match the hash in the manifest"), + CopyFailure::SourceChanged => (ContentProblem::SourceChanged, "changed while it was read"), + }; + let message = format!("{}: {} {}", name.escape_debug(), place, what); + Error::new(ErrorKind::Content(problem), message).named(name.as_str()) + } +} + +/// Reads that go on when a signal interrupts them. A bare read() fails +/// with EINTR when a handler that returns is installed, and std retries +/// only in read_exact() and friends. The copies read into a buffer of +/// their own: read_to_end() would start every piece with a small read, and +/// io::copy() reads into a small buffer of its own. +trait ReadSome: Read { + /// Reads into `buf` once. + fn read_some(&mut self, buf: &mut [u8]) -> io::Result { + loop { + match self.read(buf) { + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + result => return result, + } + } + } + + /// Copies `len` bytes to `sink` through `buffer`, or as many as there + /// are up to the end, and returns how many it copied. No read goes past + /// them. What it copies goes to `context` too, if there is one. + fn copy_up_to( + &mut self, + len: u64, + buffer: &mut [u8], + sink: &mut dyn Write, + mut context: Option<&mut Sha256Context>, + ) -> Result { + let mut copied = 0; + while copied < len { + let want = usize::try_from(len - copied).map_or(buffer.len(), |left| left.min(buffer.len())); + let read = self.read_some(&mut buffer[..want]).map_err(CopyFailure::ReadFailed)?; + if read == 0 { + break; + } + let chunk = &buffer[..read]; + sink.write_all(chunk).map_err(CopyFailure::WriteFailed)?; + if let Some(context) = &mut context { + context.update(chunk); + } + copied += read as u64; + } + Ok(copied) + } +} + +impl ReadSome for R {} + +/// A file a [`DirectorySource`] copies the data of an object from, in +/// pieces where it checks them. +struct Pieces<'a, F> { + file: F, + /// What the file is read into: [`COPY_SIZE`] bytes. + buffer: &'a mut [u8], + /// The length the file had when it was opened. + len: u64, + /// The size of its pieces, see [`PieceHashes::piece_size`]. + piece_size: u64, + /// Where in the file the next read starts. + pos: u64, + /// The data of the object in the file. + data: Range, +} + +impl Pieces<'_, F> { + /// Copies the data without a look at the rest of the file. A file that + /// ends before the data does changed since it was opened. + fn copy_data(&mut self, sink: &mut dyn Write) -> Result<(), CopyFailure> { + // Most files are copied whole and need no seek. + if self.data.start > 0 { + self.file + .seek(SeekFrom::Start(self.data.start)) + .map_err(CopyFailure::ReadFailed)?; + } + let size = self.data.end - self.data.start; + if self.file.copy_up_to(size, self.buffer, sink, None)? < size { + return Err(CopyFailure::SourceChanged); + } + Ok(()) + } + + /// Reads the next chunk of the file, at most up to `end`, and writes + /// what of it is data to `sink`. Returns the chunk, which is empty at + /// the end of the file. + fn copy_chunk(&mut self, end: u64, sink: &mut dyn Write) -> Result<&[u8], CopyFailure> { + let want = usize::try_from(end - self.pos).map_or(self.buffer.len(), |left| left.min(self.buffer.len())); + let read = self + .file + .read_some(&mut self.buffer[..want]) + .map_err(CopyFailure::ReadFailed)?; + let chunk = &self.buffer[..read]; + let within = |at: u64| at.saturating_sub(self.pos).min(read as u64) as usize; + let (start, stop) = (within(self.data.start), within(self.data.end)); + if start < stop { + sink.write_all(&chunk[start..stop]).map_err(CopyFailure::WriteFailed)?; + } + self.pos += read as u64; + Ok(chunk) + } + + /// Reads the piece that starts where the file is, writes what of it is + /// data to `sink`, and returns its hash. What it reads goes to `whole` + /// too, if there is one. A piece that ends before the file did when it + /// was opened is one of a file that changed while it was read. + fn copy_piece( + &mut self, + sink: &mut dyn Write, + mut whole: Option<&mut Sha256Context>, + ) -> Result { + let end = self.pos.saturating_add(self.piece_size).min(self.len); + let mut context = Sha256Context::default(); + while self.pos < end { + let chunk = self.copy_chunk(end, sink)?; + if chunk.is_empty() { + return Err(CopyFailure::SourceChanged); + } + context.update(chunk); + if let Some(whole) = &mut whole { + whole.update(chunk); + } + } + Ok(context.finalize()) + } + + /// Reads all of the file, as long as it was when it was opened, copies + /// the data, and checks the file against `sha256`. The hash of every + /// piece goes to `pieces`, if there is one. A file that ends early, or + /// goes on after that, changed while it was read. + fn copy_hashed( + &mut self, + sink: &mut dyn Write, + mut pieces: Option<&mut Vec>, + sha256: Sha256, + ) -> Result<(), CopyFailure> { + let mut context = Sha256Context::default(); + while self.pos < self.len { + match &mut pieces { + Some(pieces) => { + let piece = self.copy_piece(sink, Some(&mut context))?; + pieces.push(piece); + } + None => { + let chunk = self.copy_chunk(self.len, sink)?; + if chunk.is_empty() { + return Err(CopyFailure::SourceChanged); + } + context.update(chunk); + } + } + } + // One byte more says whether the file ends where it did. + if self.file.read_some(&mut [0u8; 1]).map_err(CopyFailure::ReadFailed)? != 0 { + return Err(CopyFailure::SourceChanged); + } + if context.finalize() != sha256 { + return Err(CopyFailure::HashMismatch); + } + Ok(()) + } + + /// Copies the data and checks every piece it is in against its hash + /// in `pieces`, those of the file that was read whole. + fn copy_checked(&mut self, sink: &mut dyn Write, pieces: &[Sha256]) -> Result<(), CopyFailure> { + if self.data.is_empty() { + return Ok(()); + } + let first = self.data.start / self.piece_size; + self.pos = first * self.piece_size; + if self.pos > 0 { + self.file + .seek(SeekFrom::Start(self.pos)) + .map_err(CopyFailure::ReadFailed)?; + } + let mut expected = pieces.iter().skip(usize::try_from(first).unwrap_or(usize::MAX)); + while self.pos < self.data.end { + let piece = self.copy_piece(sink, None)?; + if expected.next() != Some(&piece) { + return Err(CopyFailure::HashMismatch); + } + } + Ok(()) + } +} + +impl ContentSource for DirectorySource { + fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + let (file, len) = self + .directory + .open(reference.file) + .map_err(|e| reference.unavailable(object, e))?; + let size = reference.check_len(object, len)?; + self.buffer.resize(COPY_SIZE, 0); + let mut pieces = Pieces { + file, + buffer: &mut self.buffer, + len, + piece_size: PieceHashes::piece_size(len), + pos: 0, + // check_len made sure that this is inside the file. + data: reference.offset..reference.offset + size, + }; + let extent = if pieces.data == (0..len) { + DataExtent::WholeFile + } else { + DataExtent::PartOfFile + }; + let failed = |failure: CopyFailure| failure.into_error(object, &reference.file.escape_debug().to_string()); + let Some(sha256) = object.original_sha256_to_check(reference.original_sha256, extent) else { + return pieces.copy_data(sink).map_err(failed); + }; + let piece_count = PieceHashes::piece_count(len); + // All of the file is read where it is the data or a single piece. + // What is not the data of the object is hashed and not copied. + let copied = if extent == DataExtent::WholeFile || piece_count < 2 { + pieces.copy_hashed(sink, None, sha256) + } else if let Some(known) = self.hashes.get(sha256, len) { + // The file was read whole for another part of it. + pieces.copy_checked(sink, known) + } else if self.hashes.is_keepable(len) { + let mut hashes = Vec::with_capacity(usize::try_from(piece_count).unwrap_or_default()); + let copied = pieces.copy_hashed(sink, Some(&mut hashes), sha256); + if copied.is_ok() { + self.hashes.keep(sha256, len, hashes.into_boxed_slice()); + } + copied + } else { + // The hashes of the file do not fit into what is left of the + // room for them. The specification lets a consumer that takes a + // part of a file skip the checks of all of it. + pieces.copy_data(sink) + }; + copied.map_err(failed) + } +} + +/// Takes the data of file objects from one stream: the data of every +/// object that has it outside of the manifest, back to back, in the order +/// of the manifest. +/// +/// The stream has the data of an object and nothing else of its file. So +/// an object needs a size, which says where its data ends, and one whose +/// data starts at an offset in its file is refused. The data is checked +/// against the hash the manifest gives for the whole file where it is all +/// of the file: where its contents object gives the size of the file, and +/// that is the size of the object. A part of a file is checked against the +/// hash of its object, and is taken unchecked where the object gives none, +/// as the specification permits a consumer that takes a part of a file. +pub struct StreamSource { + reader: R, + /// What a copy goes through, made when the first file is copied. + buffer: Vec, + /// The name and the size of the last file object the stream had the + /// data of, if it had the data of one, which data left at its end is + /// about. + last: Option<(String, u64)>, +} + +impl StreamSource { + /// A source that takes the data from `reader`. + pub fn new(reader: R) -> StreamSource { + StreamSource { + reader, + buffer: Vec::new(), + last: None, + } + } + + /// Notes the file object of the name `name` and the size `size` as the + /// last one the stream had the data of. + fn note_served(&mut self, name: &Name, size: u64) { + let (last, last_size) = self.last.get_or_insert_with(Default::default); + last.clear(); + last.push_str(name); + *last_size = size; + } +} + +impl fmt::Debug for StreamSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StreamSource") + .field("reader", &self.reader) + .field( + "buffer", + &format_args!("{}/{}", self.buffer.len(), self.buffer.capacity()), + ) + .field("last", &self.last) + .finish() + } +} + +impl ContentSource for StreamSource { + fn copy(&mut self, object: &FileObject, reference: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + let name = &object.name; + if reference.offset != 0 { + let message = format!( + "{}: an offset cannot be used with streamed contents", + name.escape_debug() + ); + return Err( + Error::new(ErrorKind::Unsupported(UnsupportedContent::OffsetInStream), message).named(name.as_str()), + ); + } + let Some(size) = object.size else { + let message = format!("{}: streamed contents need a known size", name.escape_debug()); + return Err(Error::new(ErrorKind::Unsupported(UnsupportedContent::NoSize), message) + .at(Field::Size) + .named(name.as_str())); + }; + // The stream has all of the file where the contents object gives + // its size, and that is the size of the object. A part cannot be + // checked against the hash of the whole file. + let sha256 = if reference.original_size == Some(size) { + object.original_sha256_to_check(reference.original_sha256, DataExtent::WholeFile) + } else { + None + }; + let mut context = sha256.map(|_| Sha256Context::default()); + // No read goes past the file, into the data of the next one. + self.buffer.resize(COPY_SIZE, 0); + let copied = self + .reader + .copy_up_to(size, &mut self.buffer, sink, context.as_mut()) + .map_err(|failure| failure.into_error(object, "the stream"))?; + self.note_served(name, size); + if copied < size { + let message = format!( + "{}: the stream ended {} bytes early", + name.escape_debug(), + size - copied + ); + return Err(Error::new(ErrorKind::Content(ContentProblem::StreamEnded), message) + .named(name.as_str()) + .sizes(Some(copied), Some(size))); + } + if context.map(Finalize::finalize) != sha256 { + let message = format!( + "{}: {} does not match the hash in the manifest", + name.escape_debug(), + reference.file.escape_debug() + ); + return Err(Error::new(ErrorKind::Content(ContentProblem::HashMismatch), message).named(name.as_str())); + } + Ok(()) + } + + /// Reads past the data of `object` where the stream has it, and checks + /// it as a copy does. Data that does not match the object's size and + /// hash means that the stream is out of step with the manifest, and + /// every object after it would get the wrong bytes. + fn skip(&mut self, object: &FileObject) -> Result<(), Error> { + if object.has_external_data() { + object.copy_contents(self, &mut io::sink())?; + } + Ok(()) + } + + /// The stream ends with the last file it had the data of. Anything + /// behind it is data the manifest does not describe: the last file got + /// more than the manifest says, or no file takes data from the stream. + fn end(&mut self) -> Result<(), Error> { + let mut byte = [0u8; 1]; + let read = self.reader.read_some(&mut byte).map_err(|error| { + let message = format!("failed to read the stream after the last file: {}", error); + Error::new(ErrorKind::Source(SourceProblem::Unreadable), message).caused_by(error) + })?; + if read == 0 { + return Ok(()); + } + let kind = ErrorKind::Content(ContentProblem::SizeMismatch); + Err(match &self.last { + Some((name, size)) => { + let message = format!("{}: the stream goes on after the last file", name.escape_debug()); + Error::new(kind, message).named(name.as_str()).sizes(None, Some(*size)) + } + None => Error::new( + kind, + "the stream has data that no file of the manifest describes".into(), + ) + .sizes(None, Some(0)), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; + use crate::Digest; + use std::cell::{Cell, RefCell}; + use std::rc::Rc; + + /// What is in a directory under a name. + #[derive(Debug)] + enum Entry { + File(Rc<[u8]>), + /// A file that was `len` bytes long when it was opened and holds + /// these bytes when it is read: it changed in between. + Changed { + data: Rc<[u8]>, + len: u64, + }, + /// A file that runs into `trouble` where `at` is reached. + Troubled { + data: Rc<[u8]>, + at: u64, + trouble: Trouble, + }, + /// Something that is no regular file. + Other, + /// Something that cannot be reached, for this reason. + Fails(i32), + } + + /// What a read runs into in a file of [`Files`]. + #[derive(Clone, Copy, Debug)] + enum Trouble { + /// The read gives nothing, once, and the file goes on after that: + /// what a file that is cut short and written to again gives, or + /// one of a network file system. + Stall, + /// The read fails with this error, every time. + FailRead(i32), + /// Every seek fails with this error. + FailSeek(i32), + } + + /// A directory in memory. It counts the bytes that are read from its + /// files. + #[derive(Debug, Default)] + struct Files { + entries: RefCell>, + read: Rc>, + } + + /// A file of [`Files`]. + #[derive(Debug)] + struct Counted { + data: io::Cursor>, + read: Rc>, + /// What the read that starts at an offset runs into. + trouble: Option<(u64, Trouble)>, + } + + impl Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let pos = self.data.position(); + let trouble = self.trouble; + let buf = match trouble { + Some((at, Trouble::Stall)) if pos == at => { + self.trouble = None; + return Ok(0); + } + Some((at, Trouble::FailRead(errno))) if pos == at => return Err(io::Error::from_raw_os_error(errno)), + // A read stops where the trouble is, so that a read starts + // there. + Some((at, _)) if pos < at => { + let before = usize::try_from(at - pos).unwrap_or(usize::MAX); + let len = buf.len().min(before); + &mut buf[..len] + } + _ => buf, + }; + let read = self.data.read(buf)?; + self.read.set(self.read.get() + read as u64); + Ok(read) + } + } + + impl Seek for Counted { + fn seek(&mut self, to: SeekFrom) -> io::Result { + if let Some((_, Trouble::FailSeek(errno))) = self.trouble { + return Err(io::Error::from_raw_os_error(errno)); + } + self.data.seek(to) + } + } + + impl Files { + fn of(list: &[(&'static str, &'static [u8])]) -> Files { + let files = Files::default(); + for &(name, data) in list { + files.put(name, Entry::File(data.into())); + } + files + } + + fn put(&self, name: &'static str, entry: Entry) { + self.entries.borrow_mut().insert(name, entry); + } + + /// How many bytes were read since this was asked last. + fn read(&self) -> u64 { + self.read.replace(0) + } + } + + /// A source over a reference to the files, so that a test can look + /// at them and change them while the source has them. + impl Directory for &Files { + type File = Counted; + + fn open(&self, file: &Name) -> Result<(Counted, u64), OpenError> { + let (data, len, trouble) = match self.entries.borrow().get(file.as_str()) { + Some(Entry::File(data)) => (Rc::clone(data), data.len() as u64, None), + Some(Entry::Changed { data, len }) => (Rc::clone(data), *len, None), + Some(&Entry::Troubled { ref data, at, trouble }) => { + (Rc::clone(data), data.len() as u64, Some((at, trouble))) + } + Some(Entry::Other) => return Err(OpenError::NotRegular), + Some(Entry::Fails(errno)) => return Err(io::Error::from_raw_os_error(*errno).into()), + None => return Err(io::Error::from_raw_os_error(libc::ENOENT).into()), + }; + let file = Counted { + data: io::Cursor::new(data), + read: Rc::clone(&self.read), + trouble, + }; + Ok((file, len)) + } + } + + /// The file objects of the manifest with the records `records`. + fn objects(records: &[&str]) -> Vec { + read_whole(&manifest(records)) + .unwrap_or_else(|e| panic!("{:?}: {}", records, e)) + .objects + } + + /// The file object of `record`, which comes after the objects of the + /// directories it is in. + fn object(record: &str) -> FileObject { + let name = json::parse(record) + .ok() + .and_then(|value| value.get("name").and_then(json::Value::as_str).map(str::to_string)) + .unwrap_or_default(); + let mut records: Vec = name + .match_indices('/') + .map(|(end, _)| format!(r#"{{"name":"{}","type":"dir"}}"#, &name[..end])) + .collect(); + records.push(record.to_string()); + let records: Vec<&str> = records.iter().map(String::as_str).collect(); + objects(&records).pop().unwrap() + } + + /// Copies the contents of `object` from `source`. + fn copy(object: &FileObject, source: &mut dyn ContentSource) -> Result, Error> { + let mut out = Vec::new(); + let written = object.copy_contents(source, &mut out)?; + assert_eq!(written, out.len() as u64); + Ok(out) + } + + /// The kind, the name, the sizes and the text of an error. + fn facts(e: &Error) -> (ErrorKind, Option<&str>, Option, Option, String) { + (e.kind(), e.name(), e.found_size(), e.expected_size(), e.to_string()) + } + + /// A hash that no data in these tests has. + fn hash_of(n: u8) -> Sha256 { + Sha256::digest(&[n]) + } + + #[test] + fn where_the_data_is() { + // Without contents objects a regular file has it in the file of its + // name. + let o = object(r#"{"name":"dir/x","size":5}"#); + let Data::External(reference) = o.data().unwrap() else { + panic!() + }; + assert_eq!(reference.file.as_str(), "dir/x"); + assert_eq!( + (reference.offset, reference.original_size, reference.original_sha256), + (0, None, None) + ); + assert!(o.has_external_data()); + // The first contents object that has the data as it is in a file + // gives it: a URL and an encoding are passed over. + let file = format!( + r#"{{"file":"data/y.bin","offset":2,"originalSize":9,"originalSha256":"{}"}}"#, + WORLD + ); + let others = r#"{"url":"https://example.com/x"},{"file":"x.gz","encoding":"gzip"}"#; + let o = object(&format!( + r#"{{"name":"x","size":3,"contents":[{},{},{{"file":"z"}}]}}"#, + others, file + )); + let Data::External(reference) = o.data().unwrap() else { + panic!() + }; + assert_eq!(reference.file.as_str(), "data/y.bin"); + assert_eq!((reference.offset, reference.original_size), (2, Some(9))); + assert_eq!(reference.original_sha256, WORLD.parse().ok()); + assert!(o.has_external_data()); + // A literal is taken before any file, wherever it is among the + // contents objects. One in an encoding is not. + let literal = r#"{"literal":"aGVsbG8="}"#; + for contents in [ + format!(r#"{},{},{}"#, others, file, literal), + format!(r#"{},{}"#, file, literal), + format!(r#"{},{}"#, literal, file), + format!(r#"{{"literal":"AAAA","encoding":"gzip"}},{},{}"#, file, literal), + ] { + let o = object(&format!(r#"{{"name":"x","size":3,"contents":[{}]}}"#, contents)); + assert_eq!(o.data().unwrap(), Data::Literal(b"hel"), "{}", contents); + assert!(!o.has_external_data()); + } + // A contents object that names no place is the file of the + // object's name. + let o = object(r#"{"name":"x","contents":[{"offset":1,"originalSize":4}]}"#); + let Data::External(reference) = o.data().unwrap() else { + panic!() + }; + assert_eq!((reference.file.as_str(), reference.offset), ("x", 1)); + // The part of a literal that the object is. + for (record, data) in [ + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":1}],"size":3}"#, + "ell", + ), + (r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":3}]}"#, "lo"), + (r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":5}]}"#, ""), + (r#"{"name":"x","contents":[{"literal":"aGVsbG8="}],"size":2}"#, "he"), + ] { + assert_eq!( + object(record).data().unwrap(), + Data::Literal(data.as_bytes()), + "{}", + record + ); + } + // Data that only comes in ways this crate does not go. + let o = object(concat!( + r#"{"name":"dir/x","contents":[{"url":"https://example.com/x"},{"file":"x.zst","encoding":"zstd"},"#, + r#"{"url":"http://example.com/x"},{"literal":"AAAA","encoding":"gzip"},{"encoding":"zstd"}]}"# + )); + let e = o.data().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::UrlOrEncoding)); + assert_eq!(e.name(), Some("dir/x")); + assert_eq!(e.value(), Some("'gzip' encoding or 'zstd' encoding or a URL")); + assert_eq!( + e.to_string(), + "'dir/x' is only available through 'gzip' encoding or 'zstd' encoding or a URL, which is not supported" + ); + assert!(!o.has_external_data()); + } + + /// Only a regular file has a contents object implied. Any other object + /// without one has no data, and a copy of it fails without a look at + /// the source. + #[test] + fn objects_without_data() { + // A manifest that does not record the targets of symbolic links. + let root = r#"{"features":["size"],"mediaType":"application/vnd.uapi.16.manifest"}"#; + let none = read_whole(&sequence(&[ + root, + r#"{"name":"d","type":"dir"}"#, + r#"{"name":"f","type":"fifo"}"#, + r#"{"name":"l","type":"lnk"}"#, + r#"{"name":"r","size":5}"#, + TRAILER, + ])) + .unwrap() + .objects; + let mut stream = &b"hello"[..]; + let mut source = StreamSource::new(&mut stream); + for (o, kind) in none.iter().zip(["dir", "fifo", "lnk"]) { + let e = o.data().unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::Absent)); + assert_eq!(e.name(), Some(o.name.as_str())); + assert_eq!( + e.to_string(), + format!("'{}' is a {} without contents objects, which has no data", o.name, kind) + ); + assert!(!o.has_external_data()); + let e = copy(o, &mut source).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::Absent)); + source.skip(o).unwrap(); + } + assert_eq!(copy(&none[3], &mut source).unwrap(), b"hello"); + source.end().unwrap(); + // A symbolic link with its target in the manifest, and a directory + // that refers to a manifest of its own in a file. + let some = objects(&[ + r#"{"name":"d","type":"dir","size":3,"contents":[{"file":"d.Uapi16Manifest"}]}"#, + r#"{"name":"l","type":"lnk","contents":[{"literal":"eA=="}]}"#, + ]); + assert!(some[0].has_external_data()); + assert_eq!(some[1].data().unwrap(), Data::Literal(b"x")); + let files = Files::of(&[("d.Uapi16Manifest", b"abc")]); + let mut source = DirectorySource::new(&files); + assert_eq!(copy(&some[0], &mut source).unwrap(), b"abc"); + assert_eq!(copy(&some[1], &mut source).unwrap(), b"x"); + } + + #[test] + fn copies_from_a_directory() { + let files = Files::of(&[("a", b"hello world"), ("empty", b""), ("dir/b", b"hello")]); + let mut source = DirectorySource::new(&files); + for (record, data) in [ + // A whole file, by the name of the object and by a file reference. + (format!(r#"{{"name":"dir/b","size":5,"sha256":"{}"}}"#, HELLO), "hello"), + ( + format!( + r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"file":"dir/b"}}]}}"#, + HELLO + ), + "hello", + ), + (r#"{"name":"dir/b"}"#.to_string(), "hello"), + (r#"{"name":"empty","size":0}"#.to_string(), ""), + (r#"{"name":"empty"}"#.to_string(), ""), + // The start of a file that holds more, which is all the + // specification takes of it. + (format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO), "hello"), + (r#"{"name":"x","size":2,"contents":[{"file":"a"}]}"#.to_string(), "he"), + // Parts of a file: at an offset, and out of a larger file. + ( + format!( + r#"{{"name":"c","size":5,"sha256":"{}","contents":[{{"file":"a","offset":6}}]}}"#, + WORLD + ), + "world", + ), + ( + r#"{"name":"d","size":3,"contents":[{"file":"a","offset":2}]}"#.to_string(), + "llo", + ), + ( + r#"{"name":"d","contents":[{"file":"a","offset":6}]}"#.to_string(), + "world", + ), + (r#"{"name":"d","contents":[{"file":"a","offset":11}]}"#.to_string(), ""), + ( + format!( + r#"{{"name":"e","size":5,"sha256":"{}","contents":[{{"file":"a","originalSize":11}}]}}"#, + HELLO + ), + "hello", + ), + ( + r#"{"name":"f","size":11,"contents":[{"file":"a","originalSize":11}]}"#.to_string(), + "hello world", + ), + // The hash of the whole file is checked too. + ( + format!( + r#"{{"name":"g","size":5,"contents":[{{"file":"a","offset":6,"originalSize":11,"originalSha256":"{}"}}]}}"#, + Sha256::digest(b"hello world") + ), + "world", + ), + // A literal needs no source. + ( + r#"{"name":"missing","contents":[{"literal":"aGVsbG8="}]}"#.to_string(), + "hello", + ), + ] { + let o = object(&record); + assert_eq!(copy(&o, &mut source).unwrap(), data.as_bytes(), "{}", record); + } + } + + #[test] + fn files_that_are_not_what_the_manifest_says() { + let files = Files::of(&[("a", b"hello world"), ("dir/b", b"hello")]); + let mut source = DirectorySource::new(&files); + let size = ErrorKind::Content(ContentProblem::SizeMismatch); + let hash = ErrorKind::Content(ContentProblem::HashMismatch); + for (record, expected) in [ + // A file too short for the data. + ( + r#"{"name":"x/y","size":12,"contents":[{"file":"a"}]}"#.to_string(), + ( + size, + Some("x/y"), + Some(11), + Some(12), + "x/y: a is too short for offset 0 and size 12", + ), + ), + // An originalSize that is not the file's. + ( + r#"{"name":"h","size":5,"contents":[{"file":"a","originalSize":12}]}"#.to_string(), + ( + size, + Some("h"), + Some(11), + Some(12), + "h: a is 11 bytes, the manifest says 12", + ), + ), + // A part that runs past the end. + ( + r#"{"name":"g","size":6,"contents":[{"file":"a","offset":6}]}"#.to_string(), + ( + size, + Some("g"), + Some(11), + Some(12), + "g: a is too short for offset 6 and size 6", + ), + ), + ( + r#"{"name":"g","contents":[{"file":"a","offset":12}]}"#.to_string(), + ( + size, + Some("g"), + Some(11), + Some(12), + "g: a is too short for offset 12 and size 0", + ), + ), + // Contents that are not the ones the manifest describes. + ( + format!(r#"{{"name":"dir/b","size":5,"sha256":"{}"}}"#, WORLD), + ( + hash, + Some("dir/b"), + None, + None, + "'dir/b' does not match the hash in the manifest", + ), + ), + ( + format!( + r#"{{"name":"dir/b","size":2,"contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + WORLD + ), + ( + hash, + Some("dir/b"), + None, + None, + "dir/b: dir/b does not match the hash in the manifest", + ), + ), + // All of a file that is not what the manifest says of it, as a + // hash of the object and as one of the file. + ( + format!( + r#"{{"name":"w","size":11,"sha256":"{}","contents":[{{"file":"a","originalSha256":"{}"}}]}}"#, + Sha256::digest(b"hello world"), + WORLD + ), + ( + hash, + Some("w"), + None, + None, + "w: a does not match the hash in the manifest", + ), + ), + ] { + let o = object(&record); + let e = copy(&o, &mut source).unwrap_err(); + let (kind, name, found, expected_size, text) = expected; + assert_eq!( + facts(&e), + (kind, name, found, expected_size, text.to_string()), + "{}", + record + ); + } + // A part of an object with a hash of its own is held against that + // one, and the file is not read beyond the part. + files.read(); + let o = object(&format!( + r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"file":"a","originalSize":11,"originalSha256":"{}"}}]}}"#, + HELLO, WORLD + )); + assert_eq!(copy(&o, &mut source).unwrap(), b"hello"); + assert_eq!(files.read(), 5); + // A part of a literal is held against the hash of all of the + // literal the manifest gives, as a part of a file is, unless the + // object has a hash of its own. + for (record, data) in [ + ( + r#"{"name":"x","contents":[{"literal":"aGVsbG8=","offset":1,"originalSha256":"#, + "ello", + ), + ( + r#"{"name":"x","size":2,"contents":[{"literal":"aGVsbG8=","originalSha256":"#, + "he", + ), + ] { + let o = object(&format!(r#"{}"{}"}}]}}"#, record, HELLO)); + assert_eq!(copy(&o, &mut source).unwrap(), data.as_bytes()); + let o = object(&format!(r#"{}"{}"}}]}}"#, record, WORLD)); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!( + facts(&e), + ( + hash, + Some("x"), + None, + None, + "'x' is a part of literal contents that do not match the hash in the manifest".to_string() + ) + ); + } + let o = object(&format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"literal":"aGVsbG8=","originalSha256":"{}"}}]}}"#, + Sha256::digest(b"he"), + WORLD + )); + assert_eq!(copy(&o, &mut source).unwrap(), b"he"); + // A literal that is not what the object says. + let o = object( + r#"{"name":"x","size":5,"contents":[{"literal":"aGVsbG8="}],"sha256":"486ea46224d1bb4fb680f34f7c9ad96a8f24ec88be73ea8e5a6c65260e9cb8a7"}"#, + ); + assert_eq!(copy(&o, &mut source).unwrap_err().kind(), hash); + let mut o = object(r#"{"name":"x","contents":[{"literal":"aGVsbG8="}]}"#); + o.size = Some(6); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!( + facts(&e), + ( + size, + Some("x"), + Some(5), + Some(6), + "'x' is 5 bytes, the manifest says 6".to_string() + ) + ); + } + + /// A file that is read whole is read as long as it was when it was + /// opened, and one byte more to see that it ends there. + #[test] + fn files_that_change_while_they_are_read() { + let files = Files::default(); + let mut source = DirectorySource::new(&files); + let changed = |file: &str| { + ( + ErrorKind::Content(ContentProblem::SourceChanged), + Some("x"), + None, + None, + format!("x: {} changed while it was read", file), + ) + }; + // A file of one piece, which grew and which shrank. + let part = format!( + r#"{{"name":"x","size":2,"contents":[{{"file":"g","originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + ); + for (data, read) in [(&b"hello world"[..], 6), (b"hel", 3)] { + files.put( + "g", + Entry::Changed { + data: data.into(), + len: 5, + }, + ); + let e = copy(&object(&part), &mut source).unwrap_err(); + assert_eq!(facts(&e), changed("g")); + assert_eq!(files.read(), read); + } + // A file of pieces that grew, read for its first part: it is not + // read on to its end, and the hashes of its pieces are not kept. + let len = 2 * COPY_SIZE + 3; + let blob: Vec = (0..len + 100).map(|i| (i ^ (i >> 8)) as u8).collect(); + files.put( + "p", + Entry::Changed { + data: blob[..].into(), + len: len as u64, + }, + ); + let o = object(&format!( + r#"{{"name":"x","size":3,"contents":[{{"file":"p","offset":1,"originalSize":{},"originalSha256":"{}"}}]}}"#, + len, + Sha256::digest(&blob[..len]) + )); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!(facts(&e), changed("p")); + assert_eq!(files.read(), len as u64 + 1); + assert!(source.hashes.files.is_empty()); + // Once it is as long as it was, it is taken. + files.put("p", Entry::File(blob[..len].into())); + assert_eq!(copy(&o, &mut source).unwrap(), &blob[1..4]); + assert_eq!(files.read(), len as u64); + assert_eq!(source.hashes.files.len(), 1); + // The data of an object that is checked against its own hash only + // is taken from a file that grew. + files.put( + "g", + Entry::Changed { + data: (&b"hello world"[..]).into(), + len: 5, + }, + ); + let o = object(&format!( + r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"file":"g"}}]}}"#, + HELLO + )); + assert_eq!(copy(&o, &mut source).unwrap(), b"hello"); + assert_eq!(files.read(), 5); + // A file that is shorter than when it was opened, for an object + // that says nothing about its size or its hash and for one that + // gives its size. + files.put( + "g", + Entry::Changed { + data: (&b"hel"[..]).into(), + len: 5, + }, + ); + for record in [ + r#"{"name":"x","contents":[{"file":"g"}]}"#, + r#"{"name":"x","size":5,"contents":[{"file":"g"}]}"#, + ] { + let e = copy(&object(record), &mut source).unwrap_err(); + assert_eq!(facts(&e), changed("g"), "{}", record); + assert_eq!(files.read(), 3); + } + } + + /// A file whose read gives nothing in the middle of it and more after + /// that changed while it was read, wherever it is read, and nothing is + /// kept of it. + #[test] + fn a_read_that_stalls() { + let len = 3 * COPY_SIZE + COPY_SIZE / 2; + let blob: Rc<[u8]> = (0..len).map(|i| (i ^ (i >> 8) ^ (i >> 16)) as u8).collect(); + let whole = Sha256::digest(&blob); + // In the middle of the second piece. + let at = COPY_SIZE + COPY_SIZE / 2; + let stalling = || Entry::Troubled { + data: Rc::clone(&blob), + at: at as u64, + trouble: Trouble::Stall, + }; + let files = Files::default(); + let mut source = DirectorySource::new(&files); + let changed = ( + ErrorKind::Content(ContentProblem::SourceChanged), + Some("x"), + None, + None, + "x: blob changed while it was read".to_string(), + ); + let part = |offset: usize, size: usize| { + object(&format!( + r#"{{"name":"x","size":{},"contents":[{{"file":"blob","offset":{},"originalSize":{},"originalSha256":"{}"}}]}}"#, + size, offset, len, whole + )) + }; + // Read whole for the hash of the file, as all of the file and for a + // part, which would keep the hashes of its pieces. Read for the + // data alone. + for (o, from) in [ + ( + object(&format!( + r#"{{"name":"x","contents":[{{"file":"blob","originalSha256":"{}"}}]}}"#, + whole + )), + 0, + ), + (part(5, 10), 0), + (object(r#"{"name":"x","contents":[{"file":"blob","offset":1}]}"#), 1), + ] { + files.put("blob", stalling()); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!(facts(&e), changed, "{:?}", o); + assert_eq!(files.read(), (at - from) as u64, "{:?}", o); + assert!(source.hashes.files.is_empty()); + } + // A part checked against the hashes of the pieces of the file. + files.put("blob", Entry::File(Rc::clone(&blob))); + assert_eq!(copy(&part(5, 10), &mut source).unwrap(), &blob[5..15]); + assert_eq!(files.read(), len as u64); + files.put("blob", stalling()); + let e = copy(&part(COPY_SIZE + 7, 10), &mut source).unwrap_err(); + assert_eq!(facts(&e), changed); + assert_eq!(files.read(), (at - COPY_SIZE) as u64); + } + + /// An error of a read names the object and the file or the stream it + /// was read from. One of the sink comes back as it was, see + /// a_sink_that_fails(). + #[test] + fn reads_that_fail() { + let eio = io::Error::from_raw_os_error(libc::EIO); + let files = Files::default(); + files.put( + "bad", + Entry::Troubled { + data: (&b"hello world"[..]).into(), + at: 6, + trouble: Trouble::FailRead(libc::EIO), + }, + ); + let mut source = DirectorySource::new(&files); + let o = object(r#"{"name":"x","size":11,"contents":[{"file":"bad"}]}"#); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.to_string()), + ( + ErrorKind::Source(SourceProblem::Unreadable), + Some("x"), + format!("x: failed to read bad: {}", eio) + ) + ); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EIO)); + /// A stream whose every read fails. + struct Failing; + impl Read for Failing { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::Error::from_raw_os_error(libc::EIO)) + } + } + let o = object(r#"{"name":"x","size":5}"#); + let e = copy(&o, &mut StreamSource::new(Failing)).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.to_string()), + ( + ErrorKind::Source(SourceProblem::Unreadable), + Some("x"), + format!("x: failed to read the stream: {}", eio) + ) + ); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::EIO)); + let e = StreamSource::new(Failing).end().unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.to_string()), + ( + ErrorKind::Source(SourceProblem::Unreadable), + None, + format!("failed to read the stream after the last file: {}", eio) + ) + ); + // A seek to the data, and one to the piece a part is in after its + // file was read whole. + let blob: Rc<[u8]> = (0..2 * COPY_SIZE + 3).map(|i| (i >> 4) as u8).collect(); + let unseekable = || Entry::Troubled { + data: Rc::clone(&blob), + at: u64::MAX, + trouble: Trouble::FailSeek(libc::EIO), + }; + files.put("blob", unseekable()); + let o = object(r#"{"name":"x","size":3,"contents":[{"file":"blob","offset":2}]}"#); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!( + (e.kind(), e.name(), e.to_string()), + ( + ErrorKind::Source(SourceProblem::Unreadable), + Some("x"), + format!("x: failed to read blob: {}", eio) + ) + ); + let part = |offset: usize| { + object(&format!( + r#"{{"name":"x","size":3,"contents":[{{"file":"blob","offset":{},"originalSize":{},"originalSha256":"{}"}}]}}"#, + offset, + blob.len(), + Sha256::digest(&blob) + )) + }; + files.put("blob", Entry::File(Rc::clone(&blob))); + assert_eq!(copy(&part(0), &mut source).unwrap(), &blob[..3]); + files.put("blob", unseekable()); + let e = copy(&part(COPY_SIZE + 1), &mut source).unwrap_err(); + assert_eq!( + (e.kind(), e.to_string()), + ( + ErrorKind::Source(SourceProblem::Unreadable), + format!("x: failed to read blob: {}", eio) + ) + ); + } + + #[test] + fn parts_of_one_file() { + // A file of three pieces and a half, no two of them the same. + let len = 3 * COPY_SIZE + COPY_SIZE / 2; + let blob: Vec = (0..len).map(|i| (i ^ (i >> 8) ^ (i >> 16)) as u8).collect(); + let whole = Sha256::digest(&blob); + let files = Files::default(); + files.put("blob", Entry::File(blob[..].into())); + let mut source = DirectorySource::new(&files); + let part = |offset: usize, size: usize, total: usize, sha256: Option| { + let sha256 = sha256.map(|sha256| format!(r#","originalSha256":"{}""#, sha256)); + object(&format!( + r#"{{"name":"p","size":{},"contents":[{{"file":"blob","offset":{},"originalSize":{}{}}}]}}"#, + size, + offset, + total, + sha256.unwrap_or_default() + )) + }; + let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let parts = [ + (5, 10), + (0, 1), + (COPY_SIZE - 1, 2), + (COPY_SIZE, COPY_SIZE), + (2 * COPY_SIZE + 7, COPY_SIZE + 9), + (len - 3, 3), + (len, 0), + (17, 0), + (1, len - 1), + (0, len), + ]; + // Without the hash of the file a part is all that is read. + for (offset, size) in parts { + let o = part(offset, size, len, None); + assert_eq!(copy(&o, &mut source).unwrap(), &blob[offset..offset + size]); + assert_eq!(files.read(), size as u64); + } + // With it the file is read whole for the first part. For the + // others the pieces they are in are read. A part of no bytes has + // the hash of no data, and all of the file the hash of the file, + // which the manifest gives for the object then: those are checked + // against that alone. + let mut first = true; + for (offset, size) in parts { + let o = part(offset, size, len, Some(whole)); + assert_eq!(copy(&o, &mut source).unwrap(), &blob[offset..offset + size]); + let from = offset / COPY_SIZE * COPY_SIZE; + let to = (offset + size).next_multiple_of(COPY_SIZE).min(len); + let read = match (size, first) { + (0, _) => 0, + (_, true) => len, + _ => to - from, + }; + assert_eq!(files.read(), read as u64, "{} at {}", size, offset); + first &= size == 0; + } + // Another hash for the same file is not taken on trust. + let o = part(5, 10, len, Some(Sha256::digest(b"another file"))); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!( + facts(&e), + ( + hash, + Some("p"), + None, + None, + "p: blob does not match the hash in the manifest".to_string() + ) + ); + assert_eq!(files.read(), len as u64); + // A file that changed is found out where it changed, and a file + // of another length is read whole again. + let mut changed = blob.clone(); + changed[2 * COPY_SIZE + 100] ^= 1; + files.put("blob", Entry::File(changed[..].into())); + for (offset, size, good) in [ + (5, 10, true), + (COPY_SIZE, COPY_SIZE, true), + (2 * COPY_SIZE, 5, false), + (2 * COPY_SIZE + 100, 1, false), + (COPY_SIZE + 5, COPY_SIZE, false), + (3 * COPY_SIZE - 1, 2, false), + (3 * COPY_SIZE, 1, true), + (1, len - 1, false), + (0, len, false), + ] { + let copied = copy(&part(offset, size, len, Some(whole)), &mut source); + match copied { + Ok(data) => assert!(good && data == changed[offset..offset + size], "{} at {}", size, offset), + Err(e) => assert!(!good && e.kind() == hash, "{} at {}: {}", size, offset, e), + } + } + files.read(); + files.put("blob", Entry::File(blob[..len - 1].into())); + let e = copy(&part(5, 10, len - 1, Some(whole)), &mut source).unwrap_err(); + assert_eq!(e.kind(), hash); + assert_eq!(files.read(), len as u64 - 1); + let shorter = Sha256::digest(&blob[..len - 1]); + for _ in 0..2 { + let o = part(len - 11, 10, len - 1, Some(shorter)); + assert_eq!(copy(&o, &mut source).unwrap(), &blob[len - 11..len - 1]); + } + assert_eq!(files.read(), (len - 1 + COPY_SIZE / 2 - 1) as u64); + // A file that is one object is read once, hash or no hash. + let small = Files::of(&[("a", b"hello")]); + for record in [ + r#"{"name":"a","size":5}"#.to_string(), + format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO), + format!( + r#"{{"name":"a","contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + ), + ] { + let mut source = DirectorySource::new(&small); + for _ in 0..2 { + assert_eq!(copy(&object(&record), &mut source).unwrap(), b"hello", "{}", record); + assert_eq!(small.read(), 5); + } + } + } + + /// The file `data` to copy `part` of, hashed in pieces of `piece_size` + /// bytes. What is read of it is counted in `read`. + fn pieces_over<'a>( + data: &[u8], + piece_size: usize, + part: Range, + buffer: &'a mut [u8], + read: &Rc>, + ) -> Pieces<'a, Counted> { + Pieces { + file: Counted { + data: io::Cursor::new(data.into()), + read: Rc::clone(read), + trouble: None, + }, + buffer, + len: data.len() as u64, + piece_size: piece_size as u64, + pos: 0, + data: part.start as u64..part.end as u64, + } + } + + /// Pieces larger than what is read at a time, as those of a file of + /// more than [`MAX_PIECES`] MiB are. + #[test] + fn pieces_larger_than_a_read() { + let piece_size = 2 * COPY_SIZE + COPY_SIZE / 2; + let len = 2 * piece_size + 3; + let blob: Vec = (0..len).map(|i| (i ^ (i >> 9) ^ (i >> 17)) as u8).collect(); + let mut buffer = vec![0; COPY_SIZE]; + let read = Rc::new(Cell::new(0)); + // Read whole, a part of the file is copied and every piece hashed. + let mut hashes = Vec::new(); + let mut out = Vec::new(); + let mut pieces = pieces_over(&blob, piece_size, 7..piece_size + 9, &mut buffer, &read); + pieces + .copy_hashed(&mut out, Some(&mut hashes), Sha256::digest(&blob)) + .unwrap(); + assert_eq!(out, &blob[7..piece_size + 9]); + let expected: Vec = blob.chunks(piece_size).map(Sha256::digest).collect(); + assert_eq!(hashes, expected); + assert_eq!(read.replace(0), len as u64); + // A part is checked against the pieces it is in, and only those are + // read. + for part in [0..1, piece_size - 1..piece_size + 1, 2 * piece_size..len, 1..len - 1] { + let mut out = Vec::new(); + let mut pieces = pieces_over(&blob, piece_size, part.clone(), &mut buffer, &read); + pieces.copy_checked(&mut out, &hashes).unwrap(); + assert_eq!(out, &blob[part.clone()]); + let from = part.start / piece_size * piece_size; + let to = part.end.next_multiple_of(piece_size).min(len); + assert_eq!(read.replace(0), (to - from) as u64, "{:?}", part); + } + // A change in a piece is found where the piece is read. + let mut changed = blob.clone(); + changed[piece_size + 5] ^= 1; + for (part, matches) in [ + (0..piece_size, true), + (2..piece_size + 1, false), + (2 * piece_size - 1..2 * piece_size, false), + (2 * piece_size..len, true), + ] { + let mut pieces = pieces_over(&changed, piece_size, part.clone(), &mut buffer, &read); + match pieces.copy_checked(&mut io::sink(), &hashes) { + Ok(()) => assert!(matches, "{:?}", part), + Err(CopyFailure::HashMismatch) => assert!(!matches, "{:?}", part), + Err(e) => panic!("{:?}: {:?}", part, e), + } + } + } + + /// What a source keeps of the files it read whole does not grow with + /// the manifest, and what it decides to keep it keeps. + #[test] + fn keeps_hashes_up_to_the_bound() { + let mib = COPY_SIZE as u64; + // A file is cut into pieces of 1 MiB, and of more where it would + // have more than MAX_PIECES of them. The hashes of the pieces of a + // file of any length fit into what a source keeps. + assert_eq!(PieceHashes::piece_size(MAX_PIECES * mib), mib); + assert_eq!(PieceHashes::piece_size(MAX_PIECES * mib + 1), mib + 1); + assert_eq!(PieceHashes::piece_count(MAX_PIECES * mib + 1), MAX_PIECES); + for len in [ + 0, + 1, + mib, + mib + 1, + MAX_PIECES * mib, + 33 << 30, + 1 << 50, + u64::MAX - 1, + u64::MAX, + ] { + let (size, count) = (PieceHashes::piece_size(len), PieceHashes::piece_count(len)); + assert!(count <= MAX_PIECES, "{}", len); + assert!( + count == 0 || (count - 1) * size < len && len <= count.saturating_mul(size), + "{}", + len + ); + assert!(PieceHashes::stored_bytes(count) <= PIECE_HASH_BYTES, "{}", len); + } + // So a source that holds no hashes keeps those of any file of more + // than one piece. + let empty = PieceHashes::default(); + assert!(empty.is_keepable(u64::MAX) && empty.is_keepable(mib + 1)); + assert!(!empty.is_keepable(mib) && !empty.is_keepable(0)); + let mut kept = PieceHashes::default(); + kept.keep(hash_of(0), u64::MAX, vec![Sha256::EMPTY; MAX_PIECES as usize].into()); + assert!(kept.bytes <= PIECE_HASH_BYTES && kept.get(hash_of(0), u64::MAX).is_some()); + // At the bound: what keep() takes is what is_keepable() counts. A + // file whose hashes fill what is left is kept, one of a piece more + // is not, and nothing that was kept is dropped. + let mut kept = PieceHashes::default(); + kept.keep(hash_of(1), 1000 * mib, vec![Sha256::EMPTY; 1000].into()); + let left = PIECE_HASH_BYTES - kept.bytes; + let fitting = ((left - FILE_ENTRY_BYTES) / size_of::()) as u64; + assert!(kept.is_keepable(fitting * mib) && !kept.is_keepable(fitting * mib + 1)); + kept.keep(hash_of(2), fitting * mib, vec![Sha256::EMPTY; fitting as usize].into()); + assert!(kept.bytes <= PIECE_HASH_BYTES && PIECE_HASH_BYTES - kept.bytes < size_of::()); + assert!(!kept.is_keepable(2 * mib)); + assert!(kept.get(hash_of(1), 1000 * mib).is_some() && kept.get(hash_of(2), fitting * mib).is_some()); + // A file is known by its hash and its length. + assert!(kept.get(hash_of(1), 1000 * mib - 1).is_none() && kept.get(hash_of(2), 1000 * mib).is_none()); + // A part of a file of one piece is checked by reading all of the + // file, and nothing is kept of it. + let names = ["a", "b", "c", "d"]; + let files = Files::of(&names.map(|name| (name, &b"ab"[..]))); + let mut source = DirectorySource::new(&files); + for name in names { + let o = object(&format!( + r#"{{"name":"x","size":1,"contents":[{{"file":"{}","offset":1,"originalSize":2,"originalSha256":"{}"}}]}}"#, + name, + Sha256::digest(b"ab") + )); + assert_eq!(copy(&o, &mut source).unwrap(), b"b"); + assert_eq!(files.read(), 2); + } + assert_eq!((source.hashes.files.len(), source.hashes.bytes), (0, 0)); + // A part of a file whose hashes the source cannot keep any more is + // copied without the check of the whole file: the hash the + // manifest gives for that is not looked at. + let blob: Vec = (0..2 * COPY_SIZE).map(|i| (i >> 3) as u8).collect(); + files.put("blob", Entry::File(blob[..].into())); + source.hashes = kept; + let o = object(&format!( + r#"{{"name":"x","size":3,"contents":[{{"file":"blob","offset":5,"originalSize":{},"originalSha256":"{}"}}]}}"#, + blob.len(), + hash_of(3) + )); + assert_eq!(copy(&o, &mut source).unwrap(), &blob[5..8]); + assert_eq!(files.read(), 3); + assert_eq!(source.hashes.files.len(), 2); + } + + #[test] + fn files_that_are_not_there() { + let files = Files::of(&[("a", b"hello")]); + files.put("fifo", Entry::Other); + files.put("below-a-file/x", Entry::Fails(libc::ENOTDIR)); + files.put("odd", Entry::Fails(libc::EINVAL)); + files.put("link", Entry::Fails(libc::ELOOP)); + files.put("secret", Entry::Fails(libc::EACCES)); + let mut source = DirectorySource::new(&files); + for (file, problem, errno, text) in [ + ( + "missing", + SourceProblem::Missing, + Some(libc::ENOENT), + "x: failed to open missing: ", + ), + ( + "below-a-file/x", + SourceProblem::Missing, + Some(libc::ENOTDIR), + "x: failed to open below-a-file/x: ", + ), + ("fifo", SourceProblem::NotRegular, None, "x: fifo is not a regular file"), + ( + "odd", + SourceProblem::NotRegular, + Some(libc::EINVAL), + "x: failed to open odd: ", + ), + ( + "link", + SourceProblem::Unreadable, + Some(libc::ELOOP), + "x: failed to open link: ", + ), + ( + "secret", + SourceProblem::Unreadable, + Some(libc::EACCES), + "x: failed to open secret: ", + ), + ] { + let o = object(&format!( + r#"{{"name":"x","size":5,"contents":[{{"file":"{}"}}]}}"#, + file + )); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Source(problem), "{}", file); + assert_eq!(e.name(), Some("x")); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), errno, "{}", file); + let cause = errno.map(|errno| io::Error::from_raw_os_error(errno).to_string()); + assert_eq!(e.to_string(), format!("{}{}", text, cause.unwrap_or_default())); + } + // A name is quoted with its control characters escaped: one of C1 + // is a control sequence on a terminal. + let o = object(r#"{"name":"x\u009b2J","size":5}"#); + let e = copy(&o, &mut source).unwrap_err(); + assert_eq!(e.name(), Some("x\u{9b}2J")); + assert!( + e.to_string().starts_with(r"x\u{9b}2J: failed to open x\u{9b}2J: "), + "{}", + e + ); + } + + #[test] + fn copies_from_a_stream() { + let all = objects(&[ + &format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO), + r#"{"name":"empty","size":0}"#, + r#"{"name":"literal","contents":[{"literal":"aGVsbG8="}]}"#, + r#"{"name":"d","type":"dir"}"#, + &format!( + r#"{{"name":"d/b","size":5,"sha256":"{}","contents":[{{"file":"other"}}]}}"#, + WORLD + ), + ]); + let streamed: Vec<&FileObject> = all.iter().filter(|o| o.has_external_data()).collect(); + assert_eq!(streamed.len(), 3); + let mut stream = &b"helloworld"[..]; + let mut source = StreamSource::new(&mut stream); + assert_eq!(copy(streamed[0], &mut source).unwrap(), b"hello"); + assert_eq!(copy(&all[2], &mut source).unwrap(), b"hello"); + assert_eq!(copy(streamed[1], &mut source).unwrap(), b""); + assert_eq!(copy(streamed[2], &mut source).unwrap(), b"world"); + source.end().unwrap(); + assert!(stream.is_empty()); + + // A stream that ends early, and one that goes on after the last file. + let mut stream = &b"hellowo"[..]; + let mut source = StreamSource::new(&mut stream); + copy(streamed[0], &mut source).unwrap(); + let e = copy(streamed[2], &mut source).unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Content(ContentProblem::StreamEnded), + Some("d/b"), + Some(2), + Some(5), + "d/b: the stream ended 3 bytes early".to_string() + ) + ); + let mut stream = &b"helloworldmore"[..]; + let mut source = StreamSource::new(&mut stream); + copy(streamed[0], &mut source).unwrap(); + copy(streamed[2], &mut source).unwrap(); + let e = source.end().unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Content(ContentProblem::SizeMismatch), + Some("d/b"), + None, + Some(5), + "d/b: the stream goes on after the last file".to_string() + ) + ); + // A stream that has data when it had none of a file, and one that + // has none. + let mut stream = &b"junk"[..]; + let e = StreamSource::new(&mut stream).end().unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Content(ContentProblem::SizeMismatch), + None, + None, + Some(0), + "the stream has data that no file of the manifest describes".to_string() + ) + ); + let mut stream = &b""[..]; + StreamSource::new(&mut stream).end().unwrap(); + // Contents that are not the ones the manifest describes. + let mut stream = &b"hellp"[..]; + let e = copy(streamed[0], &mut StreamSource::new(&mut stream)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + } + + /// The hash the manifest gives for all of a file is checked where a + /// stream has all of the file, and a part of a file is checked against + /// the hash of the object alone. + #[test] + fn whole_files_and_parts_in_a_stream() { + let hash = ErrorKind::Content(ContentProblem::HashMismatch); + let check = |o: &FileObject, data: &'static [u8]| { + let mut stream = data; + let copied = copy(o, &mut StreamSource::new(&mut stream)); + assert!(stream.is_empty()); + copied + }; + // A reader gives an object that is all of its file the hash of the + // file as its own. + let sized = object(&format!( + r#"{{"name":"x","size":5,"contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + )); + assert_eq!(sized.sha256, HELLO.parse().ok()); + assert_eq!(check(&sized, b"hello").unwrap(), b"hello"); + assert_eq!(check(&sized, b"world").unwrap_err().kind(), hash); + // An object that is all of its file without a hash of its own. + let mut whole = FileObject::new(Name::new("x").unwrap()); + whole.size = Some(5); + let mut contents = Contents::new(Location::Implied); + contents.original_size = Some(5); + contents.original_sha256 = HELLO.parse().ok(); + whole.contents.push(contents); + assert_eq!(check(&whole, b"hello").unwrap(), b"hello"); + let e = check(&whole, b"world").unwrap_err(); + assert_eq!( + facts(&e), + ( + hash, + Some("x"), + None, + None, + "x: x does not match the hash in the manifest".to_string() + ) + ); + // A part with a hash of its own is held against that, and one + // without, or one the stream cannot tell from all of the file, is + // taken as it is. + let part = object(&format!( + r#"{{"name":"x","size":2,"sha256":"{}","contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + Sha256::digest(b"he"), + HELLO + )); + assert_eq!(check(&part, b"he").unwrap(), b"he"); + assert_eq!(check(&part, b"hx").unwrap_err().kind(), hash); + for record in [ + format!( + r#"{{"name":"x","size":2,"contents":[{{"originalSize":5,"originalSha256":"{}"}}]}}"#, + HELLO + ), + format!( + r#"{{"name":"x","size":5,"contents":[{{"originalSha256":"{}"}}]}}"#, + HELLO + ), + ] { + let o = object(&record); + assert_eq!(o.sha256, None); + let data: &'static [u8] = if o.size == Some(2) { b"xx" } else { b"world" }; + assert_eq!(check(&o, data).unwrap(), data, "{}", record); + } + // A stream has no place for a file without a size or at an offset. + let mut stream = &b"hello"[..]; + let mut source = StreamSource::new(&mut stream); + let e = copy(&object(r#"{"name":"x"}"#), &mut source).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::NoSize)); + assert_eq!((e.name(), e.field()), (Some("x"), Some(Field::Size))); + assert_eq!(e.to_string(), "x: streamed contents need a known size"); + let e = copy( + &object(r#"{"name":"x","size":2,"contents":[{"offset":1}]}"#), + &mut source, + ) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::OffsetInStream)); + assert_eq!(e.name(), Some("x")); + assert_eq!(stream, b"hello"); + } + + /// The data of an object that a consumer does not take is read past + /// on a stream, and checked as it would be in a copy. + #[test] + fn skips_what_is_not_taken() { + let all = objects(&[ + &format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, HELLO), + r#"{"name":"d","type":"dir"}"#, + &format!(r#"{{"name":"d/b","size":5,"sha256":"{}"}}"#, WORLD), + r#"{"name":"literal","contents":[{"literal":"aGVsbG8="}]}"#, + r#"{"name":"remote","contents":[{"url":"https://example.com/x"}]}"#, + ]); + let mut stream = &b"helloworld"[..]; + let mut source = StreamSource::new(&mut stream); + for o in [&all[0], &all[1]] { + source.skip(o).unwrap(); + } + assert_eq!(copy(&all[2], &mut source).unwrap(), b"world"); + for o in &all[3..] { + source.skip(o).unwrap(); + } + source.end().unwrap(); + // A skip fails where a copy would. + let mut stream = &b"hellp"[..]; + let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::HashMismatch)); + let mut stream = &b"hel"[..]; + let e = StreamSource::new(&mut stream).skip(&all[0]).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::StreamEnded)); + let mut stream = &b"hello"[..]; + let e = StreamSource::new(&mut stream) + .skip(&object(r#"{"name":"x"}"#)) + .unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Unsupported(UnsupportedContent::NoSize)); + // A directory has nothing to read past. + let files = Files::of(&[("a", b"hello")]); + DirectorySource::new(&files).skip(&all[0]).unwrap(); + assert_eq!(files.read(), 0); + } + + /// Writes "hello world" for every object, whatever it says. + struct Babbler { + /// Whether a write that fails fails the copy. + careful: bool, + } + + impl ContentSource for Babbler { + fn copy(&mut self, _: &FileObject, _: &Reference<'_>, sink: &mut dyn Write) -> Result<(), Error> { + let written = sink.write_all(b"hello world"); + if self.careful { + written?; + } + Ok(()) + } + } + + #[test] + fn checks_what_passes() { + let o = object(&format!(r#"{{"name":"x","size":5,"sha256":"{}"}}"#, HELLO)); + let mut check = ContentCheck::new(&o); + for piece in [&b"he"[..], b"", b"llo"] { + check.update(piece).unwrap(); + } + assert_eq!(check.finish().unwrap(), 5); + // Too few bytes, the wrong ones, and too many. + let mut check = ContentCheck::new(&o); + check.update(b"hell").unwrap(); + let e = check.finish().unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Content(ContentProblem::SizeMismatch), + Some("x"), + Some(4), + Some(5), + "'x' is 4 bytes, the manifest says 5".to_string() + ) + ); + let mut check = ContentCheck::new(&o); + check.update(b"world").unwrap(); + assert_eq!( + check.finish().unwrap_err().kind(), + ErrorKind::Content(ContentProblem::HashMismatch) + ); + let mut check = ContentCheck::new(&o); + check.update(b"hell").unwrap(); + let e = check.update(b"o!").unwrap_err(); + assert_eq!( + facts(&e), + ( + ErrorKind::Content(ContentProblem::SizeMismatch), + Some("x"), + None, + Some(5), + "'x' has more than the 5 bytes the manifest says".to_string() + ) + ); + // What it refused it did not take. + check.update(b"o").unwrap(); + assert_eq!(check.finish().unwrap(), 5); + // Without a size and a hash it counts. + let o = object(r#"{"name":"x","contents":[{"url":"https://example.com/x"}]}"#); + let mut check = ContentCheck::new(&o); + check.update(b"any").unwrap(); + check.update(b"thing").unwrap(); + assert_eq!(check.finish().unwrap(), 8); + // A source that writes more than the size of the object is stopped + // before the sink gets any of it, and fails the copy with what the + // check says, also when it passes over the error of the write. + let o = object(r#"{"name":"x","size":5}"#); + for careful in [true, false] { + let mut out = Vec::new(); + let e = o.copy_contents(&mut Babbler { careful }, &mut out).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Content(ContentProblem::SizeMismatch)); + assert_eq!((e.found_size(), e.expected_size()), (None, Some(5))); + assert!(out.is_empty()); + } + } + + /// Takes a few bytes and then fails. + #[derive(Debug)] + struct Full(usize); + + impl Write for Full { + fn write(&mut self, data: &[u8]) -> io::Result { + if data.len() > self.0 { + return Err(io::Error::from_raw_os_error(libc::ENOSPC)); + } + self.0 -= data.len(); + Ok(data.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + #[test] + fn a_sink_that_fails() { + let o = object(r#"{"name":"a","size":5}"#); + let literal = object(r#"{"name":"l","contents":[{"literal":"aGVsbG8="}]}"#); + let files = Files::of(&[("a", b"hello")]); + let nothing = Files::default(); + let mut directory = DirectorySource::new(&files); + let mut stream = &b"hello"[..]; + let mut stream = StreamSource::new(&mut stream); + let mut empty = DirectorySource::new(¬hing); + let sources: [(&FileObject, &mut dyn ContentSource); 3] = + [(&o, &mut directory), (&o, &mut stream), (&literal, &mut empty)]; + for (object, source) in sources { + let e = object.copy_contents(source, &mut Full(4)).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::Io); + assert_eq!(e.io_error().and_then(io::Error::raw_os_error), Some(libc::ENOSPC)); + } + } + + /// What a source prints for debugging says how large its buffer is, + /// and does not hold it. + #[test] + fn debug_shows_no_buffers() { + let files = Files::of(&[("a", b"hello")]); + let mut source = DirectorySource::new(&files); + copy(&object(r#"{"name":"a","size":5}"#), &mut source).unwrap(); + let text = format!("{:?}", source); + assert!(text.len() < 500, "{}", text); + assert!( + text.contains("buffer: 1048576/1048576, hashes: PieceHashes { files: 0, bytes: 0/1048576 }"), + "{}", + text + ); + let mut source = StreamSource::new(io::repeat(7).take(2 * COPY_SIZE as u64)); + copy(&object(r#"{"name":"a","size":5}"#), &mut source).unwrap(); + let text = format!("{:?}", source); + assert!(text.len() < 200, "{}", text); + assert!( + text.ends_with(r#"buffer: 1048576/1048576, last: Some(("a", 5)) }"#), + "{}", + text + ); + } +} diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index d958653..5b2fa60 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -169,6 +169,61 @@ impl Problem { } } +/// How the data of a file object cannot be had from where it is: a file +/// the manifest refers to that is not there as the manifest describes it, +/// or a file or a stream that cannot be read. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum SourceProblem { + /// The file is not there. + Missing, + /// It is not a regular file. + NotRegular, + /// The file could not be opened, or it or the stream could not be + /// read, for the reason [`Error::io_error`] gives. + Unreadable, +} + +/// How contents fail to be what the manifest describes, found while they +/// are copied. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ContentProblem { + /// They are not as many bytes as the manifest says, their file is too + /// short for them, or their file is not as long as the `originalSize` + /// the manifest gives, shorter or longer. + SizeMismatch, + /// They do not have the hash the manifest says, or their file does not + /// have the hash the manifest gives for it. + HashMismatch, + /// The stream they come from ended before they were complete. + StreamEnded, + /// The file they are in changed while it was read: it is not as long + /// as it was when it was opened, or longer. + SourceChanged, +} + +/// Contents that a manifest gives in a way this crate cannot take. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum UnsupportedContent { + /// They start at an offset in their file, and the source is a + /// [`StreamSource`](crate::StreamSource), which has them and nothing + /// else of the file. + OffsetInStream, + /// The object gives no size, and the source is a + /// [`StreamSource`](crate::StreamSource), which needs it to know where + /// they end. + NoSize, + /// Every contents object of the file has them at a URL or in an + /// encoding, and they would have to be fetched or decoded. + UrlOrEncoding, + /// There are none. The object has no contents objects, and only a + /// regular file has its contents in the file of its own name without + /// one. + Absent, +} + /// Why a file object must not be used now. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Invalid { @@ -186,6 +241,12 @@ pub enum Invalid { pub enum ErrorKind { /// The manifest is malformed. Manifest(Problem), + /// The data of a file object cannot be had from where it is. + Source(SourceProblem), + /// Contents are not what the manifest describes. + Content(ContentProblem), + /// The manifest gives contents in a way this crate cannot take. + Unsupported(UnsupportedContent), /// A file object is revoked or outside its validity window. NotValid(Invalid), /// Reading or writing failed. @@ -403,6 +464,9 @@ struct Inner { record_number: Option, name: Option, field: Option, + found_size: Option, + expected_size: Option, + value: Option, cause: Option, } @@ -414,6 +478,9 @@ impl Error { record_number: None, name: None, field: None, + found_size: None, + expected_size: None, + value: None, cause: None, })) } @@ -444,6 +511,22 @@ impl Error { self } + /// Notes the size that was found and the one that was expected. + #[must_use] + pub(crate) fn sizes(mut self, found: Option, expected: Option) -> Error { + self.0.found_size = found; + self.0.expected_size = expected; + self + } + + /// Notes what is not supported: the ways the contents are available + /// in. + #[must_use] + pub(crate) fn valued(mut self, value: impl Into) -> Error { + self.0.value = Some(value.into()); + self + } + /// Notes the I/O error behind this one. #[must_use] pub(crate) fn caused_by(mut self, error: io::Error) -> Error { @@ -573,6 +656,27 @@ impl Error { self.0.field } + /// The size that was found, when the error is about a size and it is + /// known: for a [`ContentProblem::SizeMismatch`] and a + /// [`ContentProblem::StreamEnded`]. + pub fn found_size(&self) -> Option { + self.0.found_size + } + + /// The size that was expected, when the error is about a size: the one + /// the manifest says, or the size a file needs at least to hold the + /// data the manifest says it holds. + pub fn expected_size(&self) -> Option { + self.0.expected_size + } + + /// What is not supported, for [`UnsupportedContent::UrlOrEncoding`]: + /// the ways the contents are available in, such as `'gzip' encoding or + /// a URL`. + pub fn value(&self) -> Option<&str> { + self.0.value.as_deref() + } + /// The I/O error behind this one, if there is one. pub fn io_error(&self) -> Option<&io::Error> { match &self.0.cause { @@ -643,6 +747,39 @@ mod tests { assert_eq!(io.to_string(), "incomplete"); } + #[test] + fn what_an_error_is_about() { + let e = Error::manifest(Problem::WrongFieldType, "message".to_string()) + .at(Field::MTimeNSec) + .in_record(3) + .in_record(4) + .named("a/b"); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::WrongFieldType)); + assert_eq!( + (e.record_number(), e.name(), e.field()), + (Some(3), Some("a/b"), Some(Field::MTimeNSec)) + ); + assert_eq!(e.field().unwrap().to_string(), "mTimeNSec"); + assert_eq!(e.to_string(), "message"); + assert_eq!((e.found_size(), e.expected_size(), e.value()), (None, None, None)); + assert!(e.io_error().is_none() && std::error::Error::source(&e).is_none()); + let e = Error::new(ErrorKind::Content(ContentProblem::SizeMismatch), String::new()) + .sizes(Some(1), Some(2)) + .valued("gzip"); + assert_eq!( + (e.found_size(), e.expected_size(), e.value()), + (Some(1), Some(2), Some("gzip")) + ); + let e = Error::not_json(7, json::parse("{").unwrap_err()); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NotJson)); + assert_eq!(e.record_number(), Some(7)); + assert_eq!( + e.to_string(), + "manifest record 7 is not valid JSON: expected a string key at byte 1" + ); + assert!(std::error::Error::source(&e).is_some()); + } + /// The names of the problems the vectors of refused.jsonl do not hold: /// those of the bytes of a manifest that are not UTF-8, that do not /// start with a record separator or that are too large, and the one of diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 8e12c23..c49dd48 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -24,6 +24,11 @@ //! [`InodeFlags`], [`Sha256`] and [`Uuid`] what their fields hold. What //! the root file object and a file object both have is in //! [`InodeAttributes`] and [`ValidityWindow`]. +//! - [`ContentSource`] is where the contents of the files come from when a +//! manifest is applied: [`DirectorySource`] for the files next to the +//! manifest and [`StreamSource`] for one stream with all of them. +//! [`FileObject::copy_contents`] copies the contents of a file and checks +//! them against the manifest with a [`ContentCheck`]. //! //! A manifest that does not come through a [`Read`], such as one from an //! async runtime, goes to a [`Decoder`] as it comes. [`Decoder::step`] says @@ -43,6 +48,11 @@ //! [`Encoder::signature`] and [`Encoder::finish`] append its records to a //! string, and the caller sends them on. //! +//! Contents that do not go through a [`Write`] are checked with a +//! [`ContentCheck`]: [`ContentCheck::update`] takes them as they come, and +//! [`ContentCheck::finish`] says whether they have the size and the hash +//! the manifest gives. +//! //! A manifest is input from outside and can be very large. Reading one //! takes time in proportion to its size, and keeps one record without its //! separator and the name of the file object before it in memory: less @@ -52,7 +62,8 @@ //! //! Signature objects are read and not verified: that takes an OpenPGP or //! an X.509 implementation. [`Reader::signed_len`] says how much of the -//! manifest they sign. +//! manifest they sign. Contents that are stored in an encoding or that +//! have to be fetched from a URL are not taken. //! //! The reader takes every field the specification has. A field it does //! not know is passed over, whatever its value is, as the specification @@ -66,6 +77,7 @@ #![warn(missing_docs)] mod base64; +mod content; mod decode; mod digest; mod error; @@ -77,8 +89,9 @@ mod reader; mod sequence; mod writer; +pub use content::{ContentCheck, ContentSource, Data, Directory, DirectorySource, OpenError, Reference, StreamSource}; pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; -pub use error::{Error, ErrorKind, Field, Invalid, Problem}; +pub use error::{ContentProblem, Error, ErrorKind, Field, Invalid, Problem, SourceProblem, UnsupportedContent}; pub use features::{Features, Order, UnknownFeature}; pub use name::{InvalidName, Name}; pub use object::{ From 562c8c796c0f517aa7d08a85ce4f1908ea617448 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 15:26:48 +0100 Subject: [PATCH 10/19] ufat: take one SOURCE tree assemble, populate and assemble --plan take any number of SOURCE trees and merge them, and --fit can be given more than once. No mkfs tool does that. mke2fs -d, mkfs.xfs -p and mkfs.btrfs --rootdir take one directory. mksquashfs takes several sources, but each of them becomes an entry of the root instead of being merged into it. systemd-repart takes several CopyFiles= and merges them itself, and the Varlink interface takes one sourceFileDescriptor. So let's take one tree as well. A second SOURCE or a second --fit fails with EINVAL, and merging trees is up to the caller. That is checked before anything is opened. So are the values of --times and --unsupported, right after the command line is parsed. A bad --times used to fail only when the content was written, after assemble had formatted the image or populate had made the directory --path names. Bad values are now refused whatever the command does, so also with --plan, --fit or --manifest without a SOURCE, which didn't look at them before. While at it, let's make the resolved SOURCE a proper type. Sources held a list of trees and an optional manifest, and each function that used it went through both. Now Source is nothing, a tree, or a manifest with the place its file contents come from. Source::open() resolves it, and checking, planning and filling it are its methods check(), add_to() and fill(). Data becomes ContentOrigin, since uapi16::Data is something else. Signed-off-by: Christian Brauner (Amutable) --- README.md | 8 +- src/bin/ufat/cli.rs | 429 ++++++++++++++++++++++++-------------------- tests/cli.rs | 103 ++++++++--- 3 files changed, 322 insertions(+), 218 deletions(-) diff --git a/README.md b/README.md index 333b8c2..b2b611f 100644 --- a/README.md +++ b/README.md @@ -95,9 +95,9 @@ The commands are: | Command | What it does | |---|---| -| `assemble IMAGE [SOURCE...]` | Create a file system sized to fit the sources and copy them into it. Without a SOURCE, create an empty file system. | -| `assemble --plan [SOURCE...]` | Print the smallest file system size that holds the sources. | -| `populate IMAGE [SOURCE...]` | Copy directory trees or one file into an existing file system. Without a SOURCE, create a directory. | +| `assemble IMAGE [SOURCE]` | Create a file system sized to fit SOURCE or what `--manifest` describes, and fill it with that. Without a SOURCE, create an empty file system. | +| `assemble --plan [SOURCE]` | Print the smallest file system size that holds SOURCE or what `--manifest` describes. | +| `populate IMAGE [SOURCE]` | Copy a directory tree, one file, or what `--manifest` describes into an existing file system. Without a SOURCE, create a directory. | | `remove IMAGE PATH...` | Remove files and empty directories. `-r` removes directories with everything in them. | | `list IMAGE [PATH]` | List a directory. `-l` shows sizes and times. | | `describe IMAGE` | Show the geometry of a file system. | @@ -118,7 +118,7 @@ The most common ones: serial number, as XXXX-XXXX or 8 hex digits. - `--sector-size BYTES` sets the logical sector size. See "Sector size" below. -- `--path PATH` copies directory trees below PATH instead of the root. +- `--path PATH` copies the directory tree below PATH instead of the root. For `populate` it is also the path of a single file, or the directory to create. - `--no-replace` fails instead of replacing files that exist. diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index c622c32..e9b53bf 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -31,11 +31,12 @@ Usage: ufat COMMAND [OPTIONS...] ARGS... ufat --version Commands: - assemble [OPTIONS] IMAGE [SOURCE...] Create a FAT32 file system sized to fit - the sources and fill it with them - assemble --plan [OPTIONS] [SOURCE...] Print the smallest file system size for - the sources - populate [OPTIONS] IMAGE [SOURCE...] Fill an existing FAT32 file system + assemble [OPTIONS] IMAGE [SOURCE] Create a FAT32 file system sized to fit + SOURCE or what --manifest describes, + and fill it with that + assemble --plan [OPTIONS] [SOURCE] Print the smallest file system size for + SOURCE or what --manifest describes + populate [OPTIONS] IMAGE [SOURCE] Fill an existing FAT32 file system remove [OPTIONS] IMAGE PATH... Remove files and directories list [-l] IMAGE [PATH] List a directory describe [OPTIONS] IMAGE Show a file system's geometry @@ -49,7 +50,7 @@ The commands are the methods of the org.uapi-group.FileSystem Varlink interface that ufat serves; cat and manifest have no method. assemble without a SOURCE creates an empty file system of the size of IMAGE or ---size, or sized to hold the --fit directories or what --manifest describes. +--size, or sized to hold the --fit directory or what --manifest describes. assemble refuses an IMAGE that holds a file system, a partition table or other data libblkid recognizes, or without libblkid anything that is not blank. --force formats it anyway. @@ -68,11 +69,11 @@ read, or - for the contents on standard input, back to back in manifest order: Options common to commands taking IMAGE: --offset BYTES Byte offset of the file system inside IMAGE --size BYTES Size of the file system inside IMAGE (assemble: instead - of the size that fits the sources; assemble --plan: - fail when the sources do not fit this size) + of the size that fits the content; assemble --plan: + fail when the content does not fit this size) Options for assemble: - --plan Print the size the sources need and write nothing + --plan Print the size the content needs and write nothing --sector-size BYTES Logical sector size, 512 or 4096 (1024 and 2048 work) --cluster-size BYTES Cluster size --identifier ID Volume serial number, XXXX-XXXX or 8 hex digits @@ -89,7 +90,7 @@ Options for assemble: needs --size, --fit or --manifest for that) --force, -f Format IMAGE whatever it holds --fit DIR Size IMAGE to the smallest file system holding DIR - and leave it empty (no SOURCE; repeatable) + and leave it empty (no SOURCE) --hash ALGORITHM Print the sha256 or sha512 hash of the file system written --write-hash PATH Write that hash to PATH instead, or to standard output @@ -398,13 +399,13 @@ fn fail_unsupported(args: &Args) -> Result { } } -/// Where SOURCE trees go: `--path`, the root by default. +/// Where a SOURCE tree goes: `--path`, the root by default. fn dest(args: &Args) -> &str { args.value("path").unwrap_or("/") } /// Where the contents of a manifest's files come from. -enum Data { +enum ContentOrigin { /// The tree the manifest describes, pinned. Directory { path: PathBuf, dir: OwnedFd }, /// Standard input: every file's contents back to back, in manifest @@ -412,21 +413,33 @@ enum Data { Stdin, } -/// The manifest `--manifest` named, read once, and where its data is. -struct ManifestSource { - /// How messages name the manifest: its path, or standard input. - name: String, - manifest: manifest::Manifest, - /// None for the commands that only size. - data: Option, +/// The SOURCE argument, resolved once and before any image is touched. +enum Source { + /// Neither a SOURCE nor `--manifest`. + None, + /// A directory tree, pinned. + Tree { path: PathBuf, dir: OwnedFd }, + /// The manifest `--manifest` named, read once, and where the contents + /// of its files come from. + Manifest { + /// How messages name the manifest: its path, or standard input. + name: String, + manifest: Box, + /// None for the commands that only size. + contents: Option, + }, } -/// The SOURCE arguments, resolved once and before any image is touched: -/// directory trees, or with `--manifest` the one place the manifest's file -/// contents come from. -struct Sources { - trees: Vec<(PathBuf, OwnedFd)>, - manifest: Option, +/// What a command does with its SOURCE. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Sourcing { + /// The caller sizes a file system for the SOURCE and writes nothing of + /// it. A manifest takes no SOURCE then, since it carries the sizes. + Size, + /// The caller writes the SOURCE into a file system. A manifest takes one + /// SOURCE then: the directory its file contents are read from, or "-" + /// for standard input. + Write, } /// Reads and parses the manifest `path` names, or the one on standard input @@ -449,110 +462,186 @@ fn read_manifest(path: &Path) -> Result<(manifest::Manifest, String)> { Ok((manifest, name)) } -/// Resolves the SOURCE arguments (the `--fit` directories for an empty -/// file system), each exactly once. Without `--manifest` every one is a -/// directory tree. With it there is exactly one, the directory the manifest -/// describes or "-" for the file contents on standard input; sizing takes -/// none, the manifest carries the sizes. `--path` is for trees only. -fn sources(args: &Args, paths: &[&Path], sizing: bool) -> Result { - let Some(m) = args.path("manifest") else { - let mut trees = Vec::with_capacity(paths.len()); - for &p in paths { - let dir = host::open_dir(p).map_err(|e| { - if e.errno() == errno::ENOTDIR { - e.context("a SOURCE is a directory tree; --manifest PATH names a manifest") - } else { - e +impl Source { + /// Resolves the SOURCE argument (the `--fit` directory for an empty file + /// system) exactly once. Without `--manifest` it is a directory tree. + /// With it, it is the directory the manifest describes or "-" for the + /// file contents on standard input; [`Sourcing::Size`] takes none, the + /// manifest carries the sizes. `--path` is for trees only. The SOURCE + /// arguments and `--path` are checked before anything is opened. + fn open(args: &Args, paths: &[&Path], sourcing: Sourcing) -> Result { + let Some(m) = args.path("manifest") else { + return match paths { + [] => Ok(Source::None), + [path] => { + let dir = host::open_dir(path).map_err(|e| { + if e.errno() == errno::ENOTDIR { + e.context("a SOURCE is a directory tree; --manifest PATH names a manifest") + } else { + e + } + })?; + Ok(Source::Tree { + path: path.to_path_buf(), + dir, + }) } - })?; - trees.push((p.to_path_buf(), dir)); + _ => bail!( + errno::EINVAL, + "only one directory tree can be given; --manifest PATH names a manifest" + ), + }; + }; + if m == Path::new("-") && sourcing == Sourcing::Write && matches!(paths, [p] if *p == Path::new("-")) { + bail!( + errno::EINVAL, + "--manifest - and a SOURCE of - cannot both read standard input" + ); } - return Ok(Sources { trees, manifest: None }); - }; - if m == Path::new("-") && !sizing && matches!(paths, [p] if *p == Path::new("-")) { - bail!( - errno::EINVAL, - "--manifest - and a SOURCE of - cannot both read standard input" - ); - } - let (manifest, name) = read_manifest(m)?; - if dest(args) != "/" { - bail!( - errno::EINVAL, - "--path applies to directory trees; a manifest names its paths from the root" - ); + if dest(args) != "/" { + bail!( + errno::EINVAL, + "--path applies to directory trees; a manifest names its paths from the root" + ); + } + let contents = match (sourcing, paths) { + (Sourcing::Size, []) => None, + (Sourcing::Size, _) => bail!( + errno::EINVAL, + "--manifest carries the sizes, no SOURCE or --fit directory is taken with it" + ), + (Sourcing::Write, [path]) if *path == Path::new("-") => Some(ContentOrigin::Stdin), + (Sourcing::Write, [path]) => Some(ContentOrigin::Directory { + path: path.to_path_buf(), + dir: host::open_dir(path)?, + }), + (Sourcing::Write, _) => bail!( + errno::EINVAL, + "--manifest takes exactly one SOURCE: the directory the manifest describes, or - for the file contents on standard input" + ), + }; + let (manifest, name) = read_manifest(m)?; + Ok(Source::Manifest { + name, + manifest: Box::new(manifest), + contents, + }) } - let data = match (sizing, paths) { - (true, []) => None, - (true, _) => bail!( - errno::EINVAL, - "--manifest carries the sizes, no SOURCE or --fit directory is taken with it" - ), - (false, [p]) if *p == Path::new("-") => Some(Data::Stdin), - (false, [p]) => Some(Data::Directory { - path: p.to_path_buf(), - dir: host::open_dir(p)?, - }), - (false, _) => bail!( - errno::EINVAL, - "--manifest takes exactly one SOURCE: the directory the manifest describes, or - for the file contents on standard input" - ), - }; - Ok(Sources { - trees: Vec::new(), - manifest: Some(ManifestSource { name, manifest, data }), - }) -} -/// What can be checked before an image is created, formatted or written: -/// that the manifest and, under `--unsupported fail`, the trees can be -/// stored, and that every file the manifest names is below the SOURCE with -/// the size it says. -fn check_sources(args: &Args, sources: &Sources) -> Result<()> { - if fail_unsupported(args)? { - for (path, dir) in &sources.trees { - let mut plan = Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)); - if let Some(skipped) = plan.add_tree(dir.as_fd(), dest(args), true)?.first() { - bail!( - errno::EINVAL, - "{} cannot be stored on FAT", - path.join(skipped).display() - ); + /// What can be checked before an image is created, formatted or + /// written: that the manifest and, under `--unsupported fail`, the tree + /// can be stored, and that every file the manifest names is below the + /// SOURCE with the size it says. + fn check(&self, args: &Args) -> Result<()> { + let fail = fail_unsupported(args)?; + match self { + Source::Tree { path, dir } if fail => { + let mut plan = Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)); + if let Some(skipped) = plan.add_tree(dir.as_fd(), dest(args), true)?.first() { + bail!( + errno::EINVAL, + "{} cannot be stored on FAT", + path.join(skipped).display() + ); + } + } + Source::Manifest { + name, + manifest, + contents, + } => { + if fail { + manifest.check_supported()?; + } + if let Some(ContentOrigin::Directory { path, dir }) = contents { + DirectorySource::new(dir.try_clone()?) + .follow_symlinks(true) + .verify(manifest) + .map_err(|e| { + e.context(format!( + "the files {} describes are not all below {}", + name, + path.display() + )) + })?; + } } + Source::None | Source::Tree { .. } => {} } + Ok(()) } - let Some(m) = &sources.manifest else { - return Ok(()); - }; - if fail_unsupported(args)? { - m.manifest.check_supported()?; - } - if let Some(Data::Directory { path, dir }) = &m.data { - DirectorySource::new(dir.try_clone()?) - .follow_symlinks(true) - .verify(&m.manifest) - .map_err(|e| { - e.context(format!( - "the files {} describes are not all below {}", - m.name, - path.display() - )) - })?; - } - Ok(()) -} -/// Adds the sources to a plan, the way `fill` will write them. -fn plan_sources(plan: &mut Plan, args: &Args, sources: &Sources) -> Result<()> { - for (_, dir) in &sources.trees { - plan.add_tree(dir.as_fd(), dest(args), true)?; + /// Adds the source to a plan, the way [`Source::fill`] writes it. + fn add_to(&self, plan: &mut Plan, args: &Args) -> Result<()> { + match self { + Source::None => {} + Source::Tree { dir, .. } => { + plan.add_tree(dir.as_fd(), dest(args), true)?; + } + Source::Manifest { manifest, .. } => { + for skipped in plan.add_manifest(manifest)? { + eprintln!("ufat: not counted {}: it cannot be stored on FAT", skipped); + } + } + } + Ok(()) } - if let Some(m) = &sources.manifest { - for skipped in plan.add_manifest(&m.manifest)? { - eprintln!("ufat: not counted {}: it cannot be stored on FAT", skipped); + + /// Writes the source into an open volume: the tree copied, or the + /// manifest assembled. + fn fill(&self, volume: &mut Volume, args: &Args) -> Result<()> { + let copy = CopyOptions { + times: time_policy(args)?, + replace: !args.flag("no-replace"), + follow_symlinks: true, + }; + match self { + Source::None => {} + Source::Tree { path, dir } => { + let report = volume.copy_tree(dir.as_fd(), dest(args), ©)?; + if args.flag("verbose") { + eprintln!( + "{}: {}", + path.display(), + contents(report.files, report.directories, report.bytes) + ); + } + for skipped in report.skipped { + eprintln!( + "ufat: skipped {}: not a regular file or directory", + path.join(skipped).display() + ); + } + } + Source::Manifest { + name, + manifest, + contents: origin, + } => { + let options = assemble_options(args)?; + let report = match origin { + Some(ContentOrigin::Stdin) => { + let stdin = std::io::stdin(); + let mut lock = stdin.lock(); + volume.assemble(manifest, &mut StreamSource::new(&mut lock), &options)? + } + Some(ContentOrigin::Directory { dir, .. }) => volume.assemble( + manifest, + &mut DirectorySource::new(dir.try_clone()?).follow_symlinks(true), + &options, + )?, + None => bail!(errno::EINVAL, "a manifest needs a SOURCE to be filled from"), + }; + if args.flag("verbose") { + eprintln!("{}: {}", name, contents(report.files, report.directories, report.bytes)); + } + for skipped in report.skipped { + eprintln!("ufat: skipped {}: it cannot be stored on FAT", skipped); + } + } } + Ok(()) } - Ok(()) } fn assemble_options(args: &Args) -> Result { @@ -569,59 +658,6 @@ fn assemble_options(args: &Args) -> Result { }) } -/// Writes the sources into an open volume: the trees copied in the order -/// given, or the manifest assembled. -fn fill(v: &mut Volume, args: &Args, sources: &Sources) -> Result<()> { - let copy = CopyOptions { - times: time_policy(args)?, - replace: !args.flag("no-replace"), - follow_symlinks: true, - }; - for (path, dir) in &sources.trees { - let report = v.copy_tree(dir.as_fd(), dest(args), ©)?; - if args.flag("verbose") { - eprintln!( - "{}: {}", - path.display(), - contents(report.files, report.directories, report.bytes) - ); - } - for skipped in report.skipped { - eprintln!( - "ufat: skipped {}: not a regular file or directory", - path.join(skipped).display() - ); - } - } - if let Some(m) = &sources.manifest { - let options = assemble_options(args)?; - let report = match &m.data { - Some(Data::Stdin) => { - let stdin = std::io::stdin(); - let mut lock = stdin.lock(); - v.assemble(&m.manifest, &mut StreamSource::new(&mut lock), &options)? - } - Some(Data::Directory { dir, .. }) => v.assemble( - &m.manifest, - &mut DirectorySource::new(dir.try_clone()?).follow_symlinks(true), - &options, - )?, - None => bail!(errno::EINVAL, "a manifest needs a SOURCE to be filled from"), - }; - if args.flag("verbose") { - eprintln!( - "{}: {}", - m.name, - contents(report.files, report.directories, report.bytes) - ); - } - for skipped in report.skipped { - eprintln!("ufat: skipped {}: it cannot be stored on FAT", skipped); - } - } - Ok(()) -} - /// Whether `--write-manifest -` puts the manifest on standard output. What /// the command prints there otherwise goes to standard error then. fn manifest_to_stdout(args: &Args) -> bool { @@ -689,21 +725,21 @@ fn image_arg<'a>(args: &'a Args, command: &str) -> Result<&'a Path> { } } -/// `assemble --plan`: the size the sources need, with nothing written. +/// `assemble --plan`: the size the content needs, with nothing written. fn plan(args: &Args) -> Result<()> { if args.positional.is_empty() && args.path("manifest").is_none() { - bail!(errno::EINVAL, "assemble --plan needs at least one SOURCE or --manifest"); + bail!(errno::EINVAL, "assemble --plan needs a SOURCE or --manifest"); } let options = format_options(args)?; let mut plan = Plan::new(PlanOptions::from_format_options(&options, None)?); - let sources = sources(args, &args.positional_paths(), true)?; - plan_sources(&mut plan, args, &sources)?; + let source = Source::open(args, &args.positional_paths(), Sourcing::Size)?; + source.add_to(&mut plan, args)?; let e = plan.estimate()?; if let Some(size) = args.size("size")? { if e.size() > size { bail!( errno::ENOSPC, - "the sources need a {} byte file system, more than --size {}", + "the content needs a {} byte file system, more than --size {}", e.size(), size ); @@ -723,7 +759,7 @@ fn plan(args: &Args) -> Result<()> { } /// `assemble` without a SOURCE: an empty file system, of the size of the -/// image or `--size`, or sized for the `--fit` directories or what +/// image or `--size`, or sized for the `--fit` directory or what /// `--manifest` describes. fn assemble_empty(args: &Args, path: &Path) -> Result { let mut options = format_options(args)?; @@ -749,16 +785,15 @@ fn assemble_empty(args: &Args, path: &Path) -> Result { format::format(&device, &options)?; return Volume::open(device); } - let sources = sources(args, &fit, true)?; - let (volume, estimate) = - util::fit_and_format(&target, &mut options, &mut |plan| plan_sources(plan, args, &sources)) - .map_err(|e| e.into_error(path))?; + let source = Source::open(args, &fit, Sourcing::Size)?; + let (volume, estimate) = util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args)) + .map_err(|e| e.into_error(path))?; report_estimate(args, path, &estimate); Ok(volume) } -/// `assemble` with SOURCE arguments: the file system sized to fit them, -/// unless `--size` says otherwise, and filled with them. +/// `assemble` with a SOURCE: the file system sized to fit it, unless +/// `--size` says otherwise, and filled with it. fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result { if !args.paths("fit").is_empty() { bail!( @@ -766,10 +801,10 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result "--fit sizes an empty file system; with a SOURCE the file system is sized for it" ); } - let sources = sources(args, paths, false)?; + let source = Source::open(args, paths, Sourcing::Write)?; // Better to learn about a bad manifest or tree before an image is sized // and formatted. - check_sources(args, &sources)?; + source.check(args)?; let mut options = format_options(args)?; let target = util::Target { path, @@ -777,10 +812,10 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result size: args.size("size")?, flags: args.image_flags(), }; - let (mut v, estimate) = util::fit_and_format(&target, &mut options, &mut |plan| plan_sources(plan, args, &sources)) + let (mut v, estimate) = util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args)) .map_err(|e| e.into_error(path))?; report_estimate(args, path, &estimate); - match fill(&mut v, args, &sources) { + match source.fill(&mut v, args) { Ok(()) => Ok(v), Err(e) => Err(unfinished(v, e)), } @@ -828,6 +863,10 @@ fn cmd_assemble(argv: &[OsString]) -> Result<()> { ), &with(FORMAT_FLAGS, &with(FILL_FLAGS, &["plan"])), )?; + // Bad values fail here, whatever the command goes on to do. What uses + // them takes them from args again. + fail_unsupported(&args)?; + time_policy(&args)?; if args.flag("plan") { return plan(&args); } @@ -850,7 +889,7 @@ fn cmd_assemble(argv: &[OsString]) -> Result<()> { } let (path, paths) = match args.positional_paths().split_first() { Some((&i, s)) => (i, s.to_vec()), - None => bail!(errno::EINVAL, "assemble takes an IMAGE and SOURCE arguments"), + None => bail!(errno::EINVAL, "assemble takes an IMAGE and a SOURCE"), }; let v = if paths.is_empty() { assemble_empty(&args, path) @@ -903,9 +942,13 @@ fn ensure_dir(v: &mut Volume, path: &str, parents: bool, time: SystemTime) -> Re fn cmd_populate(argv: &[OsString]) -> Result<()> { let args = Args::parse(argv, &with(IMAGE_OPTIONS, FILL_VALUES), &with(FILL_FLAGS, &["parents"]))?; + // Bad values fail here, whatever the command goes on to do. What uses + // them takes them from args again. + fail_unsupported(&args)?; + time_policy(&args)?; let (image, paths) = match args.positional_paths().split_first() { Some((&i, s)) => (i, s.to_vec()), - None => bail!(errno::EINVAL, "populate takes an IMAGE and SOURCE arguments"), + None => bail!(errno::EINVAL, "populate takes an IMAGE and a SOURCE"), }; let path = volume_path(args.last("path").unwrap_or(OsStr::new("/")))?; let (time, _) = stamp_time(&args)?; @@ -960,13 +1003,13 @@ fn cmd_populate(argv: &[OsString]) -> Result<()> { } return v.close(); } - let sources = sources(&args, &paths, false)?; - check_sources(&args, &sources)?; + let source = Source::open(&args, &paths, Sourcing::Write)?; + source.check(&args)?; let mut v = open_volume(&args, image, Access::ReadWrite)?; - if !sources.trees.is_empty() { + if matches!(source, Source::Tree { .. }) { ensure_dir(&mut v, path, parents, time)?; } - fill(&mut v, &args, &sources)?; + source.fill(&mut v, &args)?; if let Some(m) = args.path("write-manifest") { write_manifest(&v, m)?; } diff --git a/tests/cli.rs b/tests/cli.rs index d99cfc8..87d2007 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! The command line: assemble makes a file system and fills it, populate -//! fills an existing one, both take directory trees, or with --manifest the +//! fills an existing one, both take a directory tree, or with --manifest the //! tree a UAPI.16 manifest describes. The commands are the methods of the //! Varlink interface. @@ -483,9 +483,20 @@ fn assemble_and_populate_take_trees_and_manifests() { assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("standard input is not a UAPI.16 manifest")); // A SOURCE is a directory, or for populate one file that needs --path; - // a manifest is named by --manifest. + // a manifest is named by --manifest. A manifest given as a SOURCE next + // to a tree fails on the count of trees, which says so too. Nothing is + // created then. + let untouched = root.join("untouched.img"); + let untouched = untouched.to_str().unwrap(); fails(&bin, &["populate", a, m], "needs --path"); - fails(&bin, &["populate", a, m, tree_arg], "a SOURCE is a directory tree"); + fails(&bin, &["assemble", "--plan", m], "a SOURCE is a directory tree"); + fails(&bin, &["populate", a, m, tree_arg], "--manifest PATH names a manifest"); + fails( + &bin, + &["assemble", "--create", untouched, m, tree_arg], + "--manifest PATH names a manifest", + ); + assert!(!Path::new(untouched).exists()); fs::write(root.join("garbage"), b"not a manifest").unwrap(); fails( &bin, @@ -499,15 +510,17 @@ fn assemble_and_populate_take_trees_and_manifests() { "is not a UAPI.16 manifest", ); // A manifest takes exactly one SOURCE and no --path. + let nowhere = root.join("nowhere"); + let nowhere = nowhere.to_str().unwrap(); fails( &bin, - &["populate", "--manifest", m, a, tree_arg, tree_arg], + &["populate", "--manifest", nowhere, a, tree_arg, tree_arg], "exactly one SOURCE", ); - fails(&bin, &["populate", "--manifest", m, a], "exactly one SOURCE"); + fails(&bin, &["populate", "--manifest", nowhere, a], "exactly one SOURCE"); fails( &bin, - &["populate", "--manifest", m, "--path", "/x", a, tree_arg], + &["populate", "--manifest", nowhere, "--path", "/x", a, tree_arg], "--path applies to directory trees", ); // The switches and commands of the earlier command line are gone. @@ -540,18 +553,7 @@ fn assemble_and_populate_take_trees_and_manifests() { "linux.efi", ); assert!(!Path::new(d).exists()); - fails( - &bin, - &[ - "assemble", - "--create", - "--manifest", - m, - d, - root.join("nowhere").to_str().unwrap(), - ], - "nowhere", - ); + fails(&bin, &["assemble", "--create", "--manifest", m, d, nowhere], "nowhere"); assert!(!Path::new(d).exists()); // A file that grew since the manifest was written is caught the same // way. @@ -596,15 +598,74 @@ fn assemble_and_populate_take_trees_and_manifests() { assert!(run(&bin, &["check", c]).status.success()); fails( &bin, - &["assemble", "--create", "--fit", tree_arg, "--manifest", m, c], + &["assemble", "--create", "--fit", tree_arg, "--manifest", nowhere, c], "carries the sizes", ); - fails(&bin, &["assemble", "--plan"], "at least one SOURCE or --manifest"); + fails(&bin, &["assemble", "--plan"], "a SOURCE or --manifest"); fails( &bin, &["assemble", "--create", "--fit", tree_arg, c, tree_arg], "--fit sizes an empty file system", ); + // One tree is taken, as by mkfs tools. The trees are counted before + // anything is opened, so a tree that is not there is not what fails. + // The same goes for a manifest: the checks above of its SOURCE, --path + // and --fit come before it is read. + for args in [ + &["assemble", "--create", c, nowhere, tree_arg][..], + &["assemble", "--plan", nowhere, tree_arg], + &["populate", a, nowhere, tree_arg], + &["assemble", "--create", "--fit", nowhere, "--fit", tree_arg, c], + ] { + fails(&bin, args, "only one directory tree can be given"); + } + // Bad values of --unsupported and --times fail right after the command + // line is parsed, whatever the command does: before a tree, a file or a + // manifest is opened, an image is created, or anything is put into one. + let unsupported = "unknown policy 'bogus' for --unsupported"; + let times = "unknown time policy 'bogus'"; + fails(&bin, &["populate", "--unsupported", "bogus", a, nowhere], unsupported); + fails( + &bin, + &["populate", "--manifest", nowhere, "--unsupported", "bogus", a, tree_arg], + unsupported, + ); + fails( + &bin, + &["assemble", "--create", "--times", "bogus", untouched, tree_arg], + times, + ); + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "34M", + "--unsupported", + "bogus", + untouched, + ], + unsupported, + ); + assert!(!Path::new(untouched).exists()); + let file = root.join("tree/loader/entries/x.conf"); + let file = file.to_str().unwrap(); + fails( + &bin, + &["populate", "--times", "bogus", "--path", "/new", a, tree_arg], + times, + ); + fails(&bin, &["populate", "--times", "bogus", "--path", "/newdir", a], times); + fails( + &bin, + &["populate", "--unsupported", "bogus", "--path", "/new.txt", a, file], + unsupported, + ); + let listed = ok(&bin, &["list", a, "/"]); + for name in ["new/", "newdir/", "new.txt"] { + assert!(!listed.lines().any(|l| l == name), "{}", listed); + } } /// A volume too small for what goes into it. A copy that runs out of @@ -655,7 +716,7 @@ fn too_small_volumes_fail_cleanly() { assert_eq!(fs::metadata(&existing).unwrap().len(), 0); let size: u64 = ok(&bin, &["assemble", "--plan", t]).trim().parse().unwrap(); - // A plan against a size says whether the sources fit it. + // A plan against a size says whether the tree fits it. fails(&bin, &["assemble", "--plan", "--size", "1M", t], "more than --size"); assert_eq!( ok(&bin, &["assemble", "--plan", "--size", "64M", t]), From c9bcc125f30bb0e5bf0c469cf80185f9ff03fd16 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 11/19] manifest: write manifests with the uapi16 crate Currently we write manifests by hand. The generator of a host tree and the writer of a volume both build a json::Object per entry, sort its keys and frame it with write_record(). Let's port both of them to the uapi16 crate. They fill in a FileObject per entry and hand it to a uapi16::Writer, which frames the records and runs the checks of the reader on every object it writes. While at it, turn the free functions into methods. generate() becomes HostTree::write_manifest() and volume::write() becomes Volume::write_manifest(). Both take any Write, and both return a WriteReport. What a caller asks a manifest to record are the features of UAPI.16 now, uapi16::Features, instead of our own Fields. The merged specification gives the root object of a manifest two more fields (cf. [1]). features lists what the manifest records whenever that isn't the default set, and order declares the order its file objects are in. Both writers sort their objects in code point order already, so they say so with "order": "codepoint". The generator records size, sha256 and mtime and lists them. The manifest of a volume records what FAT has of what it is asked for: sizes, hashes and times. Where FAT has none of what a feature describes, as for symbolic links, device nodes, hard links and extended attributes, the manifest lists the feature and so says that there is none. The read-only attribute is different. Every entry of a volume has it set or cleared, and the specification has a read-only feature now (cf. [2]): where a manifest lists it, an object without readOnly isn't read-only. So the manifest of a volume always records the attribute, whatever the caller asks for. It lists read-only and writes readOnly where the attribute is set. The writer refuses readOnly without the feature anyway. The writer leaves out what the specification recommends leaving out. So an empty file goes out with a size of 0 and without the hash of no data, and a reader fills the hash in again. The Varlink ManifestSink follows. It took systemd-manifest's field names in fields. Now it takes the names of the features of UAPI.16 in features, with "_" in place of "-", the way systemd writes the values of enumerations. So hash is sha256 and userXattr is user_xattr. Names are uapi16::Name now, which follows the spec: a component can be longer than 255 bytes, and a name can't hold a noncharacter. An entry of a volume whose name a manifest can't carry is left out and counted in omitted as before. Note that the generator used to list a directory whose name no manifest can carry, which no reader takes, ours included. It leaves such a directory out now, with everything below it, as systemd-manifest does. The generator also left out a file whose name no manifest can carry without a word, and a name that isn't UTF-8 or a path longer than a volume takes failed the walk. Now it leaves all of them out and counts the regular files and directories among them the way the writer of a volume does, a directory with everything below it as one, and ufat manifest says how many entries aren't in the manifest, as --write-manifest does. walk_tree() leaves out and counts what it can't name when the generator asks it to. The populator and the planner still fail on it, since they couldn't store it. The long names of a volume are decoded with String::from_utf16_lossy(), so a long name with an unpaired surrogate reads with U+FFFD in its place, and two names that differ only there read as one. Reading a directory now decodes a long name with String::from_utf16(), which refuses exactly such a name, and says how the name came out in a new NameDecoding, Exact or Lossy, which Metadata carries as well. The writer of a volume leaves the lossy names out and counts them before it compares names. The NameDecoding of an entry goes next to the count of its long name slots, which becomes a byte since a set has at most 20 slots, so that the entries the directory cache keeps don't grow. Currently ufat manifest keeps the whole manifest in memory before it prints anything, 150 to 250 bytes per file. The point was to print nothing of a tree that can't be listed to its end. But the trailer covers that already: a manifest without one is incomplete and readers refuse it, and ufat exits with an error. So let's stream the manifest to standard output while the tree is walked. The generator records the size of what it hashed instead of the size that stat() reported before. So the two agree for a file that changes while it is read, and the writer never sees an empty file with the hash of some data, which it would refuse. It reads a file no further than the size the walk found, so a file that keeps growing doesn't keep it busy. Afterwards it compares the size, the modification time and the change time with what the walk found, the way tar does. A file that changed while it was read is counted in a new field of WriteReport, changed, and ufat manifest says how many there were. The exit status stays 0, since 1 says that the manifest has no trailer. Currently, the writer of a volume walks the directory tree by path. It lists a directory with read_dir(path) and reads a file with begin_read(path), and both look up every component of the path again. On a damaged volume that lookup can find another entry than the one the walk is at. Lookups fold names, so of "AAAA" and "aaaa" in one directory it finds the same one twice, and the manifest lists what "aaaa" holds under "AAAA" as well. So let's walk the tree by cluster instead. A directory is listed from the first cluster its entry names, with a crate-private read_dir_at() that does what read_dir() does once it has found the cluster. A file is read from the first cluster and the size of its entry with begin_read_at(). Note that begin_read() walks the chain of a file once before reading to see that it's long enough. begin_read_at() doesn't, and the read that runs past the end of a short chain fails with Corrupt instead. The read of the last cluster of a file looks at the FAT entry of that cluster, which has to end the chain or go on. So a chain that runs into a free, bad or invalid entry right after the file fails as it did before, and the rest of a longer chain isn't read. The writer also keeps the first cluster of every directory it listed in a HashSet, to refuse a directory tree that is cross-linked or that loops. That set grows with the number of directories on the volume. Comparing with the first clusters of the directories that are open would catch a loop only. A cross-link that doesn't loop does end, but a chain of directories that each hold two entries pointing at the next one is listed 2^k times for k levels, and 40 levels take 40 clusters of a small image. And first clusters aren't enough either, since chains can run together further down. 200 empty directories whose chains run on into the chain of a directory of 1000 files list those files 201 times, and 1000 entries of files of 4 MiB that share one chain make us hash 4 GiB. So keep one bit for every cluster of the volume instead, set for every cluster of every directory the walk lists, which Directory::chain() has, and for every cluster of every file it reads for the hash, one per read. Where the walk reaches a cluster whose bit is set already it fails with EUCLEAN and Corrupt. IOW, the walk lists no directory and reads no file twice, and takes time in proportion to the size of the volume. The bits take 16 KiB for a typical ESP and 32 MiB at the most clusters FAT32 has. A directory whose entry points at cluster 0 or past the last cluster of the volume fails with Corrupt as well, and so does a file that isn't empty when it is read for the hash, which is when the manifest records sha256. load_directory() refused a directory whose own chain loops or is longer than a directory can be with a bare EUCLEAN, which a Varlink client sees as io.systemd.System. It names the directory and its first cluster now, so Describe answers Corrupt there too. A damaged directory can also hold two entries of the same name. The writer of the crate would refuse the second one as an InvalidManifest with reason duplicateName, which blames a manifest the caller never sent. The entries of a directory are sorted right there, so compare each name with the one before and fail with EUCLEAN and Corrupt, before the record of the directory goes out. Names that FAT takes for one, like "AAAA" and "aaaa", are two names to a manifest. Since the walk follows the cluster of every entry, it lists each of them with what it holds. Linux writes such directories with some mount options. With iocharset=utf8, for instance, it compares names byte for byte. fsck reports them, which is its job, and the manifest describes what is on the volume. The systemd-manifest the fixtures were made with doesn't write features and order. systemd-manifest writes both since 118717cfe2 and 330fab5e90, which aren't in a release yet. So make-fixtures.sh adds both to the fixtures after systemd-manifest wrote them, and tests/fixtures.rs keeps comparing our writers with them byte for byte. The manifest of a volume lists read-only on top of the features systemd-manifest records, so the comparison adds read-only to the features of systemd's manifest. Adding features and order changes the bytes the signature of signed.Uapi16Manifest covers and the signature doesn't match anymore, which the README of the fixtures says. tests/fixtures.rs also gets a test that reads every fixture with the uapi16 crate and writes it back. It lives there and not in the crate, so that the crate needs no files from outside of it for its tests. Note that the systemd-manifest the fixtures were made with writes the hash of no data next to a size of 0. The writer leaves it out, and so does systemd-manifest since e83f7bce0c, which isn't in a release yet either. A reader that fills it in again marks it as filled in, so the empty file of the special case wouldn't read back as the same object. So make-fixtures.sh also takes that hash out of the file objects of size 0, as the specification recommends. The empty file of the special case is the only one, and the byte comparisons don't use that case. The errors of the crate's writer are turned into ours in src/fat/manifest/error.rs, with the errno and the detail a Varlink client sees. Instead of mirroring uapi16::Problem with a list of its own, ManifestProblem carries the problem itself, and Problem::as_str() gives the name a client sees. So the names on the wire stay what they are. noSize isn't a problem of the crate and stays ours. The interface description gains the problems the crate knows about, and tests/varlink.rs checks that its ManifestProblem has the names of Problem::ALL and noSize. verify/lib.rs builds error.rs for Kani without uapi16, so it stands in for uapi16 with a Problem that has no value. The reader is still the old one. It reports its problems with the variants of uapi16::Problem now, under the names it used before. [1]: https://github.com/uapi-group/specifications/pull/253 [2]: https://github.com/uapi-group/specifications/commit/1eb019da9ae71155d8514865e7ea712c1ffeab32 Signed-off-by: Christian Brauner (Amutable) --- Cargo.lock | 3 + Cargo.toml | 4 + README.md | 26 +- docs/org.uapi-group.FileSystem.varlink | 63 +- docs/varlink.md | 48 +- src/bin/ufat/cli.rs | 44 +- src/bin/ufat/service.rs | 41 +- src/fat/Cargo.toml | 1 + src/fat/dir.rs | 86 +- src/fat/error.rs | 92 +- src/fat/host.rs | 136 +- src/fat/manifest/error.rs | 41 + src/fat/manifest/fields.rs | 33 +- src/fat/manifest/generate.rs | 258 ++- src/fat/manifest/mod.rs | 130 +- src/fat/manifest/tests.rs | 25 +- src/fat/manifest/volume.rs | 1460 ++++++++++++----- src/fat/path.rs | 7 +- src/fat/plan.rs | 7 +- src/fat/populate.rs | 7 +- src/fat/volume/file.rs | 47 +- src/fat/volume/mod.rs | 34 +- tests/cli.rs | 62 +- tests/crash/Cargo.toml | 1 + tests/fixtures.rs | 113 +- tests/fixtures/README.md | 21 + tests/fixtures/empty/Uapi16Manifest | 2 +- tests/fixtures/esp/Uapi16Manifest | 2 +- tests/fixtures/esp/none.Uapi16Manifest | 2 +- tests/fixtures/esp/signed.Uapi16Manifest | 2 +- .../esp/size-hash-mtime.Uapi16Manifest | 2 +- tests/fixtures/make-fixtures.sh | 47 + tests/fixtures/special/Uapi16Manifest | 4 +- tests/fuzz/varlink_fuzz.py | 4 +- tests/reference.rs | 6 +- tests/varlink.rs | 183 ++- verify/lib.rs | 17 + 37 files changed, 2227 insertions(+), 834 deletions(-) create mode 100644 src/fat/manifest/error.rs diff --git a/Cargo.lock b/Cargo.lock index 68a646d..afd3e73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,6 +82,7 @@ dependencies = [ "json", "libc", "sha2", + "uapi16", ] [[package]] @@ -92,6 +93,7 @@ dependencies = [ "json", "libc", "sha2", + "uapi16", ] [[package]] @@ -164,6 +166,7 @@ dependencies = [ "json", "lexopt", "libc", + "uapi16", "varlink", ] diff --git a/Cargo.toml b/Cargo.toml index 7710f84..30776d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,7 @@ lexopt = "0.3.2" libc = "0.2.191" # 0.11.1 and later need rustc 1.88. sha2 = { version = "0.11.0", default-features = false } +uapi16 = { path = "src/uapi16" } varlink = { path = "src/varlink" } [workspace.lints.rust] @@ -73,6 +74,9 @@ lexopt.workspace = true libc.workspace = true varlink.workspace = true +[dev-dependencies] +uapi16.workspace = true + [lints] workspace = true diff --git a/README.md b/README.md index b2b611f..5b008d8 100644 --- a/README.md +++ b/README.md @@ -126,9 +126,10 @@ The most common ones: and device nodes. By default they are left out with a message. - `--write-manifest PATH` writes a UAPI.16 manifest of what the file system holds after `assemble` or `populate`, or of what `describe` - finds. It has the size and the SHA-256 hash of every file, and no - times. With `-` as PATH the manifest goes to standard output, and - what the command prints there otherwise goes to standard error. + finds. It has the size and the SHA-256 hash of every file, says which + files and directories are read-only, and has no times. With `-` as + PATH the manifest goes to standard output, and what the command prints + there otherwise goes to standard error. - `--hash sha256` or `--hash sha512` prints the hash of the file system `assemble` wrote. - `--write-hash PATH` writes that hash to PATH instead, or with `-` to @@ -181,9 +182,22 @@ size and the SHA-256 hash of every file. A mismatch fails the command. Signatures in a manifest are recognized but not verified. Verify a signed manifest before you hand it to ufat. -`ufat manifest DIR` writes a manifest of a directory tree. For a tree of -regular files and directories, the output is the same as that of -`systemd-manifest make --field=size,hash,mtime`. +`ufat manifest DIR` writes a manifest of a directory tree to standard +output. It has the size and the SHA-256 hash of every regular file, and +the modification time of every file and directory. Its root object lists +these features and declares the code point order. Other kinds of files, +such as symbolic links, are left out. So are entries whose names a +manifest cannot carry, such as names that are not UTF-8, with everything +below them, and ufat says how many it left out. A file that changes +while ufat reads it gets the size and the hash of what ufat read, and +ufat says how many files changed. When the command fails, the manifest +it wrote so far has no trailer, and readers refuse it. For a tree of +regular files and directories, `systemd-manifest make +--field=size,hash,mtime` writes the same file objects. A +systemd-manifest from before systemd commits 118717cfe2, 330fab5e90 and +e83f7bce0c, which are not in a release yet, writes neither `features` +nor `order` in the root file object. It also writes the hash of an empty +file. ### Time stamps diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index 1eb1b7a..660d13a 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -231,24 +231,43 @@ type UnsupportedPolicy( fail ) -# A per-file field of a manifest written back (ManifestSink.fields): -# systemd-manifest's vocabulary, as its --field= and repart's -# --manifest-fields= take it. The inode type is always written; the default -# set is mode, uid, gid, size, hash, symlink, device, hardlink and -# userXattr, mtime and the names are opt-in. -type ManifestField( +# A feature a manifest written through ManifestSink records: a value of the +# features field of UAPI.16 with each "-" written as "_", the way systemd +# writes the values of enumerations, so user-xattr is user_xattr. The inode +# type is always written. The default set is UAPI.16's: device, gid, +# hardlink, mode, sha256, size, symlink and uid. +type ManifestFeature( mode, uid, gid, + user_name, + group_name, size, - hash, + sha256, symlink, device, hardlink, mtime, - userXattr, - userName, - groupName + user_xattr, + flag_hidden, + flag_system, + flag_archive, + flag_append_only, + flag_immutable, + flag_no_atime, + flag_no_cow, + flag_no_dump, + read_only, + fs_uuid, + fs_label, + fat_serial, + gpt_label, + gpt_uuid, + gpt_type_uuid, + gpt_disk_uuid, + gpt_flags, + gpt_flag_no_auto, + gpt_flag_grow_file_system ) # A UAPI.16 manifest as content, read from a regular file or a pipe to its @@ -263,15 +282,20 @@ type Manifest( ) # Where a UAPI.16 manifest is written: of the whole filesystem as an Assemble -# or Populate call leaves it, or as Describe finds it, in the stored form, -# entries sorted by name with a directory's entries right after it. Only -# where writeManifest is among Capabilities.operations. +# or Populate call leaves it, or as Describe finds it, in the stored form. Its +# root file object lists what the manifest records in features and declares +# the code point order its file objects are in, so the manifest can be given +# as content again. Only where writeManifest is among Capabilities.operations. type ManifestSink( # Index of the descriptor open for writing that receives the manifest fileDescriptor: int, - # The fields the manifest carries, the default set when absent. A field - # the filesystem has no notion of is left out and not counted as omitted. - fields: ?[]ManifestField + # What the manifest records, UAPI.16's default set when absent. What the + # filesystem has no notion of is not recorded and not counted as omitted. + # Where the filesystem has none of what a feature describes, the manifest + # records that there is none, as for symbolic links, device nodes, hard + # links and extended attributes on vfat. The manifest of vfat records the + # read-only attribute whether read_only is asked for or not. + features: ?[]ManifestFeature ) # What goes into a filesystem. The source descriptor's type decides what it @@ -673,8 +697,11 @@ error InvalidLabel(label: string, reason: LabelProblem) type IdentifierProblem(malformed, wrongKind, notSupported, reserved) error InvalidIdentifier(identifier: string, reason: IdentifierProblem) -# The manifest cannot be parsed or is inconsistent. -type ManifestProblem(notJson, notObject, notUtf8, nulByte, recordSeparator, recordTooLarge, empty, noTrailer, dataAfterTrailer, fileAfterSignature, mediaType, firstHasName, firstNotDirectory, noName, invalidName, duplicateName, unknownType, fieldType, fieldRange, fieldNotPermitted, contradiction, contents, signature, extendedAttributes, noSize) +# The manifest cannot be parsed or is inconsistent. record is the number of +# the record, counting from 0, name the name of the file object and field the +# field the problem is with: for unlistedFeature the field of a feature the +# manifest does not list, such as mTimeNSec. +type ManifestProblem(notJson, duplicateKey, invalidString, notObject, notUtf8, nulByte, recordSeparator, recordTooLarge, empty, noTrailer, dataAfterTrailer, fileAfterSignature, mediaType, firstHasName, firstNotDirectory, noOrder, noName, invalidName, duplicateName, misplaced, outOfOrder, unlistedFeature, noTarget, unknownType, fieldType, fieldRange, fieldNotPermitted, contradiction, contents, signature, extendedAttributes, noSize) error InvalidManifest(reason: ManifestProblem, record: ?int, name: ?string, field: ?string) # A file the manifest names is not below the source as described. diff --git a/docs/varlink.md b/docs/varlink.md index 9fd1e1a..e83bc6f 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -418,15 +418,45 @@ The `name` of `SourceMismatch` and `ContentMismatch` is the name of the file's record in the manifest, such as `loader/loader.conf`. A `ManifestSink` has a `fileDescriptor` open for writing and optional -`fields`, the per-file fields in the vocabulary of systemd-manifest: -`mode`, `uid`, `gid`, `size`, `hash`, `symlink`, `device`, `hardlink`, -`mtime`, `userXattr`, `userName`, `groupName`. Without `fields`, the -default set of systemd-manifest is used. FAT has a notion of `size`, -`hash` and `mtime` only. The other fields are left out. An entry with -the read-only attribute carries `readOnly`. The manifest describes the -whole volume, including files that were there before the call. Entries -whose names a manifest cannot carry are left out and counted in -`omitted`. +`features`, what the manifest records. The values are the names of the +`features` field of UAPI.16 with `_` in place of `-`: `mode`, `uid`, +`gid`, `user_name`, `group_name`, `size`, `sha256`, `symlink`, `device`, +`hardlink`, `mtime`, `user_xattr`, `flag_hidden`, `flag_system`, +`flag_archive`, `flag_append_only`, `flag_immutable`, `flag_no_atime`, +`flag_no_cow`, `flag_no_dump`, `read_only`, `fs_uuid`, `fs_label`, +`fat_serial`, `gpt_label`, `gpt_uuid`, `gpt_type_uuid`, `gpt_disk_uuid`, +`gpt_flags`, `gpt_flag_no_auto` and `gpt_flag_grow_file_system`. Without +`features`, the default set of UAPI.16 is used: `device`, `gid`, +`hardlink`, `mode`, `sha256`, `size`, `symlink` and `uid`. + +FAT records `size`, `sha256` and `mtime`. FAT has no symbolic links, +device nodes, hard links or extended attributes. When asked for them, +the manifest lists them in `features` and so says that there are none. +The manifest records the read-only attribute whether it is asked for or +not, and lists `read-only` in `features`. An entry with the attribute +carries `readOnly`, and an entry without `readOnly` does not have the +attribute. FAT has no notion of modes, owners and their names, and the +manifest does not record them, nor any of the other features. The root +object declares `"order": "codepoint"`, so the manifest can be given as +content again. + +The manifest describes the whole volume, including files that were there +before the call. Entries whose names a manifest cannot carry are left out +and counted in `omitted`. Two entries whose names FAT takes for one, such +as `README.TXT` and `readme.txt`, are both listed, each with what it +holds. + +A damaged volume fails with `Corrupt`. `where` is `directory` when a +directory shares a cluster with an entry read before, as in a loop of +the tree or a cross-link, when the chain of a directory loops or is +longer than a directory can be, when the entry of a subdirectory points +at a cluster the volume does not have, or when a directory has two +entries of the same name. `where` is `chain` when the chain of a +directory or a file runs into a free, bad or invalid entry, when a file +shares a cluster with an entry read before, when the chain of a file is +shorter than the file, or when a file that is not empty starts at a +cluster the volume does not have. Files are only read when the manifest +records `sha256`. ## The more flag diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index e9b53bf..f226d5f 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -14,7 +14,7 @@ use fat::format::{self, FormatOptions, VolumeId}; use fat::fsck; use fat::host; use fat::layout::MIN_SECTOR_SIZE; -use fat::manifest::{self, AssembleOptions, DirectorySource, StreamSource}; +use fat::manifest::{self, AssembleOptions, DirectorySource, Features, HostTree, StreamSource, WriteReport}; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, TimePolicy}; use fat::probe::Prober; @@ -667,17 +667,27 @@ fn manifest_to_stdout(args: &Args) -> bool { /// Writes the UAPI.16 manifest of everything `v` holds to the file `path`, /// or to standard output for "-", for `--write-manifest`. fn write_manifest(v: &Volume, path: &Path) -> Result<()> { - let fields = manifest::volume::Fields::default(); + let features = Features::DEFAULT; let (report, shown) = if path == Path::new("-") { - let mut out = std::io::BufWriter::new(std::io::stdout().lock()); - let report = manifest::volume::write(v, v.root_time()?, fields, &mut out)?; - (report, "the manifest on standard output".to_string()) + let out = std::io::BufWriter::new(std::io::stdout().lock()); + let report = v.write_manifest(v.root_time()?, features, out)?; + (report, STDOUT_MANIFEST.to_string()) } else { let file = std::fs::File::create(path).with_context(|| format!("cannot create {}", path.display()))?; - let mut out = std::io::BufWriter::new(file); - let report = manifest::volume::write(v, v.root_time()?, fields, &mut out)?; + let report = v.write_manifest(v.root_time()?, features, std::io::BufWriter::new(file))?; (report, path.display().to_string()) }; + warn_about_manifest(&report, &shown); + Ok(()) +} + +/// How the messages name a manifest written to standard output. +const STDOUT_MANIFEST: &str = "the manifest on standard output"; + +/// Says how many entries the manifest `shown`, of which `report` is what +/// it covers, leaves out, and how many files changed while they were read +/// for it. +fn warn_about_manifest(report: &WriteReport, shown: &str) { match report.omitted { 0 => {} 1 => eprintln!( @@ -689,7 +699,17 @@ fn write_manifest(v: &Volume, path: &Path) -> Result<()> { n, shown ), } - Ok(()) + match report.changed { + 0 => {} + 1 => eprintln!( + "ufat: 1 file changed while it was read: {} has the size and the hash of what was read", + shown + ), + n => eprintln!( + "ufat: {} files changed while they were read: {} has the sizes and the hashes of what was read", + n, shown + ), + } } /// Reports the geometry of a freshly made file system. @@ -1240,8 +1260,12 @@ fn cmd_manifest(argv: &[OsString]) -> Result<()> { bail!(errno::EINVAL, "manifest takes exactly one DIR"); }; let dir = host::open_dir(Path::new(dir))?; - let bytes = manifest::generate(dir.as_fd())?; - std::io::stdout().write_all(&bytes)?; + // A manifest is complete with its trailer. What is printed of a tree + // that cannot be listed to its end has none, and the exit status says + // that it failed. + let out = std::io::BufWriter::new(std::io::stdout().lock()); + let report = HostTree::new(dir.as_fd()).write_manifest(out)?; + warn_about_manifest(&report, STDOUT_MANIFEST); Ok(()) } diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index 5f6706e..b52cf52 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -27,8 +27,7 @@ use fat::format::{self, FormatOptions, VolumeId}; use fat::fsck::{self, Problem}; use fat::host; use fat::layout::{self, LayoutParams, MAX_CLUSTER_SIZE, MAX_SECTOR_SIZE, MIN_CLUSTERS, MIN_SECTOR_SIZE}; -use fat::manifest::volume::{Fields, WriteReport}; -use fat::manifest::{AssembleOptions, AssembleReport, DirectorySource, Manifest, StreamSource}; +use fat::manifest::{AssembleOptions, AssembleReport, DirectorySource, Features, Manifest, StreamSource, WriteReport}; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, CopyReport, TimePolicy}; use fat::probe::Prober; @@ -825,29 +824,51 @@ impl Hash { } } -/// The manifest sink: the descriptor and the fields the manifest carries. +/// The manifest sink: the descriptor and what the manifest records. struct Sink { file: host::PassedStream, - fields: Fields, + features: Features, } impl Sink { + /// What separates the words in the name of a feature of UAPI.16, and + /// what stands for it in a value of the interface's ManifestFeature, as + /// systemd writes the values of enumerations: user-xattr is user_xattr. + const NAME_SEPARATOR: char = '-'; + const VALUE_SEPARATOR: &'static str = "_"; + + /// The feature the value `value` of the interface's ManifestFeature + /// stands for. + fn feature(value: &str) -> Option { + Features::ALL + .names() + .find(|name| name.replace(Sink::NAME_SEPARATOR, Sink::VALUE_SEPARATOR) == value) + .and_then(|name| name.parse().ok()) + } + fn take(p: &Params<'_>, c: &mut Connection) -> Outcome { let fd = required_fd(c, p, "fileDescriptor").map_err(|_| invalid("manifestSink"))?; let file = host::passed_sink(fd).map_err(bad("manifestSink"))?; - let fields = match p.0.get("fields") { - None | Some(Value::Null) => Fields::default(), - Some(_) => Fields::from_names(p.strings("fields")?).ok_or_else(|| invalid("manifestSink"))?, + let features = match p.0.get("features") { + None | Some(Value::Null) => Features::DEFAULT, + Some(_) => p + .strings("features")? + .into_iter() + .try_fold(Features::NONE, |features, value| { + Sink::feature(value).map(|feature| features | feature) + }) + .ok_or_else(|| invalid("manifestSink"))?, }; - Ok(Sink { file, fields }) + Ok(Sink { file, features }) } /// Writes the manifest of everything `volume` holds, telling `progress` /// what it covered so far. fn write(self, volume: &Volume, progress: &mut dyn FnMut(&Progress)) -> Outcome { let root_time = volume.root_time()?; - let mut out = BufWriter::new(self.file); - fat::manifest::volume::write_with_progress(volume, root_time, self.fields, &mut out, progress) + let out = BufWriter::new(self.file); + volume + .write_manifest_with_progress(root_time, self.features, out, progress) .map_err(bad("manifestSink")) } } diff --git a/src/fat/Cargo.toml b/src/fat/Cargo.toml index 8f0a192..7e92eb5 100644 --- a/src/fat/Cargo.toml +++ b/src/fat/Cargo.toml @@ -16,6 +16,7 @@ blkid.workspace = true json.workspace = true libc.workspace = true sha2.workspace = true +uapi16.workspace = true [lints] workspace = true diff --git a/src/fat/dir.rs b/src/fat/dir.rs index 88f88a1..e596589 100644 --- a/src/fat/dir.rs +++ b/src/fat/dir.rs @@ -33,6 +33,7 @@ use crate::dirent::{ use crate::errno::*; use crate::name::{ fold_str, join_long_name, parse_long_name_entry, short_name_to_string, valid_short_char, Alias, LongNameEntry, + LFN_MAX_ENTRIES, }; use crate::Result; @@ -54,12 +55,61 @@ type Map = proofs::AssocMap; pub(crate) struct DirEntry { /// The long name, if the entry has long name entries. pub(crate) long_name: Option, + /// How `long_name` came out of the units the entry stores. + pub(crate) long_name_decoding: NameDecoding, /// The short entry. pub(crate) short: RawDirEntry, /// Slot index of the short entry. pub(crate) slot: usize, - /// Number of long name slots preceding the short entry. - pub(crate) long_slots: usize, + /// Number of long name slots preceding the short entry, at most + /// [`LFN_MAX_ENTRIES`]. A byte is enough, which leaves room for + /// `long_name_decoding` without making every entry the index keeps + /// larger. + pub(crate) long_slots: u8, +} + +/// The long name slots of an entry fit into [`DirEntry::long_slots`]. +const _: () = assert!( + LFN_MAX_ENTRIES <= u8::MAX as usize, + "the long name slots of an entry do not fit into a byte" +); + +/// How the text of a name came out of the units an entry stores. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum NameDecoding { + /// The text is the name the entry stores. + Exact, + /// A unit of the long name is an unpaired surrogate, which no text + /// holds, and the text has U+FFFD in its place. It is not the name the + /// entry stores, and two such names can read the same. + Lossy, +} + +/// The text of a long name and how it came out of the units of its long +/// name slots. +struct NameText { + text: String, + decoding: NameDecoding, +} + +impl NameText { + /// Decodes the long name of the long name slots `units`, given in + /// sequence order. String::from_utf16() refuses exactly a name with an + /// unpaired surrogate, which then gets U+FFFD in place of the unit. + /// Every other name is decoded once. + fn decode(units: &[LongNameEntry]) -> NameText { + let name = join_long_name(units); + match String::from_utf16(&name) { + Ok(text) => NameText { + text, + decoding: NameDecoding::Exact, + }, + Err(_) => NameText { + text: String::from_utf16_lossy(&name), + decoding: NameDecoding::Lossy, + }, + } + } } impl DirEntry { @@ -73,12 +123,12 @@ impl DirEntry { /// Index of the first slot the entry occupies. pub(crate) fn first_slot(&self) -> usize { - self.slot - self.long_slots + self.slot - usize::from(self.long_slots) } /// Number of slots the entry occupies. pub(crate) fn slot_count(&self) -> usize { - self.long_slots + 1 + usize::from(self.long_slots) + 1 } /// Whether this is the "." or ".." entry of a subdirectory. @@ -543,18 +593,24 @@ impl Directory { } let short = RawDirEntry::from_bytes(raw); let mut long_name = None; + let mut long_name_decoding = NameDecoding::Exact; let mut long_slots = 0; if let Some((_, last)) = pending.last() { if last.sequence == 1 && pending[0].1.checksum == short_name_checksum(&short.name) { let units: Vec = pending.iter().rev().map(|(_, l)| *l).collect(); - long_name = Some(String::from_utf16_lossy(&join_long_name(&units))); - long_slots = pending.len(); + let NameText { text, decoding } = NameText::decode(&units); + long_name = Some(text); + long_name_decoding = decoding; + // A set is complete with the slot of sequence number 1, + // and numbers above LFN_MAX_ENTRIES do not parse. + long_slots = pending.len() as u8; pending.clear(); } } orphan(&mut pending, &mut free); entries.push(DirEntry { long_name, + long_name_decoding, short, slot: i, long_slots, @@ -739,7 +795,12 @@ impl Directory { return; } units.reverse(); - let long_name = (!long.is_empty()).then(|| String::from_utf16_lossy(&join_long_name(&units))); + let (long_name, long_name_decoding) = if long.is_empty() { + (None, NameDecoding::Exact) + } else { + let NameText { text, decoding } = NameText::decode(&units); + (Some(text), decoding) + }; if let Some((shape, next)) = self.index.pending_tail.take() { if fold_str(&short_name_to_string(short)) == shape.candidate(next - 1) { self.index.tails.insert(shape, next); @@ -747,9 +808,12 @@ impl Directory { } self.index.insert(DirEntry { long_name, + long_name_decoding, short: *short, slot: start + long.len(), - long_slots: long.len(), + // Placed, the set is well formed: its first slot has the + // sequence number long.len(), at most LFN_MAX_ENTRIES. + long_slots: long.len() as u8, }); #[cfg(any(test, kani))] self.check_index(); @@ -976,6 +1040,11 @@ mod proofs { .collect() } + /// `String::from_utf16` as [`narrow_lossy`]: every name decodes. + fn narrow(units: &[u16]) -> std::result::Result { + Ok(narrow_lossy(units)) + } + const SLOTS: usize = 4; /// A directory of four slots in one cluster, with concrete slot kinds @@ -1026,6 +1095,7 @@ mod proofs { #[kani::unwind(20)] #[kani::stub(crate::name::fold_str, ascii_fold)] #[kani::stub(std::string::String::from_utf16_lossy, narrow_lossy)] + #[kani::stub(std::string::String::from_utf16, narrow)] fn index_follows_writes_and_deletes() { let mut d = shaped_directory(); d.check_index(); diff --git a/src/fat/error.rs b/src/fat/error.rs index a1f178e..b7b8ead 100644 --- a/src/fat/error.rs +++ b/src/fat/error.rs @@ -10,6 +10,8 @@ use std::fmt; +use uapi16::Problem; + use crate::errno::{EEXIST, EINVAL, EIO, EISDIR, ENOENT, ENOMEM, ENOTDIR, ENOTEMPTY}; /// What is wrong with a name inside a volume. @@ -211,94 +213,24 @@ impl DescriptorProblem { } } -/// What is wrong with a UAPI.16 manifest. +/// What is wrong with a UAPI.16 manifest, the reason of an +/// `InvalidManifest` error of the Varlink interface. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ManifestProblem { - /// A record is not valid JSON. - NotJson, - /// A record is not a JSON object. - NotObject, - /// A record is not UTF-8. - NotUtf8, - /// A record contains a NUL byte. - NulByte, - /// A record does not start with the record separator. - RecordSeparator, - /// A record is larger than the parser accepts. - RecordTooLarge, - /// The manifest holds no object at all. - Empty, - /// The trailer object is missing. - NoTrailer, - /// Data follows the trailer object. - DataAfterTrailer, - /// A file object follows a signature object. - FileAfterSignature, - /// The media type is missing on the first object, is not a string, or - /// is not one the parser knows. - MediaType, - /// The first object has a name. - FirstHasName, - /// The first object is not a directory. - FirstNotDirectory, - /// An object after the first has no name. - NoName, - /// A name is not a normalized relative path. - InvalidName, - /// Two objects carry the same name, or names FAT folds together. - DuplicateName, - /// An inode type the parser does not know. - UnknownType, - /// A field is of the wrong JSON type or shape, named by `field`. - FieldType, - /// A field's value is out of range, named by `field`. - FieldRange, - /// A field that the object's inode type does not permit, named by - /// `field`. - FieldNotPermitted, - /// Two fields contradict each other, the first named by `field`. - Contradiction, - /// A contents entry: not an object, more than one of file, url and - /// literal, a URL that is not http or https, a literal that is not - /// Base64, an encoding that is not permitted, or too many entries. - Contents, - /// A malformed signature object. - Signature, - /// A malformed extendedAttributes object. - ExtendedAttributes, - /// A regular file without a size whose contents would have to be - /// streamed. + /// What the specification does not permit in a manifest, named by the + /// problem the [`uapi16`] crate has for it. + Malformed(Problem), + /// A regular file without a size, where the size has to be known: to + /// plan the size of a volume, or to take the contents from a stream. NoSize, } impl ManifestProblem { - /// The value as the Varlink interface spells it. + /// The value as the Varlink interface spells it, which is + /// [`Problem::as_str`] for a problem of the [`uapi16`] crate. pub fn as_str(self) -> &'static str { match self { - ManifestProblem::NotJson => "notJson", - ManifestProblem::NotObject => "notObject", - ManifestProblem::NotUtf8 => "notUtf8", - ManifestProblem::NulByte => "nulByte", - ManifestProblem::RecordSeparator => "recordSeparator", - ManifestProblem::RecordTooLarge => "recordTooLarge", - ManifestProblem::Empty => "empty", - ManifestProblem::NoTrailer => "noTrailer", - ManifestProblem::DataAfterTrailer => "dataAfterTrailer", - ManifestProblem::FileAfterSignature => "fileAfterSignature", - ManifestProblem::MediaType => "mediaType", - ManifestProblem::FirstHasName => "firstHasName", - ManifestProblem::FirstNotDirectory => "firstNotDirectory", - ManifestProblem::NoName => "noName", - ManifestProblem::InvalidName => "invalidName", - ManifestProblem::DuplicateName => "duplicateName", - ManifestProblem::UnknownType => "unknownType", - ManifestProblem::FieldType => "fieldType", - ManifestProblem::FieldRange => "fieldRange", - ManifestProblem::FieldNotPermitted => "fieldNotPermitted", - ManifestProblem::Contradiction => "contradiction", - ManifestProblem::Contents => "contents", - ManifestProblem::Signature => "signature", - ManifestProblem::ExtendedAttributes => "extendedAttributes", + ManifestProblem::Malformed(problem) => problem.as_str(), ManifestProblem::NoSize => "noSize", } } diff --git a/src/fat/host.rs b/src/fat/host.rs index 267734a..4445e76 100644 --- a/src/fat/host.rs +++ b/src/fat/host.rs @@ -420,6 +420,33 @@ impl HostEntry { .with_context(|| format!("failed to open {}", self.path.display()))?; Ok(File::from(fd)) } + + /// Whether the entry, a regular file open as `file`, is no longer what + /// the walk found: its size, its modification time or its change time + /// differs from the metadata. tar checks a file it read the same way. + pub(crate) fn has_changed(&self, file: &File) -> Result { + let now = sys::fstat(file.as_fd()).with_context(|| format!("failed to stat {}", self.path.display()))?; + let then = &self.metadata; + Ok(now.len() != then.len() + || (now.mtime(), now.mtime_nsec()) != (then.mtime(), then.mtime_nsec()) + || (now.ctime(), now.ctime_nsec()) != (then.ctime(), then.ctime_nsec())) + } +} + +/// What a walk does with an entry it cannot give a path inside the volume: +/// one whose name is not UTF-8, which could not be stored as a long name +/// anyway, or whose path inside the volume would be longer than +/// [`crate::path::MAX_PATH`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum UnnamableEntry { + /// The walk fails, with EINVAL for the name and ENAMETOOLONG for the + /// path. + Fail, + /// The walk leaves the entry out, a directory with everything below + /// it, and counts it if it is a regular file or a directory, which a + /// user of the walk would have stored. Other files are left out + /// uncounted, as the users of the walk leave them out. + Omit, } /// How a directory path reads in a message: "." for the root. @@ -472,15 +499,16 @@ struct Level { /// leaves it out: it is not there to copy. A directory that is already on /// the stack, reached through a followed link or a bind mount of a /// directory into itself, is ELOOP: the tree would otherwise go on until -/// the path limit. A name that is not UTF-8 is an error since it could not -/// be stored as a long name anyway, and so is a path inside the volume -/// longer than [`crate::path::MAX_PATH`]. +/// the path limit. An entry the walk cannot give a path inside the volume +/// fails the walk or is left out, as `unnamable` says. The walk returns how +/// many entries it left out that way. pub(crate) fn walk_tree( root: BorrowedFd<'_>, dest: &str, follow_symlinks: bool, + unnamable: UnnamableEntry, visit: &mut dyn FnMut(&str, &HostEntry) -> Result, -) -> Result<()> { +) -> Result { let names = list_names(root, Path::new("")).with_context(|| "failed to list the source directory")?; let root_md = sys::fstat(root).with_context(|| "failed to stat the source directory")?; let mut stack = vec![Level { @@ -491,25 +519,40 @@ pub(crate) fn walk_tree( path: PathBuf::new(), target: dest.to_string(), }]; + let mut omitted = 0; loop { - let Some(level) = stack.last_mut() else { return Ok(()) }; + let Some(level) = stack.last_mut() else { + return Ok(omitted); + }; let Some(name) = level.names.next() else { stack.pop(); continue; }; let path = level.path.join(OsStr::from_bytes(&name)); - let name = String::from_utf8(name).map_err(|_| err!(EINVAL, "{} is not valid UTF-8", path.display()))?; - let target = crate::path::join(&level.target, &name); - if target.len() > crate::path::MAX_PATH { - bail!( - ENAMETOOLONG, - "{}: its path inside the volume is longer than {} bytes", - path.display(), - crate::path::MAX_PATH - ); - } + // The path inside the volume, or why the entry has none. + let target = match std::str::from_utf8(&name) { + Err(_) => Err(err!(EINVAL, "{} is not valid UTF-8", path.display())), + Ok(text) => { + let target = crate::path::join(&level.target, text); + if target.len() > crate::path::MAX_PATH { + Err(err!( + ENAMETOOLONG, + "{}: its path inside the volume is longer than {} bytes", + path.display(), + crate::path::MAX_PATH + )) + } else { + Ok(target) + } + } + }; + let target = match (target, unnamable) { + (Ok(target), _) => Some(target), + (Err(e), UnnamableEntry::Fail) => return Err(e), + (Err(_), UnnamableEntry::Omit) => None, + }; let stat = || format!("failed to stat {}", path.display()); - let mut fd = match sys::pin_entry(level.dir.as_fd(), name.as_bytes()) { + let mut fd = match sys::pin_entry(level.dir.as_fd(), &name) { Ok(fd) => fd, // Vanished since the listing: nothing to copy, as for // recurse_dir(). @@ -521,6 +564,12 @@ pub(crate) fn walk_tree( fd = sys::follow_link_at(root, level.dir.as_fd(), fd.as_fd()).with_context(stat)?; metadata = sys::fstat(fd.as_fd()).with_context(stat)?; } + let Some(target) = target else { + if metadata.is_dir() || metadata.is_file() { + omitted += 1; + } + continue; + }; let entry = HostEntry { path, metadata, fd }; if visit(&target, &entry)? && entry.is_dir() { let (dev, ino) = (entry.metadata.dev(), entry.metadata.ino()); @@ -589,7 +638,7 @@ mod tests { fn walk(root: &Path, follow: bool) -> Result> { let fd = open_dir(root)?; let mut seen = Vec::new(); - walk_tree(fd.as_fd(), "/", follow, &mut |target, entry| { + walk_tree(fd.as_fd(), "/", follow, UnnamableEntry::Fail, &mut |target, entry| { let kind = if entry.is_dir() { 'd' } else if entry.is_file() { @@ -621,7 +670,7 @@ mod tests { .unwrap() .map(|e| e.unwrap().file_name().into_string().unwrap()) .collect(); - top.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + top.sort_unstable(); let mut expected = Vec::new(); for name in top { match name.as_str() { @@ -640,7 +689,7 @@ mod tests { assert_eq!(seen.last().unwrap().0, "/\u{e9}"); // The entries themselves can be opened. let fd = open_dir(root).unwrap(); - walk_tree(fd.as_fd(), "/", false, &mut |_, entry| { + walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Fail, &mut |_, entry| { if entry.is_file() { entry.open_file().unwrap(); } @@ -710,7 +759,7 @@ mod tests { let dest = format!("/{}", "d".repeat(3500)); let fd = open_dir(root).unwrap(); let mut seen = 0; - let err = walk_tree(fd.as_fd(), &dest, false, &mut |target, entry| { + let err = walk_tree(fd.as_fd(), &dest, false, UnnamableEntry::Fail, &mut |target, entry| { assert!(target.starts_with(&dest) && target.ends_with("/n")); assert!(entry.is_dir()); seen += 1; @@ -719,10 +768,20 @@ mod tests { .unwrap_err(); assert_eq!(err.errno(), ENAMETOOLONG); // Every level adds "/n" to `dest`. - assert_eq!(seen, (crate::path::MAX_PATH - dest.len()) / 2); + let levels = (crate::path::MAX_PATH - dest.len()) / 2; + assert_eq!(seen, levels); + // Left out instead, the level past the limit is one entry, with + // everything below it. + seen = 0; + let omitted = walk_tree(fd.as_fd(), &dest, false, UnnamableEntry::Omit, &mut |_, _| { + seen += 1; + Ok(true) + }) + .unwrap(); + assert_eq!((seen, omitted), (levels, 1)); // Not descending ends the walk after the first level. seen = 0; - walk_tree(fd.as_fd(), "/", false, &mut |_, _| { + walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Fail, &mut |_, _| { seen += 1; Ok(false) }) @@ -730,6 +789,31 @@ mod tests { assert_eq!(seen, 1); } + /// A name that is not UTF-8 fails the walk, or is left out with what is + /// below it and counted, if it is that of a regular file or a directory. + #[test] + fn names_that_are_not_utf8() { + let tmp = TempDir::new("walk-utf8"); + let root = tmp.path(); + fs::create_dir_all(root.join(OsStr::from_bytes(b"d\xff")).join("inside")).unwrap(); + fs::write(root.join(OsStr::from_bytes(b"f\xfe")), b"x").unwrap(); + fs::write(root.join("kept"), b"x").unwrap(); + // A symbolic link is no file a user of the walk stores, so it is not + // counted, whatever its name. + symlink("kept", root.join(OsStr::from_bytes(b"l\xfd"))).unwrap(); + let fd = open_dir(root).unwrap(); + let err = walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Fail, &mut |_, _| Ok(true)).unwrap_err(); + assert_eq!(err.errno(), EINVAL); + assert!(err.message().contains("not valid UTF-8"), "{}", err); + let mut seen = Vec::new(); + let omitted = walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Omit, &mut |target, _| { + seen.push(target.to_string()); + Ok(true) + }) + .unwrap(); + assert_eq!((seen, omitted), (vec!["/kept".to_string()], 2)); + } + /// A directory that links to itself, and one that links to its parent: /// the walk notices the directory it is about to enter is one it is in /// already and ends with ELOOP, not by running on to the path limit. @@ -740,7 +824,7 @@ mod tests { symlink(".", root.join("loop")).unwrap(); let fd = open_dir(root).unwrap(); let mut seen = 0; - let err = walk_tree(fd.as_fd(), "/", true, &mut |_, entry| { + let err = walk_tree(fd.as_fd(), "/", true, UnnamableEntry::Fail, &mut |_, entry| { assert!(entry.is_dir()); seen += 1; Ok(true) @@ -761,7 +845,7 @@ mod tests { fs::remove_dir_all(root.join("a")).unwrap(); // Without following links the link is one entry, not a directory. seen = 0; - walk_tree(fd.as_fd(), "/", false, &mut |_, entry| { + walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Fail, &mut |_, entry| { assert!(!entry.is_dir() && !entry.is_file()); seen += 1; Ok(true) @@ -844,7 +928,7 @@ mod tests { } let fd = open_dir(root).unwrap(); let mut seen = Vec::new(); - walk_tree(fd.as_fd(), "/", false, &mut |target, _| { + walk_tree(fd.as_fd(), "/", false, UnnamableEntry::Fail, &mut |target, _| { if target == "/a1" { fs::remove_file(root.join("a2")).unwrap(); } @@ -870,7 +954,7 @@ mod tests { } let fd = open_dir(root).unwrap(); let mut contents = Vec::new(); - walk_tree(fd.as_fd(), "/", true, &mut |target, entry| { + walk_tree(fd.as_fd(), "/", true, UnnamableEntry::Fail, &mut |target, entry| { if target == "/d" { // "d" is pinned; now root/d is what used to be root/c. fs::rename(root.join("d"), root.join("e")).unwrap(); diff --git a/src/fat/manifest/error.rs b/src/fat/manifest/error.rs new file mode 100644 index 0000000..6c72055 --- /dev/null +++ b/src/fat/manifest/error.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! The errors of the `uapi16` crate as errors of this one: with the errno +//! and the detail a client of the Varlink interface is told. + +use uapi16::{ErrorKind, Problem}; + +use crate::errno::*; +use crate::{Detail, Error, ManifestProblem}; + +impl From for Error { + fn from(e: uapi16::Error) -> Error { + match e.kind() { + // What the output said when it was written to comes back as it + // was. + ErrorKind::Io => Error::from(std::io::Error::from(e)), + ErrorKind::Manifest(problem) => { + let errno = match problem { + Problem::RecordTooLarge => E2BIG, + _ => EBADMSG, + }; + // These are about the manifest as a whole more than about + // one record of it, and name none. + let record = match problem { + Problem::NotObject + | Problem::InvalidMediaType + | Problem::DataAfterTrailer + | Problem::FileAfterSignature => None, + _ => e.record_number(), + }; + Error::new(errno, e.to_string()).with(Detail::Manifest { + problem: ManifestProblem::Malformed(problem), + record, + name: e.name().map(str::to_string), + field: e.field().map(|field| field.to_string()), + }) + } + // Writing a manifest fails for the reasons above only. + _ => Error::new(EIO, e.to_string()), + } + } +} diff --git a/src/fat/manifest/fields.rs b/src/fat/manifest/fields.rs index fd56452..067ae4b 100644 --- a/src/fat/manifest/fields.rs +++ b/src/fat/manifest/fields.rs @@ -4,11 +4,12 @@ //! follow systemd's reader (src/shared/uapi16-manifest.c) rule for rule. use json::{Object, Value}; +use uapi16::Problem; use super::{malformed_field, FILENAME, GPT_LABEL_MAX, NAME_MAX, PATH_MAX}; use crate::errno::*; use crate::sha256::DIGEST_SIZE; -use crate::{ManifestProblem, Result}; +use crate::Result; /// An unsigned integer. 64 bit values are a problem for many JSON /// implementations, so like systemd we also take them as decimal strings. @@ -25,7 +26,7 @@ pub(super) fn uint(v: &Value, what: &str) -> Result { } bail!( EBADMSG, - malformed_field(ManifestProblem::FieldType, what), + malformed_field(Problem::WrongFieldType, what), "manifest field '{}' is not an unsigned integer", what ) @@ -40,7 +41,7 @@ pub(super) fn access_mode(v: &Value, what: &str) -> Result { Some(_) => { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldType, what), + malformed_field(Problem::WrongFieldType, what), "manifest field '{}' is not an octal access mode", what ) @@ -50,7 +51,7 @@ pub(super) fn access_mode(v: &Value, what: &str) -> Result { if m > 0o7777 { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldRange, what), + malformed_field(Problem::FieldOutOfRange, what), "manifest field '{}' is out of range: {}", what, m @@ -63,7 +64,7 @@ pub(super) fn string<'a>(v: &'a Value, what: &str) -> Result<&'a str> { v.as_str().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::FieldType, what), + malformed_field(Problem::WrongFieldType, what), "manifest field '{}' is not a string", what ) @@ -74,7 +75,7 @@ pub(super) fn boolean(v: &Value, what: &str) -> Result { v.as_bool().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::FieldType, what), + malformed_field(Problem::WrongFieldType, what), "manifest field '{}' is not a boolean", what ) @@ -104,7 +105,7 @@ pub(super) fn hash(v: &Value, what: &str) -> Result<[u8; DIGEST_SIZE]> { .ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::FieldType, what), + malformed_field(Problem::WrongFieldType, what), "manifest field '{}' is not a SHA-256 hash", what ) @@ -170,7 +171,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { let namespaces = v.as_object().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: 'extendedAttributes' is not an object", what ) @@ -182,7 +183,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { let attrs = attrs.as_object().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: extended attribute namespace '{}' is not an object", what, ns @@ -192,7 +193,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { if name.is_empty() || name.chars().any(|c| c.is_ascii_control()) { bail!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: invalid extended attribute name '{}'", what, name @@ -201,7 +202,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { let value = value.as_object().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: value of extended attribute '{}' is not an object", what, name @@ -217,7 +218,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { if base64_decode(string(b, "base64")?).is_none() { bail!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: extended attribute '{}' is not valid Base64", what, name @@ -226,7 +227,7 @@ pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { } _ => bail!( EBADMSG, - malformed_field(ManifestProblem::ExtendedAttributes, "extendedAttributes"), + malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), "{}: extended attribute '{}' needs exactly one of 'text' and 'base64'", what, name @@ -247,7 +248,7 @@ pub(super) fn check_signature(object: &Object, index: usize) -> Result<()> { _ => { bail!( EBADMSG, - malformed_field(ManifestProblem::Signature, "mechanism"), + malformed_field(Problem::InvalidSignature, "mechanism"), "{} has no 'mechanism' string", what ) @@ -257,7 +258,7 @@ pub(super) fn check_signature(object: &Object, index: usize) -> Result<()> { if hex_bytes(string(key, "key")?).is_none() { bail!( EBADMSG, - malformed_field(ManifestProblem::Signature, "key"), + malformed_field(Problem::InvalidSignature, "key"), "{}: 'key' is not hex", what ); @@ -267,7 +268,7 @@ pub(super) fn check_signature(object: &Object, index: usize) -> Result<()> { if base64_decode(string(data, "data")?).is_none() { bail!( EBADMSG, - malformed_field(ManifestProblem::Signature, "data"), + malformed_field(Problem::InvalidSignature, "data"), "{}: 'data' is not Base64", what ); diff --git a/src/fat/manifest/generate.rs b/src/fat/manifest/generate.rs index acfa589..8dc877a 100644 --- a/src/fat/manifest/generate.rs +++ b/src/fat/manifest/generate.rs @@ -2,91 +2,209 @@ //! Writing a manifest for a host tree, the way `systemd-manifest make` //! writes it. -use std::io::{self, Write}; +use std::io::{Read, Write}; use std::os::fd::BorrowedFd; -use std::time::{SystemTime, UNIX_EPOCH}; -use json::{Object, Value}; +use uapi16::{Features, FileObject, Finalize, InodeType, InvalidName, Name, Order, RootObject, Sha256Context, Writer}; -use super::{valid_name, MEDIA_TYPE, RECORD_SEPARATOR, TRAILER_MEDIA_TYPE}; -use crate::sha256::{self, Sha256}; +use super::WriteReport; +use crate::host::{read_some, HostEntry, UnnamableEntry}; +use crate::path::SEPARATOR; use crate::sys; use crate::Result; -/// Writes one record of the JSON text sequence: the record separator, the -/// object with its keys sorted and without whitespace, a newline. The host -/// tree generator and the volume writer frame their records here, so both -/// write what `systemd-manifest` writes. Each record goes out in one write. -pub(crate) fn write_record(out: &mut dyn Write, mut o: Object) -> io::Result<()> { - o.sort(); - let record = format!("{}{}\n", char::from(RECORD_SEPARATOR), Value::Object(o)); - out.write_all(record.as_bytes()) -} +/// How much of a file is read at a time for its hash. +const READ_SIZE: usize = 1024 * 1024; -/// A time as `mTimeNSec` carries it: nanoseconds since the epoch. None for -/// a time the field cannot express, before the epoch or after the year -/// 2554. -pub(crate) fn time_nsec(time: SystemTime) -> Option { - let since = time.duration_since(UNIX_EPOCH).ok()?; - u64::try_from(since.as_nanos()).ok() +/// A directory tree on the host, by the open directory at its top. +/// +/// The descriptor is what the caller resolved its path to, with +/// [`crate::host::open_dir`] when it has a path, and may be O_PATH. +/// Everything below it is reached by descriptor. +#[derive(Clone, Copy, Debug)] +pub struct HostTree<'a> { + root: BorrowedFd<'a>, } -/// Builds a manifest for the host tree below the open directory `root` the -/// way `systemd-manifest make --field=size,hash,mtime` would, for tests and -/// for the command line tool. The descriptor is what the caller resolved -/// its path to, with [`crate::host::open_dir`] when it has a path, and may -/// be O_PATH; everything below it is reached by descriptor. Only regular -/// files and directories are listed, and a manifest stored in the tree's -/// top level is left out since its name is reserved. -pub fn generate(root: BorrowedFd<'_>) -> Result> { - fn mtime_nsec(md: &std::fs::Metadata) -> Option { - md.modified().ok().and_then(time_nsec) +impl<'a> HostTree<'a> { + /// What the manifest of a host tree records: sizes, hashes and times, + /// what `systemd-manifest make --field=size,hash,mtime` records. + const MANIFEST_FEATURES: Features = Features::SIZE.union(Features::SHA256).union(Features::MTIME); + + /// The tree below the open directory `root`. + pub fn new(root: BorrowedFd<'a>) -> HostTree<'a> { + HostTree { root } } - let mut out = Vec::new(); - // The leading object carries the tree's own time, as systemd's does. - let mut top = Object::new(); - if let Some(m) = mtime_nsec(&sys::fstat(root)?) { - top.insert("mTimeNSec", m); + + /// Writes the manifest of the tree to `out`, for tests and for the + /// command line tool, and returns what it covers. It records sizes, + /// hashes and times, as `systemd-manifest make --field=size,hash,mtime` + /// does, lists these features and declares the code point ordering it + /// is in. Each record goes out in one write, so a descriptor wants a + /// `BufWriter` around it. When writing fails, what `out` got is a + /// manifest without its trailer, which a reader refuses as incomplete. + /// + /// Only regular files and directories are listed. The names the + /// specification reserves in the top level for the manifest itself and + /// its signatures are left out silently, as `systemd-manifest` leaves + /// them out. Any other name no manifest can carry, one that is not + /// UTF-8 or that has a control character for instance, and a path + /// longer than a volume takes, is left out and counted in the report's + /// `omitted`, a directory with everything below it as one. + /// + /// A file is read up to the size the walk found it with, so one that + /// keeps growing ends, and the manifest has the size and the hash of + /// what was read. Then its size, modification time and change time are + /// compared with those the walk found. A file where one of them differs + /// changed while it was read and is counted in the report's `changed`. + pub fn write_manifest(&self, out: impl Write) -> Result { + // The root file object carries the tree's own time, as systemd's + // does. + let mut root = RootObject::default(); + root.features = Some(HostTree::MANIFEST_FEATURES); + root.order = Some(Order::CodePoint); + if let Ok(time) = sys::fstat(self.root)?.modified() { + root.inode.set_mtime(time); + } + let mut listing = Listing { + writer: Writer::begin(out, &root)?, + report: WriteReport::default(), + buf: vec![0; READ_SIZE], + }; + let omitted = crate::host::walk_tree(self.root, "", false, UnnamableEntry::Omit, &mut |target, entry| { + listing.entry(target, entry) + })?; + listing.report.omitted += omitted; + listing.writer.finish()?; + Ok(listing.report) } - top.insert("mediaType", MEDIA_TYPE); - write_record(&mut out, top)?; - let mut buf = vec![0u8; 1024 * 1024]; - crate::host::walk_tree(root, "", false, &mut |target, entry| { +} + +/// The manifest of a host tree while it is written. +struct Listing { + writer: Writer, + report: WriteReport, + /// What a file is read into for its hash, one for all of them. + buf: Vec, +} + +impl Listing { + /// Writes the object of the entry that gets the path `target` inside + /// a volume, and says whether the walk is to go into it. + fn entry(&mut self, target: &str, entry: &HostEntry) -> Result { let md = &entry.metadata; - // walk_tree joins with a leading slash; manifests want none. - let path = &target[1..]; - if md.is_file() && !valid_name(path) { + if !md.is_dir() && !md.is_file() { return Ok(false); } - let mtime = mtime_nsec(md); - let mut o = Object::new(); - if md.is_dir() { - if let Some(m) = mtime { - o.insert("mTimeNSec", m); - } - o.insert("name", path); - o.insert("type", "dir"); - write_record(&mut out, o)?; - } else if md.is_file() { - let mut file = entry.open_file()?; - let mut hasher = Sha256::new(); - loop { - let n = crate::host::read_some(&mut file, &mut buf)?; - if n == 0 { - break; - } - hasher.update(&buf[..n]); + // walk_tree joins with a leading slash; manifests want none. + let path = target.strip_prefix(SEPARATOR).unwrap_or(target); + let mut object = match Name::new(path) { + Ok(name) => FileObject::new(name), + // Only a name at the top can be one of the names reserved for + // the manifest. It is no omission. + Err(InvalidName::Reserved) => return Ok(false), + Err(_) => { + self.report.omitted += 1; + return Ok(false); } - if let Some(m) = mtime { - o.insert("mTimeNSec", m); + }; + if let Ok(time) = md.modified() { + object.inode.set_mtime(time); + } + if md.is_dir() { + object.inode_type = InodeType::Directory; + self.writer.file(&object)?; + self.report.directories += 1; + return Ok(true); + } + // Read no more than the walk found, so that a file that keeps + // growing ends. The size is that of what was hashed, so the two + // agree for a file that changes while it is read. + let found = md.len(); + let mut context = Sha256Context::default(); + let mut size = 0; + let file = entry.open_file()?; + let mut data = (&file).take(found); + loop { + let n = read_some(&mut data, &mut self.buf)?; + if n == 0 { + break; } - o.insert("name", path); - o.insert("sha256", sha256::to_hex(&hasher.finalize())); - o.insert("size", md.len()); - write_record(&mut out, o)?; + context.update(&self.buf[..n]); + size += n as u64; } - Ok(md.is_dir()) - })?; - write_record(&mut out, json::object! { "mediaType" => TRAILER_MEDIA_TYPE })?; - Ok(out) + if size != found || entry.has_changed(&file)? { + self.report.changed += 1; + } + object.sha256 = Some(context.finalize()); + object.size = Some(size); + self.writer.file(&object)?; + self.report.files += 1; + self.report.bytes += size; + Ok(false) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::host::{open_dir, walk_tree}; + use crate::test_util::TempDir; + use std::fs; + use std::os::fd::AsFd; + use std::os::unix::fs::FileExt; + use std::time::UNIX_EPOCH; + use uapi16::{Object, Reader, Sha256}; + + /// Files that change after the walk found them and before they are + /// read: one grows, one shrinks, one gets another time and one stays. + /// The manifest has what was read, no more than the walk found, and the + /// report counts the three that changed. + #[test] + fn files_that_change_while_they_are_read() { + let tmp = TempDir::new("generate-changed"); + let top = tmp.path(); + for name in ["grows", "shrinks", "stays", "touched"] { + fs::write(top.join(name), b"hello world").unwrap(); + } + let dir = open_dir(top).unwrap(); + let mut root = RootObject::default(); + root.features = Some(HostTree::MANIFEST_FEATURES); + root.order = Some(Order::CodePoint); + let mut listing = Listing { + writer: Writer::begin(Vec::new(), &root).unwrap(), + report: WriteReport::default(), + buf: vec![0; READ_SIZE], + }; + walk_tree(dir.as_fd(), "", false, UnnamableEntry::Omit, &mut |target, entry| { + let file = || fs::File::options().write(true).open(top.join(&entry.path)).unwrap(); + match entry.path.to_str() { + Some("grows") => file().write_all_at(b" and more", 11).unwrap(), + Some("shrinks") => file().set_len(5).unwrap(), + Some("touched") => file().set_modified(UNIX_EPOCH).unwrap(), + _ => {} + } + listing.entry(target, entry) + }) + .unwrap(); + assert_eq!((listing.report.files, listing.report.changed), (4, 3)); + let bytes = listing.writer.finish().unwrap(); + let read: Vec<(String, u64, Sha256)> = Reader::open(&bytes[..]) + .unwrap() + .filter_map(|object| match object.unwrap() { + Object::File(file) => Some((file.name.to_string(), file.size.unwrap(), file.sha256.unwrap())), + _ => None, + }) + .collect(); + let whole = Sha256::digest(b"hello world"); + assert_eq!( + read, + [ + ("grows".to_string(), 11, whole), + ("shrinks".to_string(), 5, Sha256::digest(b"hello")), + ("stays".to_string(), 11, whole), + ("touched".to_string(), 11, whole), + ] + ); + } } diff --git a/src/fat/manifest/mod.rs b/src/fat/manifest/mod.rs index c526009..6768c17 100644 --- a/src/fat/manifest/mod.rs +++ b/src/fat/manifest/mod.rs @@ -24,6 +24,7 @@ use std::io::Read; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use json::{Object, Value}; +use uapi16::Problem; use crate::errno::*; use crate::sha256::{self, DIGEST_SIZE}; @@ -31,15 +32,18 @@ use crate::volume::MAX_FILE_SIZE; use crate::{Detail, ManifestProblem, Result, UnsupportedKind, ValidityProblem}; mod assemble; +mod error; mod fields; mod generate; #[cfg(test)] mod tests; -pub mod volume; +mod volume; pub use assemble::{AssembleOptions, AssembleReport, ContentSource, DirectorySource, StreamSource}; pub use fields::{base64_decode, valid_name}; -pub use generate::generate; +pub use generate::HostTree; +pub use uapi16::Features; +pub use volume::WriteReport; use fields::{ access_mode, boolean, check_extended_attributes, check_signature, fat_key, hash, string, uint, valid_gpt_label, @@ -56,9 +60,9 @@ macro_rules! malformed { } /// The detail of a defect of the manifest itself. -pub(super) fn malformed(problem: ManifestProblem) -> Detail { +pub(super) fn malformed(problem: Problem) -> Detail { Detail::Manifest { - problem, + problem: ManifestProblem::Malformed(problem), record: None, name: None, field: None, @@ -66,9 +70,9 @@ pub(super) fn malformed(problem: ManifestProblem) -> Detail { } /// [`malformed`] about one field. -pub(super) fn malformed_field(problem: ManifestProblem, field: &str) -> Detail { +pub(super) fn malformed_field(problem: Problem, field: &str) -> Detail { Detail::Manifest { - problem, + problem: ManifestProblem::Malformed(problem), record: None, name: None, field: Some(field.to_string()), @@ -362,7 +366,7 @@ fn reconcile_hash_and_size(hash: &mut Option<[u8; DIGEST_SIZE]>, size: &mut Opti (Some(h), Some(s)) if h == sha256::EMPTY && s != 0 => { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "sha256"), + malformed_field(Problem::Contradiction, "sha256"), "{}: a zero hash with a non-zero size", what ) @@ -370,7 +374,7 @@ fn reconcile_hash_and_size(hash: &mut Option<[u8; DIGEST_SIZE]>, size: &mut Opti (Some(h), Some(0)) if h != sha256::EMPTY => { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "size"), + malformed_field(Problem::Contradiction, "size"), "{}: a zero size with a non-zero hash", what ) @@ -386,7 +390,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { let o = v.as_object().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::Contents, "contents"), + malformed_field(Problem::InvalidContents, "contents"), "{}: contents entry is not an object", what ) @@ -402,7 +406,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { if !valid_name(f) { bail!( EBADMSG, - malformed_field(ManifestProblem::Contents, "file"), + malformed_field(Problem::InvalidContents, "file"), "{}: contents file reference '{}' is not a valid relative path", what, f @@ -415,7 +419,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { if !(u.starts_with("http://") || u.starts_with("https://")) { bail!( EBADMSG, - malformed_field(ManifestProblem::Contents, "url"), + malformed_field(Problem::InvalidContents, "url"), "{}: contents URL '{}' is not http or https", what, u @@ -427,7 +431,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { c.literal = Some(base64_decode(string(value, "literal")?).ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::Contents, "literal"), + malformed_field(Problem::InvalidContents, "literal"), "{}: literal contents are not Base64", what ) @@ -438,7 +442,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { if e.is_empty() || e == "identity" { bail!( EBADMSG, - malformed_field(ManifestProblem::Contents, "encoding"), + malformed_field(Problem::InvalidContents, "encoding"), "{}: encoding '{}' is not permitted", what, e @@ -462,7 +466,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { { bail!( EBADMSG, - malformed(ManifestProblem::Contents), + malformed(Problem::InvalidContents), "{}: only one of file, url and literal may be set", what ); @@ -474,7 +478,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { match (c.encoded_size, c.original_size) { (Some(a), Some(b)) if a != b => bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "encodedSize"), + malformed_field(Problem::Contradiction, "encodedSize"), "{}: encoded and original size differ without an encoding", what ), @@ -485,7 +489,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { match (c.encoded_sha256, c.original_sha256) { (Some(a), Some(b)) if a != b => bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "encodedSha256"), + malformed_field(Problem::Contradiction, "encodedSha256"), "{}: encoded and original hash differ without an encoding", what ), @@ -499,7 +503,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { if s != literal.len() as u64 { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "literal"), + malformed_field(Problem::Contradiction, "literal"), "{}: literal contents are {} bytes, not {}", what, literal.len(), @@ -516,7 +520,7 @@ fn parse_contents(v: &Value, what: &str) -> Result { if c.offset > total { bail!( EBADMSG, - malformed_field(ManifestProblem::Contents, "offset"), + malformed_field(Problem::InvalidContents, "offset"), "{}: contents offset {} is beyond the data size {}", what, c.offset, @@ -563,7 +567,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if !valid_name(n) { bail!( EBADMSG, - malformed_field(ManifestProblem::InvalidName, "name"), + malformed_field(Problem::InvalidName, "name"), "manifest object {}: name '{}' is not a valid relative path", index, n @@ -577,7 +581,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { inode_type = Some(InodeType::parse(t).ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::UnknownType, "type"), + malformed_field(Problem::UnknownType, "type"), "manifest object {}: unknown inode type '{}'", index, t @@ -592,7 +596,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if v >= 0xFFFF_FFFF || v == 0xFFFF { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldRange, key), + malformed_field(Problem::FieldOutOfRange, key), "manifest object {}: {} {} is out of range", index, key, @@ -605,7 +609,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if !valid_user_group_name(n) { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldType, key), + malformed_field(Problem::WrongFieldType, key), "manifest object {}: {} '{}' is not a valid name", index, key, @@ -618,7 +622,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if !valid_gpt_label(l) { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldType, "gptLabel"), + malformed_field(Problem::WrongFieldType, "gptLabel"), "manifest object {}: '{}' is not a valid GPT partition label", index, l @@ -631,7 +635,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if !valid_id128(id) { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldType, key), + malformed_field(Problem::WrongFieldType, key), "manifest object {}: {} '{}' is not a UUID", index, key, @@ -668,14 +672,14 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { let items = value.as_array().ok_or_else(|| { err!( EBADMSG, - malformed_field(ManifestProblem::FieldType, "contents"), + malformed_field(Problem::WrongFieldType, "contents"), "manifest field 'contents' is not an array" ) })?; if items.len() > MAX_CONTENTS { bail!( EBADMSG, - malformed_field(ManifestProblem::Contents, "contents"), + malformed_field(Problem::InvalidContents, "contents"), "manifest object {}: more than {} contents entries", index, MAX_CONTENTS @@ -700,7 +704,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if mt != MEDIA_TYPE { bail!( EBADMSG, - malformed_field(ManifestProblem::MediaType, "mediaType"), + malformed_field(Problem::InvalidMediaType, "mediaType"), "manifest object {} has unexpected media type '{}'", index, mt @@ -711,21 +715,21 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if media_type.is_none() { bail!( EBADMSG, - malformed_field(ManifestProblem::MediaType, "mediaType"), + malformed_field(Problem::InvalidMediaType, "mediaType"), "the first manifest object does not carry the manifest media type" ); } if e.name.is_some() { bail!( EBADMSG, - malformed_field(ManifestProblem::FirstHasName, "name"), + malformed_field(Problem::RootHasName, "name"), "the first manifest object has a name" ); } if !matches!(inode_type, None | Some(InodeType::Directory)) { bail!( EBADMSG, - malformed_field(ManifestProblem::FirstNotDirectory, "type"), + malformed_field(Problem::RootNotDirectory, "type"), "the first manifest object is not a directory" ); } @@ -734,7 +738,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if e.name.is_none() { bail!( EBADMSG, - malformed_field(ManifestProblem::NoName, "name"), + malformed_field(Problem::NoName, "name"), "manifest object {} has no name", index ); @@ -747,7 +751,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if e.size.is_some() && !matches!(t, InodeType::Regular | InodeType::Symlink | InodeType::Directory) { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "size"), + malformed_field(Problem::FieldNotPermitted, "size"), "{}: 'size' is not permitted on a {}", w, t.as_str() @@ -756,7 +760,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if major_minor && !matches!(t, InodeType::BlockDevice | InodeType::CharDevice) { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "major"), + malformed_field(Problem::FieldNotPermitted, "major"), "{}: 'major' and 'minor' are not permitted on a {}", w, t.as_str() @@ -765,7 +769,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if e.mode.is_some() && t == InodeType::Symlink { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "mode"), + malformed_field(Problem::FieldNotPermitted, "mode"), "{}: 'mode' is not permitted on a symlink", w ); @@ -773,7 +777,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if matches!(e.inode_token, Some(tok) if tok != 0) && t == InodeType::Directory { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "inodeToken"), + malformed_field(Problem::FieldNotPermitted, "inodeToken"), "{}: 'inodeToken' is not permitted on a directory", w ); @@ -783,7 +787,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "contents"), + malformed_field(Problem::FieldNotPermitted, "contents"), "{}: 'contents' and 'sha256' are not permitted on a {}", w, t.as_str() @@ -792,7 +796,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if gpt && t != InodeType::Regular { bail!( EBADMSG, - malformed(ManifestProblem::FieldNotPermitted), + malformed(Problem::FieldNotPermitted), "{}: GPT fields are only permitted on regular files", w ); @@ -800,7 +804,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if gpt_disk && index != 0 { bail!( EBADMSG, - malformed_field(ManifestProblem::FieldNotPermitted, "gptDiskUuid"), + malformed_field(Problem::FieldNotPermitted, "gptDiskUuid"), "{}: 'gptDiskUuid' is only permitted on the first object", w ); @@ -809,7 +813,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if ro == (mode & 0o222 != 0) { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "readOnly"), + malformed_field(Problem::Contradiction, "readOnly"), "{}: 'readOnly' and 'mode' contradict each other", w ); @@ -821,7 +825,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "gptFlags"), + malformed_field(Problem::Contradiction, "gptFlags"), "{}: 'gptFlags' and the 'gptFlag*' fields contradict each other", w ); @@ -835,7 +839,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { if c.offset.checked_add(size).is_none_or(|end| end > total) { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "offset"), + malformed_field(Problem::Contradiction, "offset"), "{}: offset {} plus size {} exceeds the contents size {}", w, c.offset, @@ -852,7 +856,7 @@ pub fn parse_entry(object: &Object, index: usize) -> Result { (Some(a), Some(b)) if a != b => { bail!( EBADMSG, - malformed_field(ManifestProblem::Contradiction, "sha256"), + malformed_field(Problem::Contradiction, "sha256"), "{}: object and contents hashes differ", w ) @@ -891,7 +895,7 @@ fn next_record(buffer: &[u8], eof: bool) -> Result> { if rest[0] != RECORD_SEPARATOR { bail!( EBADMSG, - malformed(ManifestProblem::RecordSeparator), + malformed(Problem::NoRecordSeparator), "manifest record does not start with a record separator but with byte 0x{:02x}", rest[0] ); @@ -903,7 +907,7 @@ fn next_record(buffer: &[u8], eof: bool) -> Result> { None if body.len() > MAX_RECORD_SIZE => { bail!( E2BIG, - malformed(ManifestProblem::RecordTooLarge), + malformed(Problem::RecordTooLarge), "manifest record exceeds {} bytes", MAX_RECORD_SIZE ) @@ -914,7 +918,7 @@ fn next_record(buffer: &[u8], eof: bool) -> Result> { if record.len() > MAX_RECORD_SIZE { bail!( E2BIG, - malformed(ManifestProblem::RecordTooLarge), + malformed(Problem::RecordTooLarge), "manifest record exceeds {} bytes", MAX_RECORD_SIZE ); @@ -922,17 +926,12 @@ fn next_record(buffer: &[u8], eof: bool) -> Result> { if record.contains(&0) { bail!( EBADMSG, - malformed(ManifestProblem::NulByte), + malformed(Problem::ContainsNulByte), "manifest record contains a NUL byte" ); } - let text = std::str::from_utf8(record).map_err(|_| { - err!( - EBADMSG, - malformed(ManifestProblem::NotUtf8), - "manifest record is not UTF-8" - ) - })?; + let text = std::str::from_utf8(record) + .map_err(|_| err!(EBADMSG, malformed(Problem::NotUtf8), "manifest record is not UTF-8"))?; consumed += 1 + end; if text.bytes().all(|b| b.is_ascii_whitespace()) { // Empty records are skipped, as RFC 7464 suggests. Only ASCII @@ -978,7 +977,7 @@ pub fn read(reader: &mut dyn Read) -> Result { start += consumed; if trailer { malformed!( - ManifestProblem::DataAfterTrailer, + Problem::DataAfterTrailer, EBADMSG, "manifest contains data after the trailer object" ); @@ -986,7 +985,7 @@ pub fn read(reader: &mut dyn Read) -> Result { let value = json::parse(&text).map_err(|e| { err!( EBADMSG, - malformed(ManifestProblem::NotJson), + malformed(Problem::NotJson), "manifest record {} is not valid JSON: {}", index, e @@ -995,7 +994,7 @@ pub fn read(reader: &mut dyn Read) -> Result { })?; let Value::Object(object) = value else { malformed!( - ManifestProblem::NotObject, + Problem::NotObject, EBADMSG, "manifest record {} is not a JSON object", index @@ -1005,7 +1004,7 @@ pub fn read(reader: &mut dyn Read) -> Result { None => None, Some(Value::String(s)) => Some(s.as_str()), Some(_) => malformed!( - ManifestProblem::MediaType, + Problem::InvalidMediaType, EBADMSG, "manifest object {} has a mediaType that is not a string", index @@ -1014,7 +1013,7 @@ pub fn read(reader: &mut dyn Read) -> Result { if index == 0 { if media_type != Some(MEDIA_TYPE) { malformed!( - ManifestProblem::MediaType, + Problem::InvalidMediaType, EBADMSG, "the first object of the manifest is not of the manifest media type" ); @@ -1033,7 +1032,7 @@ pub fn read(reader: &mut dyn Read) -> Result { } if signatures > 0 { malformed!( - ManifestProblem::FileAfterSignature, + Problem::FileAfterSignature, EBADMSG, "manifest contains a file object after a signature object" ); @@ -1047,15 +1046,10 @@ pub fn read(reader: &mut dyn Read) -> Result { if let Some(&earlier) = names.get(&fat_key(name)) { let other = entries[earlier].name.as_deref().unwrap_or_default(); if other == name { - malformed!( - ManifestProblem::DuplicateName, - EBADMSG, - "manifest lists '{}' twice", - name - ); + malformed!(Problem::DuplicateName, EBADMSG, "manifest lists '{}' twice", name); } malformed!( - ManifestProblem::DuplicateName, + Problem::DuplicateName, EEXIST, "manifest lists '{}' and '{}', which FAT cannot tell apart", other, @@ -1068,11 +1062,11 @@ pub fn read(reader: &mut dyn Read) -> Result { index += 1; } let Some(root) = root else { - malformed!(ManifestProblem::Empty, EBADMSG, "manifest contains no objects") + malformed!(Problem::NoObjects, EBADMSG, "manifest contains no objects") }; if !trailer { malformed!( - ManifestProblem::NoTrailer, + Problem::NoTrailer, EBADMSG, "manifest lacks the trailer object, it is incomplete" ); diff --git a/src/fat/manifest/tests.rs b/src/fat/manifest/tests.rs index a66afbc..7155327 100644 --- a/src/fat/manifest/tests.rs +++ b/src/fat/manifest/tests.rs @@ -16,7 +16,11 @@ fn dir_source(path: &Path) -> DirectorySource { /// The manifest the generator writes for the tree at `path`. fn generated(path: &Path) -> Vec { - generate(crate::host::open_dir(path).unwrap().as_fd()).unwrap() + let mut out = Vec::new(); + HostTree::new(crate::host::open_dir(path).unwrap().as_fd()) + .write_manifest(&mut out) + .unwrap(); + out } fn seq(records: &[&str]) -> Vec { @@ -872,18 +876,6 @@ fn validity() { assert!(v.assemble(&m, &mut StreamSource::new(&mut empty), &opts).is_ok()); } -/// mTimeNSec holds nanoseconds since the epoch in 64 bits: up to the year -/// 2554, and nothing before 1970. -#[test] -fn times_outside_mtime_nsec_have_none() { - use std::time::{Duration, UNIX_EPOCH}; - let last = UNIX_EPOCH + Duration::from_nanos(u64::MAX); - assert_eq!(generate::time_nsec(UNIX_EPOCH), Some(0)); - assert_eq!(generate::time_nsec(last), Some(u64::MAX)); - assert_eq!(generate::time_nsec(last + Duration::from_nanos(1)), None); - assert_eq!(generate::time_nsec(UNIX_EPOCH - Duration::from_secs(1)), None); -} - /// Checks the progress a long operation reported: the counts only grow /// and end at what its report says. fn reported(seen: &[Progress], last: Progress) { @@ -925,10 +917,9 @@ fn long_operations_report_progress() { ); seen.clear(); - let w = volume::write_with_progress(&v, None, volume::Fields::default(), &mut Vec::new(), &mut |p| { - seen.push(*p) - }) - .unwrap(); + let w = v + .write_manifest_with_progress(None, Features::DEFAULT, &mut Vec::new(), &mut |p| seen.push(*p)) + .unwrap(); assert!(seen.iter().any(|p| p.files == 0 && p.bytes > 0), "{:?}", seen); reported( &seen, diff --git a/src/fat/manifest/volume.rs b/src/fat/manifest/volume.rs index e57d953..8544aff 100644 --- a/src/fat/manifest/volume.rs +++ b/src/fat/manifest/volume.rs @@ -5,143 +5,36 @@ //! This is the manifest the Varlink interface's `ManifestSink` receives //! from Assemble, Populate and Describe, see //! docs/org.uapi-group.FileSystem.varlink. It says what the volume stores -//! as the volume stores it: -//! times at FAT's 2 s, the read-only attribute as `readOnly`, and no mode, -//! owner, device numbers, hardlinks or extended attributes, since FAT has -//! no notion of them. A field the file system has no notion of is left out -//! and not counted; what FAT keeps and the manifest could not record is -//! counted in the report's `omitted`. +//! as the volume stores it: times at FAT's 2 s, the read-only attribute as +//! `readOnly`, and no mode, owner, device numbers, hardlinks or extended +//! attributes, since FAT has no notion of them. A feature the file system +//! has no notion of is not recorded and not counted; what FAT keeps and +//! the manifest could not record is counted in the report's `omitted`. //! -//! The order is the specification's: the root object first, every -//! directory's entries right after it, sorted by the bytes of their names -//! and never in on-disk order, the trailer last. Keys inside an object are -//! sorted and the records carry no whitespace, as `systemd-manifest` -//! writes them. Like `systemd-manifest` and the host tree generator, the -//! writer leaves out the inode type on the root object and on regular -//! files, where the specification implies it. So with the same fields, the -//! manifest of a volume is the one they write for the tree the volume was +//! The order is the specification's code point order: the root object +//! first, every directory's entries right after it, sorted by the bytes of +//! their names and never in on-disk order, the trailer last. The records +//! are what the `uapi16` crate writes, as `systemd-manifest` writes them: +//! keys sorted, no whitespace, no inode type on the root object and on +//! regular files. So with the same features the manifest of a volume is +//! the one the host tree generator writes for the tree the volume was //! filled from, apart from what FAT changes on the way: FAT keeps times at -//! 2 s, and a read-only file gets `readOnly`. +//! 2 s, the manifest always lists `read-only`, and a read-only file gets +//! `readOnly`. -use std::collections::HashSet; use std::io::Write; use std::time::SystemTime; -use json::Object; +use uapi16::{Features, FileObject, Finalize, InodeType, Name, Order, RootObject, Sha256, Sha256Context, Writer}; -use super::generate::{time_nsec, write_record}; -use super::{valid_name, FILENAME, MEDIA_TYPE, TRAILER_MEDIA_TYPE}; +use crate::dir::NameDecoding; use crate::dirent::ATTR_READ_ONLY; use crate::errno::*; +use crate::fat::BitSet; use crate::progress::Progress; -use crate::sha256::{self, Sha256, DIGEST_SIZE}; -use crate::volume::Volume; +use crate::volume::{Metadata, Volume}; use crate::{CorruptPlace, Detail, Result}; -/// The per-file fields a written manifest carries: systemd-manifest's -/// vocabulary, the names its `--field=` and repart's `--manifest-fields=` -/// take, as the Varlink interface's `ManifestField` spells them. The inode -/// type is always given, and `readOnly` is written where the attribute is -/// set, which no field governs. FAT has no mode, owner, symbolic links, -/// device nodes, hardlinks, extended attributes or user and group names, -/// so of these only `size`, `hash` and `mtime` change what the volume -/// writer puts out. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Fields { - /// `mode`: the access mode. - pub mode: bool, - /// `uid`: the owning user. - pub uid: bool, - /// `gid`: the owning group. - pub gid: bool, - /// `size`: the size of regular files. - pub size: bool, - /// `hash`: the SHA-256 of regular files. - pub hash: bool, - /// `symlink`: the target of symbolic links. - pub symlink: bool, - /// `device`: the numbers of device nodes. - pub device: bool, - /// `hardlink`: the hardlink group token. - pub hardlink: bool, - /// `mtime`: the modification time. - pub mtime: bool, - /// `userXattr`: the extended attributes of the user namespace. - pub user_xattr: bool, - /// `userName`: the owning user's name. - pub user_name: bool, - /// `groupName`: the owning group's name. - pub group_name: bool, -} - -impl Default for Fields { - /// systemd's default set: everything but `mtime`, `userName` and - /// `groupName`. - fn default() -> Fields { - Fields { - mode: true, - uid: true, - gid: true, - size: true, - hash: true, - symlink: true, - device: true, - hardlink: true, - mtime: false, - user_xattr: true, - user_name: false, - group_name: false, - } - } -} - -impl Fields { - /// No field at all: the manifest carries the names and the inode types, - /// and `readOnly` where the attribute is set. - pub fn none() -> Fields { - Fields { - mode: false, - uid: false, - gid: false, - size: false, - hash: false, - symlink: false, - device: false, - hardlink: false, - mtime: false, - user_xattr: false, - user_name: false, - group_name: false, - } - } - - /// The fields named with the interface's names: `mode`, `uid`, `gid`, - /// `size`, `hash`, `symlink`, `device`, `hardlink`, `mtime`, - /// `userXattr`, `userName` and `groupName`. None when a name is not one - /// of them. - pub fn from_names<'a>(names: impl IntoIterator) -> Option { - let mut fields = Fields::none(); - for name in names { - match name { - "mode" => fields.mode = true, - "uid" => fields.uid = true, - "gid" => fields.gid = true, - "size" => fields.size = true, - "hash" => fields.hash = true, - "symlink" => fields.symlink = true, - "device" => fields.device = true, - "hardlink" => fields.hardlink = true, - "mtime" => fields.mtime = true, - "userXattr" => fields.user_xattr = true, - "userName" => fields.user_name = true, - "groupName" => fields.group_name = true, - _ => return None, - } - } - Some(fields) - } -} - /// What a written manifest covers. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WriteReport { @@ -151,12 +44,18 @@ pub struct WriteReport { pub directories: u64, /// Bytes of the regular files listed. pub bytes: u64, - /// What the volume holds that the manifest could not record: entries - /// whose names a manifest cannot carry, a directory with everything - /// below it counting once. A field FAT has no notion of is not an - /// omission. A manifest with omissions does not describe the whole - /// volume, which is what repart refuses. + /// What the tree or the volume holds that the manifest could not + /// record: entries whose names a manifest cannot carry, a directory + /// with everything below it counting once. A feature the file system + /// has no notion of is not an omission. A manifest with omissions does + /// not describe all of it, and repart refuses such a manifest of a + /// volume. pub omitted: u64, + /// Regular files of a host tree that changed while they were read for + /// their hash. The manifest has the size and the hash of what was + /// read, which need not be what the file holds now. A volume does not + /// change while its manifest is written. + pub changed: u64, } impl WriteReport { @@ -170,145 +69,256 @@ impl WriteReport { } } -/// Writes the UAPI.16 manifest of everything the volume holds to `out`: -/// the root object, one object per entry, the trailer. `root_time` is the -/// time the root object carries when `fields.mtime` is on: the root -/// directory of a FAT volume has no entry of its own and so no time, the -/// caller passes the one it knows, the source directory's or the label -/// entry's. Each record goes out in one write and `out` is flushed at the -/// end, so a descriptor wants a `BufWriter` around it. -/// -/// Names the manifest cannot carry are left out, with everything below -/// them. The names the specification reserves in the top level for the -/// manifest itself and its signatures (`Uapi16Manifest`, -/// `Uapi16Manifest.*`) are left out silently, as `systemd-manifest` leaves -/// them out; any other, a component of more than 255 bytes of UTF-8 for -/// instance, which FAT stores in UTF-16 but no manifest reader takes, is -/// counted in the report's `omitted`. -pub fn write( - volume: &Volume, - root_time: Option, - fields: Fields, - out: &mut dyn Write, -) -> Result { - write_with_progress(volume, root_time, fields, out, &mut |_| {}) -} +impl Volume { + /// What the manifest of a FAT volume records whatever it is asked for: + /// the read-only attribute, which every entry has set or cleared. + const ALWAYS_RECORDED_FEATURES: Features = Features::READ_ONLY; -/// [`write`], telling `progress` what the manifest covers so far after -/// every entry and every chunk of a file it reads for the hash. -pub fn write_with_progress( - volume: &Volume, - root_time: Option, - fields: Fields, - out: &mut dyn Write, - progress: &mut dyn FnMut(&Progress), -) -> Result { - let root = volume.metadata("/")?; - let mut writer = Writer { - volume, - fields, - out, - report: WriteReport::default(), - buf: vec![0u8; volume.layout().cluster_size() as usize], - seen: HashSet::from([root.first_cluster]), - progress, - }; - // The root object is a directory by definition and carries no type. - let mut top = Object::new(); - top.insert("mediaType", MEDIA_TYPE); - if fields.mtime { - if let Some(nsec) = root_time.and_then(time_nsec) { - top.insert("mTimeNSec", nsec); - } - } - write_record(writer.out, top)?; - writer.directory("/", "")?; - write_record(writer.out, json::object! { "mediaType" => TRAILER_MEDIA_TYPE })?; - writer.out.flush()?; - Ok(writer.report) -} + /// What the manifest of a FAT volume can record: sizes, hashes, times + /// and the read-only attribute, and that there are no symbolic links, + /// device nodes, hardlinks or extended attributes. + const MANIFEST_FEATURES: Features = Features::SIZE + .union(Features::SHA256) + .union(Features::MTIME) + .union(Features::READ_ONLY) + .union(Features::SYMLINK) + .union(Features::DEVICE) + .union(Features::HARDLINK) + .union(Features::USER_XATTR); + + /// Writes the UAPI.16 manifest of everything the volume holds to `out`: + /// the root object, one object per entry, the trailer. `root_time` is + /// the time the root object carries when `features` has + /// [`Features::MTIME`]: the root directory of a FAT volume has no entry + /// of its own and so no time, the caller passes the one it knows, the + /// source directory's or the label entry's. Each record goes out in + /// one write and `out` is flushed at the end, so a descriptor wants a + /// `BufWriter` around it. + /// + /// The manifest records what `features` asks for and FAT has a notion + /// of. Of the features only [`Features::SIZE`], [`Features::SHA256`] + /// and [`Features::MTIME`] add fields. FAT has no symbolic links, + /// device nodes, hardlinks and extended attributes, so the manifest + /// records that it has none of them where `features` asks for them. FAT + /// has no mode, owner or user and group names, so the manifest does not + /// record them. It always records the read-only attribute, which every + /// entry has set or cleared: `readOnly` is written where it is set, and + /// an entry without it is not read-only. The manifest lists its + /// features, and declares the code point ordering its objects are in. + /// + /// Names the manifest cannot carry are left out, with everything below + /// them. The names the specification reserves in the top level for the + /// manifest itself and its signatures (`Uapi16Manifest`, + /// `Uapi16Manifest.*`) are left out silently, as `systemd-manifest` + /// leaves them out; any other, one with a noncharacter or an unpaired + /// surrogate for instance, which FAT stores but no manifest has, is + /// counted in the report's `omitted`. Names that FAT takes for one, + /// such as `README.TXT` and `readme.txt`, are two names to a manifest, + /// and each is listed with what its entry holds. + /// + /// What only a damaged volume has fails with EUCLEAN: a cluster that + /// belongs to two entries, or twice to one, as in a loop or a + /// cross-link, a directory whose chain is longer than a directory can + /// be, an entry that points at a cluster the volume does not have, a + /// chain that runs into a free, bad or invalid entry, a file whose + /// chain is shorter than the file, and two entries of the same name in + /// a directory. The walk lists a directory from the first cluster its + /// entry names and reads a file the same way, never by path. It keeps + /// one bit for every cluster of the volume, set for every cluster of a + /// directory it lists and of a file it reads for the hash, and ends + /// where it reaches a cluster a second time. So it lists no directory + /// and reads no file twice, and takes time in proportion to the size of + /// the volume. It reads files only for [`Features::SHA256`], and only + /// then finds what is wrong with their chains. + pub fn write_manifest( + &self, + root_time: Option, + features: Features, + out: impl Write, + ) -> Result { + self.write_manifest_with_progress(root_time, features, out, &mut |_| {}) + } -/// Whether `name`, relative to the root, is one the specification reserves -/// in the top level for the manifest itself and its signatures. -fn reserved(name: &str) -> bool { - name == FILENAME || name.strip_prefix(FILENAME).is_some_and(|rest| rest.starts_with('.')) + /// [`Volume::write_manifest`], telling `progress` what the manifest + /// covers so far after every entry and every chunk of a file it reads + /// for the hash. + pub fn write_manifest_with_progress( + &self, + root_time: Option, + features: Features, + out: impl Write, + progress: &mut dyn FnMut(&Progress), + ) -> Result { + let top = self.metadata("/")?; + let features = (features | Volume::ALWAYS_RECORDED_FEATURES) & Volume::MANIFEST_FEATURES; + // The root object is a directory by definition and carries no type. + let mut root = RootObject::default(); + root.features = Some(features); + root.order = Some(Order::CodePoint); + if let Some(time) = root_time.filter(|_| features.contains(Features::MTIME)) { + root.inode.set_mtime(time); + } + let mut listing = Listing { + volume: self, + features, + writer: Writer::begin(out, &root)?, + report: WriteReport::default(), + buf: vec![0u8; self.layout().cluster_size() as usize], + claimed: BitSet::new(self.layout().max_cluster() as usize + 1), + progress, + }; + let entries = listing.list("/", top.first_cluster)?; + listing.directory("/", &Name::ROOT, entries)?; + listing.writer.finish()?; + Ok(listing.report) + } } -struct Writer<'a> { +/// The manifest of a volume while it is written. +struct Listing<'a, W: Write> { volume: &'a Volume, - fields: Fields, - out: &'a mut dyn Write, + /// What the manifest records. + features: Features, + writer: Writer, report: WriteReport, /// One cluster, the most one read of a file returns. buf: Vec, - /// First clusters of the root and of every directory written so far. A - /// directory reached twice is a cross-linked or looping tree; without - /// the check a loop would run until the path limit. - seen: HashSet, + /// The clusters the walk read so far, one bit for every cluster of the + /// volume: those of every directory it listed and of every file it + /// read for the hash. On a damaged volume a cluster can belong to two + /// entries, or twice to one, through a loop or a cross-link, and a walk + /// that read it again would list a directory or read a file as often + /// as there are paths to it: in a loop without end, and in a chain of + /// cross-linked directories twice as often per level. + claimed: BitSet, progress: &'a mut dyn FnMut(&Progress), } -impl Writer<'_> { - /// Writes the entries of the directory at `path` inside the volume, - /// whose name in the manifest is `prefix` (empty for the root), sorted - /// by the bytes of their names, each directory followed by what is - /// below it. - fn directory(&mut self, path: &str, prefix: &str) -> Result<()> { - let mut entries = self.volume.read_dir(path)?; - entries.sort_by(|a, b| a.name.as_bytes().cmp(b.name.as_bytes())); +impl Listing<'_, W> { + /// Notes that the walk read `cluster` for the entry at `path`, a + /// directory or a file as `place` says. A cluster it read before + /// belongs to two entries, or twice to one, and fails with EUCLEAN. + fn claim(&mut self, path: &str, place: CorruptPlace, cluster: u32) -> Result<()> { + // The clusters of chains are valid, below the number of FAT entries + // the set was made for. + let bit = cluster as usize; + if self.claimed.contains(bit) { + bail!( + EUCLEAN, + Detail::Corrupt { + place, + field: None, + path: Some(path.to_string()), + cluster: Some(cluster), + }, + "'{}' is at cluster {}, which the walk reached before, the volume is cross-linked or loops", + path, + cluster + ); + } + self.claimed.insert(bit); + Ok(()) + } + + /// The entries of the directory at `path` inside the volume, whose + /// first cluster is `first_cluster`, sorted by the bytes of their + /// names, without those whose names have an unpaired surrogate, which + /// are counted as omitted. Every cluster of the directory is claimed. A + /// first cluster the volume does not have fails with EUCLEAN, and so do + /// two entries of the same name. + fn list(&mut self, path: &str, first_cluster: u32) -> Result> { + if !self.volume.layout().valid_cluster(first_cluster) { + bail!( + EUCLEAN, + Detail::Corrupt { + place: CorruptPlace::Directory, + field: None, + path: Some(path.to_string()), + cluster: Some(first_cluster), + }, + "'{}' is a directory at cluster {}, which the volume does not have", + path, + first_cluster + ); + } + let volume = self.volume; + let mut entries = volume + .read_dir_at(first_cluster, |chain| { + chain + .iter() + .try_for_each(|&cluster| self.claim(path, CorruptPlace::Directory, cluster)) + }) + .map_err(|e| e.at_path(path))?; + // A long name with an unpaired surrogate has no spelling a manifest + // takes. The listing shows it with U+FFFD in its place, which two + // such names can share, so it is left out before names are compared. + let listed = entries.len(); + entries.retain(|md| md.name_decoding == NameDecoding::Exact); + self.report.omitted += (listed - entries.len()) as u64; + entries.sort_unstable_by(|a, b| a.name.cmp(&b.name)); + // Sorted, two entries of the same name are next to each other. Names + // that FAT takes for one, such as "AAAA" and "aaaa", are two names + // to a manifest, and each is listed with what its own entry holds. + if let Some(pair) = entries.windows(2).find(|pair| pair[0].name == pair[1].name) { + let path = crate::path::join(path, &pair[1].name); + bail!( + EUCLEAN, + Detail::Corrupt { + place: CorruptPlace::Directory, + field: None, + path: Some(path.clone()), + cluster: Some(first_cluster), + }, + "'{}' is in its directory twice, the directory is damaged", + path + ); + } + Ok(entries) + } + + /// Writes `entries`, the entries of the directory at `path` inside the + /// volume as [`Listing::list`] returned them, whose name in the + /// manifest is `prefix` (the root's for the root), each directory + /// followed by what is below it. A directory is listed before its own + /// record goes out, so that a damaged one ends the manifest before it. + fn directory(&mut self, path: &str, prefix: &Name, entries: Vec) -> Result<()> { for md in &entries { - let name = if prefix.is_empty() { - md.name.clone() - } else { - format!("{}/{}", prefix, md.name) - }; - let path = format!("/{}", name); - if !valid_name(&name) || path.len() > crate::path::MAX_PATH { - if !reserved(&name) { - self.report.omitted += 1; - } + let path = crate::path::join(path, &md.name); + // A name that is reserved for the manifest, which only a name + // at the top can be, is left out and is no omission. + if prefix.is_root() && Name::is_reserved(&md.name) { continue; } - let mut o = Object::new(); - o.insert("name", name.as_str()); + let name = match prefix.join(&md.name) { + Ok(name) if path.len() <= crate::path::MAX_PATH => name, + _ => { + self.report.omitted += 1; + continue; + } + }; // A regular file is what an object without a type is. - if md.is_dir { - o.insert("type", "dir"); - } + let mut object = FileObject::new(name); if md.attributes & ATTR_READ_ONLY != 0 { - o.insert("readOnly", true); + object.inode.read_only = Some(true); } - if self.fields.mtime { - if let Some(nsec) = time_nsec(md.modified) { - o.insert("mTimeNSec", nsec); - } + if self.features.contains(Features::MTIME) { + object.inode.set_mtime(md.modified); } if md.is_dir { - if !self.seen.insert(md.first_cluster) { - bail!( - EUCLEAN, - Detail::Corrupt { - place: CorruptPlace::Directory, - field: None, - path: Some(path.clone()), - cluster: Some(md.first_cluster), - }, - "'{}' is a directory reached before, the directory tree is cross-linked or loops", - path - ); - } - write_record(self.out, o)?; + let below = self.list(&path, md.first_cluster)?; + object.inode_type = InodeType::Directory; + self.writer.file(&object)?; self.report.directories += 1; (self.progress)(&self.report.progress()); - self.directory(&path, &name)?; + self.directory(&path, &object.name, below)?; } else { - if self.fields.size { - o.insert("size", md.size); + if self.features.contains(Features::SIZE) { + object.size = Some(md.size); } - if self.fields.hash { - o.insert("sha256", sha256::to_hex(&self.hash(&path)?)); + if self.features.contains(Features::SHA256) { + object.sha256 = Some(self.hash(&path, md)?); } - write_record(self.out, o)?; + self.writer.file(&object)?; self.report.files += 1; self.report.bytes += md.size; (self.progress)(&self.report.progress()); @@ -317,17 +327,28 @@ impl Writer<'_> { Ok(()) } - /// The SHA-256 of the file at `path`, read from the volume. - fn hash(&mut self, path: &str) -> Result<[u8; DIGEST_SIZE]> { - let mut file = self.volume.begin_read(path)?; - let mut hasher = Sha256::new(); + /// The SHA-256 of the file at `path` inside the volume, read from the + /// first cluster its entry `md` names for the size the entry gives. + /// Every cluster it reads is claimed. + fn hash(&mut self, path: &str, md: &Metadata) -> Result { + let mut file = self + .volume + .begin_read_at(md.first_cluster, md.size) + .map_err(|e| e.at_path(path))?; + let mut context = Sha256Context::default(); let mut done = self.report.progress(); loop { - let n = self.volume.read_file_data(&mut file, &mut self.buf)?; + let n = self + .volume + .read_file_data(&mut file, &mut self.buf) + .map_err(|e| e.at_path(path))?; if n == 0 { - return Ok(hasher.finalize()); + return Ok(context.finalize()); } - hasher.update(&self.buf[..n]); + // A read ends at the end of a cluster and the buffer holds one, + // so every read is of a cluster of its own. + self.claim(path, CorruptPlace::Chain, file.cluster())?; + context.update(&self.buf[..n]); done.bytes += n as u64; (self.progress)(&done); } @@ -337,11 +358,13 @@ impl Writer<'_> { #[cfg(test)] mod tests { use super::*; - use crate::manifest::{self, Entry, InodeType, Manifest, RECORD_SEPARATOR}; + use crate::manifest::HostTree; use crate::populate::CopyOptions; use crate::test_util::{volume, TempDir, TempImage}; + use json::Object; use std::os::fd::AsFd; use std::time::{Duration, UNIX_EPOCH}; + use uapi16::{Digest, Object as ManifestObject, Reader, RECORD_SEPARATOR}; fn t(secs: u64) -> SystemTime { UNIX_EPOCH + Duration::from_secs(secs) @@ -427,9 +450,9 @@ mod tests { tmp } - fn written(v: &Volume, root_time: Option, fields: Fields) -> (Vec, WriteReport) { + fn written(v: &Volume, root_time: Option, features: Features) -> (Vec, WriteReport) { let mut out = Vec::new(); - let report = write(v, root_time, fields, &mut out).unwrap(); + let report = v.write_manifest(root_time, features, &mut out).unwrap(); (out, report) } @@ -457,18 +480,44 @@ mod tests { .collect() } - fn names(m: &Manifest) -> Vec<&str> { - m.entries.iter().map(|e| e.name.as_deref().unwrap()).collect() + /// A manifest a volume wrote as the tests look at it: the root file + /// object and the others. + struct WrittenManifest { + root: RootObject, + entries: Vec, } - fn entry<'a>(m: &'a Manifest, name: &str) -> &'a Entry { - m.entries.iter().find(|e| e.name.as_deref() == Some(name)).unwrap() + impl WrittenManifest { + /// Reads the manifest `bytes` to its end with the reader of the + /// `uapi16` crate, which requires the code point order. + fn read(bytes: &[u8]) -> WrittenManifest { + let reader = Reader::open(bytes).unwrap(); + reader.root().require_order(Order::CodePoint).unwrap(); + let root = reader.root().clone(); + let mut entries = Vec::new(); + for object in reader { + if let ManifestObject::File(object) = object.unwrap() { + entries.push(*object); + } + } + WrittenManifest { root, entries } + } + + /// The names of the file objects, in the order of the manifest. + fn names(&self) -> Vec<&str> { + self.entries.iter().map(|e| e.name.as_str()).collect() + } + + /// The file object of the name `name`. + fn entry(&self, name: &str) -> &FileObject { + self.entries.iter().find(|e| e.name == name).unwrap() + } } #[test] fn writes_what_the_volume_holds() { let (_img, v) = populated(); - let (bytes, report) = written(&v, None, Fields::default()); + let (bytes, report) = written(&v, None, Features::DEFAULT); assert_eq!( report, WriteReport { @@ -476,15 +525,15 @@ mod tests { directories: 4, bytes: 7 + 5000 + 10 + 7, omitted: 0, + changed: 0, } ); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(names(&m), NAMES); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.names(), NAMES); use InodeType::{Directory as D, Regular as R}; let types: Vec = m.entries.iter().map(|e| e.inode_type).collect(); assert_eq!(types, [R, D, D, R, R, D, R, R, D]); - assert_eq!(m.root.inode_type, D); - assert_eq!(m.root.mtime_nsec, None); + assert_eq!(m.root.inode.mtime_nsec, None); for (name, data) in [ ("B.txt", &b"upper B"[..]), ("EFI/BOOT/BOOTX64.EFI", &boot_data()), @@ -492,48 +541,51 @@ mod tests { ("_notes/empty", b""), ("a.txt", b"lower a"), ] { - let e = entry(&m, name); + let e = m.entry(name); assert_eq!(e.size, Some(data.len() as u64), "{}", name); - assert_eq!(e.sha256, Some(sha256::digest(data)), "{}", name); + assert_eq!(e.sha256, Some(Sha256::digest(data)), "{}", name); } - assert_eq!(entry(&m, "_notes/empty").sha256, Some(sha256::EMPTY)); + assert_eq!(m.entry("_notes/empty").sha256, Some(Sha256::EMPTY)); for name in ["EFI", "EFI/BOOT", "_notes", "zz"] { - assert_eq!((entry(&m, name).size, entry(&m, name).sha256), (None, None), "{}", name); + assert_eq!((m.entry(name).size, m.entry(name).sha256), (None, None), "{}", name); } - let boot = entry(&m, "EFI/BOOT/BOOTX64.EFI"); - assert_eq!(boot.read_only, Some(true)); - assert!(boot.is_read_only()); - for e in m + // The manifest records the read-only attribute, so what it does not + // mark read-only is not. + let boot = m.entry("EFI/BOOT/BOOTX64.EFI"); + assert_eq!(boot.inode.read_only, Some(true)); + assert!(boot.inode.is_read_only()); + for e in m.entries.iter().filter(|e| e.name != "EFI/BOOT/BOOTX64.EFI") { + assert_eq!(e.inode.read_only, Some(false), "{:?}", e.name); + assert!(!e.inode.is_read_only()); + } + assert!(m .entries .iter() - .filter(|e| e.name.as_deref() != Some("EFI/BOOT/BOOTX64.EFI")) - { - assert_eq!(e.read_only, None, "{:?}", e.name); - assert!(!e.is_read_only()); - } - assert!(m.entries.iter().all(|e| e.mtime_nsec.is_none() && e.mode.is_none())); + .all(|e| e.inode.mtime_nsec.is_none() && e.inode.mode.is_none())); // The raw records: the root object, one per entry, the trailer. As // systemd-manifest writes them, the root object and the regular // files carry no type, and FAT has no extended attributes to list. + // The empty file has no hash, which its size implies, as the + // specification recommends. let recs = records(&bytes); assert_eq!(recs.len(), 1 + NAMES.len() + 1); - assert_eq!(recs[0].0, r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#); - assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); assert_eq!( - recs[4].0, - format!( - r#"{{"name":"EFI/BOOT/BOOTX64.EFI","readOnly":true,"sha256":"{}","size":5000}}"#, - sha256::to_hex(&sha256::digest(&boot_data())) + recs[0].0, + concat!( + r#"{"features":["device","hardlink","read-only","sha256","size","symlink"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# ) ); + assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); assert_eq!( - recs[7].0, + recs[4].0, format!( - r#"{{"name":"_notes/empty","sha256":"{}","size":0}}"#, - sha256::to_hex(&sha256::EMPTY) + r#"{{"name":"EFI/BOOT/BOOTX64.EFI","readOnly":true,"sha256":"{}","size":5000}}"#, + Sha256::digest(&boot_data()) ) ); + assert_eq!(recs[7].0, r#"{"name":"_notes/empty","size":0}"#); assert_eq!(recs[10].0, r#"{"mediaType":"application/vnd.uapi.16.trailer"}"#); for ((text, o), e) in recs[1..=NAMES.len()].iter().zip(&m.entries) { assert_eq!( @@ -562,14 +614,17 @@ mod tests { } #[test] - fn fields_govern_what_is_written() { + fn features_govern_what_is_written() { let (_img, v) = populated(); - // Nothing but names and the types of directories, and the attribute - // no field governs. - let (bytes, report) = written(&v, Some(t(1_600_000_000)), Fields::none()); + // Nothing but names, the types of directories and the read-only + // attribute, which the manifest always records. + let (bytes, report) = written(&v, Some(t(1_600_000_000)), Features::NONE); assert_eq!((report.files, report.directories, report.bytes), (5, 4, 5024)); let recs = records(&bytes); - assert_eq!(recs[0].0, r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#); + assert_eq!( + recs[0].0, + r#"{"features":["read-only"],"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ); assert_eq!(recs[1].0, r#"{"name":"B.txt"}"#); assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); assert_eq!(recs[4].0, r#"{"name":"EFI/BOOT/BOOTX64.EFI","readOnly":true}"#); @@ -583,138 +638,54 @@ mod tests { }; assert_eq!(keys, expected, "{}", text); } - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(names(&m), NAMES); - assert_eq!(m.root.mtime_nsec, None); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.names(), NAMES); + assert_eq!(m.root.inode.mtime_nsec, None); assert!(m.entries.iter().all(|e| e.size.is_none() && e.sha256.is_none())); // Sizes without hashes, hashes without sizes. The empty file's hash // alone still tells the reader its size. - let (bytes, _) = written(&v, None, Fields::from_names(["size"]).unwrap()); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(entry(&m, "a.txt").size, Some(7)); - assert_eq!(entry(&m, "a.txt").sha256, None); - let (bytes, _) = written(&v, None, Fields::from_names(["hash"]).unwrap()); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(entry(&m, "a.txt").size, None); - assert_eq!(entry(&m, "a.txt").sha256, Some(sha256::digest(b"lower a"))); - assert_eq!(entry(&m, "_notes/empty").size, Some(0)); + let (bytes, _) = written(&v, None, Features::from_names(["size"]).unwrap()); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.entry("a.txt").size, Some(7)); + assert_eq!(m.entry("a.txt").sha256, None); + let (bytes, _) = written(&v, None, Features::from_names(["sha256"]).unwrap()); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.entry("a.txt").size, None); + assert_eq!(m.entry("a.txt").sha256, Some(Sha256::digest(b"lower a"))); + assert_eq!(m.entry("_notes/empty").size, Some(0)); assert!(!records(&bytes)[7].1.contains_key("size")); // Times: the stored ones, which FAT keeps at 2 s, and the root's // only when the caller has one. - let fields = Fields { - mtime: true, - ..Fields::none() - }; - let (bytes, _) = written(&v, None, fields); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(m.root.mtime_nsec, None); + let features = Features::MTIME; + let (bytes, _) = written(&v, None, features); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.root.inode.mtime_nsec, None); for e in &m.entries { - let stored = v.metadata(&e.path()).unwrap().modified; - assert_eq!(e.mtime(), Some(stored), "{}", e.path()); + let stored = v.metadata(&format!("/{}", e.name)).unwrap().modified; + assert_eq!(e.inode.mtime(), Some(stored), "{}", e.name); } assert_eq!( - entry(&m, "EFI/BOOT/BOOTX64.EFI").mtime_nsec, + m.entry("EFI/BOOT/BOOTX64.EFI").inode.mtime_nsec, Some(1_700_000_002 * 1_000_000_000) ); - assert_eq!(entry(&m, "zz").mtime_nsec, Some(1_700_000_000 * 1_000_000_000)); + assert_eq!(m.entry("zz").inode.mtime_nsec, Some(1_700_000_000 * 1_000_000_000)); let root_time = t(1_600_000_000) + Duration::from_nanos(5); - let (bytes, _) = written(&v, Some(root_time), fields); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(m.root.mtime_nsec, Some(1_600_000_000_000_000_005)); - assert_eq!(m.root.mtime(), Some(root_time)); + let (bytes, _) = written(&v, Some(root_time), features); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.root.inode.mtime_nsec, Some(1_600_000_000_000_000_005)); + assert_eq!(m.root.inode.mtime(), Some(root_time)); assert_eq!( records(&bytes)[0].0, - r#"{"mTimeNSec":1600000000000000005,"mediaType":"application/vnd.uapi.16.manifest"}"# + concat!( + r#"{"features":["mtime","read-only"],"mTimeNSec":1600000000000000005,"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ) ); - // Without the field the caller's time is not written either. - let (bytes, _) = written(&v, Some(root_time), Fields::default()); - assert_eq!(manifest::parse(&bytes).unwrap().root.mtime_nsec, None); - } - - #[test] - fn fields_from_names() { - let all = [ - "mode", - "uid", - "gid", - "size", - "hash", - "symlink", - "device", - "hardlink", - "mtime", - "userXattr", - "userName", - "groupName", - ]; - assert_eq!( - Fields::from_names(all).unwrap(), - Fields { - mode: true, - uid: true, - gid: true, - size: true, - hash: true, - symlink: true, - device: true, - hardlink: true, - mtime: true, - user_xattr: true, - user_name: true, - group_name: true, - } - ); - assert_eq!(Fields::from_names(Vec::<&str>::new()).unwrap(), Fields::none()); - // systemd's default set. - assert_eq!( - Fields::from_names([ - "mode", - "uid", - "gid", - "size", - "hash", - "symlink", - "device", - "hardlink", - "userXattr" - ]) - .unwrap(), - Fields::default() - ); - assert_eq!( - Fields::from_names(["size", "hash", "mtime", "size"]).unwrap(), - Fields { - size: true, - hash: true, - mtime: true, - ..Fields::none() - } - ); - for bad in [ - &["sha256"][..], - &["size", "user_xattr"], - &["Mode"], - &[""], - &[ - "mode", - "uid", - "gid", - "size", - "hash", - "symlink", - "device", - "hardlink", - "mtime", - "userXattr", - "userName", - "groupName", - "type", - ], - ] { - assert_eq!(Fields::from_names(bad.iter().copied()), None, "{:?}", bad); - } + // Without the feature the caller's time is not written either. + let (bytes, _) = written(&v, Some(root_time), Features::DEFAULT); + assert_eq!(WrittenManifest::read(&bytes).root.inode.mtime_nsec, None); } #[test] @@ -724,16 +695,23 @@ mod tests { let (_img, mut v) = volume(8 << 20, 512, 512); let copied = v.copy_tree(dir.as_fd(), "/", &CopyOptions::default()).unwrap(); assert_eq!((copied.files, copied.directories), (5, 4)); - // The generator writes the fields size, hash and mtime. With the - // tree's own time for the root and times FAT keeps as they are, the - // two manifests are the same bytes. - let host = manifest::generate(dir.as_fd()).unwrap(); + // The generator records sizes, hashes and times. With the tree's own + // time for the root and times FAT keeps as they are, the two + // manifests are the same bytes, but for the read-only attribute, + // which the manifest of a volume always lists in its features. + let mut host = Vec::new(); + let host_report = HostTree::new(dir.as_fd()).write_manifest(&mut host).unwrap(); + let host = String::from_utf8(host).unwrap(); + let listed = r#""features":["mtime","sha256","size"]"#; + assert!(host.contains(listed), "{}", host); + let host = host.replacen(listed, r#""features":["mtime","read-only","sha256","size"]"#, 1); let root_time = std::fs::metadata(tree.path()).unwrap().modified().unwrap(); - let fields = Fields::from_names(["size", "hash", "mtime"]).unwrap(); - let (bytes, report) = written(&v, Some(root_time), fields); - assert_eq!(String::from_utf8_lossy(&bytes), String::from_utf8_lossy(&host)); - assert_eq!(names(&manifest::parse(&bytes).unwrap()), NAMES); + let features = Features::from_names(["size", "sha256", "mtime"]).unwrap(); + let (bytes, report) = written(&v, Some(root_time), features); + assert_eq!(String::from_utf8_lossy(&bytes), host); + assert_eq!(WrittenManifest::read(&bytes).names(), NAMES); assert_eq!((report.files, report.directories, report.bytes), (5, 4, copied.bytes)); + assert_eq!(report, host_report); } #[test] @@ -747,9 +725,9 @@ mod tests { put(&mut v, "/Uapi16Manifest2", b"kept", t0, false); v.create_dir("/sub", t0).unwrap(); put(&mut v, "/sub/Uapi16Manifest", b"kept", t0, false); - let (bytes, report) = written(&v, None, Fields::default()); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(names(&m), ["Uapi16Manifest2", "sub", "sub/Uapi16Manifest"]); + let (bytes, report) = written(&v, None, Features::DEFAULT); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.names(), ["Uapi16Manifest2", "sub", "sub/Uapi16Manifest"]); assert_eq!( report, WriteReport { @@ -757,25 +735,90 @@ mod tests { directories: 1, bytes: 8, omitted: 0, + changed: 0, } ); - // A name of 100 three-byte characters is 100 UTF-16 units, which - // FAT stores, but 300 bytes of UTF-8, more than a manifest - // component may have. Such entries are left out and counted, a - // directory with everything below it as one. + // FAT stores a noncharacter such as U+FDD0, a manifest has none. + // Such entries are left out and counted, a directory with + // everything below it as one. + let odd = "a\u{fdd0}"; + v.create_dir(&format!("/{}", odd), t0).unwrap(); + put(&mut v, &format!("/{}/inside", odd), b"x", t0, false); + put(&mut v, &format!("/sub/{}", odd), b"y", t0, false); + // A name of 100 three-byte characters is 300 bytes of UTF-8. A + // manifest does not limit its components. let long: String = std::iter::repeat_n('\u{20ac}', 100).collect(); - v.create_dir(&format!("/{}", long), t0).unwrap(); - put(&mut v, &format!("/{}/inside", long), b"x", t0, false); - put(&mut v, &format!("/sub/{}", long), b"y", t0, false); - let (bytes, report) = written(&v, None, Fields::default()); - let m = manifest::parse(&bytes).unwrap(); - assert_eq!(names(&m), ["Uapi16Manifest2", "sub", "sub/Uapi16Manifest"]); - assert_eq!((report.files, report.directories, report.omitted), (2, 1, 2)); + put(&mut v, &format!("/sub/{}", long), b"z", t0, false); + let (bytes, report) = written(&v, None, Features::DEFAULT); + let m = WrittenManifest::read(&bytes); + let carried = format!("sub/{}", long); + assert_eq!( + m.names(), + ["Uapi16Manifest2", "sub", "sub/Uapi16Manifest", carried.as_str()] + ); + assert_eq!((report.files, report.directories, report.omitted), (3, 1, 2)); + } + + /// The slot of the entry of the directory cluster `cluster` that + /// `matches`, from its 32 bytes. + fn slot_of(cluster: &[u8], matches: impl Fn(&[u8]) -> bool) -> usize { + use crate::dirent::DIR_ENTRY_SIZE; + (0..cluster.len() / DIR_ENTRY_SIZE) + .find(|&i| matches(&cluster[i * DIR_ENTRY_SIZE..(i + 1) * DIR_ENTRY_SIZE])) + .unwrap() + } + + /// Points the directory entry at the byte `entry` of the image `dev` at + /// the cluster `cluster`: the high and the low half of its first + /// cluster. + fn set_first_cluster(dev: &crate::device::Device, entry: u64, cluster: u32) { + use crate::dirent; + dev.write_at( + entry + dirent::field::FIRST_CLUSTER_HI.start as u64, + &((cluster >> u16::BITS) as u16).to_le_bytes(), + ) + .unwrap(); + dev.write_at( + entry + dirent::field::FIRST_CLUSTER_LO.start as u64, + &(cluster as u16).to_le_bytes(), + ) + .unwrap(); + } + + /// The 8.3 name of every short entry of the directory whose chain + /// starts at `first_cluster`, and the byte of the image it is at. + fn short_entries(v: &Volume, first_cluster: u32) -> Vec<([u8; 11], u64)> { + use crate::dirent::DIR_ENTRY_SIZE; + let dir = v.load_directory(first_cluster).unwrap(); + let cs = v.layout().cluster_size() as usize; + dir.iter() + .map(|e| { + let at = e.slot * DIR_ENTRY_SIZE; + let cluster = dir.chain()[at / cs]; + ( + e.short.name, + v.layout().cluster_offset(cluster).unwrap() + (at % cs) as u64, + ) + }) + .collect() + } + + /// Sets the entry of `cluster` to `value` in every copy of the FAT of + /// the image `dev`. + fn set_fat_entry(dev: &crate::device::Device, layout: &crate::layout::Layout, cluster: u32, value: u32) { + use crate::fat::ENTRY_SIZE; + for copy in 0..layout.fats { + dev.write_at( + layout.fat_offset(copy) + u64::from(cluster) * ENTRY_SIZE as u64, + &value.to_le_bytes(), + ) + .unwrap(); + } } #[test] - fn a_cross_linked_directory_tree_is_refused() { + fn a_looping_directory_tree_is_refused() { use crate::bytes::le16_at; use crate::dirent::{self, ATTR_DIRECTORY, DIR_ENTRY_SIZE}; @@ -788,38 +831,496 @@ mod tests { let offset = v.layout().cluster_offset(a.first_cluster).unwrap(); let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; v.close().unwrap(); - // Point the entry of "b" inside "a" back at "a". The first cluster - // of an entry is split over a high and a low half; the entry is the - // directory one, not a dot entry, that refers to b's cluster. + // Point the entry of "b" inside "a" back at "a", the directory + // above it. The first cluster of an entry is split over a high and + // a low half; the entry is the directory one, not a dot entry, that + // refers to b's cluster. let dev = img.device(); dev.read_at(offset, &mut cluster).unwrap(); - let slot = (0..cluster.len() / DIR_ENTRY_SIZE) - .find(|&i| { - let e = &cluster[i * DIR_ENTRY_SIZE..(i + 1) * DIR_ENTRY_SIZE]; - let first = (u32::from(le16_at(e, dirent::field::FIRST_CLUSTER_HI)) << u16::BITS) - | u32::from(le16_at(e, dirent::field::FIRST_CLUSTER_LO)); - !e[dirent::field::NAME].starts_with(b".") - && e[dirent::field::ATTR] & ATTR_DIRECTORY != 0 - && first == b.first_cluster - }) - .unwrap(); - // Where that entry is in the image: slot `slot` of the cluster at - // `offset`. - let at = offset + (slot * DIR_ENTRY_SIZE) as u64; + let slot = slot_of(&cluster, |e| { + let first = (u32::from(le16_at(e, dirent::field::FIRST_CLUSTER_HI)) << u16::BITS) + | u32::from(le16_at(e, dirent::field::FIRST_CLUSTER_LO)); + !e[dirent::field::NAME].starts_with(b".") + && e[dirent::field::ATTR] & ATTR_DIRECTORY != 0 + && first == b.first_cluster + }); + // That entry is slot `slot` of the cluster at `offset`. + set_first_cluster(&dev, offset + (slot * DIR_ENTRY_SIZE) as u64, a.first_cluster); + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Directory, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/a/b" && *c == a.first_cluster + ), + "{:?}", + e + ); + // What was written before the walk ran into it is intact. + let recs = records(&out); + assert_eq!(recs.len(), 2); + assert_eq!(recs[1].0, r#"{"name":"a","type":"dir"}"#); + } + + /// Two entries of one name are a damaged directory, not a manifest + /// that names a file twice. The directory is listed before its own + /// record goes out, so the manifest ends before it. + #[test] + fn a_name_twice_in_a_directory_is_refused() { + use crate::dirent::{self, DIR_ENTRY_SIZE}; + + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + v.create_dir("/d", t0).unwrap(); + // Names of the 8.3 form in one case have no long name, so the short + // name is all there is to change. + put(&mut v, "/d/a.txt", b"a", t0, false); + put(&mut v, "/d/b.txt", b"b", t0, false); + let d = v.metadata("/d").unwrap(); + let offset = v.layout().cluster_offset(d.first_cluster).unwrap(); + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + v.close().unwrap(); + let dev = img.device(); + dev.read_at(offset, &mut cluster).unwrap(); + let slot = slot_of(&cluster, |e| &e[dirent::field::NAME] == b"B TXT"); dev.write_at( - at + dirent::field::FIRST_CLUSTER_HI.start as u64, - &((a.first_cluster >> u16::BITS) as u16).to_le_bytes(), + offset + (slot * DIR_ENTRY_SIZE + dirent::field::NAME.start) as u64, + b"A", ) .unwrap(); + drop(dev); + let v = Volume::open(img.device()).unwrap(); + assert_eq!(v.read_dir("/d").unwrap().len(), 2); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Directory, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/d/a.txt" && *c == d.first_cluster + ), + "{:?}", + e + ); + assert_eq!(records(&out).len(), 1); + } + + /// A directory at a cluster the volume does not have, 0 or one past its + /// last, is damage, found before anything is read from that cluster. + #[test] + fn a_directory_at_a_cluster_the_volume_lacks_is_refused() { + use crate::dirent::{self, DIR_ENTRY_SIZE}; + + let (img, mut v) = volume(8 << 20, 512, 512); + v.create_dir("/d", t(1_700_000_000)).unwrap(); + let root = v.metadata("/").unwrap(); + let offset = v.layout().cluster_offset(root.first_cluster).unwrap(); + let past = v.layout().max_cluster() + 1; + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + v.close().unwrap(); + img.device().read_at(offset, &mut cluster).unwrap(); + let slot = slot_of(&cluster, |e| &e[dirent::field::NAME] == b"D "); + let entry = offset + (slot * DIR_ENTRY_SIZE) as u64; + for lacking in [0, past] { + set_first_cluster(&img.device(), entry, lacking); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Directory, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/d" && *c == lacking + ), + "{:?}", + e + ); + assert_eq!(records(&out).len(), 1); + } + } + + /// A chain of directories each of which holds two entries, "x" and + /// "y", that point at the next directory: none of them is above itself, + /// and a walk that took both would list 2^40 paths for 40 levels. The + /// walk ends at the first directory it reaches a second time. + #[test] + fn a_cross_linked_chain_of_directories_is_refused() { + use crate::dirent::{self, DIR_ENTRY_SIZE}; + + const LEVELS: usize = 40; + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + // /x/x/.../x, with a "y" next to every "x". Each "y" gets the first + // cluster of the "x" next to it: where the directory holding both + // is, and that cluster. + let mut path = String::new(); + let mut links = Vec::new(); + for _ in 0..LEVELS { + let holder = v.metadata(if path.is_empty() { "/" } else { &path }).unwrap(); + v.create_dir(&format!("{}/y", path), t0).unwrap(); + path.push_str("/x"); + v.create_dir(&path, t0).unwrap(); + let x = v.metadata(&path).unwrap(); + links.push(( + v.layout().cluster_offset(holder.first_cluster).unwrap(), + x.first_cluster, + )); + } + let last = links.last().unwrap().1; + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + v.close().unwrap(); + let dev = img.device(); + for (offset, target) in links { + dev.read_at(offset, &mut cluster).unwrap(); + let slot = slot_of(&cluster, |e| &e[dirent::field::NAME] == b"Y "); + set_first_cluster(&dev, offset + (slot * DIR_ENTRY_SIZE) as u64, target); + } + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + let expected = format!("{}/y", "/x".repeat(LEVELS - 1)); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Directory, + path: Some(p), + cluster: Some(c), + .. + }) if *p == expected && *c == last + ), + "{:?}", + e + ); + // The root and the chain of "x", each once. + assert_eq!(records(&out).len(), 1 + LEVELS); + } + + /// "AAAA" and "aaaa" are two names to a manifest and one to FAT, which + /// Linux writes with some mount options. A lookup by name finds only + /// one of them, but the walk follows the cluster of each entry, so each + /// is listed with what it holds. + #[test] + fn names_that_fold_alike_are_listed_with_their_own_data() { + use crate::dirent; + + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + v.create_dir("/aaaa", t0).unwrap(); + put(&mut v, "/aaaa/f1", b"1", t0, false); + put(&mut v, "/aaaa/f2", b"2", t0, false); + v.create_dir("/bbbb", t0).unwrap(); + put(&mut v, "/bbbb/g", b"3", t0, false); + let root = v.metadata("/").unwrap(); + // "bbbb" is a name of the 8.3 form in one case, a short entry + // "BBBB" whose case flags say lower case. It becomes "AAAA". + let (_, entry) = short_entries(&v, root.first_cluster) + .into_iter() + .find(|(name, _)| name == b"BBBB ") + .unwrap(); + v.close().unwrap(); + let dev = img.device(); + dev.write_at(entry + dirent::field::NAME.start as u64, b"AAAA").unwrap(); + dev.write_at(entry + dirent::field::NT_FLAGS as u64, &[0]).unwrap(); + drop(dev); + let v = Volume::open(img.device()).unwrap(); + // A lookup of "/AAAA" finds "aaaa", the first of the two. + assert_eq!(v.read_dir("/AAAA").unwrap().len(), 2); + let (bytes, report) = written(&v, None, Features::SHA256); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.names(), ["AAAA", "AAAA/g", "aaaa", "aaaa/f1", "aaaa/f2"]); + for (name, data) in [("AAAA/g", b"3"), ("aaaa/f1", b"1"), ("aaaa/f2", b"2")] { + assert_eq!(m.entry(name).sha256, Some(Sha256::digest(data)), "{}", name); + } + assert_eq!((report.files, report.directories, report.omitted), (3, 2, 0)); + } + + /// Directories whose chains run on into the chain of another one share + /// its clusters: here 200 empty directories run into the chain of "t", + /// which holds 1000 files. A walk that listed every directory it + /// reached in full would list these files 201 times. The walk ends at + /// the second directory that reaches the clusters of "t". + #[test] + fn directories_that_run_into_another_are_refused() { + use crate::dirent::{DIR_ENTRY_SIZE, ENTRY_DELETED}; + + const DIRS: usize = 200; + const FILES: usize = 1000; + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + v.create_dir("/t", t0).unwrap(); + for i in 0..FILES { + put(&mut v, &format!("/t/f{:04}", i), b"", t0, false); + } + let mut dirs = Vec::with_capacity(DIRS); + for i in 0..DIRS { + let path = format!("/d{:03}", i); + v.create_dir(&path, t0).unwrap(); + dirs.push(v.metadata(&path).unwrap().first_cluster); + } + let target = v.metadata("/t").unwrap().first_cluster; + let layout = *v.layout(); + v.close().unwrap(); + let dev = img.device(); + for &dir in &dirs { + // The slots after the dot entries are deleted instead of + // unused, so that the directory goes on in its next cluster, + // which is the first one of "t". + let offset = layout.cluster_offset(dir).unwrap(); + for slot in 2..layout.cluster_size() as usize / DIR_ENTRY_SIZE { + dev.write_at(offset + (slot * DIR_ENTRY_SIZE) as u64, &[ENTRY_DELETED]) + .unwrap(); + } + set_fat_entry(&dev, &layout, dir, target); + } + drop(dev); + let v = Volume::open(img.device()).unwrap(); + assert_eq!(v.read_dir("/d199").unwrap().len(), FILES); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Directory, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/d001" && *c == target + ), + "{:?}", + e + ); + // The root, the first directory and the files of "t", which it + // lists as its own. + assert_eq!(records(&out).len(), 1 + 1 + FILES); + } + + /// 1000 entries of files of 4 MiB on one chain: a walk that read every + /// file in full would hash 4 GiB. The walk ends at the first cluster + /// of the second file. + #[test] + fn files_on_one_chain_are_refused() { + use crate::dirent; + + const FILES: usize = 1000; + const SIZE: usize = 4 << 20; + let (img, mut v) = volume(8 << 20, 512, 4096); + let t0 = t(1_700_000_000); + let data: Vec = (0..SIZE).map(|i| (i % 251) as u8).collect(); + put(&mut v, "/f0000", &data, t0, false); + for i in 1..FILES { + put(&mut v, &format!("/f{:04}", i), b"", t0, false); + } + let first = v.metadata("/f0000").unwrap().first_cluster; + let root = v.metadata("/").unwrap(); + let others: Vec = short_entries(&v, root.first_cluster) + .into_iter() + .filter(|(name, _)| name.starts_with(b"F") && !name.starts_with(b"F0000")) + .map(|(_, entry)| entry) + .collect(); + assert_eq!(others.len(), FILES - 1); + v.close().unwrap(); + let dev = img.device(); + for entry in others { + set_first_cluster(&dev, entry, first); + dev.write_at(entry + dirent::field::SIZE.start as u64, &(SIZE as u32).to_le_bytes()) + .unwrap(); + } + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::SHA256, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Chain, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/f0001" && *c == first + ), + "{:?}", + e + ); + let recs = records(&out); + assert_eq!(recs.len(), 2); + assert_eq!( + recs[1].0, + format!(r#"{{"name":"f0000","sha256":"{}"}}"#, Sha256::digest(&data)) + ); + } + + /// A file whose chain ends before the file does, or that starts at a + /// cluster the volume does not have, is damage, found where the read + /// for the hash runs out of the chain. + #[test] + fn a_file_longer_than_its_chain_is_refused() { + use crate::dirent; + use crate::fat::Entry; + + let (img, mut v) = volume(8 << 20, 512, 512); + put(&mut v, "/f", &boot_data(), t(1_700_000_000), false); + let f = v.metadata("/f").unwrap(); + let mut last = f.first_cluster; + while let Entry::Next(next) = v.fat_entry(last).unwrap() { + last = next; + } + let root = v.metadata("/").unwrap(); + let (_, entry) = short_entries(&v, root.first_cluster) + .into_iter() + .find(|(name, _)| name == b"F ") + .unwrap(); + let cs = u64::from(v.layout().cluster_size()); + let past = v.layout().max_cluster() + 1; + v.close().unwrap(); + // One byte more than the chain holds, and the size it has at a + // cluster that is not the volume's. + let longer = boot_data().len().div_ceil(cs as usize) as u64 * cs + 1; + for (first, size, found) in [(f.first_cluster, longer, last), (0, f.size, 0), (past, f.size, past)] { + let dev = img.device(); + set_first_cluster(&dev, entry, first); + dev.write_at(entry + dirent::field::SIZE.start as u64, &(size as u32).to_le_bytes()) + .unwrap(); + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::SHA256, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Chain, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/f" && *c == found + ), + "{:?}", + e + ); + assert_eq!(records(&out).len(), 1); + } + } + + /// The read of the last cluster of a file looks at the FAT entry of + /// that cluster, which ends the chain or goes on: one that is free, + /// bad or no cluster at all is damage. The rest of a chain that goes on + /// past the file is not read. + #[test] + fn the_fat_entry_of_the_last_cluster_of_a_file_is_checked() { + use crate::dirent; + use crate::fat::{Entry, BAD_CLUSTER, END_OF_CHAIN, FREE}; + + let (img, mut v) = volume(8 << 20, 512, 512); + let data = boot_data(); + put(&mut v, "/f", &data, t(1_700_000_000), false); + let f = v.metadata("/f").unwrap(); + let mut last = f.first_cluster; + while let Entry::Next(next) = v.fat_entry(last).unwrap() { + last = next; + } + let root = v.metadata("/").unwrap(); + let (_, entry) = short_entries(&v, root.first_cluster) + .into_iter() + .find(|(name, _)| name == b"F ") + .unwrap(); + let layout = *v.layout(); + v.close().unwrap(); + // 1 is no cluster: the first one is 2. + for value in [FREE, BAD_CLUSTER, 1] { + set_fat_entry(&img.device(), &layout, last, value); + let v = Volume::open(img.device()).unwrap(); + let mut out = Vec::new(); + let e = v.write_manifest(None, Features::SHA256, &mut out).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + assert!( + matches!( + e.detail(), + Some(Detail::Corrupt { + place: CorruptPlace::Chain, + path: Some(p), + cluster: Some(c), + .. + }) if p == "/f" && *c == last + ), + "{:?}", + e + ); + assert_eq!(records(&out).len(), 1); + } + // A file of one cluster on that chain is fine: its cluster goes on + // to the next one, and the broken end is never reached. + let cs = layout.cluster_size() as usize; + let dev = img.device(); + dev.write_at(entry + dirent::field::SIZE.start as u64, &(cs as u32).to_le_bytes()) + .unwrap(); + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let (bytes, _) = written(&v, None, Features::SHA256); + assert_eq!( + WrittenManifest::read(&bytes).entry("f").sha256, + Some(Sha256::digest(&data[..cs])) + ); + drop(v); + // And with the end of the chain where it was, all of it hashes. + set_fat_entry(&img.device(), &layout, last, END_OF_CHAIN); + let dev = img.device(); dev.write_at( - at + dirent::field::FIRST_CLUSTER_LO.start as u64, - &(a.first_cluster as u16).to_le_bytes(), + entry + dirent::field::SIZE.start as u64, + &(data.len() as u32).to_le_bytes(), ) .unwrap(); drop(dev); let v = Volume::open(img.device()).unwrap(); + let (bytes, _) = written(&v, None, Features::SHA256); + assert_eq!( + WrittenManifest::read(&bytes).entry("f").sha256, + Some(Sha256::digest(&data)) + ); + } + + /// A directory whose chain loops, here one whose FAT entry points at + /// itself, is longer than a directory can be. It fails with Corrupt + /// for the directory, which a client sees as such, and not with a + /// plain error. + #[test] + fn a_directory_whose_chain_loops_is_refused() { + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + v.create_dir("/d", t0).unwrap(); + put(&mut v, "/d/f", b"f", t0, false); + let d = v.metadata("/d").unwrap().first_cluster; + let layout = *v.layout(); + v.close().unwrap(); + set_fat_entry(&img.device(), &layout, d, d); + let v = Volume::open(img.device()).unwrap(); let mut out = Vec::new(); - let e = write(&v, None, Fields::none(), &mut out).unwrap_err(); + let e = v.write_manifest(None, Features::NONE, &mut out).unwrap_err(); assert_eq!(e.errno(), EUCLEAN); assert!( matches!( @@ -829,14 +1330,61 @@ mod tests { path: Some(p), cluster: Some(c), .. - }) if p == "/a/b" && *c == a.first_cluster + }) if p == "/d" && *c == d ), "{:?}", e ); - // What was written before the walk ran into it is intact. - let recs = records(&out); - assert_eq!(recs.len(), 2); - assert_eq!(recs[1].0, r#"{"name":"a","type":"dir"}"#); + assert_eq!(records(&out).len(), 1); + } + + /// A long name with a unit that is an unpaired surrogate has no + /// spelling in a manifest. Two such names that differ only there read + /// as the same name with U+FFFD, and are no name twice: both are left + /// out and counted. + #[test] + fn names_with_an_unpaired_surrogate_are_left_out() { + use crate::dirent::{self, ATTR_LONG_NAME, DIR_ENTRY_SIZE}; + + let (img, mut v) = volume(8 << 20, 512, 512); + let t0 = t(1_700_000_000); + v.create_dir("/d", t0).unwrap(); + // A '+' has no place in a short name, so each of these names is a + // long name of one long name entry. + put(&mut v, "/d/x+1", b"1", t0, false); + put(&mut v, "/d/x+2", b"2", t0, false); + put(&mut v, "/d/kept", b"k", t0, false); + let d = v.metadata("/d").unwrap(); + let offset = v.layout().cluster_offset(d.first_cluster).unwrap(); + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + v.close().unwrap(); + let dev = img.device(); + dev.read_at(offset, &mut cluster).unwrap(); + // The third unit of the names, the digit, becomes a high surrogate + // that no low one follows, a different one in each name. + let third = dirent::lfn_field::NAME1.start + 2 * size_of::(); + for (digit, surrogate) in [(b'1', 0xd800u16), (b'2', 0xd801)] { + let slot = slot_of(&cluster, |e| { + e[dirent::lfn_field::ATTR] == ATTR_LONG_NAME && e[third..third + 2] == [digit, 0] + }); + dev.write_at( + offset + (slot * DIR_ENTRY_SIZE + third) as u64, + &surrogate.to_le_bytes(), + ) + .unwrap(); + } + drop(dev); + let v = Volume::open(img.device()).unwrap(); + let lossy: Vec = v + .read_dir("/d") + .unwrap() + .into_iter() + .filter(|md| md.name_decoding == NameDecoding::Lossy) + .map(|md| md.name) + .collect(); + assert_eq!(lossy, ["x+\u{fffd}", "x+\u{fffd}"]); + let (bytes, report) = written(&v, None, Features::NONE); + assert_eq!(WrittenManifest::read(&bytes).names(), ["d", "d/kept"]); + assert_eq!((report.files, report.directories, report.omitted), (1, 1, 2)); } } diff --git a/src/fat/path.rs b/src/fat/path.rs index b2e7382..039cd0d 100644 --- a/src/fat/path.rs +++ b/src/fat/path.rs @@ -10,6 +10,9 @@ use crate::errno::*; use crate::Result; use crate::{Detail, NameProblem}; +/// What separates the names of a path. +pub(crate) const SEPARATOR: char = '/'; + /// Longest path accepted, in bytes: Linux's PATH_MAX without the NUL. A /// longer path could not be opened on the mounted volume in one go, and /// without a bound the paths a tree walk builds grow with the tree. @@ -30,7 +33,7 @@ pub(crate) fn components(path: &str) -> Result> { ); } let mut out = Vec::new(); - for c in path.split('/') { + for c in path.split(SEPARATOR) { if c.is_empty() { continue; } @@ -50,7 +53,7 @@ pub(crate) fn components(path: &str) -> Result> { /// Appends `name` to the directory path `dir`. pub(crate) fn join(dir: &str, name: &str) -> String { - format!("{}/{}", dir.trim_end_matches('/'), name) + format!("{}{}{}", dir.trim_end_matches(SEPARATOR), SEPARATOR, name) } #[cfg(test)] diff --git a/src/fat/plan.rs b/src/fat/plan.rs index 9605be1..4b16b16 100644 --- a/src/fat/plan.rs +++ b/src/fat/plan.rs @@ -16,7 +16,7 @@ use crate::dir::MAX_SLOTS; use crate::dirent::DIR_ENTRY_SIZE; use crate::errno::*; use crate::format::{encode_label, FormatOptions}; -use crate::host::walk_tree; +use crate::host::{walk_tree, HostEntry, UnnamableEntry}; use crate::layout::{self, Layout, LayoutParams, MAX_CLUSTERS, MAX_CLUSTER_SIZE, MAX_SECTORS_PER_CLUSTER}; use crate::name::{Alias, LongName}; use crate::path::components; @@ -284,7 +284,7 @@ impl Plan { } self.add_dir(dest)?; let mut skipped = Vec::new(); - walk_tree(source, dest, follow_symlinks, &mut |target, entry| { + let mut visit = |target: &str, entry: &HostEntry| -> Result { if entry.is_dir() { self.add_dir(target)?; Ok(true) @@ -296,7 +296,8 @@ impl Plan { skipped.push(entry.path.clone()); Ok(false) } - })?; + }; + walk_tree(source, dest, follow_symlinks, UnnamableEntry::Fail, &mut visit)?; Ok(skipped) } diff --git a/src/fat/populate.rs b/src/fat/populate.rs index fa57e39..a77e3fc 100644 --- a/src/fat/populate.rs +++ b/src/fat/populate.rs @@ -13,7 +13,7 @@ use std::path::PathBuf; use std::time::SystemTime; use crate::errno::*; -use crate::host::{walk_tree, FromStart}; +use crate::host::{walk_tree, FromStart, HostEntry, UnnamableEntry}; use crate::progress::Progress; use crate::sys; use crate::volume::{Volume, MAX_FILE_SIZE}; @@ -241,7 +241,7 @@ impl Volume { } let mut report = CopyReport::default(); self.create_dir_all(dest, options.times.resolve(source_mtime(&md)))?; - walk_tree(source, dest, options.follow_symlinks, &mut |target, entry| { + let mut visit = |target: &str, entry: &HostEntry| -> Result { if entry.is_dir() { let time = options.times.resolve(source_mtime(&entry.metadata)); match self.metadata(target) { @@ -265,7 +265,8 @@ impl Volume { report.skipped.push(entry.path.clone()); Ok(false) } - })?; + }; + walk_tree(source, dest, options.follow_symlinks, UnnamableEntry::Fail, &mut visit)?; Ok(report) } } diff --git a/src/fat/volume/file.rs b/src/fat/volume/file.rs index fee1c2d..cdd5d26 100644 --- a/src/fat/volume/file.rs +++ b/src/fat/volume/file.rs @@ -128,6 +128,27 @@ impl Volume { clusters ); } + self.begin_read_at(first, size) + } + + /// Opens the file of `size` bytes whose chain starts at `first` for + /// sequential reading, as [`Volume::begin_read`] opens the file at a + /// path, without looking up a path and without walking the chain + /// first. The reads follow the chain as far as the file goes. The read + /// that runs past the end of a chain shorter than the file fails with + /// EUCLEAN, and so does the read of the last cluster of the file when + /// the FAT entry of that cluster is free, bad or invalid. The rest of a + /// chain longer than the file is not followed. + pub(crate) fn begin_read_at(&self, first: u32, size: u64) -> Result { + if size > 0 && !self.layout.valid_cluster(first) { + bail!( + EUCLEAN, + damaged(CorruptPlace::Chain, None, Some(first)), + "a file of {} bytes starts at cluster {}, which the volume does not have", + size, + first + ); + } Ok(OpenRead { first, size, @@ -148,6 +169,7 @@ impl Volume { Entry::Next(next) => next, other => bail!( EUCLEAN, + damaged(CorruptPlace::Chain, None, Some(cluster)), "the chain of the file ends after {} clusters ({:?})", at + 1, other @@ -168,7 +190,9 @@ impl Volume { } /// Reads from an open file into `buf`, up to the end of a cluster or of - /// the file. Returns the number of bytes read, 0 at the end. + /// the file. Returns the number of bytes read, 0 at the end. The read + /// that reaches the end of the file fails with EUCLEAN when the FAT + /// entry of its last cluster is free, bad or invalid. pub fn read_file_data(&self, file: &mut OpenRead, buf: &mut [u8]) -> Result { if file.pos >= file.size || buf.is_empty() { return Ok(0); @@ -181,6 +205,21 @@ impl Volume { let off = self.layout.cluster_offset(cluster)? + within; self.device.read_at(off, &mut buf[..n])?; file.pos += n as u64; + if file.pos == file.size { + // The chain ends at the last cluster of the file or goes on. + // The steps to the clusters before looked at their entries, + // nothing looked at this one. + match self.fat_entry(cluster)? { + Entry::End | Entry::Next(_) => {} + other => bail!( + EUCLEAN, + damaged(CorruptPlace::Chain, None, Some(cluster)), + "cluster {}, the last of the file, has the FAT entry {:?}", + cluster, + other + ), + } + } Ok(n) } @@ -533,6 +572,12 @@ impl OpenRead { pub fn size(&self) -> u64 { self.size } + + /// The cluster the last read came from, the first cluster before the + /// first read. + pub(crate) fn cluster(&self) -> u32 { + self.current.map_or(self.first, |(cluster, _)| cluster) + } } /// Reads a file sequentially: an [`OpenRead`] plus the volume it belongs to. diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index dd7a1c4..60c7db3 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -25,7 +25,7 @@ use crate::boot::{ self, BootSector, FsInfo, BOOT_SECTOR_SIZE, FSINFO_SIZE, FSINFO_UNKNOWN, LABEL_SIZE, NO_NAME, NT_FLAG_DIRTY, }; use crate::device::Device; -use crate::dir::{DirEntry, Directory, MAX_SLOTS}; +use crate::dir::{DirEntry, Directory, NameDecoding, MAX_SLOTS}; use crate::dirent::{ short_name_checksum, RawDirEntry, ATTR_ARCHIVE, ATTR_DIRECTORY, ATTR_HIDDEN, ATTR_READ_ONLY, ATTR_SYSTEM, ATTR_VOLUME_ID, DIR_ENTRY_SIZE, DOTDOT_NAME, DOT_NAME, ENTRY_DELETED, ENTRY_E5_ESCAPE, ENTRY_END, SHORT_NAME_SIZE, @@ -38,7 +38,7 @@ use crate::path::components; use crate::probe::Prober; use crate::time::FatTimestamp; use crate::Result; -use crate::{Detail, NoSpaceReason, NotFat32Reason}; +use crate::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason}; mod file; #[cfg(test)] @@ -75,6 +75,9 @@ pub struct Metadata { pub attributes: u8, /// First cluster, 0 for empty files. pub(crate) first_cluster: u32, + /// How `name` came out of the units the entry stores. A short name + /// always comes out as the entry stores it. + pub(crate) name_decoding: NameDecoding, } /// Where a path led: the root, or an entry and the first cluster of the @@ -529,7 +532,13 @@ impl Volume { let Some(chain) = self.fat.chain_bounded(&self.store(), first_cluster, max_clusters)? else { bail!( EUCLEAN, - "directory at cluster {} spans more than the {} clusters a directory can have", + Detail::Corrupt { + place: CorruptPlace::Directory, + field: None, + path: None, + cluster: Some(first_cluster), + }, + "the chain of the directory at cluster {} loops or is longer than the {} clusters a directory can have", first_cluster, max_clusters ); @@ -699,6 +708,7 @@ impl Volume { created: entry.short.create_timestamp().to_system_time(), attributes: entry.short.attr, first_cluster: entry.short.first_cluster, + name_decoding: entry.long_name_decoding, } } @@ -714,6 +724,7 @@ impl Volume { created: FatTimestamp::EPOCH.to_system_time(), attributes: ATTR_DIRECTORY, first_cluster: self.boot.root_cluster, + name_decoding: NameDecoding::Exact, }), Located::Entry { entry, .. } => Ok(Self::metadata_of(&entry)), } @@ -722,7 +733,22 @@ impl Volume { /// Lists the directory at `path`, in on-disk order, without the dot /// entries and the volume label. pub fn read_dir(&self, path: &str) -> Result> { - self.with_directory(self.directory_at(path)?, |dir| { + self.read_dir_at(self.directory_at(path)?, |_| Ok(())) + } + + /// Lists the directory whose chain starts at `first_cluster`, as + /// [`Volume::read_dir`] lists the one at a path. A walk of the tree + /// takes the cluster from the entry it found, where a lookup by name + /// could find another entry of the same name on a damaged volume. + /// `chain` is shown the clusters of the directory first, and an error + /// it returns is the listing's. + pub(crate) fn read_dir_at( + &self, + first_cluster: u32, + chain: impl FnOnce(&[u32]) -> Result<()>, + ) -> Result> { + self.with_directory(first_cluster, |dir| { + chain(dir.chain())?; Ok(dir .iter() .filter(|e| !e.is_dot() && !e.short.is_volume_label()) diff --git a/tests/cli.rs b/tests/cli.rs index 87d2007..4739759 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1058,7 +1058,7 @@ fn counts_of_one() { assert!(summary.ends_with(" free, 0 lost; 1 error, 1 warning"), "{}", stdout); // An empty volume uses the one cluster of its root directory. A name - // of 100 three-byte characters fits FAT but no manifest. + // with the noncharacter U+FDD0 fits FAT but no manifest. let e = root.join("e.img"); let e = e.to_str().unwrap(); ok(&bin, &["assemble", "--create", "--size", "40M", e]); @@ -1070,8 +1070,8 @@ fn counts_of_one() { ); let device = fat::device::Device::open(Path::new(e), fat::device::Access::ReadWrite).unwrap(); let mut v = fat::volume::Volume::open(device).unwrap(); - let long: String = std::iter::repeat_n('\u{20ac}', 100).collect(); - v.create_dir(&format!("/{}", long), std::time::SystemTime::now()) + let odd = "a\u{fdd0}"; + v.create_dir(&format!("/{}", odd), std::time::SystemTime::now()) .unwrap(); v.close().unwrap(); let m = root.join("e.manifest"); @@ -1086,6 +1086,62 @@ fn counts_of_one() { assert!(stderr.starts_with("ufat: 1 entry is not in "), "{}", stderr); } +/// `ufat manifest` prints the manifest while it walks the tree. It leaves +/// out what a manifest cannot name and says how many entries it left out. +/// What it printed of a tree it cannot walk to its end has no trailer. +#[test] +fn manifest_of_a_tree_as_far_as_it_goes() { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::PermissionsExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let t = dir.path().join("tree"); + // A noncharacter, a control character and a name that is not UTF-8, a + // directory with what is in it counting as one entry, and the name of + // the manifest, which is no omission. + fs::create_dir_all(t.join("d\u{fdd0}")).unwrap(); + fs::write(t.join("d\u{fdd0}/inside"), b"x").unwrap(); + fs::write(t.join("a.txt"), b"a").unwrap(); + fs::write(t.join("b\u{1}.txt"), b"b").unwrap(); + fs::write(t.join(OsStr::from_bytes(b"z\xff")), b"z").unwrap(); + fs::write(t.join("Uapi16Manifest"), b"old").unwrap(); + let records = |stdout: &[u8]| { + let text = String::from_utf8(stdout.to_vec()).unwrap(); + text.split('\u{1e}').skip(1).map(str::to_string).collect::>() + }; + let out = run(&bin, &["manifest", t.to_str().unwrap()]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{}", stderr); + assert_eq!( + stderr, + "ufat: 3 entries are not in the manifest on standard output: their names cannot be written in a manifest\n" + ); + let printed = records(&out.stdout); + assert_eq!(printed.len(), 3, "{:?}", printed); + assert!(printed[1].contains(r#""name":"a.txt""#), "{:?}", printed); + assert_eq!(printed[2], "{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"); + + // A file that cannot be opened stops the walk where it comes. Where its + // mode keeps nobody out, as for root, there is nothing to try. + let locked = t.join("c.txt"); + fs::write(&locked, b"c").unwrap(); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap(); + if fs::File::open(&locked).is_ok() { + return eprintln!("skipping the file that cannot be opened: it opens"); + } + let out = run(&bin, &["manifest", t.to_str().unwrap()]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(stderr.contains("failed to open"), "{}", stderr); + let printed = records(&out.stdout); + assert_eq!(printed.len(), 2, "{:?}", printed); + assert!(printed[1].contains(r#""name":"a.txt""#), "{:?}", printed); +} + /// assemble prints the hash of the file system it wrote on request, and /// capabilities prints what GetCapabilities answers. #[test] diff --git a/tests/crash/Cargo.toml b/tests/crash/Cargo.toml index 90561fb..a5a807c 100644 --- a/tests/crash/Cargo.toml +++ b/tests/crash/Cargo.toml @@ -25,6 +25,7 @@ blkid.workspace = true json.workspace = true libc.workspace = true sha2.workspace = true +uapi16.workspace = true [lints] workspace = true diff --git a/tests/fixtures.rs b/tests/fixtures.rs index 62a44df..38d14f2 100644 --- a/tests/fixtures.rs +++ b/tests/fixtures.rs @@ -16,8 +16,7 @@ use fat::dirent::ATTR_READ_ONLY; use fat::errno::{EINVAL, EOPNOTSUPP}; use fat::format::{self, FormatOptions}; use fat::host; -use fat::manifest::volume::Fields; -use fat::manifest::{self, AssembleOptions, DirectorySource, InodeType, Manifest, StreamSource}; +use fat::manifest::{self, AssembleOptions, DirectorySource, Features, HostTree, InodeType, Manifest, StreamSource}; use fat::plan::{Plan, PlanOptions}; use fat::volume::Volume; @@ -353,7 +352,11 @@ fn empty_manifest_is_an_empty_volume() { } /// Our generator writes what `systemd-manifest make --field=size,hash,mtime` -/// writes for the same tree, byte for byte. +/// writes for the same tree, byte for byte, once make-fixtures.sh added +/// `"features":["mtime","sha256","size"]` and `"order":"codepoint"` to the +/// root object of systemd's manifest, see the README. The tree has no +/// empty file, whose hash the generator leaves out and the systemd-manifest +/// the fixtures come from writes. #[test] fn generator_agrees_with_systemd_manifest() { let m = load("esp", "size-hash-mtime.Uapi16Manifest"); @@ -387,7 +390,10 @@ fn generator_agrees_with_systemd_manifest() { for (dir, nsec) in dirs { std::fs::File::open(&dir).unwrap().set_modified(time(nsec)).unwrap(); } - let ours = manifest::generate(host::open_dir(copy.path()).unwrap().as_fd()).unwrap(); + let mut ours = Vec::new(); + HostTree::new(host::open_dir(copy.path()).unwrap().as_fd()) + .write_manifest(&mut ours) + .unwrap(); let theirs = std::fs::read(fixtures().join("esp/size-hash-mtime.Uapi16Manifest")).unwrap(); assert_eq!( String::from_utf8_lossy(&ours), @@ -397,28 +403,111 @@ fn generator_agrees_with_systemd_manifest() { } /// The manifest of a volume is what `systemd-manifest make` writes for the -/// tree the volume was filled from, byte for byte, for the fields FAT has -/// a notion of: none at all, and size, hash and mtime. +/// tree the volume was filled from, byte for byte, for the features FAT +/// has a notion of: none at all, and size, sha256 and mtime. The manifests +/// of systemd got their features and their order declared, see the README. +/// A manifest of a volume records the read-only attribute as well, which +/// systemd-manifest does not record. So it lists read-only next to the +/// features systemd-manifest lists. #[test] fn volume_manifest_agrees_with_systemd_manifest() { let m = load("esp", "size-hash-mtime.Uapi16Manifest"); let (_img, mut v, _) = planned_volume(&m); v.assemble(&m, &mut source("esp"), &AssembleOptions::default()).unwrap(); - for (name, fields) in [ - ("none.Uapi16Manifest", Fields::none()), + for (name, features, listed, listed_by_volume) in [ + ( + "none.Uapi16Manifest", + Features::NONE, + r#""features":[]"#, + r#""features":["read-only"]"#, + ), ( "size-hash-mtime.Uapi16Manifest", - Fields::from_names(["size", "hash", "mtime"]).unwrap(), + Features::from_names(["size", "sha256", "mtime"]).unwrap(), + r#""features":["mtime","sha256","size"]"#, + r#""features":["mtime","read-only","sha256","size"]"#, ), ] { let mut ours = Vec::new(); - manifest::volume::write(&v, m.root.mtime(), fields, &mut ours).unwrap(); - let theirs = std::fs::read(fixtures().join("esp").join(name)).unwrap(); + v.write_manifest(m.root.mtime(), features, &mut ours).unwrap(); + let theirs = std::fs::read_to_string(fixtures().join("esp").join(name)).unwrap(); + assert!(theirs.contains(listed), "{} does not list {}", name, listed); assert_eq!( String::from_utf8_lossy(&ours), - String::from_utf8_lossy(&theirs), + theirs.replacen(listed, listed_by_volume, 1), "the volume's manifest and systemd-manifest's {} disagree", name ); } } + +/// A manifest read to its end with the reader of the uapi16 crate: its +/// root file object, its file objects and its signature objects. +#[derive(Debug, PartialEq)] +struct ManifestObjects { + root: uapi16::RootObject, + files: Vec, + signatures: Vec, +} + +impl ManifestObjects { + fn read(bytes: &[u8]) -> Result { + let mut reader = uapi16::Reader::open(bytes)?; + let mut objects = ManifestObjects { + root: reader.root().clone(), + files: Vec::new(), + signatures: Vec::new(), + }; + for object in &mut reader { + match object? { + uapi16::Object::File(file) => objects.files.push(*file), + uapi16::Object::Signature(signature) => objects.signatures.push(signature), + other => panic!("{:?} is neither a file object nor a signature", other), + } + } + Ok(objects) + } + + /// The manifest the writer of the uapi16 crate writes for the objects. + fn write(&self) -> Result, uapi16::Error> { + let mut writer = uapi16::Writer::begin(Vec::new(), &self.root)?; + for file in &self.files { + writer.file(file)?; + } + for signature in &self.signatures { + writer.signature(signature)?; + } + writer.finish() + } +} + +/// The uapi16 crate reads every manifest systemd-manifest wrote, and what +/// it writes for one reads back as the same manifest. That holds since +/// make-fixtures.sh took the hash of no data out of the empty file of the +/// special case: the writer leaves out a hash given next to the size 0, +/// and a reader marks the one it fills in as filled in, so the objects +/// would differ in that mark. +#[test] +fn uapi16_reads_and_writes_back_every_fixture() { + for (case, name, files, signatures) in [ + ("esp", "Uapi16Manifest", 13, 0), + ("esp", "signed.Uapi16Manifest", 13, 1), + ("esp", "size-hash-mtime.Uapi16Manifest", 13, 0), + ("esp", "none.Uapi16Manifest", 13, 0), + ("special", "Uapi16Manifest", 13, 0), + ("empty", "Uapi16Manifest", 0, 0), + ] { + let path = fixtures().join(case).join(name); + let bytes = std::fs::read(&path).unwrap(); + let read = ManifestObjects::read(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); + assert_eq!( + (read.files.len(), read.signatures.len()), + (files, signatures), + "{}", + path.display() + ); + assert_eq!(read.root.order, Some(uapi16::Order::CodePoint), "{}", path.display()); + let written = read.write().unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); + assert_eq!(ManifestObjects::read(&written).unwrap(), read, "{}", path.display()); + } +} diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 1f14567..ef7fcac 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -20,6 +20,27 @@ from a git checkout, with `--field` as listed below. | `special` | `Uapi16Manifest` | symlink, FIFO, hardlink pair, extended attribute, empty file and directory, read-only file, mixed case and non-ASCII names | default plus mtime, user and group names | | `empty` | `Uapi16Manifest` | an empty directory | default plus mtime | +The fixtures were made with a systemd-manifest from before systemd +commits 118717cfe2, 330fab5e90 and e83f7bce0c, which are not in a +release yet. + +That systemd-manifest does not write the `features` and `order` fields +of the root file object. UAPI.16 has them since uapi-group/specifications +pull request 253, and a manifest that records other than the default +fields has to list its features. systemd-manifest writes the features +since 118717cfe2 and the order since 330fab5e90. `make-fixtures.sh` +adds both to every manifest after systemd-manifest wrote it: the +features its `--field` records and the code point ordering it is sorted +in. This changes the bytes the signature of `signed.Uapi16Manifest` +covers, so the signature no longer matches them. + +That systemd-manifest also writes the hash of no data for a file of size +0. UAPI.16 recommends to leave it out, ufat leaves it out, and +systemd-manifest does since e83f7bce0c. `make-fixtures.sh` takes it out +of the file objects of size 0, which is the file `empty` of the +`special` case. The other file objects stay as systemd-manifest wrote +them. + The `tree` directories are copies of what the manifests describe, as far as git can hold it: the FIFO is missing, the hardlinks are two files, the extended attribute is gone and the modification times are whatever the diff --git a/tests/fixtures/empty/Uapi16Manifest b/tests/fixtures/empty/Uapi16Manifest index 9f8b68c..f611451 100644 --- a/tests/fixtures/empty/Uapi16Manifest +++ b/tests/fixtures/empty/Uapi16Manifest @@ -1,2 +1,2 @@ -{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000200000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"uid":1000} +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1700000200000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} {"mediaType":"application/vnd.uapi.16.trailer"} diff --git a/tests/fixtures/esp/Uapi16Manifest b/tests/fixtures/esp/Uapi16Manifest index 989a4d9..407c2f5 100644 --- a/tests/fixtures/esp/Uapi16Manifest +++ b/tests/fixtures/esp/Uapi16Manifest @@ -1,4 +1,4 @@ -{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"uid":1000} +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI","type":"dir","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/BOOT","type":"dir","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} diff --git a/tests/fixtures/esp/none.Uapi16Manifest b/tests/fixtures/esp/none.Uapi16Manifest index ba12e9c..c76497c 100644 --- a/tests/fixtures/esp/none.Uapi16Manifest +++ b/tests/fixtures/esp/none.Uapi16Manifest @@ -1,4 +1,4 @@ -{"mediaType":"application/vnd.uapi.16.manifest"} +{"features":[],"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"} {"name":"EFI","type":"dir"} {"name":"EFI/BOOT","type":"dir"} {"name":"EFI/BOOT/BOOTX64.EFI"} diff --git a/tests/fixtures/esp/signed.Uapi16Manifest b/tests/fixtures/esp/signed.Uapi16Manifest index 0dbec80..b1996fb 100644 --- a/tests/fixtures/esp/signed.Uapi16Manifest +++ b/tests/fixtures/esp/signed.Uapi16Manifest @@ -1,4 +1,4 @@ -{"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"uid":1000} +{"extendedAttributes":{"user":{}},"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid","user-xattr"],"gid":1000,"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI","type":"dir","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1699999000000000000,"mode":509,"name":"EFI/BOOT","type":"dir","uid":1000} {"extendedAttributes":{"user":{}},"gid":1000,"mTimeNSec":1700000000000000000,"mode":436,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096,"uid":1000} diff --git a/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest b/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest index 6a1e5d5..a19baf9 100644 --- a/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest +++ b/tests/fixtures/esp/size-hash-mtime.Uapi16Manifest @@ -1,4 +1,4 @@ -{"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest"} +{"features":["mtime","sha256","size"],"mTimeNSec":1699999000000000000,"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"} {"mTimeNSec":1699999000000000000,"name":"EFI","type":"dir"} {"mTimeNSec":1699999000000000000,"name":"EFI/BOOT","type":"dir"} {"mTimeNSec":1700000000000000000,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"608047e995ccddf55441b8ed783ac49c780b9a911aa655f47d3a4c174748f86b","size":4096} diff --git a/tests/fixtures/make-fixtures.sh b/tests/fixtures/make-fixtures.sh index 97f15dc..6e410d3 100755 --- a/tests/fixtures/make-fixtures.sh +++ b/tests/fixtures/make-fixtures.sh @@ -23,6 +23,46 @@ stamp() { touch -h -d "@$t" "$@" } +follow_uapi16() { + # The committed fixtures come from a systemd-manifest from before + # systemd commits 118717cfe2, 330fab5e90 and e83f7bce0c, which are + # not in a release yet. That one does not write `features` and + # `order`, which UAPI.16 has since uapi-group/specifications#253: a + # manifest lists the features it records, as soon as they are not + # the default ones, and declares the code point ordering it is sorted + # in. make sorts that way. This adds both to the root file object of + # the manifest $1, with the features $2, what its --field= records. + # That systemd-manifest also writes the hash of no data next to the + # size 0, which UAPI.16 recommends to leave out and ufat's writers + # leave out. This takes it out of the file objects of size 0 and + # leaves the other records as they are. + python3 -I - "$1" "$2" <<'EOF' +import json, sys +path, features = sys.argv[1], sys.argv[2].split() +separator = b"\x1e" +empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +def text(o): + return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + b"\n" +records = open(path, "rb").read().split(separator) +root = json.loads(records[1]) +root["features"] = sorted(features) +root["order"] = "codepoint" +records[1] = text(root) +for i in range(2, len(records)): + o = json.loads(records[i]) + if o.get("size") == 0 and o.get("sha256") == empty: + del o["sha256"] + records[i] = text(o) +open(path, "wb").write(separator.join(records)) +EOF +} + +# What --field=default records in the systemd-manifest the committed +# fixtures come from. systemd main leaves user-xattr out of the default +# since 1843e578d2, which is not in a release yet, so regenerating the +# fixtures with it needs its default here, without user-xattr. +DEFAULT="device gid hardlink mode sha256 size symlink uid user-xattr" + copy_tree() { # Regular files, directories and symlinks only. rm -rf "$2" @@ -53,8 +93,11 @@ stamp 1700000006 "$T/loader/random-seed" stamp 1699999000 "$T/EFI/BOOT" "$T/EFI/Linux" "$T/EFI/systemd" "$T/EFI" "$T/loader/entries" "$T/loader" "$T" mkdir -p "$HERE/esp" "$MANIFEST" make --field=default,+mtime "$T" "$HERE/esp/Uapi16Manifest" +follow_uapi16 "$HERE/esp/Uapi16Manifest" "$DEFAULT mtime" "$MANIFEST" make --field=size,hash,mtime "$T" "$HERE/esp/size-hash-mtime.Uapi16Manifest" +follow_uapi16 "$HERE/esp/size-hash-mtime.Uapi16Manifest" "mtime sha256 size" "$MANIFEST" make --field=none "$T" "$HERE/esp/none.Uapi16Manifest" +follow_uapi16 "$HERE/esp/none.Uapi16Manifest" "" copy_tree "$T" "$HERE/esp/tree" # A signed copy of the same manifest, with a throwaway key. @@ -62,6 +105,8 @@ openssl req -x509 -newkey rsa:2048 -nodes -subj '/CN=ufat test' -days 3650 \ -keyout "$WORK/key.pem" -out "$WORK/cert.pem" 2>/dev/null "$MANIFEST" make --field=default,+mtime --private-key="$WORK/key.pem" --certificate="$WORK/cert.pem" \ "$T" "$HERE/esp/signed.Uapi16Manifest" +# This changes what the signature covers, so it no longer matches. +follow_uapi16 "$HERE/esp/signed.Uapi16Manifest" "$DEFAULT mtime" # ---------------------------------------------------------------- special # Everything a manifest can describe that FAT cannot hold, next to things @@ -88,6 +133,7 @@ stamp 1700000102 "$T/sub/hl_a" "$T/link" "$T/sub/fifo" "$T/sub/ümlaut ∞.txt" stamp 1699999100 "$T/sub/nested" "$T/sub" "$T/empty dir" "$T" mkdir -p "$HERE/special" "$MANIFEST" make --field=default,+mtime,+user-name,+group-name "$T" "$HERE/special/Uapi16Manifest" +follow_uapi16 "$HERE/special/Uapi16Manifest" "$DEFAULT mtime user-name group-name" copy_tree "$T" "$HERE/special/tree" # ---------------------------------------------------------------- empty @@ -96,6 +142,7 @@ mkdir -p "$T" stamp 1700000200 "$T" mkdir -p "$HERE/empty" "$MANIFEST" make --field=default,+mtime "$T" "$HERE/empty/Uapi16Manifest" +follow_uapi16 "$HERE/empty/Uapi16Manifest" "$DEFAULT mtime" # The version that made them, for the record. "$MANIFEST" --version | head -1 > "$HERE/VERSION" diff --git a/tests/fixtures/special/Uapi16Manifest b/tests/fixtures/special/Uapi16Manifest index 8e345ab..18d9767 100644 --- a/tests/fixtures/special/Uapi16Manifest +++ b/tests/fixtures/special/Uapi16Manifest @@ -1,7 +1,7 @@ -{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"features":["device","gid","group-name","hardlink","mode","mtime","sha256","size","symlink","uid","user-name","user-xattr"],"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mediaType":"application/vnd.uapi.16.manifest","mode":509,"order":"codepoint","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"Mixed Case.TXT","sha256":"480c2336b410f1ad5f8bf1b28944490255804b65350c527787e74ebdd511e3a4","size":7,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{"comment":{"text":"set by make-fixtures"}}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000100000000000,"mode":436,"name":"a.txt","sha256":"b640e840b19d378660b32fb51ae18d67dccb4a8596a29e7bd72c1b2ae5928f41","size":6,"uid":1000,"userName":"brauner"} -{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","size":0,"uid":1000,"userName":"brauner"} +{"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"mode":436,"name":"empty","size":0,"uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"empty dir","type":"dir","uid":1000,"userName":"brauner"} {"contents":[{"literal":"YS50eHQ="}],"gid":1000,"groupName":"brauner","mTimeNSec":1700000102000000000,"name":"link","size":5,"type":"lnk","uid":1000,"userName":"brauner"} {"extendedAttributes":{"user":{}},"gid":1000,"groupName":"brauner","mTimeNSec":1699999100000000000,"mode":509,"name":"sub","type":"dir","uid":1000,"userName":"brauner"} diff --git a/tests/fuzz/varlink_fuzz.py b/tests/fuzz/varlink_fuzz.py index c5090ce..95fbe26 100755 --- a/tests/fuzz/varlink_fuzz.py +++ b/tests/fuzz/varlink_fuzz.py @@ -501,8 +501,8 @@ def method_cases(rng, seeds, work, small_tree, img): ({"sourceFileDescriptor": 0}, rw), ({"sourceFileDescriptor": 1}, [img, tree]), ({"sourceFileDescriptor": 1, "unsupported": "fail"}, rw + [("/dev", "dir")]), ({"sourceFileDescriptor": 1, "uid": -1, "gid": 2 ** 40}, rw + [tree]), ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 1}}, rw + [tree]), - ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 2, "fields": ["bogus"]}}, rw + [tree, (sink_path, "wo")]), - ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 2, "fields": ["size", "hash", "mtime"]}}, rw + [tree, (sink_path, "wo")]), + ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 2, "features": ["bogus"]}}, rw + [tree, (sink_path, "wo")]), + ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 2, "features": ["size", "sha256", "mtime"]}}, rw + [tree, (sink_path, "wo")]), ({"sourceFileDescriptor": 1, "manifestSink": {"fileDescriptor": 2}}, rw + [tree, sink_path])]: content = dict(content) params = {"image": {"fileDescriptor": 0}, "path": content.pop("destination", "/"), "content": content} diff --git a/tests/reference.rs b/tests/reference.rs index afc9bda..8907fa1 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -489,7 +489,11 @@ fn matches_sha256sum() { ); } let dir = source(tree.path()); - let manifest = fat::manifest::parse(&fat::manifest::generate(dir.as_fd()).unwrap()).unwrap(); + let mut bytes = Vec::new(); + fat::manifest::HostTree::new(dir.as_fd()) + .write_manifest(&mut bytes) + .unwrap(); + let manifest = fat::manifest::parse(&bytes).unwrap(); let mut hashed = 0; for entry in &manifest.entries { if let (Some(name), Some(hash)) = (&entry.name, &entry.sha256) { diff --git a/tests/varlink.rs b/tests/varlink.rs index e172bae..805c46b 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -382,7 +382,10 @@ fn esp_tree() -> Temp { /// A manifest of the tree and the contents of its streamed files in /// manifest order. fn manifest_and_blob(tree: &Path) -> (Vec, Vec) { - let bytes = fat::manifest::generate(fat::host::open_dir(tree).unwrap().as_fd()).unwrap(); + let mut bytes = Vec::new(); + fat::manifest::HostTree::new(fat::host::open_dir(tree).unwrap().as_fd()) + .write_manifest(&mut bytes) + .unwrap(); let m = fat::manifest::parse(&bytes).unwrap(); let mut blob = Vec::new(); for e in &m.entries { @@ -419,6 +422,37 @@ fn volume(image: &Path, access: Access) -> Volume { Volume::open(Device::open(image, access).unwrap()).unwrap() } +/// Points the FAT entry of the first cluster of the directory `name`, an +/// entry of the root directory of the FAT32 volume in `image` given by its +/// 8.3 name, at that cluster itself, in every copy of the FAT: the chain of +/// the directory loops. Returns the cluster. +fn loop_root_directory(image: &Path, name: &[u8; 11]) -> u32 { + use fat::dirent::{self, ATTR_DIRECTORY, DIR_ENTRY_SIZE}; + + let f = rw(image); + let mut sector = [0u8; 512]; + f.read_exact_at(&mut sector, 0).unwrap(); + let boot = fat::boot::BootSector::parse(§or).unwrap(); + let layout = boot.layout().unwrap(); + let mut buf = vec![0u8; layout.cluster_size() as usize]; + f.read_exact_at(&mut buf, layout.cluster_offset(boot.root_cluster).unwrap()) + .unwrap(); + let slot = buf + .chunks(DIR_ENTRY_SIZE) + .find(|slot| &slot[dirent::field::NAME] == name && slot[dirent::field::ATTR] & ATTR_DIRECTORY != 0) + .unwrap(); + let half = |field: std::ops::Range| u32::from(u16::from_le_bytes(slot[field].try_into().unwrap())); + let cluster = (half(dirent::field::FIRST_CLUSTER_HI) << u16::BITS) | half(dirent::field::FIRST_CLUSTER_LO); + for copy in 0..layout.fats { + f.write_all_at( + &cluster.to_le_bytes(), + layout.fat_offset(copy) + u64::from(cluster) * fat::fat::ENTRY_SIZE as u64, + ) + .unwrap(); + } + cluster +} + /// Damages the FAT32 volume in `image`: every file entry of the root /// directory gets a modification time with hour 31 and a date with month /// 0, two findings each for a check. Returns how many entries were hit. @@ -1462,7 +1496,7 @@ fn assemble_writes_a_manifest() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"manifestSink":{{"fileDescriptor":2,"fields":["size","hash","mtime"]}}}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"manifestSink":{{"fileDescriptor":2,"features":["size","sha256","mtime"]}}}}}}"#, T0 ), &[img.as_fd(), source.as_fd(), out_file.as_fd()], @@ -1507,6 +1541,116 @@ fn assemble_writes_a_manifest() { assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); } +/// The reasons of InvalidManifest are the names of the problems of the +/// uapi16 crate and noSize, the way ManifestProblem spells them. +#[test] +fn manifest_problems_are_those_of_uapi16() { + use fat::ManifestProblem; + let Some(varlink::idl::Type::Enum(values)) = interface().types.get("ManifestProblem") else { + panic!("ManifestProblem is not an enumeration"); + }; + let mut spelled: Vec<&str> = uapi16::Problem::ALL + .iter() + .copied() + .map(ManifestProblem::Malformed) + .chain([ManifestProblem::NoSize]) + .map(ManifestProblem::as_str) + .collect(); + let mut declared: Vec<&str> = values.iter().map(String::as_str).collect(); + spelled.sort_unstable(); + declared.sort_unstable(); + assert_eq!(declared, spelled); +} + +/// The manifest sink takes the features of UAPI.16, with "_" for "-". +#[test] +fn manifests_record_and_apply_features() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + // The values of ManifestFeature are the features of UAPI.16. + let Some(varlink::idl::Type::Enum(values)) = interface().types.get("ManifestFeature") else { + panic!("ManifestFeature is not an enumeration"); + }; + let mut spelled: Vec = fat::manifest::Features::ALL + .names() + .map(|name| name.replace('-', "_")) + .collect(); + let mut declared = values.clone(); + spelled.sort_unstable(); + declared.sort_unstable(); + assert_eq!(declared, spelled); + let tree = esp_tree(); + let scratch = Temp::dir(); + let mut c = connect_fd3(&ufat); + let source = ro(tree.path()); + let (image, img) = fresh_image(); + reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + &[img.as_fd(), source.as_fd()], + )); + // The features a manifest lists in its root file object. + let listed = |path: &Path| { + let bytes = std::fs::read(path).unwrap(); + let features = uapi16::Reader::open(&bytes[..]).unwrap().root().features; + features.unwrap().names().collect::>() + }; + // Every value is taken. What FAT has no notion of is not recorded, and + // the read-only attribute always is. + let img_ro = ro(image.path()); + let out = scratch.path().join("all.manifest"); + let out_file = sink(&out); + let all: Vec = values.iter().map(|value| format!("\"{}\"", value)).collect(); + reply(call( + &mut c, + "Describe", + &format!( + r#"{{"image":{{"fileDescriptor":0}},"manifestSink":{{"fileDescriptor":1,"features":[{}]}}}}"#, + all.join(",") + ), + &[img_ro.as_fd(), out_file.as_fd()], + )); + drop(out_file); + assert_eq!( + listed(&out), + [ + "device", + "hardlink", + "mtime", + "read-only", + "sha256", + "size", + "symlink", + "user-xattr" + ] + ); + let out_file = sink(&out); + reply(call( + &mut c, + "Describe", + r#"{"image":{"fileDescriptor":0},"manifestSink":{"fileDescriptor":1}}"#, + &[img_ro.as_fd(), out_file.as_fd()], + )); + drop(out_file); + assert_eq!( + listed(&out), + ["device", "hardlink", "read-only", "sha256", "size", "symlink"] + ); + // systemd-manifest's name for sha256 is not one of them. + let out_file = sink(&out); + let e = error_of( + &mut c, + "Describe", + r#"{"image":{"fileDescriptor":0},"manifestSink":{"fileDescriptor":1,"features":["hash"]}}"#, + &[img_ro.as_fd(), out_file.as_fd()], + ); + assert_eq!(e.name, "org.varlink.service.InvalidParameter"); + assert_eq!(str_of(&e.parameters, "parameter"), "manifestSink"); +} + /// With the more flag Assemble tells which step it is in, in order. #[test] fn assemble_reports_its_phases() { @@ -1779,6 +1923,41 @@ fn describe_with_and_without_a_manifest() { assert_eq!(str_of(&e.parameters, "parameter"), "image"); } +/// Describe of a volume with a directory whose chain loops answers +/// Corrupt for that directory. +#[test] +fn describe_of_a_directory_whose_chain_loops_is_corrupt() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let tree = esp_tree(); + let scratch = Temp::dir(); + let (image, img) = fresh_image(); + let mut c = connect_fd3(&ufat); + let source = ro(tree.path()); + reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + &[img.as_fd(), source.as_fd()], + )); + drop(img); + let cluster = loop_root_directory(image.path(), b"LOADER "); + let out_file = sink(&scratch.path().join("described.manifest")); + let img_ro = ro(image.path()); + let e = error_of( + &mut c, + "Describe", + r#"{"image":{"fileDescriptor":0},"manifestSink":{"fileDescriptor":1}}"#, + &[img_ro.as_fd(), out_file.as_fd()], + ); + assert_eq!(e.name, format!("{}.Corrupt", IFACE)); + assert_eq!(str_of(&e.parameters, "where"), "directory"); + assert_eq!(str_of(&e.parameters, "path"), "/loader"); + assert_eq!(u64_of(&e.parameters, "block"), u64::from(cluster)); +} + /// Populate: a tree, one file, a manifest's tree, and a directory alone; /// the source's type decides. #[test] diff --git a/verify/lib.rs b/verify/lib.rs index a96c870..f6eac85 100644 --- a/verify/lib.rs +++ b/verify/lib.rs @@ -9,6 +9,23 @@ #[cfg(kani)] extern crate libc; +// error.rs names the problems of a manifest with uapi16::Problem. The +// proofs read no manifest, so this crate stands in for uapi16 with a +// Problem of its own, and Kani needs neither uapi16 nor the crates below +// it. +extern crate self as uapi16; + +/// What error.rs takes of `uapi16::Problem`: a type that has no value here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem {} + +impl Problem { + /// Never called: there is no problem to name. + pub const fn as_str(self) -> &'static str { + match self {} + } +} + #[macro_use] #[path = "../src/fat/error.rs"] mod error; From 7c79614a0d66f41042f8f84791eabf97c09da03e Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 12/19] manifest: assemble a volume while the manifest is read Currently we read a manifest into memory in one go, up to 256 MiB, and parse it into a fat::manifest::Manifest that holds every object and a map of every name folded the way FAT folds names. That is checked as a whole and only then is the volume assembled from it. This doesn't work for a manifest of a few gigabytes, and a manifest that describes the dataset of a large model gets there easily. It can also come through a pipe, which can be read only once. So let's never hold a whole manifest. The tools open a uapi16::Reader on the file or the pipe and read the root object up front, so a file that isn't a manifest is refused before an image is touched. Volume::assemble() then takes the records from the reader one by one and writes what each of them describes right away. So populating a file system from a manifest takes the same memory whatever the size of the manifest. fat::manifest::Manifest, fields.rs and read_all() are gone. The content sources are the ones of the uapi16 crate, and PinnedDirectory tells its DirectorySource how to open a file below the source directory, pinned with chase() as before. The crate takes contents only as they are, in the manifest or in a file next to it. Contents that are only at a URL or in an encoding fail with ContentNotSupported and what transport now, with the ways the manifest offers in value, instead of url or encoding. Nothing produces UnsupportedKind::Url and Encoding anymore, so they go. The interface keeps url and encoding for implementations that can tell them apart. What an object is to FAT is EntryKind::try_from(), which now also refuses a file FAT32 can't hold with EFBIG when its record comes. What the decoder refuses is tested by uapi16's refused.jsonl and its reader tests, and fat's tests keep what is about the assembly. A file object with "mediaType": null is taken now, since the uapi16 reader takes a field that is null for one that isn't there. A manifest that is read while it is written has to come in the order the volume is written in. UAPI.16 asks a manifest that a file system is made from to declare "order": "codepoint" (cf. [1]), and the reader checks the file objects against the order that is declared. So we require the declaration and refuse a manifest without it with InvalidManifest and reason noOrder, also when its objects are sorted. With the order checked a name that comes twice is refused, and so is an object that comes before its directory. We used to create missing directories on demand. systemd-manifest make sorts its output that way and declares it since 330fab5e90, which isn't in a release yet. The manifests of an older systemd-manifest are refused. GetCapabilities announces the order in manifest.order. Names that FAT doesn't tell apart, such as README and readme, aren't the reader's business. The uapi16 crate compares exact names and knows nothing about FAT, and finding them would take a map of every name of the manifest. Instead, the volume finds the second one when it is created. Replacing is the default, so it is taken as the same name: a file replaces the first one under its own spelling, and a directory takes the entries of the first one. There is no check of the source directory before the format anymore. Each file is looked up when its record comes. Its data is the part of the file that starts at the offset the manifest gives and is as long as the manifest says, whatever else the file holds, as UAPI.16 has it. So a file that grew since the manifest was written is copied as far as the manifest says. One that is too short for the data, or not of the originalSize the manifest gives, fails with ContentMismatch and reason size while it is copied. So SourceProblem::Size and the sizes of SourceMismatch go. A file that changes while it is read fails with ContentMismatch and the new reason sourceChanged, without sizes. Nothing names the source directory up front anymore, so the command line puts it in front of the errors about the files below it: ufat: /srv/esp: EFI/x.efi: failed to open EFI/x.efi: ... The service names a file the way the manifest does. Its caller passed the directory and knows which one it is. --unsupported fail fails on an object of a manifest when its record comes as well, and so does the plan of it, before anything is written. When the contents come in a stream, the manifest and the stream are read in lockstep: a record, then the contents of the file it describes. We used to read the whole manifest first, so a client could write all of it to one pipe and the contents to the other after it. Now such a client deadlocks with the service once the manifest is larger than the pipe and what the reader reads ahead. varlink.md and the interface say that both pipes have to be written at the same time, and a test passes a large manifest that way. ManifestInput::open() takes the passed stream, so a manifest pipe that is made non-blocking during the call fails with BadFileDescriptor and reason flags like the other passed pipes. The error names the parameter of the pipe it came from, and so do the errors of the vetting of the passed streams. So the service takes the name from the error and names only the image and a manifest refused for a plan itself. A stream also has the contents of every object that is left out, and ContentSource::skip() reads past them, a sub-manifest's included. With --unsupported fail a directory that refers to a sub-manifest is refused at its object, before the stream is asked for anything. Left out without a size it fails with InvalidManifest and reason noSize, like a file without a size, since the stream can't be read past it. A stream has the contents of each file and nothing else of it. So an object whose contents start at an offset fails with ContentNotSupported and what offset when its record comes, whatever --unsupported says. A populate that fails while it writes a tree or a manifest leaves the file system marked as not cleanly unmounted, as a failed assemble does. Dropping the volume would mark it clean with half of the content in it. But a manifest can also be refused at its first object, before anything was written, and then the file system stays as it was. Volume::is_writing() tells the two apart. For that the volume has to begin a write only when something is written. Volume::create_dir(), create_dir_all() and begin_file() marked the volume first and checked the name after, and set_times() wrote a time an entry had already. make_directory() even allocated and wrote the cluster of the new directory before it looked at the parent. Now placing an entry does everything that only reads first. It checks that the directory isn't damaged and that the name is free, makes the short name, and finds free slots or makes sure that the directory can grow and that the clusters for that are free, the one of a new directory included. Only then does it begin the write. The cluster of a new directory and the FAT still go out before its entry, so a crash in between leaks a cluster as before. The crash harness now makes directories with and without their parent growing for them. create_dir_all() walks the path to the first directory that is missing and checks the names of the directories it creates before it creates the first one, and set_times() writes only what changes, after it checked the directories it changes. So a name FAT can't store or that is too long, a name that is taken, a file named like a directory, a damaged or full directory, too few free clusters for the entry and directories that are there with their times write nothing. Populate over Varlink ran create_dir_all("/") for a manifest with parents, which marked the volume as well. Like the command line it makes sure that the destination is a directory only for a tree now. And the assembly creates a file in the volume when its first data comes. So nothing is written either when the source refuses the object, such as a stream that needs a size the object doesn't give, or a file that is missing below the source directory. A file that runs out of space is named in the error, the way a tree names it. Only the errors of the volume are named that way, since the ones about the files of the manifest name them already. The rest follows from reading a manifest once: - The stream is checked to end after the trailer, also when no file had its contents on it. - skipped is a count, and an AssembleObserver hears about every object that is left out, so Volume::assemble_with_progress() is assemble_with_observer() now. A directory that is left out takes everything below it along. ObjectTriage::decide() says what happens to each object, for the assembly and the plan alike. An object that isn't valid fails the assembly whether it would be left out or not, as before. - The switches of an assembly become AssembleFlags instead of two booleans that don't say what they mean at the call site. The default stays REPLACE. The plan takes them too. - fat uses json in its tests only from here on. - The fuzzers write their large manifests in code point order, and bench/run.sh builds the inputs an older ufat wrote again. While at it, fat::sha256 goes. fat::manifest re-exports the Sha256 of the uapi16 crate now, and the image hash uses its Sha256Context, so there is one SHA-256 context and one Sha256. fat::sha512's Sha512 is Sha512Context to match. And the interface says that its sizes and times are 64-bit integers, which can be larger than 2^53 and so more than a JSON parser that keeps numbers as doubles holds exactly. The planner takes the records the same way, with add_records() in place of add_manifest(). Note that it still keeps every name it is given, so the memory a plan takes still grows with the manifest. The next commit takes care of that. Sizing to fit is still the default, so the plan reads the manifest from its start and the assembly reads it once more. A regular file is read twice with positional reads, but a pipe can be read only once. So assemble with a SOURCE refuses a manifest that comes through a pipe, BadFileDescriptor with reason wrongType over Varlink. It does that before it reads anything from it, so all of it is still in the pipe. populate takes one. assemble --plan and assemble without a SOURCE write nothing of the content after the plan, so they plan with the reader that read the root object. They read the manifest only once and take one through a pipe as well. So does Assemble in mode plan. [1]: https://github.com/uapi-group/specifications/pull/255 Signed-off-by: Christian Brauner (Amutable) --- README.md | 48 +- bench/run.sh | 4 +- docs/org.uapi-group.FileSystem.varlink | 65 +- docs/varlink.md | 102 +- src/bin/ufat/cli.rs | 280 +++-- src/bin/ufat/service.rs | 233 ++-- src/bin/ufat/util.rs | 157 ++- src/fat/Cargo.toml | 4 +- src/fat/dir.rs | 61 +- src/fat/error.rs | 95 +- src/fat/fat.rs | 23 +- src/fat/host.rs | 151 ++- src/fat/lib.rs | 1 - src/fat/manifest/assemble.rs | 935 ++++++-------- src/fat/manifest/error.rs | 134 +- src/fat/manifest/fields.rs | 357 ------ src/fat/manifest/mod.rs | 1188 ++---------------- src/fat/manifest/tests.rs | 1521 ++++++++++++++--------- src/fat/plan.rs | 135 +- src/fat/sha256.rs | 121 -- src/fat/sha512.rs | 34 +- src/fat/volume/file.rs | 10 +- src/fat/volume/mod.rs | 195 ++- src/fat/volume/tests.rs | 340 ++++- tests/cli.rs | 371 +++++- tests/crash/crash.rs | 79 +- tests/fixtures.rs | 196 ++- tests/fuzz/mutate.py | 11 +- tests/fuzz/repro/quadratic-directory.py | 16 +- tests/fuzz/repro/uuid-char-boundary.sh | 2 +- tests/fuzz/targeted.py | 6 +- tests/reference.rs | 13 +- tests/varlink.rs | 553 +++++++- 33 files changed, 4131 insertions(+), 3310 deletions(-) delete mode 100644 src/fat/manifest/fields.rs delete mode 100644 src/fat/sha256.rs diff --git a/README.md b/README.md index 5b008d8..4abe557 100644 --- a/README.md +++ b/README.md @@ -168,16 +168,42 @@ manifest instead of a tree: With `--manifest`, the one SOURCE is the directory that the manifest's file references point into. `-` reads the file contents from standard input instead, back to back in manifest order. Standard input has to end -after the last file. A manifest names its paths from the root of the -file system, so `--path` does not apply. +after the last file. It has the contents of each file and nothing else +of it, so an entry whose contents start at an offset in their file fails +the command with `-`, whatever `--unsupported` says. A manifest names its +paths from the root of the file system, so `--path` does not apply. `--manifest -` reads the manifest from standard input. The file contents then have to come from a directory. -When the contents come from a directory, ufat first checks that every -file the manifest names is there with the size the manifest gives. This -happens before the image is changed. While copying, ufat verifies the -size and the SHA-256 hash of every file. A mismatch fails the command. +ufat reads a manifest one record at a time, and writes each file and +directory when its record comes. So `populate` takes a manifest of any +size, also through a pipe, and its memory use does not grow with the +manifest. To size the file system to fit, ufat reads the manifest once +before it writes anything, and keeps the name of every file and +directory while it does. So `assemble` with a SOURCE needs the manifest +in a regular file, and the memory `assemble` and `assemble --plan` use +grows with the manifest. `assemble --plan` and `assemble` without a +SOURCE read the manifest only once, so they take one through a pipe as +well. + +The objects of a manifest have to be in code point order: every +directory before what is in it, and the names of a directory sorted by +their bytes. The root object of the manifest has to declare that order +with `"order": "codepoint"`. `ufat manifest` writes manifests that way. +`systemd-manifest make` sorts its output that way, and declares the order +since systemd commit 330fab5e90, which is not in a release yet. ufat +refuses a manifest that does not declare the order, that is out of that +order, or that names a file twice. Two names that FAT does not tell +apart, such as `A.TXT` and `a.txt`, are taken as one name. + +While copying, ufat verifies the size and the SHA-256 hash of every file. +The data of a file is the part of its file below the SOURCE that starts +at the offset the manifest gives and is as long as the manifest says, +whatever else that file holds. A file that is missing below the SOURCE, +too short for the data, or does not match fails the command, and the file +system is left marked as not cleanly unmounted, with the files that were +complete. Signatures in a manifest are recognized but not verified. Verify a signed manifest before you hand it to ufat. @@ -298,6 +324,11 @@ crash. It holds the files that were complete when the command failed. it mounts the file system read-write. Running `assemble --force` again formats the file system anew. +When `populate` fails while it writes a tree or a manifest, ufat leaves +the file system marked the same way, unless nothing was written yet. A +manifest that is refused at its first object leaves the file system as +it was. + A crash can leave a state that readers resolve in different ways. A replaced file can briefly exist twice, and a long name can lose its long form. `ufat check` reports both. Every reader still finds a complete file. @@ -331,8 +362,9 @@ The crate `fat` provides the same operations as the tool: files and directories. - `populate` copies directory trees from the host into a volume. - `plan` computes the size a set of files needs. -- `manifest` reads UAPI.16 manifests, builds volumes from them and writes - manifests. +- `manifest` builds volumes from UAPI.16 manifests while they are read, + and writes manifests. The manifests themselves are read and written by + the crate `uapi16` in the same tree, which knows nothing of FAT. - `fsck` checks a volume. A path on the host is resolved once. Everything below it is reached diff --git a/bench/run.sh b/bench/run.sh index 03c6ad6..8584e85 100755 --- a/bench/run.sh +++ b/bench/run.sh @@ -167,7 +167,9 @@ small_file() { # small_file PATH SIZE SEED } make_inputs() { - local stamp=$IN/.ready-$WIDE + # The stamp names the order the manifests are written in: the inputs of + # a ufat from before manifests had to declare it are built again. + local stamp=$IN/.ready-$WIDE-codepoint [ -e "$stamp" ] && return say "building inputs under $IN (WIDE=$WIDE)" rm -rf "$IN"; mkdir -p "$IN" diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index 660d13a..9032497 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -23,6 +23,9 @@ # name with typed fields and every finding of Check is a kind with its facts; # the client renders them in its own language. # +# Sizes and times are 64-bit integers. They can be larger than 2^53, which a +# JSON parser that keeps numbers as doubles cannot hold exactly. +# # An implementation serves one filesystem type and is found the way mkfs # tools are found today: the executable mkfs. speaks this interface # when it is started with a socket passed as LISTEN_FDS, so that @@ -215,9 +218,23 @@ type Capabilities( nameUnit: LengthUnit, fileSizeMaxBytes: int, # Features that can be turned on or off, if any - features: ?[]Feature + features: ?[]Feature, + # What a UAPI.16 manifest given as content has to be; absent unless + # manifest is among operations + manifest: ?ManifestCapabilities +) + +# What an implementation requires of a UAPI.16 manifest given as content. +type ManifestCapabilities( + # The order the root file object has to declare in its order field, and + # its file objects have to be in; absent when any order is taken + order: ?ManifestOrder ) +# An order of the file objects of a manifest, as the order field of UAPI.16 +# names it: codepoint, the code point order of their complete names. +type ManifestOrder(codepoint) + # How copied files get their timestamps: the source's, the given time, or # the source's clamped to the given time (SOURCE_DATE_EPOCH semantics). type TimePolicy(preserve, fixed, clamp) @@ -271,8 +288,19 @@ type ManifestFeature( ) # A UAPI.16 manifest as content, read from a regular file or a pipe to its -# end as a JSON text sequence. The files it names come from the source -# directory, or back to back in manifest order from the source stream. +# end as a JSON text sequence, record by record while its content is written. +# Its root file object has to declare "order": "codepoint", which UAPI.16 asks +# of a manifest made for creating a filesystem (uapi-group/specifications#255), +# and its file objects are checked to be in that order while they are read. A +# manifest that does not declare the order is InvalidManifest with reason +# noOrder, also when its file objects are in it. The files it names come from +# the source directory, or back to back in manifest order from the source +# stream. A manifest and a source stream are read in lockstep, a record and +# then the contents of the file it describes, so a client that passes both as +# pipes writes to both at the same time. Assemble in mode assemble plans the +# content first: it reads the whole manifest before it writes and needs it in +# a regular file; a pipe is BadFileDescriptor with reason wrongType then. In +# mode plan the manifest is read once, and a pipe will do. type Manifest( # Index of the descriptor, open read-only fileDescriptor: int, @@ -303,11 +331,10 @@ type ManifestSink( # a manifest, the contents of its files back to back, a pipe is such a # stream. With a manifest the tree is what the manifest describes: every # file it names is resolved below the source directory, symbolic links -# followed and never leaving it, checked to be present with the size the -# manifest says before anything is written, and its contents verified -# against the manifest's sizes and SHA-256 hashes while copying. The root -# directory takes the source directory's owner, mode and time where the -# filesystem keeps them. +# followed and never leaving it, and its contents verified against the +# manifest's sizes and SHA-256 hashes while copying. The root directory takes +# the source directory's owner, mode and time where the filesystem keeps +# them. type Content( # Index of the descriptor of the source: a directory, a regular file or # a pipe, open read-only @@ -704,15 +731,23 @@ error InvalidIdentifier(identifier: string, reason: IdentifierProblem) type ManifestProblem(notJson, duplicateKey, invalidString, notObject, notUtf8, nulByte, recordSeparator, recordTooLarge, empty, noTrailer, dataAfterTrailer, fileAfterSignature, mediaType, firstHasName, firstNotDirectory, noOrder, noName, invalidName, duplicateName, misplaced, outOfOrder, unlistedFeature, noTarget, unknownType, fieldType, fieldRange, fieldNotPermitted, contradiction, contents, signature, extendedAttributes, noSize) error InvalidManifest(reason: ManifestProblem, record: ?int, name: ?string, field: ?string) -# A file the manifest names is not below the source as described. -type SourceProblem(missing, notRegular, size) -error SourceMismatch(name: string, reason: SourceProblem, sizeBytes: ?int, expectedSizeBytes: ?int) - -# Contents do not match the manifest. -type ContentProblem(size, hash, streamEnded) +# A file the manifest names is not below the source as described: it is +# missing, or it is not a regular file. +type SourceProblem(missing, notRegular) +error SourceMismatch(name: string, reason: SourceProblem) + +# Contents do not match the manifest, found while they are copied. A file of +# the source that is too short for them, or not of the originalSize the +# manifest gives for it, is reason size, with the size of the file in +# sizeBytes and the size it needs in expectedSizeBytes. A file of the source +# that changed while it was read is reason sourceChanged, without sizes. +type ContentProblem(size, hash, streamEnded, sourceChanged) error ContentMismatch(name: string, reason: ContentProblem, sizeBytes: ?int, expectedSizeBytes: ?int) -# Content the filesystem cannot hold, with UnsupportedPolicy fail. +# Content the filesystem cannot hold, with UnsupportedPolicy fail. Also, +# whatever the policy, contents that start at an offset in their file and +# come from a stream: a stream has the contents of each file and nothing +# else of it. type UnsupportedKind(url, encoding, offset, transport, subManifest, inodeType, ownership, extendedAttribute, hardlink, sparse, dosAttribute, inodeFlag, name, timestamp) error ContentNotSupported(name: ?string, what: UnsupportedKind, value: ?string) diff --git a/docs/varlink.md b/docs/varlink.md index e83bc6f..8977bb6 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -117,7 +117,8 @@ The reply does not depend on the call. It is: "caseSensitive" : false, "nameLengthMax" : 255, "nameUnit" : "utf16Units", - "fileSizeMaxBytes" : 4294967295 + "fileSizeMaxBytes" : 4294967295, + "manifest" : { "order" : "codepoint" } } } @@ -147,6 +148,8 @@ What the fields mean for vfat: time does not. Times are stored as UTC. - Names are compared without regard to case and hold up to 255 UTF-16 units. A file holds at most 4294967295 bytes. +- `manifest` says that the root object of a manifest given as content has + to declare `"order": "codepoint"`, see "Content". ### Assemble @@ -160,7 +163,8 @@ What the fields mean for vfat: Mode `assemble` creates the file system and copies the content into it, in one call. Mode `plan` computes the geometry and the size the content -needs. It writes nothing. +needs. It writes nothing. It reads a manifest once, from its start to +its end, so the manifest can come through a pipe. Mode `assemble` does not format over what the image holds. It fails with `ImageNotEmpty` when the part of the image that it would format holds a @@ -178,6 +182,8 @@ How the image is sized: exact size the content needs. It is never shrunk. - With a `size`, the file system gets that size. Content that does not fit fails with `TooSmall` before anything is written. +- Content is planned first. A manifest is read twice then, so it has to + be a regular file. - Without content, a regular image file is grown to `size`. An empty image file without a `size` fails with `SizeRequired`. - A block device is never resized. @@ -283,6 +289,11 @@ manifest names its paths from the root, so with a manifest `path` has to be `/`. Without content, `Populate` creates an empty directory at `path`. With `parents`, an existing directory at `path` is accepted. +Content that fails to go in leaves the file system marked as not cleanly +unmounted, as after a crash, with what was complete, unless nothing was +written yet. A manifest that is refused at its first object leaves the +file system as it was. + The reply carries the counts `files`, `directories`, `bytes` and `skipped`, and with a `manifestSink` also `omitted`. @@ -383,10 +394,45 @@ what the content is: | Directory | given | The tree the manifest describes. File references are resolved below the directory. | | none | given | Only for `Assemble` in mode `plan`, which needs no data. | -Other combinations fail with `InvalidParameter`. When a manifest's -contents come from a directory, every file the manifest names is checked -first. A file that is missing, not a regular file or of the wrong size -fails the call with `SourceMismatch` before the image is changed. +Other combinations fail with `InvalidParameter`. + +A manifest is read one record at a time, and what a record describes is +written when the record comes. So a manifest of any size can come through +a pipe, unless it is planned before its content is written: `Assemble` in +mode `assemble` plans its content first, so there it has to be a regular +file. A pipe fails with `BadFileDescriptor` and reason `wrongType` then. +Mode `plan` reads the manifest once and takes a pipe. A plan keeps the +name of every file and directory of the manifest, so the memory +`Assemble` uses grows with the manifest. + +When the file contents come from a stream, the manifest and the stream +are read in lockstep: a record of the manifest, then the contents of the +file it describes, then the next record. A client that passes both as +pipes has to write them at the same time, from two threads or with +`poll()`. A client that writes all of the manifest before the contents +can deadlock: it waits for room in the manifest pipe while the service +waits for contents. + +The root object of a manifest has to declare `"order": "codepoint"`, and +its objects have to be in that order. The manifests ufat writes are. A +manifest without the declaration fails with `InvalidManifest` and reason +`noOrder`, also when its objects are sorted. `systemd-manifest make` sorts +its output this way, and declares it since systemd commit 330fab5e90, +which is not in a release yet. An object out of order fails with reason +`outOfOrder` or `misplaced`. A name that comes twice fails with reason +`duplicateName` when it comes right after itself or right after the +objects below the directory it names, and with reason `outOfOrder` +otherwise. + +When a manifest's contents come from a directory, each file is looked up +when it is copied. The contents are the part of the file that starts at +the offset the manifest gives and is as long as the manifest says, +whatever else the file holds. A file that is missing or not a regular +file fails the call with `SourceMismatch`. A file that is too short for +the contents, or not of the `originalSize` the manifest gives for it, +fails with `ContentMismatch` and reason `size`. `sizeBytes` is the size of +the file and `expectedSizeBytes` the size it needs. A file that changes +while it is read fails with `ContentMismatch` and reason `sourceChanged`. Symbolic links below a source directory are followed. They are resolved below that directory and never lead out of it. @@ -397,14 +443,23 @@ The other fields of `Content`: |---|---| | `manifest` | A UAPI.16 manifest: `fileDescriptor` names it. `checkValidity`, true by default, rejects revoked entries and entries outside their validity window with `EntryNotValid`. | | `times` | `preserve` keeps modification times. This is the default. `fixed` sets every entry to the time stamp. `clamp` keeps times up to the time stamp and sets later ones to it. | -| `unsupported` | `skip`, the default, leaves out what FAT cannot store and counts it in `skipped`. `fail` fails with `ContentNotSupported` before anything is written. | +| `unsupported` | `skip`, the default, leaves out what FAT cannot store and counts it in `skipped`. `fail` fails with `ContentNotSupported`: for a tree before anything is written, for a manifest when the object's record comes. | | `replace` | Replaces existing files. True by default. With `false`, an existing file fails with `FileExists`. | | `extendedAttributes`, `uid`, `gid` | Accepted and ignored. FAT stores none of them. | | `manifestSink` | Writes a UAPI.16 manifest of the whole volume after the content is in. | What FAT cannot store: sockets, FIFOs and device nodes in a tree, and -manifest entries that need a `url`, an `encoding` or an `offset`, that -refer to a sub-manifest, or that have an inode type FAT does not have. +manifest entries whose contents are only at a `url` or in an `encoding`, +that refer to a sub-manifest, or that have an inode type FAT does not +have. With `skip`, a directory that is left out takes everything below it +along, and each entry counts in `skipped`. A file larger than 4294967295 +bytes fails with `TooLarge` whatever `unsupported` says. + +Contents that start at an `offset` in their file can only come from a +directory. A stream has the contents of each file and nothing else of it. +So with a stream, an entry with an `offset` fails with +`ContentNotSupported` and `what` set to `offset` when its record comes, +whatever `unsupported` says. The sizes and SHA-256 hashes in a manifest are verified while the contents are copied. A mismatch fails with `ContentMismatch`. @@ -412,7 +467,9 @@ contents are copied. A mismatch fails with `ContentMismatch`. A stream has to end after the last file. A stream that ends early fails with `ContentMismatch` and reason `streamEnded`, for the file it ended in. A stream with more data after the last file fails with -`ContentMismatch` and reason `size`, for the last file. +`ContentMismatch` and reason `size`, for the last file. That is found +when the manifest has ended, and the last file is in the file system +then. The `name` of `SourceMismatch` and `ContentMismatch` is the name of the file's record in the manifest, such as `loader/loader.conf`. @@ -489,7 +546,7 @@ Each parameter needs a descriptor of a certain kind: |---|---| | `image.fileDescriptor` | A regular file or a block device. Open read-write for `Assemble` in mode `assemble`, `Populate` and `Remove`. Read-only or read-write for `Describe`, `List` and `Check`. | | `content.sourceFileDescriptor` | A directory, a regular file or a pipe, open read-only. | -| `content.manifest.fileDescriptor` | A regular file or a pipe, open read-only. A manifest of any size can be passed this way. | +| `content.manifest.fileDescriptor` | A regular file or a pipe, open read-only. A manifest of any size can be passed this way. `Assemble` in mode `assemble` needs a regular file. | | `manifestSink.fileDescriptor` | A regular file or a pipe, open for writing. `O_APPEND` is allowed. | The service checks every descriptor before it uses it. The call fails @@ -504,11 +561,13 @@ descriptor: - is not open read-write for a method that writes (`notReadWrite`), - is not open read-only for a source or a manifest (`notReadOnly`), - is not open for writing for a manifest sink (`notWritable`), -- is not of the type the parameter needs (`wrongType`). +- is not of the type the parameter needs (`wrongType`), also a manifest + on a pipe for `Assemble` in mode `assemble`. -All descriptors are checked, and the manifest is read and verified, -before the image is opened. A call that fails this way leaves the image -unchanged. +All descriptors are checked, and the first record of a manifest is read, +before the image is opened. `Assemble` in mode `assemble` reads the +whole manifest before the image is changed. A call that fails this way +leaves the image unchanged. A pipe that is made non-blocking during the call fails it with `BadFileDescriptor` and the reason `flags` once the service has to wait @@ -550,10 +609,10 @@ The service returns no text. Every error is a name with typed fields. | `InvalidName` | A name FAT cannot store. | `name`, `reason` (`empty`, `dotComponent`, `invalidCharacter`, `leadingSpace`, `trailingSpaceOrDot`, `tooLong`) | | `InvalidLabel` | A label that breaks the label rules. | `label`, `reason` (`tooLong`, `invalidCharacter`) | | `InvalidIdentifier` | A serial number that is not `XXXX-XXXX` or eight hex digits. | `identifier`, `reason` (`malformed`) | -| `InvalidManifest` | The manifest cannot be parsed or is inconsistent. | `reason`, `record`, `name`, `field` | -| `SourceMismatch` | A file the manifest names is missing from the source directory, not a regular file, or of the wrong size. | `name`, `reason` (`missing`, `notRegular`, `size`), `sizeBytes`, `expectedSizeBytes` | -| `ContentMismatch` | Copied contents do not match the manifest. | `name`, `reason` (`size`, `hash`, `streamEnded`), `sizeBytes`, `expectedSizeBytes` | -| `ContentNotSupported` | Content FAT cannot store, with `unsupported` set to `fail`. | `what` (`url`, `encoding`, `offset`, `transport`, `subManifest`, `inodeType`), `name`, `value` | +| `InvalidManifest` | The manifest cannot be parsed or is inconsistent. A key twice in an object is reason `duplicateKey`. With reason `unlistedFeature`, `field` names the field of a feature the manifest does not list, such as `mTimeNSec`. | `reason`, `record`, `name`, `field` | +| `SourceMismatch` | A file the manifest names is missing from the source directory, or not a regular file. | `name`, `reason` (`missing`, `notRegular`) | +| `ContentMismatch` | Copied contents do not match the manifest, or a file of the source directory is too short for them or changed while it was read. | `name`, `reason` (`size`, `hash`, `streamEnded`, `sourceChanged`), `sizeBytes`, `expectedSizeBytes` | +| `ContentNotSupported` | Content FAT cannot store, with `unsupported` set to `fail`. Contents at an `offset` that come from a stream. | `what` (`offset`, `subManifest`, `inodeType`, or `transport` for contents only at a URL or in an encoding, which `value` names), `name`, `value` | | `EntryNotValid` | A manifest entry is revoked or outside its validity window. | `name`, `reason` (`revoked`, `notYetValid`, `expired`) | | `NotReproducible` | `reproducible` without `identifier` or `timestampUSec`. | `reason` (`identifierRequired`, `timestampRequired`) | | `ImageBusy` | The block device is mounted or claimed by another process. | none | @@ -628,8 +687,9 @@ Notes: - Files below a passed directory are opened with the service's credentials. This is why only root and the service's own user may connect. -- Memory use does not grow with the volume. 512M leaves room for several - connections. +- Memory use does not grow with the volume, and not with a manifest that + `Populate` writes. `Assemble` keeps the names of a manifest while it + plans it. 512M leaves room for several connections. - `DynamicUser=yes` works. Only root can then connect. - Do not set `LimitFSIZE=`. A write past the limit kills the process with SIGXFSZ. diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index f226d5f..00eb67b 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -14,16 +14,19 @@ use fat::format::{self, FormatOptions, VolumeId}; use fat::fsck; use fat::host; use fat::layout::MIN_SECTOR_SIZE; -use fat::manifest::{self, AssembleOptions, DirectorySource, Features, HostTree, StreamSource, WriteReport}; +use fat::manifest::{ + AssembleFlags, AssembleObserver, AssembleOptions, DirectorySource, Features, HostTree, Name, PinnedDirectory, + Problem, SkipReason, StreamSource, WriteReport, +}; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, TimePolicy}; use fat::probe::Prober; use fat::time::civil_from_days; use fat::volume::Volume; -use fat::{bail, err, Context, Detail, Error, Result}; +use fat::{bail, err, Context, DescriptorProblem, Detail, Error, ManifestProblem, Result}; use crate::service; -use crate::util::{self, ImageFlags}; +use crate::util::{self, ImageFlags, ManifestInput, ManifestUse}; const USAGE: &str = "\ Usage: ufat COMMAND [OPTIONS...] ARGS... @@ -59,7 +62,11 @@ Without a SOURCE it creates the directory --path. A SOURCE is a directory tree, or for populate one file. With --manifest the one SOURCE is the tree the manifest describes, where its file contents are -read, or - for the contents on standard input, back to back in manifest order: +read, or - for the contents on standard input, back to back in manifest order. +The manifest has to declare \"order\": \"codepoint\" and be in that order. +assemble with a SOURCE reads the manifest twice, to plan the file system and +to fill it, and needs it in a regular file. populate, assemble --plan and +assemble without a SOURCE read it once and take a pipe: --manifest PATH Build what the UAPI.16 manifest at PATH, or on standard input for -, describes --no-check-validity Accept revoked and expired manifest entries @@ -419,13 +426,14 @@ enum Source { None, /// A directory tree, pinned. Tree { path: PathBuf, dir: OwnedFd }, - /// The manifest `--manifest` named, read once, and where the contents - /// of its files come from. + /// The manifest `--manifest` named, open with its root file object + /// read, and where the contents of its files come from. Manifest { /// How messages name the manifest: its path, or standard input. name: String, - manifest: Box, - /// None for the commands that only size. + manifest: Box, + /// None for the commands that only size, and once the contents + /// were written. contents: Option, }, } @@ -434,17 +442,29 @@ enum Source { #[derive(Clone, Copy, PartialEq, Eq)] enum Sourcing { /// The caller sizes a file system for the SOURCE and writes nothing of - /// it. A manifest takes no SOURCE then, since it carries the sizes. + /// it. A manifest takes no SOURCE then, since it carries the sizes, and + /// is planned on from its root file object, so it is read once. Size, - /// The caller writes the SOURCE into a file system. A manifest takes one - /// SOURCE then: the directory its file contents are read from, or "-" - /// for standard input. - Write, + /// The caller writes the SOURCE into a file system, and reads a manifest + /// as the use says. A manifest takes one SOURCE then: the directory its + /// file contents are read from, or "-" for standard input. + Write(ManifestUse), } -/// Reads and parses the manifest `path` names, or the one on standard input -/// for "-". Returns it with the name messages give it. -fn read_manifest(path: &Path) -> Result<(manifest::Manifest, String)> { +impl Sourcing { + /// What the command does with a manifest. + fn manifest_use(self) -> ManifestUse { + match self { + Sourcing::Size => ManifestUse::PlanOnly, + Sourcing::Write(manifest_use) => manifest_use, + } + } +} + +/// Opens the manifest `path` names, or the one on standard input for "-", +/// for `manifest_use`, and reads its first record. Returns it with the name +/// messages give it. +fn read_manifest(path: &Path, manifest_use: ManifestUse) -> Result<(ManifestInput, String)> { let (file, name) = if path == Path::new("-") { // A descriptor of our own, since the reader closes it. let fd = std::io::stdin().as_fd().try_clone_to_owned()?; @@ -452,14 +472,25 @@ fn read_manifest(path: &Path) -> Result<(manifest::Manifest, String)> { } else { (host::open_file(path)?, path.display().to_string()) }; - let manifest = util::read_manifest(file).map_err(|e| { - if e.is_manifest() { - e.context(format_args!("{} is not a UAPI.16 manifest", name)) - } else { - e.context(format_args!("cannot read {} as a manifest", name)) - } + let input = ManifestInput::open(file, manifest_use).map_err(|e| match e.detail() { + // A manifest, but not one ufat takes. + Some(Detail::Manifest { + problem: ManifestProblem::Malformed(Problem::NoOrder), + .. + }) => e.context(&name), + // A pipe, refused before anything was read from it. + Some(Detail::Descriptor { + problem: DescriptorProblem::WrongType, + .. + }) => err!( + errno::EINVAL, + "{} is not a regular file: assemble with a SOURCE needs the manifest in one", + name + ), + _ if e.is_manifest() => e.context(format_args!("{} is not a UAPI.16 manifest", name)), + _ => e.context(format_args!("cannot read {} as a manifest", name)), })?; - Ok((manifest, name)) + Ok((input, name)) } impl Source { @@ -468,7 +499,9 @@ impl Source { /// With it, it is the directory the manifest describes or "-" for the /// file contents on standard input; [`Sourcing::Size`] takes none, the /// manifest carries the sizes. `--path` is for trees only. The SOURCE - /// arguments and `--path` are checked before anything is opened. + /// arguments and `--path` are checked before anything is opened. The + /// manifest is opened last, for what `sourcing` does with it, and its + /// root file object is read. fn open(args: &Args, paths: &[&Path], sourcing: Sourcing) -> Result { let Some(m) = args.path("manifest") else { return match paths { @@ -492,7 +525,7 @@ impl Source { ), }; }; - if m == Path::new("-") && sourcing == Sourcing::Write && matches!(paths, [p] if *p == Path::new("-")) { + if m == Path::new("-") && sourcing != Sourcing::Size && matches!(paths, [p] if *p == Path::new("-")) { bail!( errno::EINVAL, "--manifest - and a SOURCE of - cannot both read standard input" @@ -510,17 +543,17 @@ impl Source { errno::EINVAL, "--manifest carries the sizes, no SOURCE or --fit directory is taken with it" ), - (Sourcing::Write, [path]) if *path == Path::new("-") => Some(ContentOrigin::Stdin), - (Sourcing::Write, [path]) => Some(ContentOrigin::Directory { + (Sourcing::Write(_), [path]) if *path == Path::new("-") => Some(ContentOrigin::Stdin), + (Sourcing::Write(_), [path]) => Some(ContentOrigin::Directory { path: path.to_path_buf(), dir: host::open_dir(path)?, }), - (Sourcing::Write, _) => bail!( + (Sourcing::Write(_), _) => bail!( errno::EINVAL, "--manifest takes exactly one SOURCE: the directory the manifest describes, or - for the file contents on standard input" ), }; - let (manifest, name) = read_manifest(m)?; + let (manifest, name) = read_manifest(m, sourcing.manifest_use())?; Ok(Source::Manifest { name, manifest: Box::new(manifest), @@ -529,67 +562,59 @@ impl Source { } /// What can be checked before an image is created, formatted or - /// written: that the manifest and, under `--unsupported fail`, the tree - /// can be stored, and that every file the manifest names is below the - /// SOURCE with the size it says. + /// written: under `--unsupported fail`, that the tree can be stored. A + /// manifest is checked as it is written. fn check(&self, args: &Args) -> Result<()> { - let fail = fail_unsupported(args)?; match self { - Source::Tree { path, dir } if fail => { - let mut plan = Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)); - if let Some(skipped) = plan.add_tree(dir.as_fd(), dest(args), true)?.first() { + Source::Tree { .. } if fail_unsupported(args)? => { + self.add_to(&mut Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)), args)?; + } + _ => {} + } + Ok(()) + } + + /// Adds the source to a plan, the way [`Source::fill`] writes it, and + /// returns how many objects of a manifest are left out. Under + /// `--unsupported fail` what FAT cannot store of a tree fails the plan. + /// The plan reads the manifest once more from its start, so its content + /// can be written after. + fn add_to(&self, plan: &mut Plan, args: &Args) -> Result { + match self { + Source::None => Ok(0), + Source::Tree { path, dir } => { + let skipped = plan.add_tree(dir.as_fd(), dest(args), true)?; + if let (Some(skipped), true) = (skipped.first(), fail_unsupported(args)?) { bail!( errno::EINVAL, "{} cannot be stored on FAT", path.join(skipped).display() ); } + Ok(0) } - Source::Manifest { - name, - manifest, - contents, - } => { - if fail { - manifest.check_supported()?; - } - if let Some(ContentOrigin::Directory { path, dir }) = contents { - DirectorySource::new(dir.try_clone()?) - .follow_symlinks(true) - .verify(manifest) - .map_err(|e| { - e.context(format!( - "the files {} describes are not all below {}", - name, - path.display() - )) - })?; - } - } - Source::None | Source::Tree { .. } => {} + Source::Manifest { name, manifest, .. } => plan + .add_records(&mut manifest.plan_reader()?, assemble_flags(args)?) + .map_err(about_manifest(name)), } - Ok(()) } - /// Adds the source to a plan, the way [`Source::fill`] writes it. - fn add_to(&self, plan: &mut Plan, args: &Args) -> Result<()> { + /// Adds the source to a plan when nothing is written after it, and + /// returns how many objects of a manifest are left out. The manifest is + /// read on from its root file object, so it is read once. + fn into_plan(self, plan: &mut Plan, args: &Args) -> Result { match self { - Source::None => {} - Source::Tree { dir, .. } => { - plan.add_tree(dir.as_fd(), dest(args), true)?; - } - Source::Manifest { manifest, .. } => { - for skipped in plan.add_manifest(manifest)? { - eprintln!("ufat: not counted {}: it cannot be stored on FAT", skipped); - } - } + Source::Manifest { name, mut manifest, .. } => plan + .add_records(manifest.reader(), assemble_flags(args)?) + .map_err(about_manifest(&name)), + source => source.add_to(plan, args), } - Ok(()) } /// Writes the source into an open volume: the tree copied, or the - /// manifest assembled. - fn fill(&self, volume: &mut Volume, args: &Args) -> Result<()> { + /// manifest assembled while it is read, which takes the contents of its + /// files. + fn fill(&mut self, volume: &mut Volume, args: &Args) -> Result<()> { let copy = CopyOptions { times: time_policy(args)?, replace: !args.flag("no-replace"), @@ -619,37 +644,59 @@ impl Source { contents: origin, } => { let options = assemble_options(args)?; - let report = match origin { + let reader = manifest.reader(); + let report = match origin.take() { Some(ContentOrigin::Stdin) => { let stdin = std::io::stdin(); let mut lock = stdin.lock(); - volume.assemble(manifest, &mut StreamSource::new(&mut lock), &options)? + let mut source = StreamSource::new(&mut lock); + volume.assemble_with_observer(reader, &mut source, &options, &mut SkipNotes) + } + Some(ContentOrigin::Directory { path, dir }) => { + let mut source = DirectorySource::new(PinnedDirectory::new(dir).follow_symlinks(true)); + volume + .assemble_with_observer(reader, &mut source, &options, &mut SkipNotes) + .map_err(about_source_directory(&path)) } - Some(ContentOrigin::Directory { dir, .. }) => volume.assemble( - manifest, - &mut DirectorySource::new(dir.try_clone()?).follow_symlinks(true), - &options, - )?, None => bail!(errno::EINVAL, "a manifest needs a SOURCE to be filled from"), - }; + } + .map_err(about_manifest(name))?; if args.flag("verbose") { eprintln!("{}: {}", name, contents(report.files, report.directories, report.bytes)); } - for skipped in report.skipped { - eprintln!("ufat: skipped {}: it cannot be stored on FAT", skipped); - } } } Ok(()) } } +/// Says what an assembly leaves out, on standard error. +struct SkipNotes; + +impl AssembleObserver for SkipNotes { + fn skipped(&mut self, name: &Name, reason: SkipReason) { + match reason { + SkipReason::Unsupported => eprintln!("ufat: skipped {}: it cannot be stored on FAT", name), + _ => eprintln!("ufat: skipped {}: the directory it is in was skipped", name), + } + } +} + +/// How the command line asks an assembly, and the plan of one, to store a +/// manifest's objects: replacing what is there unless `--no-replace`, and +/// leaving out what FAT cannot store unless `--unsupported fail`. +fn assemble_flags(args: &Args) -> Result { + Ok(AssembleFlags::NONE + .with(AssembleFlags::REPLACE, !args.flag("no-replace")) + .with(AssembleFlags::SKIP_UNSUPPORTED, !fail_unsupported(args)?)) +} + +/// What the command line asks of an assembly. fn assemble_options(args: &Args) -> Result { let (time, _) = stamp_time(args)?; Ok(AssembleOptions { default_time: time, - replace: !args.flag("no-replace"), - skip_unsupported: !fail_unsupported(args)?, + flags: assemble_flags(args)?, now_usec: if args.flag("no-check-validity") { None } else { @@ -658,6 +705,21 @@ fn assemble_options(args: &Args) -> Result { }) } +/// Names the manifest `name` in an error that is about it. +fn about_manifest(name: &str) -> impl Fn(Error) -> Error + '_ { + move |e| if e.is_manifest() { e.context(name) } else { e } +} + +/// Names the directory `path`, where the contents of a manifest's files +/// are looked up, in an error about one of its files: one that is missing +/// or not a regular file, or whose contents are not what the manifest says. +fn about_source_directory(path: &Path) -> impl Fn(Error) -> Error + '_ { + move |e| match e.detail() { + Some(Detail::Source { .. } | Detail::Content { .. }) => e.context(path.display()), + _ => e, + } +} + /// Whether `--write-manifest -` puts the manifest on standard output. What /// the command prints there otherwise goes to standard error then. fn manifest_to_stdout(args: &Args) -> bool { @@ -752,8 +814,16 @@ fn plan(args: &Args) -> Result<()> { } let options = format_options(args)?; let mut plan = Plan::new(PlanOptions::from_format_options(&options, None)?); + // Nothing is written after a plan, so it reads the manifest on from its + // root file object, and the manifest is read once. A pipe will do. let source = Source::open(args, &args.positional_paths(), Sourcing::Size)?; - source.add_to(&mut plan, args)?; + let skipped = source.into_plan(&mut plan, args)?; + if skipped > 0 { + eprintln!( + "ufat: not counted: {}", + plural(skipped, "object FAT cannot store", "objects FAT cannot store") + ); + } let e = plan.estimate()?; if let Some(size) = args.size("size")? { if e.size() > size { @@ -805,9 +875,15 @@ fn assemble_empty(args: &Args, path: &Path) -> Result { format::format(&device, &options)?; return Volume::open(device); } - let source = Source::open(args, &fit, Sourcing::Size)?; - let (volume, estimate) = util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args)) - .map_err(|e| e.into_error(path))?; + // Nothing of the content is written, so a manifest is planned on from + // its root file object, through the reader that read it, and is read + // once: a pipe will do. fit_and_format() plans the content once. + let mut source = Some(Source::open(args, &fit, Sourcing::Size)?); + let mut add = |plan: &mut Plan| match source.take() { + Some(source) => source.into_plan(plan, args).map(drop), + None => bail!(errno::EINVAL, "the content is planned once"), + }; + let (volume, estimate) = util::fit_and_format(&target, &mut options, &mut add).map_err(|e| e.into_error(path))?; report_estimate(args, path, &estimate); Ok(volume) } @@ -821,8 +897,9 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result "--fit sizes an empty file system; with a SOURCE the file system is sized for it" ); } - let source = Source::open(args, paths, Sourcing::Write)?; - // Better to learn about a bad manifest or tree before an image is sized + // The manifest is planned before its content is written. + let mut source = Source::open(args, paths, Sourcing::Write(ManifestUse::Plan))?; + // Better to learn about a tree FAT cannot hold before an image is sized // and formatted. source.check(args)?; let mut options = format_options(args)?; @@ -832,8 +909,9 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result size: args.size("size")?, flags: args.image_flags(), }; - let (mut v, estimate) = util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args)) - .map_err(|e| e.into_error(path))?; + let (mut v, estimate) = + util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args).map(drop)) + .map_err(|e| e.into_error(path))?; report_estimate(args, path, &estimate); match source.fill(&mut v, args) { Ok(()) => Ok(v), @@ -1023,13 +1101,23 @@ fn cmd_populate(argv: &[OsString]) -> Result<()> { } return v.close(); } - let source = Source::open(&args, &paths, Sourcing::Write)?; + let mut source = Source::open(&args, &paths, Sourcing::Write(ManifestUse::Write))?; source.check(&args)?; let mut v = open_volume(&args, image, Access::ReadWrite)?; if matches!(source, Source::Tree { .. }) { ensure_dir(&mut v, path, parents, time)?; } - source.fill(&mut v, &args)?; + if let Err(e) = source.fill(&mut v, &args) { + // Once something was written, the file system is left marked as not + // cleanly unmounted, as after a crash, with what was complete. A + // SOURCE refused before that, such as a manifest refused at its + // first object, leaves it as it was. An error of the close is not + // the one the user needs to hear about. + if v.is_writing() { + let _ = v.close_unfinished(); + } + return Err(e); + } if let Some(m) = args.path("write-manifest") { write_manifest(&v, m)?; } diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index b52cf52..ee31d97 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -27,19 +27,21 @@ use fat::format::{self, FormatOptions, VolumeId}; use fat::fsck::{self, Problem}; use fat::host; use fat::layout::{self, LayoutParams, MAX_CLUSTER_SIZE, MAX_SECTOR_SIZE, MIN_CLUSTERS, MIN_SECTOR_SIZE}; -use fat::manifest::{AssembleOptions, AssembleReport, DirectorySource, Features, Manifest, StreamSource, WriteReport}; +use fat::manifest::{ + AssembleFlags, AssembleOptions, AssembleReport, DirectorySource, Features, Finalize, Order, PinnedDirectory, + Sha256Context, StreamSource, WriteReport, +}; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, CopyReport, TimePolicy}; use fat::probe::Prober; use fat::progress::Progress; -use fat::sha256::Sha256; -use fat::sha512::Sha512; +use fat::sha512::Sha512Context; use fat::volume::{Metadata, Volume}; use fat::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason, UnsupportedKind}; use json::{Object, Value}; use varlink::{Activation, Call, Connection, Info, Reply, Server, Service}; -use crate::util; +use crate::util::{self, ManifestInput, ManifestUse}; /// The interface description, served verbatim. pub(crate) const INTERFACE: &str = include_str!("../../../docs/org.uapi-group.FileSystem.varlink"); @@ -117,19 +119,20 @@ fn invalid(parameter: &str) -> Failure { Failure::Invalid(parameter.to_string()) } -/// Turns the error of a passed descriptor that cannot be used, found when -/// it is vetted or when it is read or written (see [`host::PassedStream`]), -/// into the interface's error for it, naming the parameter; anything else -/// passes through. +/// Turns the error of a passed descriptor that cannot be used into the +/// interface's error for it, naming `parameter` where the error names no +/// parameter itself: the vetting of the image does not, nor does a manifest +/// refused for a plan. The errors of the passed streams and their vetting +/// name theirs, see [`host::passed_stream`], and [`map_error`] maps them. +/// Anything else passes through. fn bad(parameter: &str) -> impl Fn(fat::Error) -> Failure + '_ { move |e| { - if matches!(e.detail(), Some(Detail::Descriptor { .. })) { - Failure::BadDescriptor { - parameter: parameter.to_string(), - error: e, - } - } else { - Failure::Other(e) + let Some(&Detail::Descriptor { parameter: named, .. }) = e.detail() else { + return Failure::Other(e); + }; + Failure::BadDescriptor { + parameter: named.unwrap_or(parameter).to_string(), + error: e, } } } @@ -252,9 +255,14 @@ fn map_error(e: &fat::Error) -> varlink::Error { optional(&mut o, "block", *cluster); interface_error("Corrupt", o) } - // A descriptor problem is reported by the method that knows which - // parameter it came with, see `bad`; one without is a plain errno. - Detail::Descriptor { .. } => varlink::Error::system(e.errno()), + // A descriptor problem that names the parameter it came with is + // that parameter's. One that names none is named by the method that + // knows it, see `bad`, or is a plain errno. + Detail::Descriptor { + parameter: Some(parameter), + .. + } => bad_file_descriptor(parameter, e), + Detail::Descriptor { parameter: None, .. } => varlink::Error::system(e.errno()), Detail::Manifest { problem, record, @@ -267,17 +275,10 @@ fn map_error(e: &fat::Error) -> varlink::Error { optional(&mut o, "field", field.as_deref()); interface_error("InvalidManifest", o) } - Detail::Source { - name, - problem, - size, - expected, - } => { - let mut o = json::object! { "name" => name.as_str(), "reason" => problem.as_str() }; - optional(&mut o, "sizeBytes", *size); - optional(&mut o, "expectedSizeBytes", *expected); - interface_error("SourceMismatch", o) - } + Detail::Source { name, problem } => interface_error( + "SourceMismatch", + json::object! { "name" => name.as_str(), "reason" => problem.as_str() }, + ), Detail::Content { name, problem, @@ -303,18 +304,22 @@ fn map_error(e: &fat::Error) -> varlink::Error { } } +/// BadFileDescriptor for the error `e` of the descriptor passed as +/// `parameter`. +fn bad_file_descriptor(parameter: &str, e: &fat::Error) -> varlink::Error { + let (problem, flags) = match e.detail() { + Some(Detail::Descriptor { problem, flags, .. }) => (problem.as_str(), *flags), + _ => ("wrongType", None), + }; + let mut o = json::object! { "parameter" => parameter, "reason" => problem }; + optional(&mut o, "flags", flags); + interface_error("BadFileDescriptor", o) +} + fn fail(f: Failure) -> varlink::Error { match f { Failure::Invalid(parameter) => varlink::Error::invalid_parameter(¶meter), - Failure::BadDescriptor { parameter, error } => { - let (problem, flags) = match error.detail() { - Some(Detail::Descriptor { problem, flags }) => (problem.as_str(), *flags), - _ => ("wrongType", None), - }; - let mut o = json::object! { "parameter" => parameter, "reason" => problem }; - optional(&mut o, "flags", flags); - interface_error("BadFileDescriptor", o) - } + Failure::BadDescriptor { parameter, error } => bad_file_descriptor(¶meter, &error), Failure::TooSmall { minimal, actual } => interface_error( "TooSmall", json::object! { @@ -780,21 +785,24 @@ pub(crate) fn capabilities() -> fat::Result { "nameLengthMax" => 255, "nameUnit" => "utf16Units", "fileSizeMaxBytes" => fat::volume::MAX_FILE_SIZE, + // A manifest has to declare the code point order, see + // ManifestInput::open. + "manifest" => json::object! { "order" => Order::CodePoint.as_str() }, }) } /// The hash of a file system as it is in its image, as `imageHash` asks /// for it. pub(crate) enum Hash { - Sha256(Sha256), - Sha512(Sha512), + Sha256(Sha256Context), + Sha512(Sha512Context), } impl Hash { pub(crate) fn new(algorithm: &str) -> Option { match algorithm { - "sha256" => Some(Hash::Sha256(Sha256::new())), - "sha512" => Some(Hash::Sha512(Sha512::new())), + "sha256" => Some(Hash::Sha256(Sha256Context::default())), + "sha512" => Some(Hash::Sha512(Sha512Context::default())), _ => None, } } @@ -808,8 +816,8 @@ impl Hash { let n = (device.len() - offset).min(HASH_STEP as u64) as usize; device.read_at(offset, &mut buf[..n])?; match &mut self { - Hash::Sha256(h) => h.update(&buf[..n]), - Hash::Sha512(h) => h.update(&buf[..n]), + Hash::Sha256(context) => context.update(&buf[..n]), + Hash::Sha512(context) => context.update(&buf[..n]), } offset += n as u64; progress(&Progress { @@ -818,8 +826,8 @@ impl Hash { }); } Ok(match self { - Hash::Sha256(h) => fat::sha256::to_hex(&h.finalize()), - Hash::Sha512(h) => fat::sha512::to_hex(&h.finalize()), + Hash::Sha256(context) => context.finalize().to_string(), + Hash::Sha512(context) => fat::sha512::to_hex(&context.finalize()), }) } } @@ -848,7 +856,7 @@ impl Sink { fn take(p: &Params<'_>, c: &mut Connection) -> Outcome { let fd = required_fd(c, p, "fileDescriptor").map_err(|_| invalid("manifestSink"))?; - let file = host::passed_sink(fd).map_err(bad("manifestSink"))?; + let file = host::passed_sink(fd, "manifestSink")?; let features = match p.0.get("features") { None | Some(Value::Null) => Features::DEFAULT, Some(_) => p @@ -867,9 +875,7 @@ impl Sink { fn write(self, volume: &Volume, progress: &mut dyn FnMut(&Progress)) -> Outcome { let root_time = volume.root_time()?; let out = BufWriter::new(self.file); - volume - .write_manifest_with_progress(root_time, self.features, out, progress) - .map_err(bad("manifestSink")) + Ok(volume.write_manifest_with_progress(root_time, self.features, out, progress)?) } } @@ -881,11 +887,11 @@ enum Fill { /// One regular file, Populate only. File(host::PassedStream), /// A manifest with its files below a directory. - FromDirectory(Manifest, DirectorySource), + FromDirectory(ManifestInput, DirectorySource), /// A manifest with its files' contents in a stream. - FromStream(Manifest, host::PassedStream), + FromStream(ManifestInput, host::PassedStream), /// A manifest alone, enough for a plan. - ManifestOnly(Manifest), + ManifestOnly(ManifestInput), } /// Which method takes the content: what it may be depends on it. @@ -931,7 +937,7 @@ impl Counts { files: r.files, directories: r.directories, bytes: r.bytes, - skipped: r.skipped.len() as u64, + skipped: r.skipped, } } @@ -964,9 +970,10 @@ fn refuse_skipped(skipped: &[PathBuf]) -> fat::Result<()> { } } -/// The `Content` parameter, taken and vetted: every descriptor checked, -/// the manifest parsed, the source verified against it, before any image -/// is touched. +/// The `Content` parameter, taken and vetted: every descriptor checked +/// and the root file object of the manifest read, before any image is +/// touched. The rest of the manifest is read while its content is +/// written. struct Content { fill: Option, /// The fixed or clamping time of the time policy, and the time of @@ -986,22 +993,29 @@ struct Content { } impl Content { - /// Takes the content's descriptors and reads its manifest. `time` is - /// the content's time, Assemble's `timestampUSec` or Populate's, the + /// Takes the content's descriptors and reads the root file object of + /// its manifest, which is used as `manifest_use` says. `time` is the + /// content's time, Assemble's `timestampUSec` or Populate's, the /// current time when neither was given. - fn take(p: &Params<'_>, c: &mut Connection, time: SystemTime, taker: Taker) -> Outcome { + fn take( + p: &Params<'_>, + c: &mut Connection, + time: SystemTime, + taker: Taker, + manifest_use: ManifestUse, + ) -> Outcome { let source = match fd_param(c, p, "sourceFileDescriptor")? { None => None, - Some(fd) => Some(host::passed_source(fd).map_err(bad("sourceFileDescriptor"))?), + Some(fd) => Some(host::passed_source(fd, "sourceFileDescriptor")?), }; let mut check_validity = true; let manifest = match p.object("manifest") { None => None, Some(m) => { let fd = required_fd(c, &m, "fileDescriptor").map_err(|_| invalid("manifest"))?; - let file = host::passed_stream(fd).map_err(bad("manifest"))?; + let file = host::passed_stream(fd, "manifest")?; check_validity = m.bool("checkValidity", true); - Some(util::read_manifest(file).map_err(bad("manifest"))?) + Some(ManifestInput::open(file, manifest_use).map_err(bad("manifest"))?) } }; let sink = match p.object("manifestSink") { @@ -1016,16 +1030,11 @@ impl Content { let fail_unsupported = p.str("unsupported") == Some("fail"); // extendedAttributes, uid and gid are accepted and ignored: FAT // keeps none of them. - if fail_unsupported { - if let Some(m) = &manifest { - m.check_supported()?; - } - } let source_mtime = match &source { Some(host::PassedSource::Directory(dir)) => File::from(dir.try_clone()?).metadata()?.modified().ok(), _ => None, }; - let manifest_mtime = manifest.as_ref().and_then(|m| m.root.mtime()); + let manifest_mtime = manifest.as_ref().and_then(|m| m.root().inode.mtime()); let fill = match (source, manifest) { (None, None) => None, // A manifest names files that have to come from somewhere, @@ -1046,8 +1055,7 @@ impl Content { // Symbolic links are followed, resolved below the source // directory and never outside it; the interface has no // switch for that. - let source = DirectorySource::new(dir).follow_symlinks(true); - source.verify(&m)?; + let source = DirectorySource::new(PinnedDirectory::new(dir).follow_symlinks(true)); Some(Fill::FromDirectory(m, source)) } (Some(host::PassedSource::Stream(file)), Some(m)) => Some(Fill::FromStream(m, file)), @@ -1092,7 +1100,7 @@ impl Content { } } Some(Fill::FromDirectory(m, _) | Fill::FromStream(m, _) | Fill::ManifestOnly(m)) => { - plan.add_manifest(m)?; + plan.add_records(&mut m.plan_reader()?, self.assemble_flags())?; } Some(Fill::File(_)) | None => { return Err( @@ -1104,6 +1112,19 @@ impl Content { Ok(()) } + /// Puts the content into `plan`, for a plan and nothing else. A + /// manifest is read on from its root file object, so it is read once. + fn plan_once(self, plan: &mut Plan) -> fat::Result<()> { + let flags = self.assemble_flags(); + match self.fill { + Some(Fill::FromDirectory(mut m, _) | Fill::FromStream(mut m, _) | Fill::ManifestOnly(mut m)) => { + plan.add_records(m.reader(), flags)?; + Ok(()) + } + _ => self.plan(plan), + } + } + /// Under UnsupportedPolicy fail, walks a tree that is to go below /// `dest` before anything is copied, so that an entry FAT cannot hold /// fails the call with nothing written. @@ -1115,6 +1136,15 @@ impl Content { Ok(()) } + /// How an assembly of the manifest, and its plan, store its objects: + /// replacing what is there with replace, and leaving out what FAT + /// cannot store unless UnsupportedPolicy fail. + fn assemble_flags(&self) -> AssembleFlags { + AssembleFlags::NONE + .with(AssembleFlags::REPLACE, self.replace) + .with(AssembleFlags::SKIP_UNSUPPORTED, !self.fail_unsupported) + } + /// Puts the content into the volume at `dest`: the directory a tree goes /// below, the path of one file. A manifest's tree goes below the root. fn write_into(&mut self, v: &mut Volume, dest: &str, progress: &mut dyn FnMut(&Progress)) -> Outcome { @@ -1125,8 +1155,7 @@ impl Content { }; let assembly = AssembleOptions { default_time: self.time, - replace: self.replace, - skip_unsupported: !self.fail_unsupported, + flags: self.assemble_flags(), now_usec: if self.check_validity { Some(fat::time::to_usec(util::now())) } else { @@ -1141,13 +1170,18 @@ impl Content { bytes: v.copy_file_with_progress(file.as_fd(), dest, ©, progress)?, ..Counts::default() }, - Some(Fill::FromDirectory(m, mut source)) => { - Counts::of_assembly(&v.assemble_with_progress(&m, &mut source, &assembly, progress)?) - } - Some(Fill::FromStream(m, mut file)) => Counts::of_assembly( - &v.assemble_with_progress(&m, &mut StreamSource::new(&mut file), &assembly, progress) - .map_err(bad("sourceFileDescriptor"))?, - ), + Some(Fill::FromDirectory(mut m, mut source)) => Counts::of_assembly(&v.assemble_with_observer( + m.reader(), + &mut source, + &assembly, + &mut |p: &Progress| progress(p), + )?), + Some(Fill::FromStream(mut m, mut file)) => Counts::of_assembly(&v.assemble_with_observer( + m.reader(), + &mut StreamSource::new(&mut file), + &assembly, + &mut |p: &Progress| progress(p), + )?), // Never taken for a method that writes, see Content::take. Some(Fill::ManifestOnly(_)) => return Err(invalid("content")), }) @@ -1197,11 +1231,18 @@ impl FileSystemService { }; let options = format_options(p.object("options"))?; let content_time = options.format.timestamp.unwrap_or_else(util::now); - let taker = if plan_only { Taker::Plan } else { Taker::Assemble }; + // The content is planned. A plan alone reads a manifest once, on + // from its root file object; an assembly reads it for the plan from + // its start, and once more while its content is written. + let (taker, manifest_use) = if plan_only { + (Taker::Plan, ManifestUse::PlanOnly) + } else { + (Taker::Assemble, ManifestUse::Plan) + }; let content = match p.object("content") { None => None, Some(cp) => { - let content = Content::take(&cp, c, content_time, taker)?; + let content = Content::take(&cp, c, content_time, taker, manifest_use)?; if matches!(content.shape(), Shape::Nothing) { return Err(invalid("content")); } @@ -1242,7 +1283,7 @@ impl FileSystemService { let time = p.time("timestampUSec")?.unwrap_or_else(util::now); let mut content = match p.object("content") { None => None, - Some(cp) => Some(Content::take(&cp, c, time, Taker::Populate)?), + Some(cp) => Some(Content::take(&cp, c, time, Taker::Populate, ManifestUse::Write)?), }; // A manifest names its paths from the root. if matches!(content.as_ref().map(Content::shape), Some(Shape::Manifest)) && path != "/" { @@ -1260,12 +1301,28 @@ impl FileSystemService { } } } - _ => { + Shape::Tree => { ct.check_tree(path)?; ensure_dir(&mut v, path, parents, time)?; } + // A manifest names its paths from the root, which is + // there. + Shape::Manifest | Shape::Nothing => {} + } + match ct.write_into(&mut v, path, &mut |p| r.tick(p)) { + Ok(counts) => counts, + Err(e) => { + // Once something was written, the filesystem is + // left marked as not cleanly unmounted, as after a + // crash, with what was complete. Content refused + // before that, such as a manifest refused at its + // first object, leaves it as it was. + if v.is_writing() { + let _ = v.close_unfinished(); + } + return Err(e); + } } - ct.write_into(&mut v, path, &mut |p| r.tick(p))? } // Nothing to put in: an empty directory at path. _ => { @@ -1390,8 +1447,8 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more // for the label, or to carry the root's time (see format_image). plan_options.label = true; let mut plan = Plan::new(plan_options); - if let Some(ct) = &content { - ct.plan(&mut plan)?; + if let Some(ct) = content { + ct.plan_once(&mut plan)?; } let e = plan.estimate()?; e.apply(&mut options.format); diff --git a/src/bin/ufat/util.rs b/src/bin/ufat/util.rs index b4342d2..4271d05 100644 --- a/src/bin/ufat/util.rs +++ b/src/bin/ufat/util.rs @@ -1,45 +1,162 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! Helpers shared by the command line interface and the Varlink service. -use std::io::Read; +use std::fs::File; +use std::io::{self, Read, Seek}; +use std::os::fd::AsFd; +use std::os::unix::fs::FileExt; use std::path::Path; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use fat::device::{Access, Device}; use fat::errno; use fat::format::FormatOptions; +use fat::manifest::{Order, Reader, RootObject}; use fat::plan::{Estimate, Plan, PlanOptions}; use fat::probe::Prober; use fat::volume::Volume; -use fat::{bail, err, Context, Error, Result}; +use fat::{bail, err, DescriptorProblem, Detail, Error, Result}; /// The current time. pub(crate) fn now() -> SystemTime { SystemTime::now() } -/// The largest manifest read into memory. A record is at most 4 MiB and a -/// tree of a hundred thousand files describes itself in some tens of MiB, -/// so anything above this is not a manifest, an image given by mistake for -/// one, and is refused before it is read into memory. -pub(crate) const MAX_MANIFEST_BYTES: u64 = 256 * 1024 * 1024; +/// The bytes of a manifest, as its reader takes them. +pub(crate) enum ManifestBytes { + /// A regular file, read with positional reads from `offset` on. The + /// manifest starts at `start` in it. Positional reads leave the + /// position of the descriptor alone, so the file can be read once more + /// from the same place. + At { file: File, start: u64, offset: u64 }, + /// A pipe, read as the bytes come. + Stream(Box), +} + +impl ManifestBytes { + /// The bytes of the same manifest once more from its start. None for a + /// pipe, which can be read once only. + fn again(&self) -> io::Result> { + let ManifestBytes::At { file, start, .. } = self else { + return Ok(None); + }; + Ok(Some(ManifestBytes::At { + file: file.try_clone()?, + start: *start, + offset: *start, + })) + } +} + +impl Read for ManifestBytes { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self { + ManifestBytes::At { file, offset, .. } => { + let read = file.read_at(buf, *offset)?; + *offset += read as u64; + Ok(read) + } + ManifestBytes::Stream(stream) => stream.read(buf), + } + } +} + +/// What a command does with its manifest, which decides what the manifest +/// can come through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ManifestUse { + /// It is read once, while the content it describes is written. A pipe + /// will do. + Write, + /// It is planned and none of its content is written: it is read once, + /// on from its root file object. A pipe will do. + PlanOnly, + /// It is planned before its content is written, and has to be in a + /// regular file for that: the plan reads it once more from its start. + Plan, +} -/// Reads a UAPI.16 manifest from an open file or pipe to its end, within -/// [`MAX_MANIFEST_BYTES`], and parses it. -pub(crate) fn read_manifest(file: impl Read) -> Result { - let text = read_all(file, MAX_MANIFEST_BYTES).with_context(|| "cannot read the manifest")?; - fat::manifest::parse(&text) +/// A manifest the tool was handed, open for reading. +/// +/// Its first record, the root file object, is read when it is opened, so a +/// file that is not a manifest, or a manifest that does not declare the +/// code point order, is found before anything is written. The reader goes +/// on from there when the content is written, or a plan alone reads on +/// from there. A manifest in a regular file can be read once more before +/// the content is written, from its start, for a plan. Standard input and +/// pipes can be read once only. +pub(crate) struct ManifestInput { + /// The reader the content is taken from. + reader: Reader, } -/// Reads an open file to its end, refusing one of more than `limit` bytes -/// (EFBIG) instead of holding it in memory. -pub(crate) fn read_all(file: impl Read, limit: u64) -> Result> { - let mut data = Vec::new(); - file.take(limit + 1).read_to_end(&mut data)?; - if data.len() as u64 > limit { - bail!(errno::EFBIG, "more than {} bytes", limit); +impl ManifestInput { + /// Opens the manifest `stream`, a regular file or a pipe, from where its + /// position is, for `manifest_use`, and reads its root file object. A + /// pipe for [`ManifestUse::Plan`] is refused before anything is read + /// from it, so what it holds is left to whoever reads it next. A pipe + /// is read through `stream`, such as a [`fat::host::PassedStream`], + /// which fails a read when the pipe was made non-blocking during the + /// call. The manifest has to declare the code point order, see + /// [`RootObject::require_order`]. + pub(crate) fn open(stream: S, manifest_use: ManifestUse) -> Result + where + S: Read + AsFd + Send + 'static, + { + // A regular file is read with positional reads, through a + // descriptor of its own. + let mut file = File::from(stream.as_fd().try_clone_to_owned()?); + let bytes = if file.metadata()?.is_file() { + let start = file.stream_position()?; + ManifestBytes::At { + file, + start, + offset: start, + } + } else if manifest_use == ManifestUse::Plan { + return Err(ManifestInput::not_plannable()); + } else { + ManifestBytes::Stream(Box::new(stream)) + }; + let reader = Reader::open(bytes)?; + reader.root().require_order(Order::CodePoint)?; + Ok(ManifestInput { reader }) + } + + /// The root file object of the manifest. + pub(crate) fn root(&self) -> &RootObject { + self.reader.root() + } + + /// The error for a manifest that cannot be read once more for a plan: + /// its descriptor is not of the type a plan needs. + pub(crate) fn not_plannable() -> Error { + err!( + errno::EBADFD, + Detail::Descriptor { + problem: DescriptorProblem::WrongType, + flags: None, + parameter: None, + }, + "the manifest is not in a regular file, and sizing to fit reads it before its content is written" + ) + } + + /// A reader of the whole manifest once more, for a plan before the + /// content is written. The reader the content is taken from is left as + /// it is. + pub(crate) fn plan_reader(&self) -> Result> { + let Some(bytes) = self.reader.get_ref().again()? else { + return Err(ManifestInput::not_plannable()); + }; + Ok(Reader::open(bytes)?) + } + + /// The reader the content is taken from, which goes on after the root + /// file object. + pub(crate) fn reader(&mut self) -> &mut Reader { + &mut self.reader } - Ok(data) } /// Parses seconds since the epoch, as `--timestamp` and `SOURCE_DATE_EPOCH` diff --git a/src/fat/Cargo.toml b/src/fat/Cargo.toml index 7e92eb5..ca92cfa 100644 --- a/src/fat/Cargo.toml +++ b/src/fat/Cargo.toml @@ -13,10 +13,12 @@ path = "lib.rs" [dependencies] blkid.workspace = true -json.workspace = true libc.workspace = true sha2.workspace = true uapi16.workspace = true +[dev-dependencies] +json.workspace = true + [lints] workspace = true diff --git a/src/fat/dir.rs b/src/fat/dir.rs index e596589..6bd98f5 100644 --- a/src/fat/dir.rs +++ b/src/fat/dir.rs @@ -35,7 +35,7 @@ use crate::name::{ fold_str, join_long_name, parse_long_name_entry, short_name_to_string, valid_short_char, Alias, LongNameEntry, LFN_MAX_ENTRIES, }; -use crate::Result; +use crate::{Detail, Error, NoSpaceReason, Result}; /// Largest number of slots a directory may have: 2 MiB of entries. Linux /// refuses to create entries beyond that and EDK2 addresses slots with 16 @@ -714,6 +714,29 @@ impl Directory { self.index.first_fit(count) } + /// The free slots at the end of the directory, which a cluster appended + /// to it continues. + pub(crate) fn free_at_end(&self) -> usize { + self.index + .holes + .last_key_value() + .filter(|&(&start, &len)| start + len == self.slots()) + .map_or(0, |(_, &len)| len) + } + + /// The error for a directory that would grow past [`MAX_SLOTS`] slots. + pub(crate) fn full() -> Error { + err!( + ENOSPC, + Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + path: None, + }, + "directory is full, it cannot hold more than {} entries", + MAX_SLOTS + ) + } + /// Chooses the short name for an alias that needs a numeric tail: the /// candidate with the smallest tail no entry answers to, as mtools and /// Windows choose it. Candidates below a remembered hint are known to be @@ -1176,6 +1199,42 @@ mod tests { short_name } + /// The free slots at the end, which a cluster appended continues: + /// free slots before an entry do not count, nor do reserved ones. + #[test] + fn free_at_end() { + let name = |i: usize| { + let mut n = [b' '; SHORT_NAME_SIZE]; + n[..3].copy_from_slice(format!("F{:02}", i).as_bytes()); + n + }; + let at = |d: &Directory, slot: usize| d.entries().into_iter().find(|e| e.slot == slot).unwrap(); + let mut d = dir(); + assert_eq!(d.free_at_end(), 16); + for i in 0..13 { + d.write_entry(i, &[], &short(&name(i), ATTR_ARCHIVE)); + } + assert_eq!(d.free_at_end(), 3); + assert_eq!(d.find_free_run(3), Some(13)); + assert_eq!(d.find_free_run(4), None); + let e = at(&d, 5); + d.delete(&e); + assert_eq!(d.free_at_end(), 3); + assert!(d.reserve(13, 3)); + assert_eq!(d.free_at_end(), 0); + assert!(d.release_reservation(13)); + assert_eq!(d.free_at_end(), 3); + d.append_cluster(3); + assert_eq!(d.free_at_end(), 19); + for i in 13..32 { + d.write_entry(i, &[], &short(&name(i), ATTR_ARCHIVE)); + } + assert_eq!(d.free_at_end(), 0); + let e = at(&d, 31); + d.delete(&e); + assert_eq!(d.free_at_end(), 1); + } + #[test] fn insert_find_delete() { let mut d = dir(); diff --git a/src/fat/error.rs b/src/fat/error.rs index b7b8ead..51f4423 100644 --- a/src/fat/error.rs +++ b/src/fat/error.rs @@ -237,16 +237,15 @@ impl ManifestProblem { } /// How a file below the source directory fails to be what the manifest -/// describes, found before anything is written. +/// describes, found when it is opened to be copied. A file too short for +/// the contents the manifest says it holds, or not of the size the manifest +/// gives for it, is found while it is copied, see [`ContentProblem::Size`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SourceProblem { /// The file is not there. Missing, /// It is not a regular file. NotRegular, - /// Its size is not what the manifest says, or too short for the - /// offset and size asked for. - Size, } impl SourceProblem { @@ -255,7 +254,6 @@ impl SourceProblem { match self { SourceProblem::Missing => "missing", SourceProblem::NotRegular => "notRegular", - SourceProblem::Size => "size", } } } @@ -263,12 +261,16 @@ impl SourceProblem { /// How file contents fail to match the manifest while being copied. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ContentProblem { - /// Not as many bytes as the manifest says. + /// Not as many bytes as the manifest says, or in a file of the source + /// that is too short for them or not of the size the manifest gives for + /// it. Size, /// Not the SHA-256 hash the manifest says. Hash, /// The stream ended before the file was complete. StreamEnded, + /// The file of the source they are in changed while it was read. + SourceChanged, } impl ContentProblem { @@ -278,6 +280,7 @@ impl ContentProblem { ContentProblem::Size => "size", ContentProblem::Hash => "hash", ContentProblem::StreamEnded => "streamEnded", + ContentProblem::SourceChanged => "sourceChanged", } } } @@ -285,10 +288,6 @@ impl ContentProblem { /// What a manifest asks for that cannot be done. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum UnsupportedKind { - /// Contents to be fetched from a URL. - Url, - /// Contents in an encoding, named by `value`. - Encoding, /// Contents at an offset into a streamed source. Offset, /// Contents only available through a transport, named by `value`. @@ -303,8 +302,6 @@ impl UnsupportedKind { /// The value as the Varlink interface spells it. pub fn as_str(self) -> &'static str { match self { - UnsupportedKind::Url => "url", - UnsupportedKind::Encoding => "encoding", UnsupportedKind::Offset => "offset", UnsupportedKind::Transport => "transport", UnsupportedKind::SubManifest => "subManifest", @@ -414,6 +411,10 @@ pub enum Detail { problem: DescriptorProblem, /// The offending status flags, when that is the problem. flags: Option, + /// The parameter the descriptor was passed as, where its vetting or + /// a read or write of it knows that name, as host::passed_stream() + /// and the stream it returns do. + parameter: Option<&'static str>, }, /// The manifest is malformed. Manifest { @@ -427,18 +428,16 @@ pub enum Detail { field: Option, }, /// A file the manifest names is not below the source directory as the - /// manifest describes it, found before anything is written. + /// manifest describes it: missing, or not a regular file. Source { /// The entry's name, exactly as its record in the manifest has it. name: String, /// What is wrong. problem: SourceProblem, - /// The size found, when sizes are the problem. - size: Option, - /// The size the manifest says, when sizes are the problem. - expected: Option, }, - /// File contents do not match the manifest. + /// File contents do not match the manifest, found while they are + /// copied: a file below the source directory that is too short for + /// them among them, or one that changed while it was read. Content { /// The entry's name, exactly as its record in the manifest has it. name: String, @@ -446,7 +445,8 @@ pub enum Detail { problem: ContentProblem, /// The size found, when sizes are the problem. size: Option, - /// The size the manifest says, when sizes are the problem. + /// The size the manifest says, when sizes are the problem: for a + /// part of a file, the size the file needs to hold it. expected: Option, }, /// The manifest asks for something that cannot be done. @@ -540,21 +540,6 @@ impl Error { self } - /// Fills in the record index and the object's name of a manifest - /// error that lacks them. - #[must_use] - pub fn in_record(mut self, index: u64, object: Option<&str>) -> Self { - if let Some(Detail::Manifest { record, name, .. }) = &mut self.0.detail { - if record.is_none() { - *record = Some(index); - } - if name.is_none() { - *name = object.map(str::to_string); - } - } - self - } - /// The message describing this error. pub fn message(&self) -> &str { &self.0.message @@ -578,21 +563,45 @@ impl fmt::Debug for Error { } } -impl From for Error { - fn from(e: std::io::Error) -> Self { - // An io::Error wrapping one of our own errors comes back unchanged. - if let Some(inner) = e.get_ref().and_then(|i| i.downcast_ref::()) { - return inner.clone(); +/// The errno of an [`std::io::Error`], and an error of ours it carries. +pub(crate) trait IoErrorExt { + /// The error of ours the error carries, such as the one a passed + /// stream fails with when it was made non-blocking during the call + /// (host::PassedStream). + fn own_error(&self) -> Option<&Error>; + + /// The errno the error stands for: that of an error of ours it + /// carries, the one the system gave, or the one that fits its kind. + fn errno(&self) -> i32; +} + +impl IoErrorExt for std::io::Error { + fn own_error(&self) -> Option<&Error> { + self.get_ref().and_then(|inner| inner.downcast_ref::()) + } + + fn errno(&self) -> i32 { + if let Some(own) = self.own_error() { + return own.errno(); } - let errno = match e.raw_os_error() { + match self.raw_os_error() { Some(n) => n, - None => match e.kind() { + None => match self.kind() { std::io::ErrorKind::InvalidInput => EINVAL, std::io::ErrorKind::OutOfMemory => ENOMEM, _ => EIO, }, - }; - Error::new(errno, e.to_string()) + } + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + // An io::Error wrapping one of our own errors comes back unchanged. + if let Some(inner) = e.own_error() { + return inner.clone(); + } + Error::new(e.errno(), e.to_string()) } } diff --git a/src/fat/fat.rs b/src/fat/fat.rs index 71a626f..52e6b46 100644 --- a/src/fat/fat.rs +++ b/src/fat/fat.rs @@ -34,7 +34,7 @@ use crate::bytes::le32; use crate::errno::*; use crate::layout::{Layout, FIRST_CLUSTER}; use crate::Result; -use crate::{CorruptPlace, Detail, NoSpaceReason}; +use crate::{CorruptPlace, Detail, Error, NoSpaceReason}; /// The detail of a chain that is damaged at `cluster`. fn broken_chain(cluster: u32) -> Detail { @@ -300,6 +300,18 @@ impl Fat { self.free } + /// The error for clusters that are needed and not free. + pub(crate) fn no_free_clusters() -> Error { + err!( + ENOSPC, + Detail::NoSpace { + reason: NoSpaceReason::Clusters, + path: None, + }, + "no free clusters left" + ) + } + /// The last allocated cluster, stored in the FSInfo sector as the hint /// where to continue searching. pub fn cursor(&self) -> u32 { @@ -558,14 +570,7 @@ impl Fat { bail!(EINVAL, "allocation of zero clusters"); } if self.free == 0 { - bail!( - ENOSPC, - Detail::NoSpace { - reason: NoSpaceReason::Clusters, - path: None, - }, - "no free clusters left" - ); + return Err(Fat::no_free_clusters()); } let max_cluster = self.layout.max_cluster(); let first = match self.find_free(store, self.cursor + 1, max_cluster)? { diff --git a/src/fat/host.rs b/src/fat/host.rs index 4445e76..c495075 100644 --- a/src/fat/host.rs +++ b/src/fat/host.rs @@ -32,9 +32,14 @@ use crate::sys; use crate::{Context, Result}; use crate::{DescriptorProblem, Detail}; -/// The detail of a passed descriptor that cannot be used. -fn unusable(problem: DescriptorProblem, flags: Option) -> Detail { - Detail::Descriptor { problem, flags } +/// The detail of a passed descriptor that cannot be used, passed as +/// `parameter` where the caller named it. +fn unusable(problem: DescriptorProblem, flags: Option, parameter: Option<&'static str>) -> Detail { + Detail::Descriptor { + problem, + flags, + parameter, + } } /// Resolves `path`, a directory, once and returns it pinned: the descriptor @@ -84,13 +89,15 @@ pub fn open_parent(path: &Path) -> Result<(OwnedFd, OsString)> { /// would make positional writes append, O_DIRECT would make them fail on /// alignment, O_NONBLOCK would make reads from a pipe fail at random. /// Returns the access mode; O_WRONLY is refused since everything here reads. -fn vet_flags(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { - match vet_status(fd, extra, what)? { +/// The errors name `parameter`, the name the descriptor was passed as, +/// where the caller has one. +fn vet_flags(fd: BorrowedFd<'_>, extra: i32, what: &str, parameter: Option<&'static str>) -> Result { + match vet_status(fd, extra, what, parameter)? { sys::O_RDONLY => Ok(Access::ReadOnly), sys::O_RDWR => Ok(Access::ReadWrite), _ => bail!( EBADFD, - unusable(DescriptorProblem::WriteOnly, None), + unusable(DescriptorProblem::WriteOnly, None, parameter), "the {} descriptor is open for writing only", what ), @@ -99,12 +106,12 @@ fn vet_flags(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { /// The checks of [`vet_flags`] up to the access mode, which is returned as /// it is (O_RDONLY, O_WRONLY or O_RDWR) for the caller to judge. -fn vet_status(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { +fn vet_status(fd: BorrowedFd<'_>, extra: i32, what: &str, parameter: Option<&'static str>) -> Result { let flags = sys::descriptor_flags(fd)?; if flags & sys::O_PATH != 0 { bail!( EBADFD, - unusable(DescriptorProblem::OPath, None), + unusable(DescriptorProblem::OPath, None, parameter), "the {} descriptor was opened with O_PATH and cannot be read", what ); @@ -119,7 +126,7 @@ fn vet_status(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { }; bail!( EBADFD, - unusable(DescriptorProblem::Flags, Some(unexpected)), + unusable(DescriptorProblem::Flags, Some(unexpected), parameter), "the {} descriptor has flags set we cannot work with: 0o{:o}{}", what, unexpected, @@ -130,7 +137,7 @@ fn vet_status(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { mode @ (sys::O_RDONLY | sys::O_WRONLY | sys::O_RDWR) => Ok(mode), other => bail!( EBADFD, - unusable(DescriptorProblem::Flags, Some(other)), + unusable(DescriptorProblem::Flags, Some(other), parameter), "the {} descriptor has no valid access mode", what ), @@ -145,11 +152,11 @@ fn vet_status(fd: BorrowedFd<'_>, extra: i32, what: &str) -> Result { /// exclusively; no lock is taken on a passed descriptor, the caller holds /// its own, see [`crate::device::Device::from_passed`]. pub fn passed_image(fd: OwnedFd, access: Access) -> Result { - let open_for = vet_flags(fd.as_fd(), sys::O_NONBLOCK, "image")?; + let open_for = vet_flags(fd.as_fd(), sys::O_NONBLOCK, "image", None)?; if access == Access::ReadWrite && open_for != Access::ReadWrite { bail!( EBADFD, - unusable(DescriptorProblem::NotReadWrite, None), + unusable(DescriptorProblem::NotReadWrite, None, None), "the image descriptor is not open for reading and writing" ); } @@ -157,7 +164,7 @@ pub fn passed_image(fd: OwnedFd, access: Access) -> Result { if !ft.is_file() && !ft.is_block_device() { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, None), "the image descriptor is not a regular file or block device" ); } @@ -168,17 +175,17 @@ pub fn passed_image(fd: OwnedFd, access: Access) -> Result { /// the root everything below is resolved against: a directory, open for /// reading only (O_DIRECTORY accepted, O_PATH refused). pub fn passed_directory(fd: OwnedFd) -> Result { - if vet_flags(fd.as_fd(), sys::O_DIRECTORY, "source directory")? != Access::ReadOnly { + if vet_flags(fd.as_fd(), sys::O_DIRECTORY, "source directory", None)? != Access::ReadOnly { bail!( EBADFD, - unusable(DescriptorProblem::NotReadOnly, None), + unusable(DescriptorProblem::NotReadOnly, None, None), "the source directory descriptor is not open read-only" ); } if !sys::fstat(fd.as_fd())?.is_dir() { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, None), "the source directory descriptor is not a directory" ); } @@ -189,17 +196,17 @@ pub fn passed_directory(fd: OwnedFd) -> Result { /// regular file open for reading only, read with positional reads from /// its start, so the position of the client's descriptor is left alone. pub fn passed_file(fd: OwnedFd) -> Result { - if vet_flags(fd.as_fd(), 0, "source file")? != Access::ReadOnly { + if vet_flags(fd.as_fd(), 0, "source file", None)? != Access::ReadOnly { bail!( EBADFD, - unusable(DescriptorProblem::NotReadOnly, None), + unusable(DescriptorProblem::NotReadOnly, None, None), "the source file descriptor is not open read-only" ); } if !sys::fstat(fd.as_fd())?.is_file() { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, None), "the source file descriptor is not a regular file" ); } @@ -215,14 +222,19 @@ pub fn passed_file(fd: OwnedFd) -> Result { /// client can set it during the call. A blocking pipe or a regular file /// never fails with EAGAIN, so a read or write that does while O_NONBLOCK /// is set fails as the vetting fails a descriptor with the flag: EBADFD -/// with the `Flags` problem. +/// with the `Flags` problem. Its detail names the parameter the stream was +/// passed as, since a call can read a manifest and the contents of its +/// files from two streams at once. #[derive(Debug)] -pub struct PassedStream(File); +pub struct PassedStream { + file: File, + parameter: &'static str, +} impl PassedStream { /// The metadata of the file or pipe. pub fn metadata(&self) -> io::Result { - self.0.metadata() + self.file.metadata() } /// The error a read or write returned, or the flags problem when it @@ -231,10 +243,10 @@ impl PassedStream { if e.kind() != io::ErrorKind::WouldBlock { return e; } - match sys::descriptor_flags(self.0.as_fd()) { + match sys::descriptor_flags(self.file.as_fd()) { Ok(flags) if flags & sys::O_NONBLOCK != 0 => err!( EBADFD, - unusable(DescriptorProblem::Flags, Some(sys::O_NONBLOCK)), + unusable(DescriptorProblem::Flags, Some(sys::O_NONBLOCK), Some(self.parameter)), "the descriptor was made non-blocking during the call" ) .into(), @@ -245,23 +257,23 @@ impl PassedStream { impl Read for PassedStream { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.read(buf).map_err(|e| self.explain(e)) + self.file.read(buf).map_err(|e| self.explain(e)) } } impl Write for PassedStream { fn write(&mut self, buf: &[u8]) -> io::Result { - self.0.write(buf).map_err(|e| self.explain(e)) + self.file.write(buf).map_err(|e| self.explain(e)) } fn flush(&mut self) -> io::Result<()> { - self.0.flush() + self.file.flush() } } impl AsFd for PassedStream { fn as_fd(&self) -> BorrowedFd<'_> { - self.0.as_fd() + self.file.as_fd() } } @@ -279,12 +291,14 @@ pub enum PassedSource { /// line's SOURCE is a directory or "-": a directory, open read-only /// (O_DIRECTORY accepted), is the tree the manifest describes; a regular /// file or pipe, open read-only and blocking, carries the contents in -/// manifest order. Anything else is EBADFD. -pub fn passed_source(fd: OwnedFd) -> Result { - if vet_flags(fd.as_fd(), sys::O_DIRECTORY, "source")? != Access::ReadOnly { +/// manifest order. Anything else is EBADFD. `parameter` is the name the +/// descriptor was passed as, which its errors name, those of reading a +/// stream included. +pub fn passed_source(fd: OwnedFd, parameter: &'static str) -> Result { + if vet_flags(fd.as_fd(), sys::O_DIRECTORY, "source", Some(parameter))? != Access::ReadOnly { bail!( EBADFD, - unusable(DescriptorProblem::NotReadOnly, None), + unusable(DescriptorProblem::NotReadOnly, None, Some(parameter)), "the source descriptor is not open read-only" ); } @@ -292,11 +306,14 @@ pub fn passed_source(fd: OwnedFd) -> Result { if ft.is_dir() { Ok(PassedSource::Directory(fd)) } else if ft.is_file() || ft.is_fifo() { - Ok(PassedSource::Stream(PassedStream(File::from(fd)))) + Ok(PassedSource::Stream(PassedStream { + file: File::from(fd), + parameter, + })) } else { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, Some(parameter)), "the source descriptor is not a directory, a regular file or a pipe" ); } @@ -307,11 +324,13 @@ pub fn passed_source(fd: OwnedFd) -> Result { /// manifest order: a regular file or a pipe, open for reading only, without /// O_NONBLOCK since a pipe would then fail instead of wait. A socket is /// always open for reading and writing and so never passes here. -pub fn passed_stream(fd: OwnedFd) -> Result { - if vet_flags(fd.as_fd(), 0, "stream")? != Access::ReadOnly { +/// `parameter` is the name the descriptor was passed as, which its errors +/// name, those of reading the stream included. +pub fn passed_stream(fd: OwnedFd, parameter: &'static str) -> Result { + if vet_flags(fd.as_fd(), 0, "stream", Some(parameter))? != Access::ReadOnly { bail!( EBADFD, - unusable(DescriptorProblem::NotReadOnly, None), + unusable(DescriptorProblem::NotReadOnly, None, Some(parameter)), "the stream descriptor is not open read-only" ); } @@ -319,11 +338,14 @@ pub fn passed_stream(fd: OwnedFd) -> Result { if !ft.is_file() && !ft.is_fifo() { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, Some(parameter)), "the stream descriptor is not a regular file or pipe" ); } - Ok(PassedStream(File::from(fd))) + Ok(PassedStream { + file: File::from(fd), + parameter, + }) } /// Takes a descriptor another process handed over as the sink a manifest @@ -332,12 +354,13 @@ pub fn passed_stream(fd: OwnedFd) -> Result { /// and where in its file the caller wants it is the caller's business; /// O_NONBLOCK is not, since a full pipe would then fail instead of wait. /// A descriptor open read-only is `NotWritable`, anything but a regular -/// file or pipe `WrongType`. -pub fn passed_sink(fd: OwnedFd) -> Result { - if vet_status(fd.as_fd(), sys::O_APPEND, "sink")? == sys::O_RDONLY { +/// file or pipe `WrongType`. `parameter` is the name the descriptor was +/// passed as, which its errors name, those of writing to it included. +pub fn passed_sink(fd: OwnedFd, parameter: &'static str) -> Result { + if vet_status(fd.as_fd(), sys::O_APPEND, "sink", Some(parameter))? == sys::O_RDONLY { bail!( EBADFD, - unusable(DescriptorProblem::NotWritable, None), + unusable(DescriptorProblem::NotWritable, None, Some(parameter)), "the sink descriptor is not open for writing" ); } @@ -345,11 +368,14 @@ pub fn passed_sink(fd: OwnedFd) -> Result { if !ft.is_file() && !ft.is_fifo() { bail!( EBADFD, - unusable(DescriptorProblem::WrongType, None), + unusable(DescriptorProblem::WrongType, None, Some(parameter)), "the sink descriptor is not a regular file or pipe" ); } - Ok(PassedStream(File::from(fd))) + Ok(PassedStream { + file: File::from(fd), + parameter, + }) } /// Raises the soft limit on open descriptors to the hard limit and returns @@ -1015,24 +1041,28 @@ mod tests { EBADFD ); // Streams: a regular file or a pipe, blocking. - assert!(passed_stream(open("file", sys::O_RDONLY)).is_ok()); - assert_eq!(passed_stream(open("dir", sys::O_RDONLY)).unwrap_err().errno(), EBADFD); + assert!(passed_stream(open("file", sys::O_RDONLY), "stream").is_ok()); + assert_eq!( + passed_stream(open("dir", sys::O_RDONLY), "stream").unwrap_err().errno(), + EBADFD + ); sys::make_fifo(&root.join("fifo")).unwrap(); let reader = open("fifo", sys::O_RDONLY | sys::O_NONBLOCK); let _writer = open("fifo", sys::O_WRONLY); - let err = passed_stream(open("fifo", sys::O_RDONLY | sys::O_NONBLOCK)).unwrap_err(); + let err = passed_stream(open("fifo", sys::O_RDONLY | sys::O_NONBLOCK), "stream").unwrap_err(); assert!( matches!( err.detail(), Some(Detail::Descriptor { problem: DescriptorProblem::Flags, flags: Some(f), + parameter: Some("stream"), }) if f & sys::O_NONBLOCK != 0 ), "{:?}", err ); - assert!(passed_stream(open("fifo", sys::O_RDONLY)).is_ok()); + assert!(passed_stream(open("fifo", sys::O_RDONLY), "stream").is_ok()); drop(reader); // The image: read-write for writing, O_APPEND never. assert!(passed_image(open("file", sys::O_RDONLY), Access::ReadOnly).is_ok()); @@ -1058,6 +1088,7 @@ mod tests { Some(Detail::Descriptor { problem: DescriptorProblem::Flags, flags: Some(f), + parameter: None, }) if f & sys::O_APPEND != 0 ), "{:?}", @@ -1072,20 +1103,23 @@ mod tests { assert!(passed_image(open("file", sys::O_RDWR | sys::O_NONBLOCK), Access::ReadWrite).is_ok()); // A source is whatever its type says, as long as it is read-only. assert!(matches!( - passed_source(open("dir", sys::O_RDONLY)).unwrap(), + passed_source(open("dir", sys::O_RDONLY), "source").unwrap(), PassedSource::Directory(_) )); assert!(matches!( - passed_source(open("file", sys::O_RDONLY)).unwrap(), + passed_source(open("file", sys::O_RDONLY), "source").unwrap(), PassedSource::Stream(_) )); let _reader = open("fifo", sys::O_RDONLY | sys::O_NONBLOCK); let _writer = open("fifo", sys::O_WRONLY); assert!(matches!( - passed_source(open("fifo", sys::O_RDONLY)).unwrap(), + passed_source(open("fifo", sys::O_RDONLY), "source").unwrap(), PassedSource::Stream(_) )); - assert_eq!(passed_source(open("file", sys::O_RDWR)).unwrap_err().errno(), EBADFD); + assert_eq!( + passed_source(open("file", sys::O_RDWR), "source").unwrap_err().errno(), + EBADFD + ); } /// What a full pipe is filled with at a time. @@ -1113,15 +1147,15 @@ mod tests { sys::set_status_flags(reader.as_fd(), flags & !sys::O_NONBLOCK).unwrap(); let writer = fs::OpenOptions::new().write(true).open(&fifo).unwrap(); let clients = [reader.try_clone().unwrap(), writer.try_clone().unwrap()]; - let mut stream = passed_stream(OwnedFd::from(reader)).unwrap(); - let mut sink = passed_sink(OwnedFd::from(writer)).unwrap(); + let mut stream = passed_stream(OwnedFd::from(reader), "stream").unwrap(); + let mut sink = passed_sink(OwnedFd::from(writer), "sink").unwrap(); let again = stream.explain(io::Error::from_raw_os_error(EAGAIN)); assert_eq!(again.raw_os_error(), Some(EAGAIN)); for client in &clients { let flags = sys::descriptor_flags(client.as_fd()).unwrap(); sys::set_status_flags(client.as_fd(), flags | sys::O_NONBLOCK).unwrap(); } - let refused = |e: io::Error| { + let refused = |e: io::Error, parameter: &'static str| { let e = crate::Error::from(e); assert_eq!(e.errno(), EBADFD); assert_eq!( @@ -1129,17 +1163,18 @@ mod tests { Some(&Detail::Descriptor { problem: DescriptorProblem::Flags, flags: Some(sys::O_NONBLOCK), + parameter: Some(parameter), }) ); assert_eq!(e.message(), "the descriptor was made non-blocking during the call"); }; - refused(stream.read(&mut [0; 1]).unwrap_err()); + refused(stream.read(&mut [0; 1]).unwrap_err(), "stream"); let full = loop { if let Err(e) = sink.write(FILL) { break e; } }; - refused(full); + refused(full, "sink"); let other = stream.explain(io::Error::from_raw_os_error(EIO)); assert_eq!(other.raw_os_error(), Some(EIO)); } diff --git a/src/fat/lib.rs b/src/fat/lib.rs index 89fe6a9..17eeca6 100644 --- a/src/fat/lib.rs +++ b/src/fat/lib.rs @@ -42,7 +42,6 @@ pub mod plan; pub mod populate; pub mod probe; pub mod progress; -pub mod sha256; pub mod sha512; mod sys; #[cfg(test)] diff --git a/src/fat/manifest/assemble.rs b/src/fat/manifest/assemble.rs index a78f687..c3dab77 100644 --- a/src/fat/manifest/assemble.rs +++ b/src/fat/manifest/assemble.rs @@ -1,116 +1,51 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! Assembling a volume from a manifest: where file contents come from, and -//! the walk over the manifest that creates directories and files and -//! verifies sizes and hashes. - -use std::io::{Read, Write}; +//! Assembling a volume from a manifest while it is read: the directory on +//! the host the contents of the files come from, and the walk over the +//! records that creates directories and files and verifies sizes and +//! hashes. + +use std::fmt; +use std::io::{self, Read, Write}; +use std::ops::{BitOr, BitOrAssign}; use std::os::fd::{AsFd, OwnedFd}; use std::time::{SystemTime, UNIX_EPOCH}; -use super::{Contents, Entry, InodeType, Manifest, Storable}; +use uapi16::{ContentSource, Directory, ErrorKind, FileObject, Name, Object, OpenError, Order, Reader}; + +use super::{path_in_volume, EntryKind, ObjectAction, ObjectTriage}; use crate::errno::*; use crate::progress::Progress; -use crate::sha256::{Sha256, DIGEST_SIZE}; use crate::sys; -use crate::volume::Volume; -use crate::{ContentProblem, Detail, ManifestProblem, SourceProblem, UnsupportedKind}; -use crate::{Context, Error, Result}; - -/// Supplies the data of regular files during assembly. -pub trait ContentSource { - /// Writes the data of `entry` to `sink`: exactly `entry.size` bytes when - /// the size is known. `contents` is the contents entry chosen by - /// [`Entry::fat_contents`], if there is one. - fn copy(&mut self, entry: &Entry, contents: Option<&Contents>, sink: &mut dyn Write) -> Result<()>; - - /// Called after the data of `last`, the last file whose data comes from - /// the source, was copied and checked, before that file is stored. A - /// source that has more data than the manifest's files fails here. - fn end(&mut self, _last: &Entry) -> Result<()> { - Ok(()) - } -} - -/// Size of the buffer a source copies through. -const COPY_BUFFER: usize = 1024 * 1024; - -/// The buffer a source copies through, allocated on first use and kept. -fn copy_buffer(buf: &mut Vec) -> &mut [u8] { - if buf.len() != COPY_BUFFER { - buf.resize(COPY_BUFFER, 0); - } - buf -} - -/// Reads file data from the directory the manifest lives in, or from the -/// directory the caller chose instead. +use crate::volume::{FileWriter, Volume}; +use crate::{Detail, Error, Result}; + +/// The directory on the host the files of a manifest are taken from: the +/// one the manifest lives in, or the one the caller chose instead. It is +/// opened once and never looked up again, and each file below it is +/// pinned before it is opened. +/// +/// A [`uapi16::DirectorySource`] reads the data of the files from it for an +/// assembly. A file that is missing, is not a regular file or is too short +/// for the data the manifest says it holds fails the assembly when its +/// object comes. #[derive(Debug)] -pub struct DirectorySource { +pub struct PinnedDirectory { dir: OwnedFd, follow_symlinks: bool, - buf: Vec, -} - -/// The detail of a file the manifest names that is not below the source -/// directory as described. -fn mismatch(name: &str, problem: SourceProblem, size: Option, expected: Option) -> Detail { - Detail::Source { - name: name.to_string(), - problem, - size, - expected, - } -} - -/// The detail of file contents that do not match the manifest. -fn differs(name: &str, problem: ContentProblem, size: Option, expected: Option) -> Detail { - Detail::Content { - name: name.to_string(), - problem, - size, - expected, - } } -/// The detail of something the manifest asks for that cannot be done. -fn unsupported(name: &str, what: UnsupportedKind, value: Option<&str>) -> Detail { - Detail::Unsupported { - name: Some(name.to_string()), - what, - value: value.map(str::to_string), - } -} - -/// A failure to reach a file the manifest names, as the source mismatch of -/// the entry `name` where the failure says the file is not what the -/// manifest describes: missing (or behind something that is not a -/// directory), or not a regular file. -fn source_failure(e: Error, name: &str) -> Error { - let problem = match e.errno() { - ENOENT | ENOTDIR => Some(SourceProblem::Missing), - EINVAL => Some(SourceProblem::NotRegular), - _ => None, - }; - let e = e.context(name); - match problem { - Some(p) => e.with(mismatch(name, p, None, None)), - None => e, - } -} - -impl DirectorySource { - /// Reads files below the open directory `dir`, which the caller resolved +impl PinnedDirectory { + /// The files below the open directory `dir`, which the caller resolved /// once (with [`crate::host::open_dir`] when it has a path) and which is /// never looked up again. A file reference is resolved below it the way /// systemd's chase() resolves a path below a root: an absolute symbolic /// link target starts over at `dir`, `..` at `dir` stays there, nothing /// resolves to anything outside it, and symbolic links are followed - /// only when [`DirectorySource::follow_symlinks`] allows them. - pub fn new(dir: OwnedFd) -> DirectorySource { - DirectorySource { + /// only when [`PinnedDirectory::follow_symlinks`] allows them. + pub fn new(dir: OwnedFd) -> PinnedDirectory { + PinnedDirectory { dir, follow_symlinks: false, - buf: Vec::new(), } } @@ -119,339 +54,113 @@ impl DirectorySource { /// tree would otherwise make a privileged assembly read any file on the /// host. #[must_use] - pub fn follow_symlinks(mut self, follow: bool) -> DirectorySource { + pub fn follow_symlinks(mut self, follow: bool) -> PinnedDirectory { self.follow_symlinks = follow; self } - /// Opens the file `relative` names below the directory: pinned, checked - /// to be a regular file, and only then opened for reading. - fn open(&self, relative: &str) -> Result<(std::fs::File, std::fs::Metadata)> { - let failed = || format!("failed to open {}", relative); - let pinned = - sys::chase(self.dir.as_fd(), relative.as_bytes(), self.follow_symlinks, false).with_context(failed)?; - let md = sys::fstat(pinned.as_fd()).with_context(failed)?; + /// Pins the file `file` names below the directory and checks that it + /// is a regular file. Returns it with its size. + fn pin(&self, file: &Name) -> std::result::Result<(OwnedFd, u64), OpenError> { + let pinned = sys::chase(self.dir.as_fd(), file.as_bytes(), self.follow_symlinks, false)?; + let md = sys::fstat(pinned.as_fd())?; if !md.is_file() { - bail!(EINVAL, "{} is not a regular file", relative); + return Err(OpenError::NotRegular); } - let fd = sys::reopen(pinned.as_fd(), sys::O_RDONLY | sys::O_NONBLOCK | sys::O_NOCTTY).with_context(failed)?; - Ok((std::fs::File::from(fd), md)) + Ok((pinned, md.len())) } +} - /// Checks, without reading any data, that every file the manifest would - /// read from the directory is there, is a regular file and is as long - /// as the manifest says: one lookup and one fstat each, found the way - /// the copy will find them. Run before an image is created or - /// formatted, so that a wrong source directory fails with nothing - /// half-made left behind. Entries the assembly cannot store, literal - /// contents and contents it would refuse anyway are passed over here; - /// the sizes and hashes of the data itself are checked while copying. - pub fn verify(&self, manifest: &Manifest) -> Result<()> { - for entry in &manifest.entries { - if !matches!(entry.inode_type, InodeType::Regular) || entry.check_supported().is_err() { - continue; - } - let Ok(contents) = entry.fat_contents() else { continue }; - if contents.is_some_and(|c| c.literal.is_some()) { - continue; - } - let Ok(source) = reference(entry, contents) else { - continue; - }; - let name = entry.name.as_deref().unwrap_or_default(); - let failed = |e: std::io::Error| { - source_failure( - Error::from(e).context(format_args!("failed to open {}", source.relative)), - name, - ) - }; - let pinned = sys::chase( - self.dir.as_fd(), - source.relative.as_bytes(), - self.follow_symlinks, - false, - ) - .map_err(failed)?; - let md = sys::fstat(pinned.as_fd()).map_err(failed)?; - if !md.is_file() { - bail!( - EINVAL, - mismatch(name, SourceProblem::NotRegular, None, None), - "{}: {} is not a regular file", - name, - source.relative - ); - } - source.check_len(name, md.len(), entry.size, |found, expected| { - mismatch(name, SourceProblem::Size, found, expected) - })?; - } - Ok(()) +impl Directory for PinnedDirectory { + type File = std::fs::File; + + /// Opens the file: pinned, checked to be a regular file, and only then + /// opened for reading. + fn open(&self, file: &Name) -> std::result::Result<(std::fs::File, u64), OpenError> { + let (pinned, len) = self.pin(file)?; + let fd = sys::reopen(pinned.as_fd(), sys::O_RDONLY | sys::O_NONBLOCK | sys::O_NOCTTY)?; + Ok((std::fs::File::from(fd), len)) } } -/// The file below the source directory a regular entry's data comes from. -struct Reference { - /// The file's path below the source directory. - relative: String, - /// Where the entry's data starts in the file. - offset: u64, - /// The size the manifest declares for the whole file, if any. - original_size: Option, - /// The hash the manifest declares for the whole file, if any. - original_sha256: Option<[u8; DIGEST_SIZE]>, -} +/// What an assembly does where it could also fail. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct AssembleFlags(u8); -impl Reference { - /// Checks the length `len` of the file against the manifest, for the - /// entry `name` of `size` bytes, and returns the size of its data: the - /// rest of the file after the offset when the manifest gives none. - /// A reference without an offset and without `originalSize` is the - /// whole file, which has to be exactly `size` bytes long. A part of a - /// file, at an offset or out of a larger `originalSize`, has to fit - /// into it. `detail` makes the error's detail of the length found and - /// the one expected. - fn check_len( - &self, - name: &str, - len: u64, - size: Option, - detail: impl Fn(Option, Option) -> Detail, - ) -> Result { - if let Some(total) = self.original_size { - if total != len { - bail!( - EBADMSG, - detail(Some(len), Some(total)), - "{}: {} is {} bytes, the manifest says {}", - name, - self.relative, - len, - total - ); - } - } - let size = size.unwrap_or(len.saturating_sub(self.offset)); - // Without an offset and without originalSize the file holds the - // data and nothing else, as systemd-sysupdate takes it. A file that - // grew since the manifest was written would otherwise be cut short. - if self.offset == 0 && self.original_size.is_none() && len != size { - bail!( - EBADMSG, - detail(Some(len), Some(size)), - "{}: {} is {} bytes, the manifest says {}", - name, - self.relative, - len, - size - ); - } - if self.offset.checked_add(size).is_none_or(|end| end > len) { - bail!( - EBADMSG, - detail(Some(len), self.offset.checked_add(size)), - "{}: {} is too short for offset {} and size {}", - name, - self.relative, - self.offset, - size - ); - } - Ok(size) +impl AssembleFlags { + /// Replace files that exist in the volume instead of failing. + pub const REPLACE: AssembleFlags = AssembleFlags(1 << 0); + /// Skip entries this crate cannot store (see [`EntryKind`]) instead of + /// failing. + pub const SKIP_UNSUPPORTED: AssembleFlags = AssembleFlags(1 << 1); + /// No flag: an assembly fails in both cases. + pub const NONE: AssembleFlags = AssembleFlags(0); + + /// Every single flag with its name. + const NAMES: [(AssembleFlags, &'static str); 2] = [ + (AssembleFlags::REPLACE, "REPLACE"), + (AssembleFlags::SKIP_UNSUPPORTED, "SKIP_UNSUPPORTED"), + ]; + + /// Whether every flag of `flags` is among these. + pub const fn contains(self, flags: AssembleFlags) -> bool { + self.0 & flags.0 == flags.0 } -} -/// Where a regular entry's data comes from. Contents that would have to be -/// fetched or decoded are refused (EOPNOTSUPP). -fn reference(entry: &Entry, contents: Option<&Contents>) -> Result { - let path = entry.path(); - match contents { - None => Ok(Reference { - relative: entry.name.clone().unwrap_or_default(), - offset: 0, - original_size: None, - original_sha256: None, - }), - Some(c) => { - if c.url.is_some() { - bail!( - EOPNOTSUPP, - unsupported(&path, UnsupportedKind::Url, None), - "{}: fetching contents from a URL is not supported", - path - ); - } - if let Some(enc) = &c.encoding { - bail!( - EOPNOTSUPP, - unsupported(&path, UnsupportedKind::Encoding, Some(enc)), - "{}: contents encoded with '{}' are not supported", - path, - enc - ); - } - Ok(Reference { - relative: c.file.clone().or_else(|| entry.name.clone()).unwrap_or_default(), - offset: c.offset, - original_size: c.original_size, - original_sha256: c.original_sha256, - }) + /// These flags with `flags` among them if `on` says so, and without + /// them if not. + #[must_use] + pub const fn with(self, flags: AssembleFlags, on: bool) -> AssembleFlags { + if on { + AssembleFlags(self.0 | flags.0) + } else { + AssembleFlags(self.0 & !flags.0) } } } -impl ContentSource for DirectorySource { - fn copy(&mut self, entry: &Entry, contents: Option<&Contents>, sink: &mut dyn Write) -> Result<()> { - let name = entry.name.as_deref().unwrap_or_default(); - let source = reference(entry, contents)?; - let (mut file, md) = self.open(&source.relative).map_err(|e| source_failure(e, name))?; - let size = source.check_len(name, md.len(), entry.size, |found, expected| { - differs(name, ContentProblem::Size, found, expected) - })?; - let offset = source.offset; - // The hash of the whole source, when given, is checked by reading - // everything; the part before the offset is hashed but not copied. - let mut hasher = source.original_sha256.map(|_| Sha256::new()); - let buf = copy_buffer(&mut self.buf); - let mut pos = 0u64; - loop { - let n = crate::host::read_some(&mut file, buf)?; - if n == 0 { - break; - } - let chunk = &buf[..n]; - if let Some(h) = hasher.as_mut() { - h.update(chunk); - } - let start = offset.saturating_sub(pos).min(n as u64) as usize; - let end = (offset + size).saturating_sub(pos).min(n as u64) as usize; - if start < end { - sink.write_all(&chunk[start..end])?; - } - pos += n as u64; - if hasher.is_none() && pos >= offset + size { - break; - } - } - if let (Some(h), Some(expected)) = (hasher, source.original_sha256) { - if h.finalize() != expected { - bail!( - EBADMSG, - differs(name, ContentProblem::Hash, None, None), - "{}: {} does not match the hash in the manifest", - name, - source.relative - ); - } - } - Ok(()) +impl Default for AssembleFlags { + /// [`AssembleFlags::REPLACE`]. + fn default() -> AssembleFlags { + AssembleFlags::REPLACE } } -/// Reads file data from one stream carrying every streamed file's contents -/// back to back in manifest order. -pub struct StreamSource<'a> { - reader: &'a mut dyn Read, - buf: Vec, -} +impl BitOr for AssembleFlags { + type Output = AssembleFlags; -impl std::fmt::Debug for StreamSource<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("StreamSource").finish_non_exhaustive() + fn bitor(self, other: AssembleFlags) -> AssembleFlags { + AssembleFlags(self.0 | other.0) } } -impl<'a> StreamSource<'a> { - /// Wraps the stream. - pub fn new(reader: &'a mut dyn Read) -> StreamSource<'a> { - StreamSource { - reader, - buf: Vec::new(), - } +impl BitOrAssign for AssembleFlags { + fn bitor_assign(&mut self, other: AssembleFlags) { + self.0 |= other.0; } } -impl ContentSource for StreamSource<'_> { - fn copy(&mut self, entry: &Entry, contents: Option<&Contents>, sink: &mut dyn Write) -> Result<()> { - let path = entry.path(); - if let Some(c) = contents { - if c.encoding.is_some() || c.offset != 0 { - let what = if c.encoding.is_some() { - UnsupportedKind::Encoding - } else { - UnsupportedKind::Offset - }; - bail!( - EOPNOTSUPP, - unsupported(&path, what, c.encoding.as_deref()), - "{}: encodings and offsets cannot be used with streamed contents", - path - ); - } - } - let total = entry.size.ok_or_else(|| { - err!( - EINVAL, - Detail::Manifest { - problem: ManifestProblem::NoSize, - record: None, - name: Some(path.clone()), - field: Some("size".into()), - }, - "{}: streamed contents need a known size", - path - ) - })?; - let mut remaining = total; - let buf = copy_buffer(&mut self.buf); - while remaining > 0 { - let want = (buf.len() as u64).min(remaining) as usize; - let n = crate::host::read_some(&mut *self.reader, &mut buf[..want])?; - if n == 0 { - let name = entry.name.as_deref().unwrap_or_default(); - bail!( - EBADMSG, - differs(name, ContentProblem::StreamEnded, Some(total - remaining), Some(total)), - "{}: the stream ended {} bytes early", - name, - remaining - ); +impl fmt::Debug for AssembleFlags { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let names = AssembleFlags::NAMES.iter().filter(|(flag, _)| self.contains(*flag)); + f.write_str("AssembleFlags(")?; + for (i, (_, name)) in names.enumerate() { + if i > 0 { + f.write_str(" | ")?; } - sink.write_all(&buf[..n])?; - remaining -= n as u64; - } - Ok(()) - } - - /// The stream ends with the last file. Anything after it would be data - /// the manifest does not describe, so the last file got more than the - /// manifest says. - fn end(&mut self, last: &Entry) -> Result<()> { - let mut byte = [0u8; 1]; - if crate::host::read_some(&mut *self.reader, &mut byte)? > 0 { - let name = last.name.as_deref().unwrap_or_default(); - bail!( - EBADMSG, - differs(name, ContentProblem::Size, None, last.size), - "{}: the stream goes on after the last file", - name - ); + f.write_str(name)?; } - Ok(()) + f.write_str(")") } } /// Options for [`Volume::assemble`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AssembleOptions { - /// Time stamped on entries without `mTimeNSec` and on directories - /// created implicitly. + /// Time stamped on entries without `mTimeNSec`. pub default_time: SystemTime, - /// Replace files that exist in the volume instead of failing. - pub replace: bool, - /// Skip entries this crate cannot store (see [`Entry::check_supported`]) - /// instead of failing. - pub skip_unsupported: bool, + /// What to do where an assembly could also fail. + pub flags: AssembleFlags, /// The current time for validity checks, or None to skip them. pub now_usec: Option, } @@ -460,15 +169,14 @@ impl Default for AssembleOptions { fn default() -> Self { AssembleOptions { default_time: UNIX_EPOCH, - replace: true, - skip_unsupported: false, + flags: AssembleFlags::default(), now_usec: None, } } } /// What an assembly did. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct AssembleReport { /// Files written. pub files: u64, @@ -477,217 +185,312 @@ pub struct AssembleReport { pub directories: u64, /// File bytes written. pub bytes: u64, - /// Entries skipped because they cannot be stored. - pub skipped: Vec, + /// File objects left out, see [`SkipReason`]. + pub skipped: u64, +} + +impl AssembleReport { + /// What the assembly has done so far, as an observer hears it. + fn progress(&self) -> Progress { + Progress { + files: self.files, + directories: self.directories, + bytes: self.bytes, + } + } +} + +/// Why an assembly leaves a file object out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SkipReason { + /// This crate cannot store the object, see [`EntryKind`], and + /// [`AssembleFlags::SKIP_UNSUPPORTED`] says to leave it out. + Unsupported, + /// The object is below a directory that is left out. + BelowSkipped, } -/// Hashes what passes through it and tells `progress` after every write how -/// many bytes it took, on top of what `done` counts. -struct HashingWriter<'a> { +/// What an assembly tells its caller while it runs. Every method does +/// nothing unless an observer has it do something. +/// +/// A closure that takes a [`Progress`] is an observer of the progress. +pub trait AssembleObserver { + /// What was written so far, after every directory, every file and + /// every chunk of a file's contents. + fn progress(&mut self, _progress: &Progress) {} + + /// The file object of the name `name` is left out, for the reason + /// `reason`. + fn skipped(&mut self, _name: &Name, _reason: SkipReason) {} +} + +impl AssembleObserver for F { + fn progress(&mut self, progress: &Progress) { + self(progress); + } +} + +/// A writer that passes everything on to `inner` and tells the observer +/// after every write how many bytes went through, on top of what `done` +/// counts. +struct ProgressWriter<'a> { inner: &'a mut dyn Write, - hasher: Sha256, written: u64, done: Progress, - progress: &'a mut dyn FnMut(&Progress), + observer: &'a mut dyn AssembleObserver, } -impl Write for HashingWriter<'_> { - fn write(&mut self, buf: &[u8]) -> std::io::Result { +impl Write for ProgressWriter<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { self.inner.write_all(buf)?; - self.hasher.update(buf); self.written += buf.len() as u64; - (self.progress)(&Progress { + self.observer.progress(&Progress { bytes: self.done.bytes + self.written, ..self.done }); Ok(buf.len()) } - fn flush(&mut self) -> std::io::Result<()> { + fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } -impl AssembleReport { - /// What the assembly has done so far, as a progress callback hears it. - fn progress(&self) -> Progress { - Progress { - files: self.files, - directories: self.directories, - bytes: self.bytes, +/// A file an assembly writes, created in the volume when its first data +/// comes, or when it is finished without any. So a file object whose +/// source refuses it, such as a stream that needs its size, leaves nothing +/// in the volume, not even the marks of a write. +struct PendingFile<'a> { + /// The volume, until the file is created in it. + volume: Option<&'a mut Volume>, + /// The file once it is created. It is aborted when it is dropped + /// unfinished. + writer: Option>, + /// Where the file goes in the volume. + path: &'a str, + /// The file object the file is made for. + object: &'a FileObject, + /// The assembly's options. The file takes their `default_time` where + /// its object has no time, and their `flags` say whether it replaces a + /// file of the same name. + options: &'a AssembleOptions, +} + +impl PendingFile<'_> { + /// Whether the file is created. + fn is_created(&self) -> bool { + self.writer.is_some() + } + + /// Creates the file unless it is created: with the object's time, or + /// the assembly's where it gives none, read-only as the object is, and + /// replacing a file of the same name where the assembly says so. + fn create(&mut self) -> Result<()> { + if let Some(volume) = self.volume.take() { + let time = self.object.inode.mtime().unwrap_or(self.options.default_time); + let replace = self.options.flags.contains(AssembleFlags::REPLACE); + let mut writer = volume.create_file(self.path, time, replace)?; + writer.set_read_only(self.object.inode.is_read_only()); + self.writer = Some(writer); + } + Ok(()) + } + + /// Finishes the file that was created. + fn finish(self) -> Result<()> { + match self.writer { + Some(writer) => writer.finish(), + None => Err(self.not_created()), + } + } + + /// The error of a write or a finish after the file could not be + /// created. + fn not_created(&self) -> Error { + err!(EBADF, "'{}' was not created", self.path) + } +} + +impl Write for PendingFile<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.create()?; + match &mut self.writer { + Some(writer) => writer.write(buf), + None => Err(self.not_created().into()), + } + } + + fn flush(&mut self) -> io::Result<()> { + match &mut self.writer { + Some(writer) => writer.flush(), + None => Ok(()), + } + } +} + +/// An assembly while the records of its manifest come. +struct Assembly<'a> { + volume: &'a mut Volume, + source: &'a mut dyn ContentSource, + options: &'a AssembleOptions, + observer: &'a mut dyn AssembleObserver, + report: AssembleReport, + triage: ObjectTriage, +} + +impl Assembly<'_> { + /// Applies the file object that came next: stores it as a file or as a + /// directory, or leaves it out. An object that is not valid fails the + /// assembly, also one that would be left out. + fn apply(&mut self, object: &FileObject) -> Result<()> { + // An invalid directory takes its entries with it: its object comes + // first and fails the whole assembly. + if let Some(now) = self.options.now_usec { + object.check_validity(now)?; + } + match self.triage.decide(object, self.options.flags)? { + ObjectAction::Store(EntryKind::Directory) => self.store_directory(object), + ObjectAction::Store(EntryKind::File) => self.store_file(object), + ObjectAction::Skip(reason) => self.skip(object, reason), + } + } + + /// Leaves `object` out. A source that hands out the contents in + /// manifest order has them all the same, and passes over them with the + /// checks of a copy: data that does not match the object's size and + /// hash means that the stream is out of step with the manifest, and + /// every object after it would get the wrong bytes. + fn skip(&mut self, object: &FileObject, reason: SkipReason) -> Result<()> { + self.report.skipped += 1; + self.observer.skipped(&object.name, reason); + self.source.skip(object)?; + Ok(()) + } + + /// Creates the directory `object` describes, or gives the one that is + /// there its time. + fn store_directory(&mut self, object: &FileObject) -> Result<()> { + let path = path_in_volume(&object.name); + let time = object.inode.mtime().unwrap_or(self.options.default_time); + match self.volume.metadata(&path) { + Ok(md) if md.is_dir => self.volume.set_times(&path, time)?, + Ok(_) => bail!( + ENOTDIR, + Detail::Path(path.clone()), + "'{}' exists in the volume and is not a directory", + path + ), + Err(e) if e.errno() == ENOENT => self.volume.create_dir(&path, time)?, + Err(e) => return Err(e), } + self.report.directories += 1; + self.observer.progress(&self.report.progress()); + Ok(()) + } + + /// Creates the file `object` describes, with its contents checked + /// against the manifest. The file is created when its first data comes, + /// see [`PendingFile`]. + fn store_file(&mut self, object: &FileObject) -> Result<()> { + let path = path_in_volume(&object.name); + let mut file = PendingFile { + volume: Some(&mut *self.volume), + writer: None, + path: &path, + object, + options: self.options, + }; + let mut sink = ProgressWriter { + inner: &mut file, + written: 0, + done: self.report.progress(), + observer: &mut *self.observer, + }; + let copied = object.copy_contents(self.source, &mut sink); + // An error of the volume comes back from the copy as an I/O error. + // One of creating the file is as the volume said it. One of writing + // it knows nothing of the file it was writing, while those of the + // manifest and of its files name the file already. + let named = |e: Error| e.at_path(&path).context(format!("copying {}", object.name)); + let written = copied.map_err(|e| match e.kind() { + ErrorKind::Io if file.is_created() => named(e.into()), + _ => e.into(), + })?; + file.create()?; + file.finish().map_err(named)?; + self.report.files += 1; + self.report.bytes += written; + self.observer.progress(&self.report.progress()); + Ok(()) + } + + /// Ends the assembly after the trailer of the manifest. + fn finish(self) -> Result { + self.source.end()?; + Ok(self.report) } } impl Volume { /// Creates the directories and files a manifest describes, each at its - /// name below the root directory. Data comes from `source` for regular - /// files without literal contents. Sizes and SHA-256 hashes in the - /// manifest are verified; a mismatch removes the file again and fails - /// with EBADMSG. So does data the source has after the last file it - /// supplies. A directory object listed after its children, or for a - /// directory that already exists, sets the directory's timestamp. - pub fn assemble( + /// name below the root directory, while `reader` reads the manifest to + /// its end. The caller opened the reader, and the reader read the root + /// file object then. + /// + /// The manifest has to declare the code point order, see + /// [`Order::CodePoint`], in its root file object, as UAPI.16 asks of a + /// manifest that a file system is made from. One that does not fails + /// with EBADMSG before anything is written. The reader checks the file + /// objects against that order, so it refuses a name that comes twice, + /// and every directory comes before what is in it. Data comes from + /// `source` for regular files without literal contents. Sizes and + /// SHA-256 hashes in the manifest are verified; a mismatch removes the + /// file again and fails with EBADMSG. So does data the source has after + /// the last file it supplies, which is found after the trailer of the + /// manifest. + /// + /// A file the volume holds under the same name, or under a name FAT + /// does not tell apart from it, is replaced with + /// [`AssembleFlags::REPLACE`] and fails with EEXIST without it. A + /// directory the volume holds under such a name gets the directory + /// object's time. + pub fn assemble( &mut self, - manifest: &Manifest, + reader: &mut Reader, source: &mut dyn ContentSource, options: &AssembleOptions, ) -> Result { - self.assemble_with_progress(manifest, source, options, &mut |_| {}) + self.assemble_with_observer(reader, source, options, &mut |_: &Progress| {}) } - /// [`Volume::assemble`], telling `progress` what it wrote so far after - /// every directory, every file and every chunk of a file. - pub fn assemble_with_progress( + /// [`Volume::assemble`], telling `observer` what it wrote so far after + /// every directory, every file and every chunk of a file, and every + /// object it leaves out. + pub fn assemble_with_observer( &mut self, - manifest: &Manifest, + reader: &mut Reader, source: &mut dyn ContentSource, options: &AssembleOptions, - progress: &mut dyn FnMut(&Progress), + observer: &mut dyn AssembleObserver, ) -> Result { - let mut report = AssembleReport::default(); + reader.root().require_order(Order::CodePoint)?; if let Some(now) = options.now_usec { - manifest.root.check_validity(now)?; - } - // The source has to end with the last file it supplies. - let last = manifest.entries.iter().rposition(Entry::is_streamed); - for (index, entry) in manifest.entries.iter().enumerate() { - let name = entry.name.clone().unwrap_or_default(); - let path = format!("/{name}"); - // An invalid directory takes its children with it: the directory - // object comes first and fails the whole assembly here. - if let Some(now) = options.now_usec { - entry.check_validity(now)?; - } - let storable = match entry.storable() { - Ok(storable) => storable, - Err(e) if e.errno() == EOPNOTSUPP && options.skip_unsupported => { - report.skipped.push(name); - continue; - } - Err(e) => return Err(e), - }; - let time = entry.mtime().unwrap_or(options.default_time); - if let Some((parent, _)) = name.rsplit_once('/') { - self.create_dir_all(&format!("/{parent}"), options.default_time)?; - } - match storable { - Storable::Directory => { - match self.metadata(&path) { - Ok(m) if m.is_dir => self.set_times(&path, time)?, - Ok(_) => bail!( - ENOTDIR, - Detail::Path(path.clone()), - "'{}' exists in the volume and is not a directory", - path - ), - Err(e) if e.errno() == ENOENT => self.create_dir(&path, time)?, - Err(e) => return Err(e), - } - report.directories += 1; - progress(&report.progress()); - } - Storable::File(contents) => { - // The writer aborts the file when it is dropped on an - // error. - let mut writer = self.create_file(&path, time, options.replace)?; - writer.set_read_only(entry.is_read_only()); - let mut hashing = HashingWriter { - inner: &mut writer, - hasher: Sha256::new(), - written: 0, - done: report.progress(), - progress: &mut *progress, - }; - match contents.and_then(|c| c.literal.as_ref()) { - Some(literal) => { - // An offset or a size beyond the literal takes it - // all; the checks below find the difference. - let offset = usize::try_from(contents.map_or(0, |c| c.offset)).unwrap_or(usize::MAX); - let data = literal.get(offset..).unwrap_or(&[]); - let data = match entry.size.map(usize::try_from) { - Some(Ok(size)) => data.get(..size).unwrap_or(data), - _ => data, - }; - hashing.write_all(data)?; - } - None => source.copy(entry, contents, &mut hashing)?, - } - let HashingWriter { written, hasher, .. } = hashing; - let digest = hasher.finalize(); - if let Some(size) = entry.size { - if written != size { - bail!( - EBADMSG, - differs(&name, ContentProblem::Size, Some(written), Some(size)), - "'{}' is {} bytes, the manifest says {}", - name, - written, - size - ); - } - } - if let Some(expected) = entry.sha256 { - if digest != expected { - bail!( - EBADMSG, - differs(&name, ContentProblem::Hash, None, None), - "'{}' does not match the hash in the manifest", - name - ); - } - } - if last == Some(index) { - source.end(entry)?; - } - writer.finish()?; - report.files += 1; - report.bytes += written; - progress(&report.progress()); - } - } + reader.root().check_validity(now)?; } - Ok(report) - } -} - -impl crate::plan::Plan { - /// Adds the files and directories of a manifest. Returns the entries - /// that cannot be stored (see [`Entry::check_supported`]), which the - /// assembler skips or refuses, so a plan and an assembly with - /// `skip_unsupported` cover the same entries. - pub fn add_manifest(&mut self, manifest: &Manifest) -> Result> { - let mut skipped = Vec::new(); - for entry in &manifest.entries { - let name = entry.name.clone().unwrap_or_default(); - let storable = match entry.storable() { - Ok(storable) => storable, - Err(e) if e.errno() == EOPNOTSUPP => { - skipped.push(name); - continue; - } - Err(e) => return Err(e), - }; - match storable { - Storable::Directory => self.add_dir(&format!("/{}", name))?, - Storable::File(_) => { - let Some(size) = entry.size else { - bail!( - EINVAL, - Detail::Manifest { - problem: ManifestProblem::NoSize, - record: None, - name: Some(format!("/{}", name)), - field: Some("size".into()), - }, - "'{}' has no size in the manifest", - name - ); - }; - self.add_file(&format!("/{}", name), size)?; - } + let mut assembly = Assembly { + volume: self, + source, + options, + observer, + report: AssembleReport::default(), + triage: ObjectTriage::default(), + }; + for object in reader { + if let Object::File(object) = object? { + assembly.apply(&object)?; } } - Ok(skipped) + assembly.finish() } } diff --git a/src/fat/manifest/error.rs b/src/fat/manifest/error.rs index 6c72055..0d677d9 100644 --- a/src/fat/manifest/error.rs +++ b/src/fat/manifest/error.rs @@ -2,16 +2,66 @@ //! The errors of the `uapi16` crate as errors of this one: with the errno //! and the detail a client of the Varlink interface is told. -use uapi16::{ErrorKind, Problem}; +use uapi16::{ErrorKind, Field, Invalid, Problem, UnsupportedContent}; +use super::path_in_volume; use crate::errno::*; -use crate::{Detail, Error, ManifestProblem}; +use crate::error::IoErrorExt; +use crate::{ContentProblem, Detail, Error, ManifestProblem, SourceProblem, UnsupportedKind, ValidityProblem}; + +/// What the size of a regular file of a manifest is needed for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SizePurpose { + /// Planning the size of a volume for the file. + Planning, + /// Taking its contents from a stream, which has the contents of every + /// file back to back. + Streaming, +} + +impl SizePurpose { + /// The word messages use for it, as in "cannot be planned". + fn as_str(self) -> &'static str { + match self { + SizePurpose::Planning => "planned", + SizePurpose::Streaming => "streamed", + } + } +} + +impl Error { + /// The error for the regular file `name` of a manifest, in the record + /// `record` when that is known, that has no size although `purpose` + /// needs one. + pub(crate) fn no_size(name: &str, record: Option, purpose: SizePurpose) -> Error { + let what = match record { + Some(record) => format!("manifest object {} ({})", record, name), + None => format!("'{}'", name), + }; + Error::new( + EINVAL, + format!("{}: a file without a size cannot be {}", what, purpose.as_str()), + ) + .with(Detail::Manifest { + problem: ManifestProblem::NoSize, + record, + name: Some(name.to_string()), + field: Some(Field::Size.as_str().to_string()), + }) + } +} impl From for Error { fn from(e: uapi16::Error) -> Error { + // A file is named by its path inside the volume where the error is + // about what the volume is to hold, and by its name in the + // manifest where it is about the manifest or its files. + let name = e.name().unwrap_or_default(); + let path = path_in_volume(name); match e.kind() { - // What the output said when it was written to comes back as it - // was. + // What the volume said when it was written to, and what the + // output said when a manifest was written to it, comes back as + // it was. ErrorKind::Io => Error::from(std::io::Error::from(e)), ErrorKind::Manifest(problem) => { let errno = match problem { @@ -34,7 +84,81 @@ impl From for Error { field: e.field().map(|field| field.to_string()), }) } - // Writing a manifest fails for the reasons above only. + ErrorKind::Source(problem) => { + let cause = e.io_error().map(IoErrorExt::errno); + let (errno, problem) = match problem { + uapi16::SourceProblem::Missing => (cause.unwrap_or(ENOENT), SourceProblem::Missing), + uapi16::SourceProblem::NotRegular => (EINVAL, SourceProblem::NotRegular), + // A file that cannot be read for a reason of the host, + // SourceProblem::Unreadable, is no mismatch between the + // manifest and its files. An error of ours behind it + // keeps its detail, such as that of a passed stream made + // non-blocking during the call. + _ => { + let error = Error::new(cause.unwrap_or(EIO), e.to_string()); + return match e.io_error().and_then(IoErrorExt::own_error).and_then(Error::detail) { + Some(detail) => error.with(detail.clone()), + None => error, + }; + } + }; + Error::new(errno, e.to_string()).with(Detail::Source { + name: name.to_string(), + problem, + }) + } + ErrorKind::Content(problem) => { + let problem = match problem { + uapi16::ContentProblem::SizeMismatch => ContentProblem::Size, + uapi16::ContentProblem::HashMismatch => ContentProblem::Hash, + uapi16::ContentProblem::StreamEnded => ContentProblem::StreamEnded, + uapi16::ContentProblem::SourceChanged => ContentProblem::SourceChanged, + _ => return Error::new(EBADMSG, e.to_string()), + }; + Error::new(EBADMSG, e.to_string()).with(Detail::Content { + name: name.to_string(), + problem, + size: e.found_size(), + expected: e.expected_size(), + }) + } + ErrorKind::Unsupported(what) => { + let (what, message) = match what { + UnsupportedContent::OffsetInStream => ( + UnsupportedKind::Offset, + format!("{}: an offset cannot be used with streamed contents", path), + ), + UnsupportedContent::UrlOrEncoding => ( + UnsupportedKind::Transport, + format!( + "'{}' is only available through {}, which is not supported", + path, + e.value().unwrap_or_default() + ), + ), + UnsupportedContent::NoSize => { + return Error::no_size(name, e.record_number(), SizePurpose::Streaming) + } + // An object without data, UnsupportedContent::Absent: + // only the data of regular files is copied, and they + // always have some. + _ => return Error::new(EOPNOTSUPP, e.to_string()), + }; + Error::new(EOPNOTSUPP, message).with(Detail::Unsupported { + name: Some(path), + what, + value: e.value().map(str::to_string), + }) + } + ErrorKind::NotValid(reason) => { + let (errno, problem) = match reason { + Invalid::Revoked => (EKEYREVOKED, ValidityProblem::Revoked), + Invalid::NotYetValid => (EKEYEXPIRED, ValidityProblem::NotYetValid), + Invalid::Expired => (EKEYEXPIRED, ValidityProblem::Expired), + }; + Error::new(errno, e.to_string()).with(Detail::Validity { name: path, problem }) + } + // A kind of error this crate does not know of. _ => Error::new(EIO, e.to_string()), } } diff --git a/src/fat/manifest/fields.rs b/src/fat/manifest/fields.rs deleted file mode 100644 index 067ae4b..0000000 --- a/src/fat/manifest/fields.rs +++ /dev/null @@ -1,357 +0,0 @@ -// SPDX-License-Identifier: LGPL-2.1-or-later -//! The field level rules of a manifest: how a value is read and what is a -//! valid name, hash, UUID, label, user name or extended attribute. They -//! follow systemd's reader (src/shared/uapi16-manifest.c) rule for rule. - -use json::{Object, Value}; -use uapi16::Problem; - -use super::{malformed_field, FILENAME, GPT_LABEL_MAX, NAME_MAX, PATH_MAX}; -use crate::errno::*; -use crate::sha256::DIGEST_SIZE; -use crate::Result; - -/// An unsigned integer. 64 bit values are a problem for many JSON -/// implementations, so like systemd we also take them as decimal strings. -pub(super) fn uint(v: &Value, what: &str) -> Result { - if let Some(n) = v.as_u64() { - return Ok(n); - } - if let Some(s) = v.as_str() { - if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) { - if let Ok(n) = s.parse() { - return Ok(n); - } - } - } - bail!( - EBADMSG, - malformed_field(Problem::WrongFieldType, what), - "manifest field '{}' is not an unsigned integer", - what - ) -} - -/// An access mode: a number, or a string in octal as everywhere else. -pub(super) fn access_mode(v: &Value, what: &str) -> Result { - let m = match v.as_str() { - Some(s) if !s.is_empty() && s.bytes().all(|b| (b'0'..=b'7').contains(&b)) => { - u64::from_str_radix(s, 8).unwrap_or(u64::MAX) - } - Some(_) => { - bail!( - EBADMSG, - malformed_field(Problem::WrongFieldType, what), - "manifest field '{}' is not an octal access mode", - what - ) - } - None => uint(v, what)?, - }; - if m > 0o7777 { - bail!( - EBADMSG, - malformed_field(Problem::FieldOutOfRange, what), - "manifest field '{}' is out of range: {}", - what, - m - ); - } - Ok(m as u32) -} - -pub(super) fn string<'a>(v: &'a Value, what: &str) -> Result<&'a str> { - v.as_str().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::WrongFieldType, what), - "manifest field '{}' is not a string", - what - ) - }) -} - -pub(super) fn boolean(v: &Value, what: &str) -> Result { - v.as_bool().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::WrongFieldType, what), - "manifest field '{}' is not a boolean", - what - ) - }) -} - -/// Hex digits with whitespace allowed in between, as systemd decodes them. -pub(super) fn hex_bytes(text: &str) -> Option> { - let mut out = Vec::new(); - let mut high = None; - for c in text.chars().filter(|c| !c.is_ascii_whitespace()) { - let d = c.to_digit(16)? as u8; - match high.take() { - None => high = Some(d), - Some(h) => out.push((h << 4) | d), - } - } - if high.is_some() { - return None; - } - Some(out) -} - -pub(super) fn hash(v: &Value, what: &str) -> Result<[u8; DIGEST_SIZE]> { - hex_bytes(string(v, what)?) - .and_then(|b| <[u8; DIGEST_SIZE]>::try_from(b).ok()) - .ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::WrongFieldType, what), - "manifest field '{}' is not a SHA-256 hash", - what - ) - }) -} - -/// A 128 bit ID as systemd spells them: 32 hex digits, or a GUID with the -/// usual dashes, optionally behind "urn:uuid:". -pub(super) fn valid_id128(s: &str) -> bool { - // Compare bytes: slicing the string at a byte offset would panic inside a - // multi-byte character, and the string comes from the manifest. - let s = match s.as_bytes().get(..9) { - Some(prefix) if prefix.eq_ignore_ascii_case(b"urn:uuid:") => &s[9..], - _ => s, - }; - let bytes = s.as_bytes(); - match bytes.len() { - 32 => bytes.iter().all(u8::is_ascii_hexdigit), - 36 => bytes.iter().enumerate().all(|(i, &b)| { - if matches!(i, 8 | 13 | 18 | 23) { - b == b'-' - } else { - b.is_ascii_hexdigit() - } - }), - _ => false, - } -} - -/// A GPT partition label: no control characters and at most 36 UTF-16 -/// units, which is what the partition table has room for. -pub(super) fn valid_gpt_label(s: &str) -> bool { - let mut units = 0; - for c in s.chars() { - if c < ' ' || ('\x7f'..='\u{9f}').contains(&c) { - return false; - } - units += c.len_utf16(); - if units > GPT_LABEL_MAX { - return false; - } - } - true -} - -/// User and group names, as liberally as systemd's relaxed rules allow: -/// anything that is not obviously broken or a number in disguise. -pub(super) fn valid_user_group_name(s: &str) -> bool { - if s.is_empty() || s.starts_with(' ') || s.ends_with(' ') || s == "." || s == ".." { - return false; - } - if s.chars().any(|c| c.is_ascii_control() || c == ':' || c == '/') { - return false; - } - let digits = s.strip_prefix('-').unwrap_or(s); - !digits.bytes().all(|b| b.is_ascii_digit()) -} - -/// The `extendedAttributes` object: namespaces mapping names to values, a -/// value being an object with exactly one of `text` and `base64`. Only the -/// `user` namespace is defined; others are ignored, as systemd does. -pub(super) fn check_extended_attributes(v: &Value, what: &str) -> Result<()> { - let namespaces = v.as_object().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: 'extendedAttributes' is not an object", - what - ) - })?; - for (ns, attrs) in namespaces.iter() { - if ns != "user" || attrs.is_null() { - continue; - } - let attrs = attrs.as_object().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: extended attribute namespace '{}' is not an object", - what, - ns - ) - })?; - for (name, value) in attrs.iter() { - if name.is_empty() || name.chars().any(|c| c.is_ascii_control()) { - bail!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: invalid extended attribute name '{}'", - what, - name - ); - } - let value = value.as_object().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: value of extended attribute '{}' is not an object", - what, - name - ) - })?; - let text = value.get("text").filter(|v| !v.is_null()); - let base64 = value.get("base64").filter(|v| !v.is_null()); - match (text, base64) { - (Some(t), None) => { - string(t, "text")?; - } - (None, Some(b)) => { - if base64_decode(string(b, "base64")?).is_none() { - bail!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: extended attribute '{}' is not valid Base64", - what, - name - ); - } - } - _ => bail!( - EBADMSG, - malformed_field(Problem::InvalidExtendedAttributes, "extendedAttributes"), - "{}: extended attribute '{}' needs exactly one of 'text' and 'base64'", - what, - name - ), - } - } - } - Ok(()) -} - -/// Checks a signature object's shape. The signature is not verified, but a -/// manifest whose signature objects are malformed is refused like systemd -/// refuses it. -pub(super) fn check_signature(object: &Object, index: usize) -> Result<()> { - let what = format!("manifest signature object {}", index); - match object.get("mechanism") { - Some(Value::String(_)) => {} - _ => { - bail!( - EBADMSG, - malformed_field(Problem::InvalidSignature, "mechanism"), - "{} has no 'mechanism' string", - what - ) - } - } - if let Some(key) = object.get("key").filter(|v| !v.is_null()) { - if hex_bytes(string(key, "key")?).is_none() { - bail!( - EBADMSG, - malformed_field(Problem::InvalidSignature, "key"), - "{}: 'key' is not hex", - what - ); - } - } - if let Some(data) = object.get("data").filter(|v| !v.is_null()) { - if base64_decode(string(data, "data")?).is_none() { - bail!( - EBADMSG, - malformed_field(Problem::InvalidSignature, "data"), - "{}: 'data' is not Base64", - what - ); - } - } - Ok(()) -} - -/// Whether `name` is a normalized relative path without control characters -/// that does not clash with the manifest's own name. Components are limited -/// to NAME_MAX bytes and the whole name to PATH_MAX, as on Linux. -pub fn valid_name(name: &str) -> bool { - if name.is_empty() || name.len() >= PATH_MAX || name.starts_with('/') || name.ends_with('/') { - return false; - } - if name.chars().any(|c| c.is_ascii_control()) { - return false; - } - if name - .split('/') - .any(|c| c.is_empty() || c == "." || c == ".." || c.len() > NAME_MAX) - { - return false; - } - !(name == FILENAME || name.starts_with(&format!("{}.", FILENAME))) -} - -/// The key under which FAT, which folds case, files `name`. -pub(super) fn fat_key(name: &str) -> Vec { - let mut key = Vec::new(); - for (i, component) in name.split('/').enumerate() { - if i > 0 { - key.push(u16::from(b'/')); - } - key.extend(crate::name::fold_str(component)); - } - key -} - -/// Decodes Base64 exactly as systemd's unbase64mem() does, which reads the -/// `literal` contents, the `base64` extended attributes and the signature -/// `data` of a manifest: -/// -/// - The digits are those of the standard and of the URL-safe alphabet, -/// in any mix. -/// - Space, tab, newline and carriage return are skipped wherever they -/// are. -/// - The digits come in groups of four. The last group can end in "=" or -/// "==", and then the bits the padding leaves over have to be zero. -/// Nothing but whitespace may follow the padding. -pub fn base64_decode(text: &str) -> Option> { - // The padding character among the digits. - const PAD: u8 = 64; - let mut digits = text.bytes().filter(|c| !b" \t\n\r".contains(c)).map(|c| match c { - b'A'..=b'Z' => Some(c - b'A'), - b'a'..=b'z' => Some(c - b'a' + 26), - b'0'..=b'9' => Some(c - b'0' + 52), - b'+' | b'-' => Some(62), - b'/' | b'_' => Some(63), - b'=' => Some(PAD), - _ => None, - }); - let mut out = Vec::with_capacity(text.len() / 4 * 3); - while let Some(a) = digits.next() { - // The first two digits of a group are never padding, and the input - // never ends in the middle of a group. - let a = a.filter(|&a| a != PAD)?; - let b = digits.next()?.filter(|&b| b != PAD)?; - let c = digits.next()??; - let d = digits.next()??; - match (c, d) { - (PAD, PAD) if b & 15 == 0 && digits.next().is_none() => { - out.push((a << 2) | (b >> 4)); - break; - } - (PAD, _) => return None, - (_, PAD) if c & 3 == 0 && digits.next().is_none() => { - out.extend([(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2)]); - break; - } - (_, PAD) => return None, - _ => out.extend([(a << 2) | (b >> 4), ((b & 15) << 4) | (c >> 2), ((c & 3) << 6) | d]), - } - } - Some(out) -} diff --git a/src/fat/manifest/mod.rs b/src/fat/manifest/mod.rs index 6768c17..6370aaa 100644 --- a/src/fat/manifest/mod.rs +++ b/src/fat/manifest/mod.rs @@ -1,12 +1,19 @@ // SPDX-License-Identifier: LGPL-2.1-or-later -//! UAPI.16 file manifests: reading them and assembling a volume from one. +//! UAPI.16 file manifests: assembling a volume from one while it is read, +//! and writing the manifest of a volume or of a tree on the host. //! -//! A manifest is an RFC 7464 JSON text sequence: each object is preceded by -//! an ASCII record separator (0x1E). The first object describes the manifest -//! itself, file objects follow, then optional signature objects and finally -//! the trailer. Objects with unknown media types are skipped, as the -//! specification requires. The structural checks are the ones systemd's -//! reader applies. +//! The manifests themselves are the business of the `uapi16` crate: the +//! objects, the [`Reader`] that checks them against the specification +//! record by record, the writer and the sources of file contents. This +//! module adds what FAT has to say. A FAT volume holds regular files and +//! directories, no file of 4 GiB or more, and no two names that differ in +//! case only. +//! +//! An assembly reads one record at a time and writes what it describes +//! right away. It never holds a whole manifest, so a manifest of any size +//! can come through a pipe. The planner in [`crate::plan`] takes the +//! records as they come too, but it keeps the name of every file and +//! directory it is given. //! //! Signatures are recognised but not verified: that needs an X.509 stack. //! Callers who need authenticated manifests must verify them before handing @@ -19,1106 +26,151 @@ //! device nodes, FIFOs, sockets) is refused unless the caller asks for it to //! be skipped. -use std::collections::HashMap; -use std::io::Read; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use json::{Object, Value}; -use uapi16::Problem; - use crate::errno::*; -use crate::sha256::{self, DIGEST_SIZE}; +use crate::path::SEPARATOR; use crate::volume::MAX_FILE_SIZE; -use crate::{Detail, ManifestProblem, Result, UnsupportedKind, ValidityProblem}; +use crate::{Detail, Result, UnsupportedKind}; mod assemble; mod error; -mod fields; mod generate; #[cfg(test)] mod tests; mod volume; -pub use assemble::{AssembleOptions, AssembleReport, ContentSource, DirectorySource, StreamSource}; -pub use fields::{base64_decode, valid_name}; +pub use assemble::{AssembleFlags, AssembleObserver, AssembleOptions, AssembleReport, PinnedDirectory, SkipReason}; pub use generate::HostTree; -pub use uapi16::Features; -pub use volume::WriteReport; - -use fields::{ - access_mode, boolean, check_extended_attributes, check_signature, fat_key, hash, string, uint, valid_gpt_label, - valid_id128, valid_user_group_name, +pub use uapi16::{ + ContentSource, Contents, DirectorySource, Features, FileObject, Finalize, InodeType, Location, Name, Object, Order, + Problem, Reader, RootObject, Sha256, Sha256Context, StreamSource, }; +pub use volume::WriteReport; -/// `bail!` for a defect of the manifest itself, with the problem a client -/// is told about; the record and the object's name are filled in by the -/// reader. -macro_rules! malformed { - ($problem:expr, $errno:expr, $($arg:tt)*) => { - return Err($crate::err!($errno, $crate::manifest::malformed($problem), $($arg)*)) - }; -} - -/// The detail of a defect of the manifest itself. -pub(super) fn malformed(problem: Problem) -> Detail { - Detail::Manifest { - problem: ManifestProblem::Malformed(problem), - record: None, - name: None, - field: None, - } -} +pub(crate) use error::SizePurpose; -/// [`malformed`] about one field. -pub(super) fn malformed_field(problem: Problem, field: &str) -> Detail { - Detail::Manifest { - problem: ManifestProblem::Malformed(problem), - record: None, - name: None, - field: Some(field.to_string()), - } +/// The path inside a volume of the file object with the name `name`: the +/// name below the root directory. +pub(crate) fn path_in_volume(name: &str) -> String { + crate::path::join("/", name) } -/// Media type of the leading object. -pub const MEDIA_TYPE: &str = "application/vnd.uapi.16.manifest"; -/// Media type of signature objects. -pub const SIGNATURE_MEDIA_TYPE: &str = "application/vnd.uapi.16.signature"; -/// Media type of the trailer object. -pub const TRAILER_MEDIA_TYPE: &str = "application/vnd.uapi.16.trailer"; -/// Name of a manifest stored inside the tree it describes. -pub const FILENAME: &str = "Uapi16Manifest"; -/// Suffix of manifests stored next to what they describe. -pub const SUFFIX: &str = ".Uapi16Manifest"; -/// Largest record accepted, the same cap as systemd's reader. -pub const MAX_RECORD_SIZE: usize = 4 * 1024 * 1024; -/// Largest number of `contents` entries per object, as in systemd. -pub const MAX_CONTENTS: usize = 256; -/// Longest path component accepted, Linux's NAME_MAX. -const NAME_MAX: usize = 255; -/// Longest name accepted, below Linux's PATH_MAX. -const PATH_MAX: usize = 4096; -/// Longest GPT partition label, in UTF-16 units. -const GPT_LABEL_MAX: usize = 36; -/// GPT partition flag bits `gptFlagNoAuto` and `gptFlagGrowFileSystem` -/// mirror. -const GPT_FLAG_NO_AUTO: u64 = 1 << 63; -const GPT_FLAG_GROWFS: u64 = 1 << 59; -/// The record separator starting every record. -pub const RECORD_SEPARATOR: u8 = 0x1E; - -/// The inode type of a file object. +/// What a file object becomes in a FAT volume. +/// +/// FAT stores regular files and directories. Symbolic links, device +/// nodes, FIFOs and sockets it cannot store. Neither can this crate store +/// a directory that refers to a manifest of its own, nor a file whose +/// contents would have to be decoded or fetched. Converting any of them +/// fails with EOPNOTSUPP. A regular file larger than a FAT32 file can be +/// fails with EFBIG. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum InodeType { - /// `reg` - Regular, - /// `dir` +pub enum EntryKind { + /// A regular file. + File, + /// A directory. Directory, - /// `lnk` - Symlink, - /// `fifo` - Fifo, - /// `chr` - CharDevice, - /// `blk` - BlockDevice, - /// `sock` - Socket, } -impl InodeType { - fn parse(s: &str) -> Option { - Some(match s { - "reg" => InodeType::Regular, - "dir" => InodeType::Directory, - "lnk" => InodeType::Symlink, - "fifo" => InodeType::Fifo, - "chr" => InodeType::CharDevice, - "blk" => InodeType::BlockDevice, - "sock" => InodeType::Socket, - _ => return None, - }) - } - - /// The name used in manifests. - pub fn as_str(self) -> &'static str { - match self { - InodeType::Regular => "reg", - InodeType::Directory => "dir", - InodeType::Symlink => "lnk", - InodeType::Fifo => "fifo", - InodeType::CharDevice => "chr", - InodeType::BlockDevice => "blk", - InodeType::Socket => "sock", - } - } -} - -/// Where the data of a file object comes from. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct Contents { - /// A path relative to the manifest. - pub file: Option, - /// An http or https URL. - pub url: Option, - /// The data itself. - pub literal: Option>, - /// HTTP content coding the data is stored in. - pub encoding: Option, - /// Size of the encoded data. - pub encoded_size: Option, - /// SHA-256 of the encoded data. - pub encoded_sha256: Option<[u8; DIGEST_SIZE]>, - /// Size of the decoded data. - pub original_size: Option, - /// SHA-256 of the decoded data. - pub original_sha256: Option<[u8; DIGEST_SIZE]>, - /// Offset of the file's data inside the decoded data. - pub offset: u64, -} - -/// A file object. Fields this crate has no use for (ownership, extended -/// attributes, GPT metadata) are type checked and dropped. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Entry { - /// Relative, normalized path; None only for the leading object. - pub name: Option, - /// The inode type. - pub inode_type: InodeType, - /// Size in bytes, when known. - pub size: Option, - /// Access mode bits. - pub mode: Option, - /// Modification time in nanoseconds since the epoch. - pub mtime_nsec: Option, - /// Whether the file is read-only. - pub read_only: Option, - /// Hardlink group token, 0 or absent for none. - pub inode_token: Option, - /// Content sources. - pub contents: Vec, - /// SHA-256 of the file's data. - pub sha256: Option<[u8; DIGEST_SIZE]>, - /// Start of the validity window in microseconds since the epoch. - pub valid_since_usec: u64, - /// End of the validity window, if any. - pub valid_until_usec: Option, - /// Whether the entry is revoked. - pub revoked: bool, -} +impl TryFrom<&FileObject> for EntryKind { + type Error = crate::Error; -impl Entry { - /// The path of the entry inside a volume. - pub fn path(&self) -> String { - format!("/{}", self.name.as_deref().unwrap_or("")) - } - - /// Checks the validity window and the revocation flag against `now`. - pub fn check_validity(&self, now_usec: u64) -> Result<()> { - let what = self.name.as_deref().unwrap_or("the manifest"); - let invalid = |problem: ValidityProblem| Detail::Validity { - name: self.path(), - problem, + fn try_from(object: &FileObject) -> Result { + let unsupported = |what, value: Option<&str>| Detail::Unsupported { + name: Some(path_in_volume(&object.name)), + what, + value: value.map(str::to_string), }; - if self.revoked { - bail!(EKEYREVOKED, invalid(ValidityProblem::Revoked), "{} is revoked", what); - } - if now_usec < self.valid_since_usec { - bail!( - EKEYEXPIRED, - invalid(ValidityProblem::NotYetValid), - "{} is not valid yet", - what - ); - } - if let Some(until) = self.valid_until_usec { - if now_usec >= until { - bail!(EKEYEXPIRED, invalid(ValidityProblem::Expired), "{} has expired", what); - } - } - Ok(()) - } - - /// The modification time, if the manifest has one. - pub fn mtime(&self) -> Option { - self.mtime_nsec - .map(|n| UNIX_EPOCH + Duration::new(n / 1_000_000_000, (n % 1_000_000_000) as u32)) - } - - /// Whether the file is read-only according to `readOnly` or `mode`. - pub fn is_read_only(&self) -> bool { - match (self.read_only, self.mode) { - (Some(r), _) => r, - (None, Some(m)) => m & 0o222 == 0, - (None, None) => false, - } - } - - /// The `contents` entry the file's data is taken from: the first one - /// without an `encoding` or a `url`, which this crate does not handle. - /// None means the data is the file of the object's own name next to the - /// manifest. An entry whose every contents alternative needs an encoding - /// or a URL is refused with EOPNOTSUPP. - pub fn fat_contents(&self) -> Result> { - if self.contents.is_empty() { - return Ok(None); - } - if let Some(c) = self.contents.iter().find(|c| c.encoding.is_none() && c.url.is_none()) { - return Ok(Some(c)); - } - let mut reasons = Vec::new(); - for c in &self.contents { - if let Some(e) = &c.encoding { - reasons.push(format!("'{}' encoding", e)); - } else if c.url.is_some() { - reasons.push("a URL".to_string()); + match object.inode_type { + InodeType::Regular => { + object.data()?; + if let Some(size) = object.size.filter(|&size| size > MAX_FILE_SIZE) { + let path = path_in_volume(&object.name); + bail!( + EFBIG, + Detail::TooLarge { + path: Some(path.clone()), + size, + maximum: MAX_FILE_SIZE, + }, + "'{}' is {} bytes, a FAT32 file holds at most {}", + path, + size, + MAX_FILE_SIZE + ); + } + Ok(EntryKind::File) } - } - reasons.sort(); - reasons.dedup(); - bail!( - EOPNOTSUPP, - Detail::Unsupported { - name: Some(self.path()), - what: UnsupportedKind::Transport, - value: Some(reasons.join(" or ")), - }, - "'{}' is only available through {}, which is not supported", - self.path(), - reasons.join(" or ") - ) - } - - /// Whether the entry can be stored on FAT by this crate. Symlinks, - /// device nodes, FIFOs and sockets cannot; neither can a directory that - /// refers to a sub-manifest nor a file whose contents need decoding or - /// fetching. All of them are refused with EOPNOTSUPP. - pub fn check_supported(&self) -> Result<()> { - self.storable().map(|_| ()) - } - - /// What the entry is to FAT, if it can be stored, see - /// [`Entry::check_supported`]. - pub fn storable(&self) -> Result> { - match self.inode_type { - InodeType::Regular => self.fat_contents().map(Storable::File), InodeType::Directory => { - if !self.contents.is_empty() || self.sha256.is_some() { + if !object.contents.is_empty() || object.sha256.is_some() { bail!( EOPNOTSUPP, - Detail::Unsupported { - name: Some(self.path()), - what: UnsupportedKind::SubManifest, - value: None, - }, + unsupported(UnsupportedKind::SubManifest, None), "'{}' refers to a sub-manifest, which is not supported", - self.path() + path_in_volume(&object.name) ); } - Ok(Storable::Directory) + Ok(EntryKind::Directory) } other => bail!( EOPNOTSUPP, - Detail::Unsupported { - name: Some(self.path()), - what: UnsupportedKind::InodeType, - value: Some(other.as_str().to_string()), - }, + unsupported(UnsupportedKind::InodeType, Some(other.as_str())), "'{}' is a {}, which FAT cannot store", - self.path(), - other.as_str() + path_in_volume(&object.name), + other ), } } - - /// Whether the data comes from outside the manifest, i.e. from a - /// [`ContentSource`] rather than from a literal. Entries this crate - /// cannot store are not streamed either. - pub fn is_streamed(&self) -> bool { - self.inode_type == InodeType::Regular - && matches!(self.fat_contents(), Ok(c) if c.is_none_or(|c| c.literal.is_none())) - } } -/// An entry as FAT stores it, see [`Entry::storable`]. +/// What an assembly, and the plan of one, do with a file object. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Storable<'a> { - /// A regular file, with its contents if the manifest names any. - File(Option<&'a Contents>), - /// A directory. - Directory, -} - -/// A parsed manifest. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Manifest { - /// The leading object. - pub root: Entry, - /// The file objects, in manifest order. - pub entries: Vec, - /// Number of signature objects seen. None of them was verified. - pub signatures: usize, -} - -/// Applies the empty-hash/zero-size rules: a known empty hash implies size -/// 0 and vice versa. -fn reconcile_hash_and_size(hash: &mut Option<[u8; DIGEST_SIZE]>, size: &mut Option, what: &str) -> Result<()> { - match (*hash, *size) { - (Some(h), Some(s)) if h == sha256::EMPTY && s != 0 => { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "sha256"), - "{}: a zero hash with a non-zero size", - what - ) - } - (Some(h), Some(0)) if h != sha256::EMPTY => { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "size"), - "{}: a zero size with a non-zero hash", - what - ) - } - (Some(h), None) if h == sha256::EMPTY => *size = Some(0), - (None, Some(0)) => *hash = Some(sha256::EMPTY), - _ => {} - } - Ok(()) -} - -fn parse_contents(v: &Value, what: &str) -> Result { - let o = v.as_object().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::InvalidContents, "contents"), - "{}: contents entry is not an object", - what - ) - })?; - let mut c = Contents::default(); - for (key, value) in o.iter() { - if value.is_null() { - continue; - } - match key { - "file" => { - let f = string(value, "file")?; - if !valid_name(f) { - bail!( - EBADMSG, - malformed_field(Problem::InvalidContents, "file"), - "{}: contents file reference '{}' is not a valid relative path", - what, - f - ); - } - c.file = Some(f.to_string()); - } - "url" => { - let u = string(value, "url")?; - if !(u.starts_with("http://") || u.starts_with("https://")) { - bail!( - EBADMSG, - malformed_field(Problem::InvalidContents, "url"), - "{}: contents URL '{}' is not http or https", - what, - u - ); - } - c.url = Some(u.to_string()); - } - "literal" => { - c.literal = Some(base64_decode(string(value, "literal")?).ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::InvalidContents, "literal"), - "{}: literal contents are not Base64", - what - ) - })?); - } - "encoding" => { - let e = string(value, "encoding")?.to_ascii_lowercase(); - if e.is_empty() || e == "identity" { - bail!( - EBADMSG, - malformed_field(Problem::InvalidContents, "encoding"), - "{}: encoding '{}' is not permitted", - what, - e - ); - } - c.encoding = Some(e); - } - "encodedSize" => c.encoded_size = Some(uint(value, key)?), - "encodedSha256" => c.encoded_sha256 = Some(hash(value, key)?), - "originalSize" => c.original_size = Some(uint(value, key)?), - "originalSha256" => c.original_sha256 = Some(hash(value, key)?), - "offset" => c.offset = uint(value, key)?, - _ => {} - } - } - if [c.file.is_some(), c.url.is_some(), c.literal.is_some()] - .into_iter() - .filter(|&set| set) - .count() - > 1 - { - bail!( - EBADMSG, - malformed(Problem::InvalidContents), - "{}: only one of file, url and literal may be set", - what - ); - } - reconcile_hash_and_size(&mut c.encoded_sha256, &mut c.encoded_size, what)?; - reconcile_hash_and_size(&mut c.original_sha256, &mut c.original_size, what)?; - if c.encoding.is_none() { - // Without an encoding the encoded and the original data are the same. - match (c.encoded_size, c.original_size) { - (Some(a), Some(b)) if a != b => bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "encodedSize"), - "{}: encoded and original size differ without an encoding", - what - ), - (Some(a), None) => c.original_size = Some(a), - (None, Some(b)) => c.encoded_size = Some(b), - _ => {} - } - match (c.encoded_sha256, c.original_sha256) { - (Some(a), Some(b)) if a != b => bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "encodedSha256"), - "{}: encoded and original hash differ without an encoding", - what - ), - (Some(a), None) => c.original_sha256 = Some(a), - (None, Some(b)) => c.encoded_sha256 = Some(b), - _ => {} - } - } - if let Some(literal) = &c.literal { - if let Some(s) = c.encoded_size { - if s != literal.len() as u64 { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "literal"), - "{}: literal contents are {} bytes, not {}", - what, - literal.len(), - s - ); - } - } - c.encoded_size = Some(literal.len() as u64); - if c.encoding.is_none() { - c.original_size = c.encoded_size; - } - } - if let Some(total) = c.original_size { - if c.offset > total { - bail!( - EBADMSG, - malformed_field(Problem::InvalidContents, "offset"), - "{}: contents offset {} is beyond the data size {}", - what, - c.offset, - total - ); - } - } - Ok(c) -} - -/// Parses one file object. `index` is its position in the manifest; 0 is -/// the leading object. -pub fn parse_entry(object: &Object, index: usize) -> Result { - let mut e = Entry { - name: None, - inode_type: InodeType::Regular, - size: None, - mode: None, - mtime_nsec: None, - read_only: None, - inode_token: None, - contents: Vec::new(), - sha256: None, - valid_since_usec: 0, - valid_until_usec: None, - revoked: false, - }; - let mut inode_type = None; - let mut media_type = None; - let mut major_minor = false; - let mut gpt = false; - let mut gpt_disk = false; - let mut gpt_flags = None; - let mut gpt_no_auto = None; - let mut gpt_growfs = None; - let what = |e: &Entry| format!("manifest object {} ({})", index, e.name.as_deref().unwrap_or("root")); - for (key, value) in object.iter() { - if value.is_null() { - continue; - } - match key { - "name" => { - let n = string(value, key)?; - if !valid_name(n) { - bail!( - EBADMSG, - malformed_field(Problem::InvalidName, "name"), - "manifest object {}: name '{}' is not a valid relative path", - index, - n - ); - } - e.name = Some(n.to_string()); - } - "mediaType" => media_type = Some(string(value, key)?.to_string()), - "type" => { - let t = string(value, key)?; - inode_type = Some(InodeType::parse(t).ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::UnknownType, "type"), - "manifest object {}: unknown inode type '{}'", - index, - t - ) - })?); - } - "size" => e.size = Some(uint(value, key)?), - "mode" => e.mode = Some(access_mode(value, key)?), - "uid" | "gid" => { - // 0xFFFF and 0xFFFFFFFF are the invalid IDs. - let v = uint(value, key)?; - if v >= 0xFFFF_FFFF || v == 0xFFFF { - bail!( - EBADMSG, - malformed_field(Problem::FieldOutOfRange, key), - "manifest object {}: {} {} is out of range", - index, - key, - v - ); - } - } - "userName" | "groupName" => { - let n = string(value, key)?; - if !valid_user_group_name(n) { - bail!( - EBADMSG, - malformed_field(Problem::WrongFieldType, key), - "manifest object {}: {} '{}' is not a valid name", - index, - key, - n - ); - } - } - "gptLabel" => { - let l = string(value, key)?; - if !valid_gpt_label(l) { - bail!( - EBADMSG, - malformed_field(Problem::WrongFieldType, "gptLabel"), - "manifest object {}: '{}' is not a valid GPT partition label", - index, - l - ); - } - gpt = true; - } - "gptUuid" | "gptTypeUuid" | "gptDiskUuid" => { - let id = string(value, key)?; - if !valid_id128(id) { - bail!( - EBADMSG, - malformed_field(Problem::WrongFieldType, key), - "manifest object {}: {} '{}' is not a UUID", - index, - key, - id - ); - } - if key == "gptDiskUuid" { - gpt_disk = true; - } else { - gpt = true; - } - } - "major" | "minor" => { - uint(value, key)?; - major_minor = true; - } - "gptFlags" => { - gpt_flags = Some(uint(value, key)?); - gpt = true; - } - "gptFlagNoAuto" => { - gpt_no_auto = Some(boolean(value, key)?); - gpt = true; - } - "gptFlagGrowFileSystem" => { - gpt_growfs = Some(boolean(value, key)?); - gpt = true; - } - "mTimeNSec" => e.mtime_nsec = Some(uint(value, key)?), - "inodeToken" => e.inode_token = Some(uint(value, key)?), - "extendedAttributes" => check_extended_attributes(value, &format!("manifest object {}", index))?, - "readOnly" => e.read_only = Some(boolean(value, key)?), - "contents" => { - let items = value.as_array().ok_or_else(|| { - err!( - EBADMSG, - malformed_field(Problem::WrongFieldType, "contents"), - "manifest field 'contents' is not an array" - ) - })?; - if items.len() > MAX_CONTENTS { - bail!( - EBADMSG, - malformed_field(Problem::InvalidContents, "contents"), - "manifest object {}: more than {} contents entries", - index, - MAX_CONTENTS - ); - } - for item in items { - e.contents - .push(parse_contents(item, &format!("manifest object {}", index))?); - } - } - "sha256" => e.sha256 = Some(hash(value, key)?), - "validSinceUSec" => e.valid_since_usec = uint(value, key)?, - "validUntilUSec" => e.valid_until_usec = Some(uint(value, key)?), - "validity" => { - // Unknown values are treated as "good", as the spec asks. - e.revoked = string(value, key)? == "revoked"; - } - _ => {} - } - } - if let Some(mt) = &media_type { - if mt != MEDIA_TYPE { - bail!( - EBADMSG, - malformed_field(Problem::InvalidMediaType, "mediaType"), - "manifest object {} has unexpected media type '{}'", - index, - mt - ); - } - } - if index == 0 { - if media_type.is_none() { - bail!( - EBADMSG, - malformed_field(Problem::InvalidMediaType, "mediaType"), - "the first manifest object does not carry the manifest media type" - ); - } - if e.name.is_some() { - bail!( - EBADMSG, - malformed_field(Problem::RootHasName, "name"), - "the first manifest object has a name" - ); - } - if !matches!(inode_type, None | Some(InodeType::Directory)) { - bail!( - EBADMSG, - malformed_field(Problem::RootNotDirectory, "type"), - "the first manifest object is not a directory" - ); - } - e.inode_type = InodeType::Directory; - } else { - if e.name.is_none() { - bail!( - EBADMSG, - malformed_field(Problem::NoName, "name"), - "manifest object {} has no name", - index - ); - } - e.inode_type = inode_type.unwrap_or(InodeType::Regular); - } - // Fields the inode type does not permit. - let t = e.inode_type; - let w = what(&e); - if e.size.is_some() && !matches!(t, InodeType::Regular | InodeType::Symlink | InodeType::Directory) { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "size"), - "{}: 'size' is not permitted on a {}", - w, - t.as_str() - ); - } - if major_minor && !matches!(t, InodeType::BlockDevice | InodeType::CharDevice) { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "major"), - "{}: 'major' and 'minor' are not permitted on a {}", - w, - t.as_str() - ); - } - if e.mode.is_some() && t == InodeType::Symlink { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "mode"), - "{}: 'mode' is not permitted on a symlink", - w - ); - } - if matches!(e.inode_token, Some(tok) if tok != 0) && t == InodeType::Directory { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "inodeToken"), - "{}: 'inodeToken' is not permitted on a directory", - w - ); - } - if (!e.contents.is_empty() || e.sha256.is_some()) - && !matches!(t, InodeType::Regular | InodeType::Symlink | InodeType::Directory) - { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "contents"), - "{}: 'contents' and 'sha256' are not permitted on a {}", - w, - t.as_str() - ); - } - if gpt && t != InodeType::Regular { - bail!( - EBADMSG, - malformed(Problem::FieldNotPermitted), - "{}: GPT fields are only permitted on regular files", - w - ); - } - if gpt_disk && index != 0 { - bail!( - EBADMSG, - malformed_field(Problem::FieldNotPermitted, "gptDiskUuid"), - "{}: 'gptDiskUuid' is only permitted on the first object", - w - ); - } - if let (Some(ro), Some(mode)) = (e.read_only, e.mode) { - if ro == (mode & 0o222 != 0) { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "readOnly"), - "{}: 'readOnly' and 'mode' contradict each other", - w - ); - } - } - if let Some(flags) = gpt_flags { - if gpt_no_auto.is_some_and(|b| b != (flags & GPT_FLAG_NO_AUTO != 0)) - || gpt_growfs.is_some_and(|b| b != (flags & GPT_FLAG_GROWFS != 0)) - { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "gptFlags"), - "{}: 'gptFlags' and the 'gptFlag*' fields contradict each other", - w - ); - } - } - reconcile_hash_and_size(&mut e.sha256, &mut e.size, &w)?; - // Sizes and hashes of contents and object must agree where they overlap. - for c in &e.contents { - match (e.size, c.original_size) { - (Some(size), Some(total)) => { - if c.offset.checked_add(size).is_none_or(|end| end > total) { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "offset"), - "{}: offset {} plus size {} exceeds the contents size {}", - w, - c.offset, - size, - total - ); - } - } - (None, Some(total)) => e.size = Some(total - c.offset), - _ => {} - } - if c.offset == 0 && e.size.is_some() && c.original_size == e.size { - match (e.sha256, c.original_sha256) { - (Some(a), Some(b)) if a != b => { - bail!( - EBADMSG, - malformed_field(Problem::Contradiction, "sha256"), - "{}: object and contents hashes differ", - w - ) - } - (None, Some(b)) => e.sha256 = Some(b), - _ => {} - } - } - } - if e.size.is_some_and(|s| s > MAX_FILE_SIZE) && t == InodeType::Regular { - bail!( - EFBIG, - Detail::TooLarge { - path: Some(e.path()), - size: e.size.unwrap_or(0), - maximum: MAX_FILE_SIZE, - }, - "{}: {} bytes exceed what FAT32 can store", - w, - e.size.unwrap_or(0) - ); - } - Ok(e) -} - -/// Splits JSON text sequence records off the front of `buffer`. Returns the -/// record text and the number of bytes consumed, or None if the buffer holds -/// no complete record yet (unless `eof` is set). -fn next_record(buffer: &[u8], eof: bool) -> Result> { - let mut consumed = 0; - loop { - let rest = &buffer[consumed..]; - if rest.is_empty() { - return Ok(None); - } - if rest[0] != RECORD_SEPARATOR { - bail!( - EBADMSG, - malformed(Problem::NoRecordSeparator), - "manifest record does not start with a record separator but with byte 0x{:02x}", - rest[0] - ); - } - let body = &rest[1..]; - let end = match body.iter().position(|&b| b == RECORD_SEPARATOR) { - Some(p) => p, - None if eof => body.len(), - None if body.len() > MAX_RECORD_SIZE => { - bail!( - E2BIG, - malformed(Problem::RecordTooLarge), - "manifest record exceeds {} bytes", - MAX_RECORD_SIZE - ) - } - None => return Ok(None), - }; - let record = &body[..end]; - if record.len() > MAX_RECORD_SIZE { - bail!( - E2BIG, - malformed(Problem::RecordTooLarge), - "manifest record exceeds {} bytes", - MAX_RECORD_SIZE - ); - } - if record.contains(&0) { - bail!( - EBADMSG, - malformed(Problem::ContainsNulByte), - "manifest record contains a NUL byte" - ); - } - let text = std::str::from_utf8(record) - .map_err(|_| err!(EBADMSG, malformed(Problem::NotUtf8), "manifest record is not UTF-8"))?; - consumed += 1 + end; - if text.bytes().all(|b| b.is_ascii_whitespace()) { - // Empty records are skipped, as RFC 7464 suggests. Only ASCII - // whitespace counts as empty, like systemd's strstrip(). - continue; - } - return Ok(Some((text, consumed))); - } -} - -/// Reads a manifest. -pub fn read(reader: &mut dyn Read) -> Result { - let mut buffer = Vec::new(); - let mut root = None; - let mut entries: Vec = Vec::new(); - // FAT folds case, so names are keyed by their folded form. - let mut names: HashMap, usize> = HashMap::new(); - let mut signatures = 0; - let mut trailer = false; - let mut index = 0; - let mut eof = false; - // Records are consumed by moving `start`; the bytes before it are - // dropped when more input is read, once per chunk and not once per - // record. - let mut start = 0; - let mut chunk = vec![0u8; 65536]; - loop { - let (text, consumed) = match next_record(&buffer[start..], eof).map_err(|e| e.in_record(index as u64, None))? { - Some((t, c)) => (t.to_string(), c), - None if eof => break, - None => { - buffer.drain(..start); - start = 0; - let n = crate::host::read_some(reader, &mut chunk)?; - if n == 0 { - eof = true; - } else { - buffer.extend_from_slice(&chunk[..n]); - } - continue; - } - }; - start += consumed; - if trailer { - malformed!( - Problem::DataAfterTrailer, - EBADMSG, - "manifest contains data after the trailer object" - ); - } - let value = json::parse(&text).map_err(|e| { - err!( - EBADMSG, - malformed(Problem::NotJson), - "manifest record {} is not valid JSON: {}", - index, - e - ) - .in_record(index as u64, None) - })?; - let Value::Object(object) = value else { - malformed!( - Problem::NotObject, - EBADMSG, - "manifest record {} is not a JSON object", - index - ) - }; - let media_type = match object.get("mediaType") { - None => None, - Some(Value::String(s)) => Some(s.as_str()), - Some(_) => malformed!( - Problem::InvalidMediaType, - EBADMSG, - "manifest object {} has a mediaType that is not a string", - index - ), - }; - if index == 0 { - if media_type != Some(MEDIA_TYPE) { - malformed!( - Problem::InvalidMediaType, - EBADMSG, - "the first object of the manifest is not of the manifest media type" - ); - } - } else if let Some(mt) = media_type.filter(|&mt| mt != MEDIA_TYPE) { - match mt { - TRAILER_MEDIA_TYPE => trailer = true, - SIGNATURE_MEDIA_TYPE => { - check_signature(&object, index).map_err(|e| e.in_record(index as u64, None))?; - signatures += 1; - } - _ => {} - } - index += 1; - continue; - } - if signatures > 0 { - malformed!( - Problem::FileAfterSignature, - EBADMSG, - "manifest contains a file object after a signature object" - ); - } - let entry = parse_entry(&object, index) - .map_err(|e| e.in_record(index as u64, object.get("name").and_then(Value::as_str)))?; - if index == 0 { - root = Some(entry); - } else { - let name = entry.name.as_deref().unwrap_or_default(); - if let Some(&earlier) = names.get(&fat_key(name)) { - let other = entries[earlier].name.as_deref().unwrap_or_default(); - if other == name { - malformed!(Problem::DuplicateName, EBADMSG, "manifest lists '{}' twice", name); - } - malformed!( - Problem::DuplicateName, - EEXIST, - "manifest lists '{}' and '{}', which FAT cannot tell apart", - other, - name - ); - } - names.insert(fat_key(name), entries.len()); - entries.push(entry); - } - index += 1; - } - let Some(root) = root else { - malformed!(Problem::NoObjects, EBADMSG, "manifest contains no objects") - }; - if !trailer { - malformed!( - Problem::NoTrailer, - EBADMSG, - "manifest lacks the trailer object, it is incomplete" - ); - } - Ok(Manifest { - root, - entries, - signatures, - }) -} - -/// Parses a manifest held in memory. -pub fn parse(bytes: &[u8]) -> Result { - let mut slice = bytes; - read(&mut slice) -} - -impl Manifest { - /// Fails with EOPNOTSUPP for the first entry this crate cannot store, - /// see [`Entry::check_supported`]. Assembling without `skip_unsupported` - /// would fail at that entry; checking first avoids formatting for - /// nothing. - pub fn check_supported(&self) -> Result<()> { - self.entries.iter().try_for_each(Entry::check_supported) - } - - /// Total size of the data a [`ContentSource`] has to deliver: the sizes - /// of all regular files without literal contents, in manifest order. - /// Every such file needs a known size. Entries that cannot be stored do - /// not count, since they are skipped or stop the assembly. - pub fn streamed_bytes(&self) -> Result { - let mut total = 0u64; - for e in &self.entries { - if e.is_streamed() { - let size = e.size.ok_or_else(|| { - err!( - EINVAL, - Detail::Manifest { - problem: ManifestProblem::NoSize, - record: None, - name: Some(e.path()), - field: Some("size".into()), - }, - "'{}' has no size, so its contents cannot be streamed", - e.path() - ) - })?; - total = total - .checked_add(size) - .ok_or_else(|| err!(EOVERFLOW, "total manifest size overflows"))?; - } +pub(crate) enum ObjectAction { + /// Store it as a file or as a directory. + Store(EntryKind), + /// Leave it out. + Skip(SkipReason), +} + +/// Decides what an assembly, and the plan of one, do with the file objects +/// of a manifest, one after the other in manifest order: store each as a +/// file or as a directory, or leave it out. +/// +/// The objects below a directory come right after it in a manifest, so the +/// name of the last directory left out is all that has to be kept. +#[derive(Debug, Default)] +pub(crate) struct ObjectTriage { + /// The name of the last directory left out, as long as the objects + /// after it are below it, and empty otherwise: no file object has an + /// empty name. The string is kept and filled again, so leaving out a + /// directory allocates only for a name longer than any before. + skipped_directory: String, +} + +impl ObjectTriage { + /// What to do with `object`, the file object that comes after the ones + /// decided on before. An object below a directory that is left out is + /// left out as well. One that this crate cannot store, see + /// [`EntryKind`], is left out where [`AssembleFlags::SKIP_UNSUPPORTED`] + /// among `flags` allows it, and fails otherwise. + pub(crate) fn decide(&mut self, object: &FileObject, flags: AssembleFlags) -> Result { + if !self.skipped_directory.is_empty() { + let below = object + .name + .strip_prefix(self.skipped_directory.as_str()) + .is_some_and(|rest| rest.starts_with(SEPARATOR)); + if below { + return Ok(ObjectAction::Skip(SkipReason::BelowSkipped)); + } + self.skipped_directory.clear(); + } + match EntryKind::try_from(object) { + Ok(kind) => Ok(ObjectAction::Store(kind)), + Err(e) if e.errno() == EOPNOTSUPP && flags.contains(AssembleFlags::SKIP_UNSUPPORTED) => { + if object.inode_type == InodeType::Directory { + self.skipped_directory.push_str(&object.name); + } + Ok(ObjectAction::Skip(SkipReason::Unsupported)) + } + Err(e) => Err(e), } - Ok(total) } } diff --git a/src/fat/manifest/tests.rs b/src/fat/manifest/tests.rs index 7155327..d020e59 100644 --- a/src/fat/manifest/tests.rs +++ b/src/fat/manifest/tests.rs @@ -4,14 +4,21 @@ use crate::populate::CopyOptions; use crate::progress::Progress; use crate::test_util::{volume, TempDir, TempImage}; use crate::volume::Volume; -use crate::{ContentProblem, SourceProblem}; +use crate::{ContentProblem, Error, ManifestProblem, SourceProblem}; +use std::io::{Read, Write}; use std::os::fd::AsFd; use std::path::Path; +use std::time::{Duration, UNIX_EPOCH}; +use uapi16::{Data, Digest, Mode, MAX_RECORD_SIZE, RECORD_SEPARATOR}; /// A directory resolved once, the way the tool resolves the SOURCE of a /// manifest. -fn dir_source(path: &Path) -> DirectorySource { - DirectorySource::new(crate::host::open_dir(path).unwrap()) +fn source_dir(path: &Path) -> PinnedDirectory { + PinnedDirectory::new(crate::host::open_dir(path).unwrap()) +} + +fn dir_source(path: &Path) -> DirectorySource { + DirectorySource::new(source_dir(path)) } /// The manifest the generator writes for the tree at `path`. @@ -23,6 +30,44 @@ fn generated(path: &Path) -> Vec { out } +/// Reads the manifest `bytes` to its end with the reader of the `uapi16` +/// crate, which requires the code point order, and returns its root file +/// object and its file objects. A test can hold a manifest whole. +fn read(bytes: &[u8]) -> Result<(RootObject, Vec)> { + let reader = Reader::open(bytes)?; + reader.root().require_order(Order::CodePoint)?; + let root = reader.root().clone(); + let mut objects = Vec::new(); + for object in reader { + if let Object::File(object) = object? { + objects.push(*object); + } + } + Ok((root, objects)) +} + +/// The file objects of the manifest `bytes`. +fn objects(bytes: &[u8]) -> Vec { + read(bytes).unwrap().1 +} + +/// Assembles the manifest `bytes` into `v`. +fn assemble( + v: &mut Volume, + bytes: &[u8], + source: &mut dyn ContentSource, + options: &AssembleOptions, +) -> Result { + v.assemble(&mut Reader::open(bytes)?, source, options) +} + +/// Assembles the manifest `bytes` into `v` with the contents of the files +/// from `stream`. +fn assemble_stream(v: &mut Volume, bytes: &[u8], stream: &[u8], options: &AssembleOptions) -> Result { + let mut stream = stream; + assemble(v, bytes, &mut StreamSource::new(&mut stream), options) +} + fn seq(records: &[&str]) -> Vec { let mut out = Vec::new(); for r in records { @@ -33,343 +78,265 @@ fn seq(records: &[&str]) -> Vec { out } -const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#; +const ROOT: &str = r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"#; const TRAILER: &str = r#"{"mediaType":"application/vnd.uapi.16.trailer"}"#; +/// A root file object of a manifest that records modification times too. +const ROOT_MTIME: &str = concat!( + r#"{"features":["device","gid","hardlink","mode","mtime","sha256","size","symlink","uid"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# +); + +/// The contents of a file read back from the volume. +fn contents(v: &Volume, path: &str) -> Vec { + let mut back = Vec::new(); + v.open_file(path).unwrap().read_to_end(&mut back).unwrap(); + back +} + +/// Records what an assembly reports to its observer. +#[derive(Debug, Default)] +struct Recorder { + progress: Vec, + skipped: Vec<(String, SkipReason)>, +} + +impl AssembleObserver for Recorder { + fn progress(&mut self, progress: &Progress) { + self.progress.push(*progress); + } + + fn skipped(&mut self, name: &Name, reason: SkipReason) { + self.skipped.push((name.to_string(), reason)); + } +} #[test] -fn parses_a_manifest() { - let hello = sha256::to_hex(&sha256::digest(b"hello")); - let m = parse(&seq(&[ - ROOT, +fn assembles_what_a_manifest_describes() { + let hello = Sha256::digest(b"hello").to_string(); + let m = seq(&[ + ROOT_MTIME, r#"{"mode":493,"name":"EFI","type":"dir","uid":0,"gid":0}"#, r#"{"name":"EFI/BOOT","type":"dir"}"#, &format!( r#"{{"mTimeNSec":1700000000000000000,"mode":420,"name":"EFI/BOOT/BOOTX64.EFI","sha256":"{}","size":5}}"#, hello ), - r#"{"name":"empty","size":"0"}"#, - r#"{"contents":[{"literal":"aGVs bG8="}],"name":"literal.txt","mode":"644"}"#, + r#"{"name":"empty","size":0}"#, r#"{"contents":[{"literal":"aGVsbG8="}],"name":"link","type":"lnk"}"#, + r#"{"contents":[{"literal":"aGVsbG8="}],"name":"literal.txt","mode":420}"#, r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"AAAA"}"#, r#"{"mediaType":"application/x-unknown","whatever":1}"#, TRAILER, - ])) - .unwrap(); - assert_eq!(m.entries.len(), 6); - assert_eq!(m.entries[4].mode, Some(0o644)); - assert_eq!(m.signatures, 1); - assert_eq!(m.root.inode_type, InodeType::Directory); - let boot = &m.entries[2]; - assert_eq!(boot.name.as_deref(), Some("EFI/BOOT/BOOTX64.EFI")); - assert_eq!(boot.size, Some(5)); - assert_eq!(boot.mtime(), Some(UNIX_EPOCH + Duration::from_secs(1_700_000_000))); - assert!(!boot.is_read_only()); - assert!(boot.is_streamed()); - let empty = &m.entries[3]; - assert_eq!(empty.sha256, Some(sha256::EMPTY)); - let literal = &m.entries[4]; - assert_eq!(literal.contents[0].literal.as_deref(), Some(&b"hello"[..])); - assert_eq!(literal.size, Some(5)); - assert!(!literal.is_streamed()); - assert_eq!(m.streamed_bytes().unwrap(), 5); - assert_eq!(m.entries[5].inode_type, InodeType::Symlink); + ]); + let entries = objects(&m); + assert_eq!(entries.len(), 6); + assert_eq!(entries[5].inode.mode.map(Mode::bits), Some(0o644)); + let boot = &entries[2]; + assert_eq!( + boot.inode.mtime(), + Some(UNIX_EPOCH + Duration::from_secs(1_700_000_000)) + ); + assert!(!boot.inode.is_read_only() && boot.has_external_data()); + assert_eq!(entries[3].sha256, Some(Sha256::EMPTY)); + assert!(!entries[5].has_external_data()); + let (_img, mut v) = volume(8 << 20, 512, 512); + let options = AssembleOptions { + flags: AssembleFlags::SKIP_UNSUPPORTED, + ..AssembleOptions::default() + }; + let r = assemble_stream(&mut v, &m, b"hello", &options).unwrap(); + assert_eq!((r.files, r.directories, r.bytes, r.skipped), (3, 2, 10, 1)); + assert_eq!(contents(&v, "/EFI/BOOT/BOOTX64.EFI"), b"hello"); + assert_eq!( + v.metadata("/EFI/BOOT/BOOTX64.EFI").unwrap().modified, + UNIX_EPOCH + Duration::from_secs(1_700_000_000) + ); + assert_eq!(contents(&v, "/literal.txt"), b"hello"); + assert_eq!(v.metadata("/empty").unwrap().size, 0); + assert_eq!(v.metadata("/link").unwrap_err().errno(), ENOENT); } +/// What the reader refuses is for the uapi16 crate to test, in its +/// refused.jsonl. An assembly fails on it before it writes what the record +/// describes, with the problem in the detail. #[test] fn rejects_broken_manifests() { - let cases: &[&[&str]] = &[ - &[], - &[ROOT], - &[r#"{"name":"x"}"#, TRAILER], - &[ROOT, r#"{"name":"x"}"#], - &[ROOT, TRAILER, r#"{"name":"x"}"#], - &[ - ROOT, - r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"AA=="}"#, - r#"{"name":"x"}"#, - TRAILER, - ], - &[ROOT, r#"{"name":"/abs"}"#, TRAILER], - &[ROOT, r#"{"name":"a/../b"}"#, TRAILER], - &[ROOT, r#"{"name":"Uapi16Manifest"}"#, TRAILER], - &[ROOT, r#"{"name":"x","type":"weird"}"#, TRAILER], - &[ROOT, r#"{"name":"x","type":"dir","size":1,"inodeToken":1}"#, TRAILER], - &[ROOT, r#"{"name":"x","type":"fifo","size":1}"#, TRAILER], - &[ROOT, r#"{"name":"x","mode":420,"readOnly":true}"#, TRAILER], - &[ - ROOT, - r#"{"name":"x","size":3,"sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"x","contents":[{"file":"a","literal":"AA=="}]}"#, - TRAILER, - ], - &[ROOT, r#"{"name":"x","contents":[{"encoding":"identity"}]}"#, TRAILER], - &[ - ROOT, - r#"{"name":"x","size":5,"contents":[{"originalSize":4}]}"#, - TRAILER, - ], - &[ROOT, r#"{"name":"x"}"#, r#"{"name":"x"}"#, TRAILER], - &[ROOT, r#"{"name":"x","mode":5000}"#, TRAILER], - &[ROOT, r#"{"name":"x","mode":"9"}"#, TRAILER], - &[ - r#"{"mediaType":"application/vnd.uapi.16.manifest","name":"x"}"#, - TRAILER, - ], - // The rules systemd's reader applies on top. - &[ROOT, r#"{"name":"x","uid":65535}"#, TRAILER], - &[ROOT, r#"{"name":"x","mediaType":null}"#, TRAILER], - &[ROOT, r#"{"name":"x","extendedAttributes":[]}"#, TRAILER], - &[ROOT, r#"{"name":"x","extendedAttributes":{"user":{"a":"b"}}}"#, TRAILER], - &[ - ROOT, - r#"{"name":"x","extendedAttributes":{"user":{"":{"text":"b"}}}}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"x","extendedAttributes":{"user":{"a":{"text":"b","base64":"Yg=="}}}}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"x","extendedAttributes":{"user":{"a":{"base64":"!"}}}}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"x","extendedAttributes":{"user":{"a":{"base64":"Yg"}}}}"#, - TRAILER, - ], - &[ROOT, r#"{"name":"x","contents":[{"literal":"aGVsbG8"}]}"#, TRAILER], - &[ROOT, r#"{"name":"x","userName":""}"#, TRAILER], - &[ROOT, r#"{"name":"x","userName":"123"}"#, TRAILER], - &[ROOT, r#"{"name":"x","userName":"a:b"}"#, TRAILER], - &[ROOT, r#"{"name":"x","groupName":" g"}"#, TRAILER], - &[ROOT, r#"{"name":"x","gptUuid":"not-a-uuid"}"#, TRAILER], - &[ROOT, r#"{"name":"x","gptUuid":"12345678\u00e9"}"#, TRAILER], - &[ - ROOT, - r#"{"name":"x","gptTypeUuid":"\u00e9\u00e9\u00e9\u00e9\u00e9"}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"x","gptLabel":"0123456789012345678901234567890123456"}"#, - TRAILER, - ], - &[ROOT, r#"{"name":"x","gptFlags":0,"gptFlagNoAuto":true}"#, TRAILER], - &[ - ROOT, - r#"{"mediaType":"application/vnd.uapi.16.signature","data":"AAAA"}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","key":"xyz"}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"!!"}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"pkcs7","data":"AA="}"#, - TRAILER, - ], - &[ - ROOT, - r#"{"name":"a.txt","size":0}"#, - r#"{"name":"A.TXT","size":0}"#, - TRAILER, - ], - ]; - for records in cases { - assert!(parse(&seq(records)).is_err(), "{:?} accepted", records); - } - let long = "x".repeat(256); - assert!(parse(&seq(&[ROOT, &format!(r#"{{"name":"{}","size":0}}"#, long), TRAILER])).is_err()); - let contents = format!("[{}]", vec![r#"{"literal":"AA=="}"#; 257].join(",")); - assert!(parse(&seq(&[ - ROOT, - &format!(r#"{{"name":"x","contents":{}}}"#, contents), - TRAILER - ])) - .is_err()); - let contents = format!("[{}]", vec![r#"{"literal":"AA=="}"#; 256].join(",")); - assert!(parse(&seq(&[ - ROOT, - &format!(r#"{{"name":"x","contents":{}}}"#, contents), - TRAILER - ])) - .is_ok()); - // Records beyond the cap. + let (_img, mut v) = volume(8 << 20, 512, 512); + let m = seq(&[ROOT, r#"{"name":"x","size":1,"mode":5000}"#, TRAILER]); + let e = assemble_stream(&mut v, &m, b"x", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EBADMSG); + assert_eq!( + e.detail(), + Some(&Detail::Manifest { + problem: ManifestProblem::Malformed(Problem::FieldOutOfRange), + record: Some(1), + name: Some("x".to_string()), + field: Some("mode".to_string()), + }) + ); + assert!(v.read_dir("/").unwrap().is_empty()); + // A record beyond the cap fails with E2BIG. let big = format!(r#"{{"name":"x","size":0,"pad":"{}"}}"#, "p".repeat(MAX_RECORD_SIZE)); - assert_eq!(parse(&seq(&[ROOT, &big, TRAILER])).unwrap_err().errno(), E2BIG); - // No record separator at all. - assert!(parse(ROOT.as_bytes()).is_err()); - // Whitespace-only records are fine, as long as it is ASCII whitespace. - let mut bytes = seq(&[ROOT]); - bytes.extend_from_slice(&[RECORD_SEPARATOR, b'\n', b' ']); - bytes.extend_from_slice(&seq(&[TRAILER])); - assert!(parse(&bytes).is_ok()); - let mut bytes = seq(&[ROOT]); - bytes.push(RECORD_SEPARATOR); - bytes.extend_from_slice("\u{2028}".as_bytes()); - bytes.extend_from_slice(&seq(&[TRAILER])); - assert!(parse(&bytes).is_err()); - // The rules systemd relaxes are relaxed here too. - let m = parse(&seq(&[ - ROOT, - r#"{"name":"x","size":"5","sha256":"2cf2 4dba 5fb0 a30e 26e8 3b2a c5b9 e29e 1b16 1e5c 1fa7 425e 7304 3362 938b 9824","validUntilUSec":"18446744073709551615"}"#, - r#"{"name":"y","size":0,"uid":4294967294,"userName":"Domain Users","gptUuid":"urn:uuid:4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709","gptLabel":"root","gptFlags":9223372036854775808,"gptFlagNoAuto":true,"extendedAttributes":{"user":{"a":{"text":"b"},"c":{"base64":"Yg=="}},"other":5}}"#, - TRAILER, - ])) - .unwrap(); - assert_eq!(m.entries[0].size, Some(5)); - assert_eq!(m.entries[0].sha256, Some(sha256::digest(b"hello"))); - assert_eq!(m.entries[0].valid_until_usec, Some(u64::MAX)); -} - -/// The test vectors of systemd's unbase64mem() in -/// src/test/test-hexdecoct.c: what it decodes and what it refuses. -#[test] -fn base64() { - for (text, data) in [ - ("", ""), - ("Zg==", "f"), - ("Zm8=", "fo"), - ("Zm9v", "foo"), - ("Zm9vYg==", "foob"), - ("Zm9vYmE=", "fooba"), - ("Zm9vYmFy", "foobar"), - (" ", ""), - (" \n\r ", ""), - (" Zg\n== ", "f"), - (" Zm 8=\r", "fo"), - (" Zm9\n\r\r\nv ", "foo"), - (" Z m9vYg==\n\r", "foob"), - (" Zm 9vYmE= ", "fooba"), - (" Z m9v YmFy ", "foobar"), - ("aGVs\nbG8 =", "hello"), + let e = assemble_stream(&mut v, &seq(&[ROOT, &big, TRAILER]), b"", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), E2BIG); + assert!(e.is_manifest(), "{:?}", e); + assert!(v.read_dir("/").unwrap().is_empty()); + // A manifest that does not declare the code point order is refused + // before anything is written, also when its objects are in that order. + for root in [ + r#"{"mediaType":"application/vnd.uapi.16.manifest"}"#, + r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"bytes"}"#, ] { - assert_eq!(base64_decode(text).as_deref(), Some(data.as_bytes()), "{:?}", text); - } - for text in ["A", "A====", "AAB==", " A A A B = ", " Z m 8 = q u u x "] { - assert_eq!(base64_decode(text), None, "{:?}", text); + let undeclared = seq(&[ + root, + r#"{"name":"a","type":"dir"}"#, + r#"{"name":"b","size":0}"#, + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &undeclared, b"", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EBADMSG); + assert_eq!( + e.detail(), + Some(&Detail::Manifest { + problem: ManifestProblem::Malformed(Problem::NoOrder), + record: Some(0), + name: None, + field: Some("order".to_string()), + }), + "{}", + root + ); + assert!(v.read_dir("/").unwrap().is_empty()); } + // A manifest does not limit a component on its own. A name too long + // for FAT is refused when it would be written, and nothing is. + let long = format!(r#"{{"name":"{}","size":0}}"#, "x".repeat(256)); + assert!(read(&seq(&[ROOT, &long, TRAILER])).is_ok()); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &seq(&[ROOT, &long, TRAILER]), b"", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), ENAMETOOLONG); + assert!(!v.is_writing()); } -/// Both alphabets, in any mix, with the values systemd's unbase64char() -/// gives the digits, and its test of the two spellings of the same data. +/// What the volume refuses at the first object of a manifest leaves it as +/// it was, not even marked as being written: a file where it has a +/// directory, a name FAT cannot store, as a file and as a directory, and a +/// name it holds when nothing is replaced. #[test] -fn base64_alphabets() { - assert_eq!(base64_decode("AZaz").unwrap(), [1, 150, 179]); - assert_eq!(base64_decode("09+/").unwrap(), [211, 223, 191]); - assert_eq!(base64_decode("09-_").unwrap(), [211, 223, 191]); - assert_eq!(base64_decode("_-8=").unwrap(), [0xff, 0xef]); - let plaintext: &[u8] = &[ - 0xcc, 0xa1, 0x72, 0x22, 0xae, 0xda, 0x66, 0x7e, 0x04, 0xa6, 0xe0, 0x82, 0x9a, 0x97, 0x05, 0xf6, 0x33, 0xe0, - 0x0f, 0xc2, 0x45, 0x13, 0x58, 0x3f, 0xc5, 0xf4, 0xf4, 0x31, 0xab, 0x3c, 0x5f, 0x83, 0x34, 0x5b, 0x27, 0x32, - 0x8a, 0x04, 0x6c, 0x43, 0x82, 0x07, 0xe3, 0x2c, 0xac, 0xb9, 0xfb, 0xac, 0xd0, 0x03, 0x91, 0x42, 0xcb, 0xa4, - 0xde, 0x87, 0x86, 0x85, 0x10, 0xbb, 0xb7, 0x5b, 0x4b, 0xc8, 0xa0, 0xf4, 0x22, 0x1d, 0x15, 0x71, 0x87, 0x9d, - 0xbf, 0x9f, 0xa9, 0xf1, 0xee, 0xa2, 0xb6, 0xaa, 0xc8, 0xc3, 0x37, 0x9c, 0xbb, 0xdf, 0x3e, 0xac, 0xdc, 0x94, - 0x54, 0x38, 0x56, 0x07, 0x34, 0xb4, 0x3c, 0xcc, 0x31, 0x13, - ]; - for text in [ - "zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g/xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5+p8e6itqrIwzecu98+rNyUVDhWBzS0PMwxEw==", - "zKFyIq7aZn4EpuCCmpcF9jPgD8JFE1g_xfT0Mas8X4M0WycyigRsQ4IH4yysufus0AORQsuk3oeGhRC7t1tLyKD0Ih0VcYedv5-p8e6itqrIwzecu98-rNyUVDhWBzS0PMwxEw==", +fn refusals_at_the_first_object_write_nothing() { + let (_img, mut v) = volume(8 << 20, 512, 512); + let t0 = UNIX_EPOCH + Duration::from_secs(1_600_000_000); + v.create_dir("/d", t0).unwrap(); + v.write_file("/f", &mut &b"old"[..], t0, false).unwrap(); + v.sync().unwrap(); + let keep = AssembleOptions { + flags: AssembleFlags::NONE, + ..AssembleOptions::default() + }; + for (object, errno) in [ + (r#"{"name":"d","size":0}"#, EISDIR), + (r#"{"name":"a:b","size":0}"#, EINVAL), + (r#"{"name":"a:b","type":"dir"}"#, EINVAL), + (r#"{"name":"f","size":3}"#, EEXIST), ] { - assert_eq!(base64_decode(text).as_deref(), Some(plaintext)); + let e = assemble_stream(&mut v, &seq(&[ROOT, object, TRAILER]), b"new", &keep).unwrap_err(); + assert_eq!(e.errno(), errno, "{}", object); + assert!(!v.is_writing(), "{}", object); } + assert_eq!(contents(&v, "/f"), b"old"); } -/// What systemd refuses: a last group without its padding, incomplete -/// padding, padding with nothing to pad, padding that leaves bits set, -/// anything after the padding, and any character that is not a digit, -/// "=" or one of space, tab, newline and carriage return. +/// A manifest that lists a file before the object of its directory, or +/// its objects out of code point order, is refused when the object comes. +/// What came before it is written. #[test] -fn base64_refuses() { - for text in [ - "Zg", "Zm8", "aGVsbG8", "Zg=", "Zm9v=", "Zm9v==", "=", "==", " = ", "Zh==", "Zm9=", "Zg==Zg==", "Zg== x", - "Z=g=", "====", "Zm9\x0cv", "Zm9\x0bv", "!!!!", "Zm9v\0", +fn misplaced_and_unsorted_manifests_are_refused() { + for (records, problem, written) in [ + ( + &[ + ROOT, + r#"{"name":"d/x","size":0}"#, + r#"{"name":"d","type":"dir","mTimeNSec":1700000000000000000}"#, + TRAILER, + ][..], + ManifestProblem::Malformed(Problem::Misplaced), + 0, + ), + ( + &[ + ROOT, + r#"{"name":"a","type":"dir"}"#, + r#"{"name":"b","size":0}"#, + r#"{"name":"a/x","size":0}"#, + TRAILER, + ], + ManifestProblem::Malformed(Problem::Misplaced), + 2, + ), + // In tree order, but the names of a directory are not sorted. + ( + &[ROOT, r#"{"name":"b","size":0}"#, r#"{"name":"a","size":0}"#, TRAILER], + ManifestProblem::Malformed(Problem::OutOfOrder), + 1, + ), + ( + &[ + ROOT, + r#"{"name":"a-b","size":0}"#, + r#"{"name":"a","type":"dir"}"#, + TRAILER, + ], + ManifestProblem::Malformed(Problem::OutOfOrder), + 1, + ), ] { - assert_eq!(base64_decode(text), None, "{:?}", text); - } -} - -/// Data of every length up to 300 bytes comes back from its padded -/// encoding broken into lines of any width, the way systemd's -/// base64mem_full() writes it. -#[test] -fn base64_round_trip() { - const DIGITS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut x = 1u32; - for len in 0..300usize { - let data: Vec = (0..len) - .map(|_| { - x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); - (x >> 16) as u8 - }) - .collect(); - let mut text = Vec::new(); - for chunk in data.chunks(3) { - let n = chunk.iter().fold(0u32, |n, &b| (n << 8) | u32::from(b)) << (8 * (3 - chunk.len())); - for i in 0..4 { - let digit = DIGITS[((n >> (18 - 6 * i)) & 63) as usize]; - text.push(if i <= chunk.len() { digit } else { b'=' }); - } - } - let mut lines = Vec::new(); - for line in text.chunks(1 + len % 77) { - lines.extend_from_slice(line); - lines.push(b'\n'); - } - let decoded = base64_decode(std::str::from_utf8(&lines).unwrap()); - assert_eq!(decoded.as_deref(), Some(&data[..]), "{} bytes", len); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &seq(records), b"", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EBADMSG, "{:?}", records); + assert!( + matches!(e.detail(), Some(Detail::Manifest { problem: p, .. }) if *p == problem), + "{:?}: {:?}", + records, + e + ); + assert_eq!(v.read_dir("/").unwrap().len(), written, "{:?}", records); } } -fn manifest_with_tree() -> (Manifest, Vec) { +/// The manifest of a tree, with the contents of its streamed files in +/// manifest order. +fn manifest_with_tree() -> (Vec, Vec) { let a = b"first file".to_vec(); let b = vec![7u8; 5000]; - let m = parse(&seq(&[ - ROOT, + let m = seq(&[ + ROOT_MTIME, r#"{"mTimeNSec":1700000000000000000,"name":"EFI","type":"dir"}"#, - &format!( - r#"{{"mTimeNSec":1700000001000000000,"name":"EFI/a.txt","sha256":"{}","size":{}}}"#, - sha256::to_hex(&sha256::digest(&a)), - a.len() - ), + r#"{"name":"EFI/Linux","type":"dir"}"#, &format!( r#"{{"mode":292,"name":"EFI/Linux/b.efi","sha256":"{}","size":{}}}"#, - sha256::to_hex(&sha256::digest(&b)), + Sha256::digest(&b), b.len() ), + &format!( + r#"{{"mTimeNSec":1700000001000000000,"name":"EFI/a.txt","sha256":"{}","size":{}}}"#, + Sha256::digest(&a), + a.len() + ), r#"{"contents":[{"literal":"aGVsbG8="}],"name":"literal.txt","size":5}"#, TRAILER, - ])) - .unwrap(); - let mut blob = a; - blob.extend(b); + ]); + let mut blob = b; + blob.extend(a); (m, blob) } #[test] fn assembles_from_a_stream() { let (m, blob) = manifest_with_tree(); - assert_eq!(m.streamed_bytes().unwrap(), blob.len() as u64); let (_img, mut v) = volume(8 << 20, 512, 512); - let mut reader: &[u8] = &blob; - let report = v - .assemble(&m, &mut StreamSource::new(&mut reader), &AssembleOptions::default()) - .unwrap(); - assert_eq!((report.files, report.directories, report.bytes), (3, 1, 5015)); + let report = assemble_stream(&mut v, &m, &blob, &AssembleOptions::default()).unwrap(); + assert_eq!((report.files, report.directories, report.bytes), (3, 2, 5015)); assert_eq!( v.metadata("/EFI/a.txt").unwrap().modified, UNIX_EPOCH + Duration::from_secs(1_700_000_000) @@ -380,96 +347,118 @@ fn assembles_from_a_stream() { b.attributes & crate::dirent::ATTR_READ_ONLY, crate::dirent::ATTR_READ_ONLY ); - // Implicitly created directories get the default time, clamped to - // the FAT epoch. + // A directory without a time gets the default time, clamped to the FAT + // epoch. assert_eq!( v.metadata("/EFI/Linux").unwrap().modified, UNIX_EPOCH + Duration::from_secs(crate::time::FAT_EPOCH as u64) ); - let mut back = String::new(); - v.open_file("/literal.txt").unwrap().read_to_string(&mut back).unwrap(); - assert_eq!(back, "hello"); + assert_eq!(contents(&v, "/literal.txt"), b"hello"); - // A short stream fails at the file it runs out in and leaves no - // trace of it. The files before it are complete. + // A short stream fails at the file it runs out in and leaves no trace + // of it. The directories before it are there. let (_img, mut v) = volume(8 << 20, 512, 512); - let mut short: &[u8] = &blob[..100]; - assert_eq!( - v.assemble(&m, &mut StreamSource::new(&mut short), &AssembleOptions::default()) - .unwrap_err() - .errno(), - EBADMSG + let e = assemble_stream(&mut v, &m, &blob[..100], &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EBADMSG); + assert!( + matches!( + e.detail(), + Some(Detail::Content { + problem: ContentProblem::StreamEnded, + .. + }) + ), + "{:?}", + e ); assert!(v.metadata("/EFI/Linux/b.efi").is_err()); - assert_eq!(v.metadata("/EFI/a.txt").unwrap().size, 10); + assert!(v.metadata("/EFI/Linux").unwrap().is_dir); - // A stream that goes on after the last file fails at that file, which - // got more than the manifest says. It is not stored either. + // A stream that goes on after the last file fails once the manifest + // ended, naming that file. The files are all there by then. let (_img, mut v) = volume(8 << 20, 512, 512); let long_blob = [&blob[..], b"more"].concat(); - let mut long: &[u8] = &long_blob; - let e = v - .assemble(&m, &mut StreamSource::new(&mut long), &AssembleOptions::default()) - .unwrap_err(); + let e = assemble_stream(&mut v, &m, &long_blob, &AssembleOptions::default()).unwrap_err(); assert_eq!(e.errno(), EBADMSG); assert!( matches!( e.detail(), Some(Detail::Content { problem: ContentProblem::Size, + name, size: None, - expected: Some(5000), - .. - }) + expected: Some(10), + }) if name == "EFI/a.txt" ), "{:?}", e ); - assert!(v.metadata("/EFI/Linux/b.efi").is_err()); assert_eq!(v.metadata("/EFI/a.txt").unwrap().size, 10); + assert_eq!(contents(&v, "/literal.txt"), b"hello"); // A corrupted stream fails the hash check. The file it was about to // replace survives untouched. let mut bad = blob.clone(); bad[0] ^= 1; - let mut bad_reader: &[u8] = &bad; - let e = v - .assemble(&m, &mut StreamSource::new(&mut bad_reader), &AssembleOptions::default()) - .unwrap_err(); + let replace = AssembleOptions { + flags: AssembleFlags::REPLACE, + ..AssembleOptions::default() + }; + let e = assemble_stream(&mut v, &m, &bad, &replace).unwrap_err(); assert!(e.message().contains("hash"), "{}", e); - let mut back = String::new(); - v.open_file("/EFI/a.txt").unwrap().read_to_string(&mut back).unwrap(); - assert_eq!(back, "first file"); + assert_eq!(contents(&v, "/EFI/Linux/b.efi"), vec![7u8; 5000]); // On a fresh volume the failed file leaves nothing behind. let (_img, mut v) = volume(8 << 20, 512, 512); - let mut bad_reader: &[u8] = &bad; - v.assemble(&m, &mut StreamSource::new(&mut bad_reader), &AssembleOptions::default()) - .unwrap_err(); - assert!(v.metadata("/EFI/a.txt").is_err()); - assert!(v.metadata("/EFI").is_ok()); + assemble_stream(&mut v, &m, &bad, &AssembleOptions::default()).unwrap_err(); + assert!(v.metadata("/EFI/Linux/b.efi").is_err()); + assert!(v.metadata("/EFI/Linux").is_ok()); } +/// A manifest is read once, from its start to its end: from a pipe as +/// well as from a file. #[test] -fn assembles_from_a_directory() { - let tmp = TempDir::new("manifest"); +fn assembles_while_a_manifest_comes_through_a_pipe() { + let tmp = TempDir::new("manifest-pipe"); let dir = tmp.path().to_path_buf(); std::fs::create_dir_all(dir.join("EFI/Linux")).unwrap(); std::fs::write(dir.join("EFI/a.txt"), b"first file").unwrap(); std::fs::write(dir.join("EFI/Linux/b.efi"), vec![7u8; 5000]).unwrap(); let (m, _) = manifest_with_tree(); + let (mut ours, mut theirs) = std::os::unix::net::UnixStream::pair().unwrap(); + let writer = std::thread::spawn(move || { + // A record at a time, the way a producer writes them. + for record in m.split_inclusive(|&b| b == b'\n') { + theirs.write_all(record).unwrap(); + } + }); let (_img, mut v) = volume(8 << 20, 512, 512); + let mut reader = Reader::open(&mut ours).unwrap(); let report = v - .assemble(&m, &mut dir_source(&dir), &AssembleOptions::default()) + .assemble(&mut reader, &mut dir_source(&dir), &AssembleOptions::default()) .unwrap(); + writer.join().unwrap(); + assert_eq!((report.files, report.directories, report.bytes), (3, 2, 5015)); + assert_eq!(contents(&v, "/EFI/a.txt"), b"first file"); +} + +#[test] +fn assembles_from_a_directory() { + let tmp = TempDir::new("manifest"); + let dir = tmp.path().to_path_buf(); + std::fs::create_dir_all(dir.join("EFI/Linux")).unwrap(); + std::fs::write(dir.join("EFI/a.txt"), b"first file").unwrap(); + std::fs::write(dir.join("EFI/Linux/b.efi"), vec![7u8; 5000]).unwrap(); + let (m, _) = manifest_with_tree(); + let (_img, mut v) = volume(8 << 20, 512, 512); + let report = assemble(&mut v, &m, &mut dir_source(&dir), &AssembleOptions::default()).unwrap(); assert_eq!(report.files, 3); // The generator produces a manifest the reader accepts and the // planner and assembler agree on. let generated = generated(&dir); - let g = parse(&generated).unwrap(); assert_eq!( - g.entries.iter().filter_map(|e| e.name.clone()).collect::>(), + objects(&generated).iter().map(|e| e.name.as_str()).collect::>(), vec!["EFI", "EFI/Linux", "EFI/Linux/b.efi", "EFI/a.txt"] ); let mut plan = crate::plan::Plan::new(crate::plan::PlanOptions { @@ -477,7 +466,11 @@ fn assembles_from_a_directory() { cluster_size: Some(512), ..crate::plan::PlanOptions::new(512) }); - assert!(plan.add_manifest(&g).unwrap().is_empty()); + let mut reader = Reader::open(&generated[..]).unwrap(); + assert_eq!( + plan.add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED).unwrap(), + 0 + ); let est = plan.estimate().unwrap(); let img = TempImage::new(est.size()); let mut o = crate::format::FormatOptions { @@ -487,147 +480,272 @@ fn assembles_from_a_directory() { est.apply(&mut o); crate::format::format(&img.device(), &o).unwrap(); let mut v = Volume::open(img.device()).unwrap(); - v.assemble(&g, &mut dir_source(&dir), &AssembleOptions::default()) - .unwrap(); + assemble(&mut v, &generated, &mut dir_source(&dir), &AssembleOptions::default()).unwrap(); assert_eq!(v.free_clusters(), 0); } +/// What FAT cannot store is refused, or left out with everything below it +/// and counted. The contents of a file that is left out are read past in +/// a stream, which ends with them all the same. #[test] fn unsupported_entries() { - let hello = sha256::to_hex(&sha256::digest(b"hello")); - let m = parse(&seq(&[ + let hello = Sha256::digest(b"hello").to_string(); + let m = seq(&[ ROOT, - r#"{"name":"a/b/link","type":"lnk","contents":[{"literal":"eA=="}]}"#, r#"{"name":"encoded","size":5,"contents":[{"literal":"H4sIAAAAAAAAA8tIzcnJBwCGphA2BQAAAA==","encoding":"gzip"}]}"#, + r#"{"name":"link","type":"lnk","contents":[{"literal":"eA=="}]}"#, + r#"{"name":"ok","size":2}"#, r#"{"name":"remote","size":5,"contents":[{"url":"https://example.com/x"}]}"#, &format!(r#"{{"name":"sub","type":"dir","sha256":"{}","size":5}}"#, hello), - r#"{"name":"ok","size":0}"#, + r#"{"name":"sub/deeper","type":"dir"}"#, + r#"{"name":"sub/deeper/x","size":3}"#, + r#"{"name":"sub/inner","size":0}"#, + r#"{"name":"z","size":1}"#, TRAILER, - ])) - .unwrap(); - let unsupported: Vec = m - .entries + ]); + let unsupported: Vec = objects(&m) .iter() - .filter(|e| e.check_supported().is_err()) - .map(|e| e.name.clone().unwrap()) + .filter(|e| EntryKind::try_from(*e).is_err()) + .map(|e| e.name.to_string()) .collect(); - assert_eq!(unsupported, vec!["a/b/link", "encoded", "remote", "sub"]); - assert_eq!(m.check_supported().unwrap_err().errno(), EOPNOTSUPP); - assert_eq!(m.streamed_bytes().unwrap(), 0); + assert_eq!(unsupported, vec!["encoded", "link", "remote", "sub"]); let (_img, mut v) = volume(8 << 20, 512, 512); - let mut empty: &[u8] = &[]; - let e = v - .assemble(&m, &mut StreamSource::new(&mut empty), &AssembleOptions::default()) - .unwrap_err(); + let e = assemble_stream(&mut v, &m, b"okxyzZ", &AssembleOptions::default()).unwrap_err(); assert_eq!(e.errno(), EOPNOTSUPP); - // Nothing was created for the entry that failed, not even parents. + // Nothing was created for the entry that failed. assert_eq!(v.read_dir("/").unwrap().len(), 0); + let options = AssembleOptions { + flags: AssembleFlags::SKIP_UNSUPPORTED, + ..Default::default() + }; + let mut recorder = Recorder::default(); + let mut stream: &[u8] = b"okxyzZ"; let r = v - .assemble( - &m, - &mut StreamSource::new(&mut empty), - &AssembleOptions { - skip_unsupported: true, - ..Default::default() - }, + .assemble_with_observer( + &mut Reader::open(&m[..]).unwrap(), + &mut StreamSource::new(&mut stream), + &options, + &mut recorder, ) .unwrap(); - assert_eq!(r.skipped, unsupported); - assert_eq!((r.files, r.directories), (1, 0)); - assert_eq!(v.metadata("/a").unwrap_err().errno(), ENOENT); - // The planner skips the same entries. + assert_eq!((r.files, r.directories, r.bytes, r.skipped), (2, 0, 3, 7)); + use SkipReason::{BelowSkipped as Below, Unsupported as Cannot}; + let skipped: Vec<(&str, SkipReason)> = recorder.skipped.iter().map(|(n, r)| (n.as_str(), *r)).collect(); + assert_eq!( + skipped, + [ + ("encoded", Cannot), + ("link", Cannot), + ("remote", Cannot), + ("sub", Cannot), + ("sub/deeper", Below), + ("sub/deeper/x", Below), + ("sub/inner", Below), + ] + ); + assert_eq!(contents(&v, "/ok"), b"ok"); + assert_eq!(contents(&v, "/z"), b"Z"); + assert_eq!(v.metadata("/sub").unwrap_err().errno(), ENOENT); + // The stream had the contents of the file below the directory that + // was left out, and nothing else. + for stream in [&b"okxyz"[..], b"okxyzZmore"] { + let (_img, mut v) = volume(8 << 20, 512, 512); + assert_eq!( + assemble_stream(&mut v, &m, stream, &options).unwrap_err().errno(), + EBADMSG + ); + } + // A file larger than a FAT32 file can be is no object to leave out. + let big = seq(&[ROOT, r#"{"name":"big","size":4294967296}"#, TRAILER]); + let e = assemble_stream(&mut v, &big, b"", &options).unwrap_err(); + assert_eq!(e.errno(), EFBIG); + assert!( + matches!( + e.detail(), + Some(Detail::TooLarge { + path: Some(path), + size: 4294967296, + .. + }) if path == "/big" + ), + "{:?}", + e + ); + // The planner leaves out the same objects. let mut plan = crate::plan::Plan::new(crate::plan::PlanOptions { allow_small: true, ..crate::plan::PlanOptions::new(512) }); - assert_eq!(plan.add_manifest(&m).unwrap(), unsupported); + let mut reader = Reader::open(&m[..]).unwrap(); + assert_eq!( + plan.add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED).unwrap(), + 7 + ); + assert_eq!((plan.estimate().unwrap().files, plan.estimate().unwrap().bytes), (2, 3)); } +/// Directories that are left out one after the other each take what is +/// below them along, and nothing else: a name that only starts like the +/// name of one is not below it. The stream has the contents of the files +/// below them as well. #[test] -fn contents_are_chosen_by_what_can_be_used() { - let hello = sha256::to_hex(&sha256::digest(b"hello")); - let m = parse(&seq(&[ +fn directories_left_out_one_after_the_other() { + let hello = Sha256::digest(b"hello").to_string(); + let sub = |name: &str| format!(r#"{{"name":"{}","sha256":"{}","size":5,"type":"dir"}}"#, name, hello); + let m = seq(&[ ROOT, - // A URL first, then an encoded literal, then plain data. - &format!(r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"url":"https://example.com/x"}},{{"literal":"AAAA","encoding":"gzip"}},{{"literal":"aGVsbG8="}}]}}"#, hello), - // A URL with a file as the alternative is read from the source. - &format!(r#"{{"name":"y","size":5,"sha256":"{}","contents":[{{"url":"https://example.com/y"}},{{"file":"data/y.bin"}}]}}"#, hello), + &sub("a"), + r#"{"name":"a/x","size":1}"#, + r#"{"name":"ab","size":1}"#, + &sub("b"), + r#"{"name":"b/y","size":1}"#, + &sub("c"), + r#"{"name":"d","size":1}"#, TRAILER, - ])) - .unwrap(); - assert_eq!( - m.entries[0].fat_contents().unwrap().unwrap().literal.as_deref(), - Some(&b"hello"[..]) - ); - assert!(!m.entries[0].is_streamed()); - assert_eq!( - m.entries[1].fat_contents().unwrap().unwrap().file.as_deref(), - Some("data/y.bin") - ); - assert!(m.entries[1].is_streamed()); - let tmp = TempDir::new("manifest-contents"); - let dir = tmp.path().to_path_buf(); - std::fs::create_dir_all(dir.join("data")).unwrap(); - std::fs::write(dir.join("data/y.bin"), b"hello").unwrap(); + ]); + let options = AssembleOptions { + flags: AssembleFlags::SKIP_UNSUPPORTED, + ..Default::default() + }; let (_img, mut v) = volume(8 << 20, 512, 512); + let mut recorder = Recorder::default(); + let mut stream: &[u8] = b"xAyD"; let r = v - .assemble(&m, &mut dir_source(&dir), &AssembleOptions::default()) + .assemble_with_observer( + &mut Reader::open(&m[..]).unwrap(), + &mut StreamSource::new(&mut stream), + &options, + &mut recorder, + ) .unwrap(); - assert_eq!((r.files, r.bytes), (2, 10)); - for name in ["/x", "/y"] { - let mut back = String::new(); - v.open_file(name).unwrap().read_to_string(&mut back).unwrap(); - assert_eq!(back, "hello"); + assert_eq!((r.files, r.skipped), (2, 5)); + use SkipReason::{BelowSkipped as Below, Unsupported as Cannot}; + let skipped: Vec<(&str, SkipReason)> = recorder.skipped.iter().map(|(n, r)| (n.as_str(), *r)).collect(); + assert_eq!( + skipped, + [ + ("a", Cannot), + ("a/x", Below), + ("b", Cannot), + ("b/y", Below), + ("c", Cannot), + ] + ); + assert_eq!(contents(&v, "/ab"), b"A"); + assert_eq!(contents(&v, "/d"), b"D"); +} + +/// A regular file without a size can be neither streamed nor planned, and +/// both say so alike: by its name in the manifest, and the size field. The +/// stream refuses it before anything is written. +#[test] +fn files_without_a_size() { + let m = seq(&[ROOT, r#"{"name":"x"}"#, TRAILER]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let streamed = assemble_stream(&mut v, &m, b"", &AssembleOptions::default()).unwrap_err(); + assert!(!v.is_writing()); + let mut plan = crate::plan::Plan::new(crate::plan::PlanOptions::new(512)); + let mut reader = Reader::open(&m[..]).unwrap(); + let planned = plan.add_records(&mut reader, AssembleFlags::NONE).unwrap_err(); + for e in [streamed, planned] { + let Some(Detail::Manifest { + problem, name, field, .. + }) = e.detail() + else { + panic!("{:?}", e); + }; + assert_eq!(*problem, ManifestProblem::NoSize); + assert_eq!((name.as_deref(), field.as_deref()), (Some("x"), Some("size"))); } } -/// A file the manifest takes whole has exactly the size the manifest gives. -/// One that grew since the manifest was written fails like one that shrank, -/// when the source is verified and again while it is copied. A part of a -/// file, at an offset or out of a larger originalSize, only has to fit. +/// A directory that refers to a sub-manifest is refused at its object, +/// before the stream is asked for the sub-manifest, with or without a size. +/// Left out instead, it takes its sub-manifest along: the stream has that +/// too, and reads past it as far as the size says. Without a size it +/// cannot. #[test] -fn whole_files_have_the_size_of_the_manifest() { - let tmp = TempDir::new("manifest-sizes"); - let dir = tmp.path().to_path_buf(); - std::fs::write(dir.join("a"), b"hello world").unwrap(); - let hello = sha256::to_hex(&sha256::digest(b"hello")); - let world = sha256::to_hex(&sha256::digest(b"world")); - // The manifest was written when `a` held "hello". The file is found by - // the entry's name or through a file reference. - for record in [ - format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, hello), - format!( - r#"{{"name":"b","size":5,"sha256":"{}","contents":[{{"file":"a"}}]}}"#, - hello - ), - ] { - let m = parse(&seq(&[ROOT, &record, TRAILER])).unwrap(); - let e = dir_source(&dir).verify(&m).unwrap_err(); - assert_eq!(e.errno(), EBADMSG); +fn sub_manifests_and_a_stream() { + let hello = Sha256::digest(b"hello").to_string(); + let m = |size: &str| { + seq(&[ + ROOT, + &format!( + r#"{{"contents":[{{"file":"sub.manifest"}}],"name":"sub","sha256":"{}"{},"type":"dir"}}"#, + hello, size + ), + r#"{"name":"z","size":1}"#, + TRAILER, + ]) + }; + for size in ["", r#","size":5"#] { + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &m(size), b"helloZ", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EOPNOTSUPP, "{:?}", e); assert!( matches!( e.detail(), - Some(Detail::Source { - problem: SourceProblem::Size, - size: Some(11), - expected: Some(5), + Some(Detail::Unsupported { + what: UnsupportedKind::SubManifest, .. }) ), "{:?}", e ); + assert!(v.read_dir("/").unwrap().is_empty()); + } + let skip = AssembleOptions { + flags: AssembleFlags::SKIP_UNSUPPORTED, + ..AssembleOptions::default() + }; + let (_img, mut v) = volume(8 << 20, 512, 512); + let r = assemble_stream(&mut v, &m(r#","size":5"#), b"helloZ", &skip).unwrap(); + assert_eq!((r.files, r.skipped), (1, 1)); + assert_eq!(contents(&v, "/z"), b"Z"); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &m(""), b"helloZ", &skip).unwrap_err(); + assert!( + matches!( + e.detail(), + Some(Detail::Manifest { + problem: ManifestProblem::NoSize, + .. + }) + ), + "{:?}", + e + ); +} + +/// Contents at an offset in their file come from a directory, and a stream, +/// which has the contents of each file and nothing else of it, refuses +/// them when the object comes, whether objects FAT cannot store are left +/// out or not, before anything is written. So does a directory whose file +/// is missing. +#[test] +fn offsets_and_a_stream() { + let tmp = TempDir::new("manifest-offset"); + let dir = tmp.path().to_path_buf(); + std::fs::write(dir.join("a"), b"hello world").unwrap(); + let m = seq(&[ + ROOT, + r#"{"contents":[{"file":"a","offset":6}],"name":"w","size":5}"#, + TRAILER, + ]); + for flags in [AssembleFlags::NONE, AssembleFlags::SKIP_UNSUPPORTED] { + let options = AssembleOptions { + flags, + ..AssembleOptions::default() + }; let (_img, mut v) = volume(8 << 20, 512, 512); - let e = v - .assemble(&m, &mut dir_source(&dir), &AssembleOptions::default()) - .unwrap_err(); + let e = assemble_stream(&mut v, &m, b"world", &options).unwrap_err(); + assert_eq!(e.errno(), EOPNOTSUPP, "{:?}", e); assert!( matches!( e.detail(), - Some(Detail::Content { - problem: ContentProblem::Size, - size: Some(11), - expected: Some(5), + Some(Detail::Unsupported { + what: UnsupportedKind::Offset, .. }) ), @@ -635,10 +753,240 @@ fn whole_files_have_the_size_of_the_manifest() { e ); assert!(v.read_dir("/").unwrap().is_empty()); + assert!(!v.is_writing()); + let empty = TempDir::new("manifest-offset-empty"); + let e = assemble(&mut v, &m, &mut dir_source(empty.path()), &options).unwrap_err(); + assert_eq!(e.errno(), ENOENT, "{:?}", e); + assert!(!v.is_writing()); + let r = assemble(&mut v, &m, &mut dir_source(&dir), &options).unwrap(); + assert_eq!((r.files, r.skipped), (1, 0)); + assert_eq!(contents(&v, "/w"), b"world"); + } +} + +/// A file that changes while it is read fails with SourceChanged, without +/// sizes. A file of procfs says it is empty when it is opened and has data +/// when it is read, which is how a file that grew after it was opened looks +/// to the source. Checked against a hash of all of it, it is read past its +/// length. +#[test] +fn files_that_change_while_they_are_read() { + let hello = Sha256::digest(b"hello").to_string(); + let m = seq(&[ + ROOT, + &format!( + r#"{{"contents":[{{"originalSha256":"{}"}}],"name":"version","size":0}}"#, + hello + ), + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble( + &mut v, + &m, + &mut dir_source(Path::new("/proc")), + &AssembleOptions::default(), + ) + .unwrap_err(); + assert_eq!(e.errno(), EBADMSG); + assert_eq!( + e.detail(), + Some(&Detail::Content { + name: "version".to_string(), + problem: ContentProblem::SourceChanged, + size: None, + expected: None, + }) + ); + assert!(v.read_dir("/").unwrap().is_empty()); +} + +/// Names FAT does not tell apart, the second of which an assembly finds +/// in the volume: taken as the same name. +#[test] +fn case_collisions_are_one_name() { + let m = seq(&[ + ROOT, + r#"{"name":"A.TXT","size":1}"#, + r#"{"name":"EFI","type":"dir"}"#, + r#"{"name":"EFI/x","size":1}"#, + r#"{"name":"a.txt","size":2}"#, + r#"{"name":"efi","type":"dir"}"#, + r#"{"name":"efi/y","size":1}"#, + TRAILER, + ]); + // A file replaces the one it collides with, under its own name, and a + // directory takes the entries of the one it collides with. + let (_img, mut v) = volume(8 << 20, 512, 512); + let r = assemble_stream(&mut v, &m, b"Axyyz", &AssembleOptions::default()).unwrap(); + assert_eq!((r.files, r.directories, r.bytes), (4, 2, 5)); + let names = |v: &Volume, path: &str| { + let mut names: Vec = v.read_dir(path).unwrap().into_iter().map(|md| md.name).collect(); + names.sort(); + names + }; + assert_eq!(names(&v, "/"), ["EFI", "a.txt"]); + assert_eq!(contents(&v, "/a.txt"), b"yy"); + assert_eq!(names(&v, "/EFI"), ["x", "y"]); +} + +/// Directories that the volume holds with the times the manifest gives +/// are not written again. So a manifest refused at a file after them, or +/// one of nothing but such directories, leaves the volume as it was. +#[test] +fn directories_that_are_there_with_their_times_write_nothing() { + let dirs = [ + r#"{"mTimeNSec":1700000000000000000,"name":"EFI","type":"dir"}"#, + r#"{"mTimeNSec":1700000000000000000,"name":"EFI/BOOT","type":"dir"}"#, + ]; + let m = seq(&[ + ROOT_MTIME, + dirs[0], + dirs[1], + r#"{"name":"EFI/BOOT/x","size":1}"#, + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + assemble_stream(&mut v, &m, b"x", &AssembleOptions::default()).unwrap(); + v.sync().unwrap(); + let keep = AssembleOptions { + flags: AssembleFlags::NONE, + ..AssembleOptions::default() + }; + let e = assemble_stream(&mut v, &m, b"x", &keep).unwrap_err(); + assert_eq!(e.errno(), EEXIST); + assert!(!v.is_writing()); + let r = assemble_stream(&mut v, &seq(&[ROOT_MTIME, dirs[0], dirs[1], TRAILER]), b"", &keep).unwrap(); + assert_eq!(r.directories, 2); + assert!(!v.is_writing()); + // Another time is written. + let later = seq(&[ + ROOT_MTIME, + r#"{"mTimeNSec":1800000000000000000,"name":"EFI","type":"dir"}"#, + TRAILER, + ]); + assemble_stream(&mut v, &later, b"", &keep).unwrap(); + assert!(v.is_writing()); + assert_eq!( + v.metadata("/EFI").unwrap().modified, + UNIX_EPOCH + Duration::from_secs(1_800_000_000) + ); +} + +/// What a volume holds under the same name as an object was there before +/// the assembly: a directory takes the entries, a file is replaced only +/// with REPLACE. +#[test] +fn entries_of_the_same_name_that_are_there() { + let (_img, mut v) = volume(8 << 20, 512, 512); + let t0 = UNIX_EPOCH + Duration::from_secs(1_600_000_000); + v.create_dir("/EFI", t0).unwrap(); + v.write_file("/EFI/x", &mut &b"old"[..], t0, false).unwrap(); + let m = seq(&[ + ROOT_MTIME, + r#"{"mTimeNSec":1700000000000000000,"name":"EFI","type":"dir"}"#, + r#"{"name":"EFI/x","size":3}"#, + r#"{"name":"EFI/y","size":1}"#, + TRAILER, + ]); + let keep = AssembleOptions { + flags: AssembleFlags::NONE, + ..AssembleOptions::default() + }; + let e = assemble_stream(&mut v, &m, b"newy", &keep).unwrap_err(); + assert_eq!(e.errno(), EEXIST); + assert_eq!(e.detail(), Some(&Detail::Path("/EFI/x".into()))); + assert_eq!( + v.metadata("/EFI").unwrap().modified, + UNIX_EPOCH + Duration::from_secs(1_700_000_000) + ); + assert_eq!(contents(&v, "/EFI/x"), b"old"); + let replace = AssembleOptions { + flags: AssembleFlags::REPLACE, + ..AssembleOptions::default() + }; + let r = assemble_stream(&mut v, &m, b"newy", &replace).unwrap(); + assert_eq!((r.files, r.directories), (2, 1)); + assert_eq!(contents(&v, "/EFI/x"), b"new"); + // A file where the volume has a directory, and the other way round. + for (records, errno) in [ + (&[ROOT, r#"{"name":"EFI","size":0}"#, TRAILER][..], EISDIR), + ( + &[ + ROOT, + r#"{"name":"EFI","type":"dir"}"#, + r#"{"name":"EFI/x","type":"dir"}"#, + TRAILER, + ], + ENOTDIR, + ), + ] { + assert_eq!( + assemble_stream(&mut v, &seq(records), b"", &replace) + .unwrap_err() + .errno(), + errno + ); + } +} + +#[test] +fn contents_are_chosen_by_what_can_be_used() { + let hello = Sha256::digest(b"hello").to_string(); + let m = seq(&[ + ROOT, + // A URL first, then an encoded literal, then plain data. + &format!( + r#"{{"name":"x","size":5,"sha256":"{}","contents":[{{"url":"https://example.com/x"}},{{"literal":"AAAA","encoding":"gzip"}},{{"literal":"aGVsbG8="}}]}}"#, + hello + ), + // A URL with a file as the alternative is read from the source. + &format!( + r#"{{"name":"y","size":5,"sha256":"{}","contents":[{{"url":"https://example.com/y"}},{{"file":"data/y.bin"}}]}}"#, + hello + ), + TRAILER, + ]); + let entries = objects(&m); + assert_eq!(entries[0].data().unwrap(), Data::Literal(b"hello")); + assert!(!entries[0].has_external_data()); + assert!(matches!(entries[1].data(), Ok(Data::External(reference)) if reference.file == "data/y.bin")); + assert!(entries[1].has_external_data()); + let tmp = TempDir::new("manifest-contents"); + let dir = tmp.path().to_path_buf(); + std::fs::create_dir_all(dir.join("data")).unwrap(); + std::fs::write(dir.join("data/y.bin"), b"hello").unwrap(); + let (_img, mut v) = volume(8 << 20, 512, 512); + let r = assemble(&mut v, &m, &mut dir_source(&dir), &AssembleOptions::default()).unwrap(); + assert_eq!((r.files, r.bytes), (2, 10)); + for name in ["/x", "/y"] { + assert_eq!(contents(&v, name), b"hello"); } - // Parts of `a`: the file may go on after them. - let m = parse(&seq(&[ +} + +/// The data of an object is the part of its file that starts at the offset +/// and is as long as the object says, whatever else the file holds, as the +/// specification has it. A file that grew since the manifest was written is +/// copied as far as the manifest says. The file has to be long enough for +/// the data, and as long as the originalSize the manifest gives for it. +#[test] +fn files_hold_the_data_the_manifest_says() { + let tmp = TempDir::new("manifest-sizes"); + let dir = tmp.path().to_path_buf(); + std::fs::write(dir.join("a"), b"hello world").unwrap(); + let hello = Sha256::digest(b"hello").to_string(); + let world = Sha256::digest(b"world").to_string(); + // The manifest was written when `a` held "hello". The file is found by + // the entry's name or through a file reference. + let m = seq(&[ ROOT, + &format!(r#"{{"name":"a","size":5,"sha256":"{}"}}"#, hello), + &format!( + r#"{{"name":"b","size":5,"sha256":"{}","contents":[{{"file":"a"}}]}}"#, + hello + ), + // Parts of `a`, at an offset and out of the originalSize the + // manifest gives. &format!( r#"{{"name":"c","size":5,"sha256":"{}","contents":[{{"file":"a","offset":6}}]}}"#, world @@ -650,39 +998,49 @@ fn whole_files_have_the_size_of_the_manifest() { ), r#"{"name":"f","size":11,"contents":[{"file":"a","originalSize":11}]}"#, TRAILER, - ])) - .unwrap(); - dir_source(&dir).verify(&m).unwrap(); + ]); let (_img, mut v) = volume(8 << 20, 512, 512); - v.assemble(&m, &mut dir_source(&dir), &AssembleOptions::default()) - .unwrap(); - for (name, data) in [("/c", "world"), ("/d", "llo"), ("/e", "hello"), ("/f", "hello world")] { - let mut back = String::new(); - v.open_file(name).unwrap().read_to_string(&mut back).unwrap(); - assert_eq!(back, data, "{}", name); + assemble(&mut v, &m, &mut dir_source(&dir), &AssembleOptions::default()).unwrap(); + for (name, data) in [ + ("/a", "hello"), + ("/b", "hello"), + ("/c", "world"), + ("/d", "llo"), + ("/e", "hello"), + ("/f", "hello world"), + ] { + assert_eq!(contents(&v, name), data.as_bytes(), "{}", name); } - // A part that runs past the end, and an originalSize that is not the - // file's. - for record in [ + // A file too short for the data, at an offset and as a whole, and an + // originalSize that is not the file's, larger and smaller. + for (record, expected) in [ r#"{"name":"g","size":6,"contents":[{"file":"a","offset":6}]}"#, - r#"{"name":"h","size":5,"contents":[{"file":"a","originalSize":12}]}"#, - r#"{"name":"i","size":5,"contents":[{"file":"a","originalSize":5}]}"#, - ] { - let m = parse(&seq(&[ROOT, record, TRAILER])).unwrap(); - let e = dir_source(&dir).verify(&m).unwrap_err(); + r#"{"name":"h","size":12,"contents":[{"file":"a"}]}"#, + r#"{"name":"i","size":5,"contents":[{"file":"a","originalSize":12}]}"#, + r#"{"name":"j","size":5,"contents":[{"file":"a","originalSize":5}]}"#, + ] + .into_iter() + .zip([12, 12, 12, 5]) + { + let m = seq(&[ROOT, record, TRAILER]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble(&mut v, &m, &mut dir_source(&dir), &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EBADMSG); assert!( matches!( e.detail(), - Some(Detail::Source { - problem: SourceProblem::Size, + Some(Detail::Content { + problem: ContentProblem::Size, size: Some(11), + expected: Some(n), .. - }) + }) if *n == expected ), "{}: {:?}", record, e ); + assert!(v.read_dir("/").unwrap().is_empty()); } } @@ -694,10 +1052,10 @@ fn mismatches_name_the_record() { let dir = tmp.path().to_path_buf(); std::fs::create_dir_all(dir.join("loader/entries")).unwrap(); std::fs::write(dir.join("loader/loader.conf"), b"timeout 3\n").unwrap(); - let conf = sha256::to_hex(&sha256::digest(b"timeout 3\n")); - let other = sha256::to_hex(&sha256::digest(b"timeout 5\n")); + let conf = Sha256::digest(b"timeout 3\n").to_string(); + let other = Sha256::digest(b"timeout 5\n").to_string(); // In the detail and in the message. - let named = |e: crate::Error, name: &str| { + let named = |e: Error, name: &str| { match e.detail() { Some(Detail::Source { name: n, .. } | Detail::Content { name: n, .. }) => assert_eq!(n, name, "{:?}", e), _ => panic!("{:?}", e), @@ -705,50 +1063,78 @@ fn mismatches_name_the_record() { let text = e.to_string(); assert!(text.contains(name) && !text.contains(&format!("/{}", name)), "{}", text); }; - // Found before anything is written: missing, not a regular file, of - // another size. - for (record, name) in [ - (r#"{"name":"loader/entries/a.conf","size":1}"#, "loader/entries/a.conf"), + const LOADER: &str = r#"{"name":"loader","type":"dir"}"#; + // Missing, not a regular file, too short, and the hash of the file and + // that of the whole source. The last record of each names the file. + let cases: [(&[&str], &str, String); 5] = [ ( - r#"{"name":"x/y","size":1,"contents":[{"file":"loader/entries"}]}"#, + &[LOADER, r#"{"name":"loader/entries","type":"dir"}"#], + "loader/entries/a.conf", + r#"{"name":"loader/entries/a.conf","size":1}"#.to_string(), + ), + ( + &[LOADER, r#"{"name":"x","type":"dir"}"#], "x/y", + r#"{"name":"x/y","size":1,"contents":[{"file":"loader/entries"}]}"#.to_string(), ), - (r#"{"name":"loader/loader.conf","size":5}"#, "loader/loader.conf"), - ] { - let m = parse(&seq(&[ROOT, record, TRAILER])).unwrap(); - named(dir_source(&dir).verify(&m).unwrap_err(), name); - } - // Found while copying: the hash of the file, and that of the whole - // source. - for record in [ - format!(r#"{{"name":"loader/loader.conf","size":10,"sha256":"{}"}}"#, other), - format!( - r#"{{"name":"loader/loader.conf","size":5,"contents":[{{"originalSize":10,"originalSha256":"{}"}}]}}"#, - other + ( + &[LOADER], + "loader/loader.conf", + r#"{"name":"loader/loader.conf","size":12}"#.to_string(), ), - ] { - let m = parse(&seq(&[ROOT, &record, TRAILER])).unwrap(); + ( + &[LOADER], + "loader/loader.conf", + format!(r#"{{"name":"loader/loader.conf","size":10,"sha256":"{}"}}"#, other), + ), + ( + &[LOADER], + "loader/loader.conf", + format!( + r#"{{"name":"loader/loader.conf","size":5,"contents":[{{"originalSize":10,"originalSha256":"{}"}}]}}"#, + other + ), + ), + ]; + for (directories, name, record) in &cases { + let records = [&[ROOT][..], directories, &[record.as_str(), TRAILER]].concat(); let (_img, mut v) = volume(8 << 20, 512, 512); - let e = v - .assemble(&m, &mut dir_source(&dir), &AssembleOptions::default()) - .unwrap_err(); - named(e, "loader/loader.conf"); + let e = assemble( + &mut v, + &seq(&records), + &mut dir_source(&dir), + &AssembleOptions::default(), + ) + .unwrap_err(); + named(e, name); } // From a stream that ends early or goes on after the last file. - let m = parse(&seq(&[ + let m = seq(&[ ROOT, + LOADER, &format!(r#"{{"name":"loader/loader.conf","size":10,"sha256":"{}"}}"#, conf), TRAILER, - ])) - .unwrap(); + ]); for data in [&b"timeout"[..], &b"timeout 3\nmore"[..]] { let (_img, mut v) = volume(8 << 20, 512, 512); - let mut stream = data; - let e = v - .assemble(&m, &mut StreamSource::new(&mut stream), &AssembleOptions::default()) - .unwrap_err(); + let e = assemble_stream(&mut v, &m, data, &AssembleOptions::default()).unwrap_err(); named(e, "loader/loader.conf"); } + let missing = seq(&[ROOT, r#"{"name":"nowhere","size":1}"#, TRAILER]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble(&mut v, &missing, &mut dir_source(&dir), &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), ENOENT); + assert!( + matches!( + e.detail(), + Some(Detail::Source { + problem: SourceProblem::Missing, + .. + }) + ), + "{:?}", + e + ); } #[test] @@ -764,65 +1150,24 @@ fn source_files_stay_inside_the_source_directory() { let record = |name: &str, file: &str| format!(r#"{{"name":"{}","size":6,"contents":[{{"file":"{}"}}]}}"#, name, file); let base = dir.join("tree"); + let options = AssembleOptions::default(); let (_img, mut v) = volume(8 << 20, 512, 512); // Plain files work; a symlink does not until asked for. - let m = parse(&seq(&[ROOT, &record("a", "sub/inside.txt"), TRAILER])).unwrap(); - v.assemble(&m, &mut dir_source(&base), &AssembleOptions::default()) - .unwrap(); - let m = parse(&seq(&[ROOT, &record("b", "in.lnk"), TRAILER])).unwrap(); - assert!(v - .assemble(&m, &mut dir_source(&base), &AssembleOptions::default()) - .is_err()); - v.assemble( - &m, - &mut dir_source(&base).follow_symlinks(true), - &AssembleOptions::default(), - ) - .unwrap(); + let m = seq(&[ROOT, &record("a", "sub/inside.txt"), TRAILER]); + assemble(&mut v, &m, &mut dir_source(&base), &options).unwrap(); + let m = seq(&[ROOT, &record("b", "in.lnk"), TRAILER]); + assert!(assemble(&mut v, &m, &mut dir_source(&base), &options).is_err()); + let mut following = DirectorySource::new(source_dir(&base).follow_symlinks(true)); + assemble(&mut v, &m, &mut following, &options).unwrap(); // Nothing leads out of the tree, however it is spelled. for file in ["out.lnk", "abs.lnk"] { - let m = parse(&seq(&[ROOT, &record("c", file), TRAILER])).unwrap(); - assert!( - v.assemble( - &m, - &mut dir_source(&base).follow_symlinks(true), - &AssembleOptions::default() - ) - .is_err(), - "{}", - file - ); + let m = seq(&[ROOT, &record("c", file), TRAILER]); + let mut following = DirectorySource::new(source_dir(&base).follow_symlinks(true)); + assert!(assemble(&mut v, &m, &mut following, &options).is_err(), "{}", file); } assert_eq!(v.read_dir("/").unwrap().len(), 2); } -#[test] -fn directory_objects_after_their_children() { - let m = parse(&seq(&[ - ROOT, - r#"{"name":"d/x","size":0}"#, - r#"{"name":"d","type":"dir","mTimeNSec":1700000000000000000}"#, - TRAILER, - ])) - .unwrap(); - let (_img, mut v) = volume(8 << 20, 512, 512); - let mut empty: &[u8] = &[]; - let opts = AssembleOptions { - default_time: UNIX_EPOCH + Duration::from_secs(1_000_000_000), - ..Default::default() - }; - let r = v.assemble(&m, &mut StreamSource::new(&mut empty), &opts).unwrap(); - assert_eq!((r.files, r.directories), (1, 1)); - assert_eq!( - v.metadata("/d").unwrap().modified, - UNIX_EPOCH + Duration::from_secs(1_700_000_000) - ); - assert_eq!( - v.metadata("/d/x").unwrap().modified, - UNIX_EPOCH + Duration::from_secs(1_000_000_000) - ); -} - #[test] fn generator_leaves_the_manifest_out() { let tmp = TempDir::new("manifest-generate"); @@ -832,48 +1177,76 @@ fn generator_leaves_the_manifest_out() { std::fs::write(dir.join("Uapi16Manifest.sig"), b"old").unwrap(); std::fs::write(dir.join("Uapi16Manifest2"), b"kept").unwrap(); std::fs::write(dir.join("sub/Uapi16Manifest"), b"kept").unwrap(); - let m = parse(&generated(&dir)).unwrap(); - let names: Vec<&str> = m.entries.iter().filter_map(|e| e.name.as_deref()).collect(); + let entries = objects(&generated(&dir)); + let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect(); assert_eq!(names, vec!["Uapi16Manifest2", "sub", "sub/Uapi16Manifest"]); } #[test] fn validity() { - let m = parse(&seq(&[ROOT, r#"{"name":"x","size":0,"validity":"revoked"}"#, TRAILER])).unwrap(); + let revoked = seq(&[ROOT, r#"{"name":"x","size":0,"validity":"revoked"}"#, TRAILER]); let (_img, mut v) = volume(8 << 20, 512, 512); - let mut empty: &[u8] = &[]; - let opts = AssembleOptions { - now_usec: Some(1), + let at = |now| AssembleOptions { + now_usec: Some(now), ..Default::default() }; assert_eq!( - v.assemble(&m, &mut StreamSource::new(&mut empty), &opts) - .unwrap_err() - .errno(), + assemble_stream(&mut v, &revoked, b"", &at(1)).unwrap_err().errno(), EKEYREVOKED ); - let m = parse(&seq(&[ + let m = seq(&[ ROOT, r#"{"name":"d","type":"dir","validUntilUSec":10}"#, r#"{"name":"d/x","size":0}"#, TRAILER, - ])) - .unwrap(); - let opts = AssembleOptions { - now_usec: Some(20), - ..Default::default() - }; + ]); assert_eq!( - v.assemble(&m, &mut StreamSource::new(&mut empty), &opts) - .unwrap_err() - .errno(), + assemble_stream(&mut v, &m, b"", &at(20)).unwrap_err().errno(), EKEYEXPIRED ); - let opts = AssembleOptions { - now_usec: Some(5), + assert!(v.read_dir("/").unwrap().is_empty()); + assert!(assemble_stream(&mut v, &m, b"", &at(5)).is_ok()); + // So does the root file object, for the whole manifest. + let expired = seq(&[ + r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint","validUntilUSec":10}"#, + TRAILER, + ]); + assert_eq!( + assemble_stream(&mut v, &expired, b"", &at(20)).unwrap_err().errno(), + EKEYEXPIRED + ); + // An object is checked before it is left out, also one below a + // directory that is left out. Without the check both are left out. + let skipping = |now_usec| AssembleOptions { + flags: AssembleFlags::SKIP_UNSUPPORTED, + now_usec, ..Default::default() }; - assert!(v.assemble(&m, &mut StreamSource::new(&mut empty), &opts).is_ok()); + let hello = Sha256::digest(b"hello").to_string(); + let sub = format!(r#"{{"name":"sub","sha256":"{}","size":5,"type":"dir"}}"#, hello); + for (m, skipped) in [ + ( + seq(&[ + ROOT, + r#"{"contents":[{"literal":"eA=="}],"name":"link","type":"lnk","validity":"revoked"}"#, + TRAILER, + ]), + 1, + ), + ( + seq(&[ROOT, &sub, r#"{"name":"sub/x","size":0,"validity":"revoked"}"#, TRAILER]), + 2, + ), + ] { + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &m, b"", &skipping(Some(1))).unwrap_err(); + assert_eq!(e.errno(), EKEYREVOKED); + assert!(v.read_dir("/").unwrap().is_empty()); + assert_eq!( + assemble_stream(&mut v, &m, b"", &skipping(None)).unwrap().skipped, + skipped + ); + } } /// Checks the progress a long operation reported: the counts only grow @@ -931,14 +1304,14 @@ fn long_operations_report_progress() { ); seen.clear(); - let manifest = parse(&generated(&tree)).unwrap(); + let manifest = generated(&tree); let (_img2, mut v2) = volume(64 << 20, 512, 4096); let a = v2 - .assemble_with_progress( - &manifest, + .assemble_with_observer( + &mut Reader::open(&manifest[..]).unwrap(), &mut dir_source(&tree), &AssembleOptions::default(), - &mut |p| seen.push(*p), + &mut |p: &Progress| seen.push(*p), ) .unwrap(); assert!(seen.iter().any(|p| p.files == 0 && p.bytes > 0), "{:?}", seen); @@ -963,3 +1336,31 @@ fn long_operations_report_progress() { ); assert_eq!((removed.files, removed.directories), (2, 2)); } + +#[test] +fn assemble_flags() { + let both = AssembleFlags::REPLACE | AssembleFlags::SKIP_UNSUPPORTED; + assert_eq!(AssembleFlags::default(), AssembleFlags::REPLACE); + assert_eq!(AssembleOptions::default().flags, AssembleFlags::REPLACE); + assert!(both.contains(AssembleFlags::REPLACE) && both.contains(AssembleFlags::SKIP_UNSUPPORTED)); + assert!(both.contains(both) && both.contains(AssembleFlags::NONE)); + assert!(!AssembleFlags::REPLACE.contains(AssembleFlags::SKIP_UNSUPPORTED)); + assert!(!AssembleFlags::NONE.contains(AssembleFlags::REPLACE)); + for (replace, skip) in [(false, false), (false, true), (true, false), (true, true)] { + let flags = AssembleFlags::NONE + .with(AssembleFlags::REPLACE, replace) + .with(AssembleFlags::SKIP_UNSUPPORTED, skip); + assert_eq!(flags.contains(AssembleFlags::REPLACE), replace); + assert_eq!(flags.contains(AssembleFlags::SKIP_UNSUPPORTED), skip); + assert_eq!( + both.with(AssembleFlags::REPLACE, replace) + .with(AssembleFlags::SKIP_UNSUPPORTED, skip), + flags + ); + } + let mut flags = AssembleFlags::NONE; + flags |= AssembleFlags::SKIP_UNSUPPORTED; + assert_eq!(format!("{:?}", flags), "AssembleFlags(SKIP_UNSUPPORTED)"); + assert_eq!(format!("{:?}", both), "AssembleFlags(REPLACE | SKIP_UNSUPPORTED)"); + assert_eq!(format!("{:?}", AssembleFlags::NONE), "AssembleFlags()"); +} diff --git a/src/fat/plan.rs b/src/fat/plan.rs index 4b16b16..84c2674 100644 --- a/src/fat/plan.rs +++ b/src/fat/plan.rs @@ -9,20 +9,24 @@ //! FAT32 minimum demands. use std::collections::BTreeMap; +use std::io::Read; use std::os::fd::BorrowedFd; use std::path::PathBuf; +use uapi16::{Object, Order, Reader}; + use crate::dir::MAX_SLOTS; use crate::dirent::DIR_ENTRY_SIZE; use crate::errno::*; use crate::format::{encode_label, FormatOptions}; use crate::host::{walk_tree, HostEntry, UnnamableEntry}; use crate::layout::{self, Layout, LayoutParams, MAX_CLUSTERS, MAX_CLUSTER_SIZE, MAX_SECTORS_PER_CLUSTER}; +use crate::manifest::{path_in_volume, AssembleFlags, EntryKind, ObjectAction, ObjectTriage, SizePurpose}; use crate::name::{Alias, LongName}; use crate::path::components; use crate::sys; use crate::volume::MAX_FILE_SIZE; -use crate::{Context, Result}; +use crate::{Context, Error, Result}; use crate::{Detail, NoSpaceReason}; /// Parameters the size of a volume depends on. @@ -301,6 +305,40 @@ impl Plan { Ok(skipped) } + /// Adds the files and directories of a manifest while `reader` reads + /// it to its end, the way an assembly with `flags` stores them: what + /// this crate cannot store fails the plan as it fails the assembly, + /// unless [`AssembleFlags::SKIP_UNSUPPORTED`] leaves it out. Returns how + /// many file objects are left out, see [`EntryKind`]. The manifest has to + /// declare the code point order, and its file objects have to be in it, + /// as for an assembly. Every regular file needs a size. + pub fn add_records(&mut self, reader: &mut Reader, flags: AssembleFlags) -> Result { + reader.root().require_order(Order::CodePoint)?; + let mut triage = ObjectTriage::default(); + let mut skipped = 0; + while let Some(object) = reader.next() { + let Object::File(object) = object? else { + continue; + }; + let path = path_in_volume(&object.name); + match triage.decide(&object, flags)? { + ObjectAction::Skip(_) => skipped += 1, + ObjectAction::Store(EntryKind::Directory) => self.add_dir(&path)?, + ObjectAction::Store(EntryKind::File) => { + let Some(size) = object.size else { + return Err(Error::no_size( + object.name.as_str(), + Some(reader.record_number()), + SizePurpose::Planning, + )); + }; + self.add_file(&path, size)?; + } + } + } + Ok(skipped) + } + /// The smallest volume for the plan with a given cluster size. pub fn estimate_for(&self, cluster_size: u32) -> Result { let ss = self.options.sector_size; @@ -392,6 +430,7 @@ impl Plan { #[cfg(test)] mod tests { use super::*; + use crate::ManifestProblem; fn options(ss: u32, cs: Option) -> PlanOptions { PlanOptions { @@ -482,4 +521,98 @@ mod tests { assert!(e.layout.clusters >= layout::MIN_CLUSTERS); assert!(e.size() > 256 << 20); } + + #[test] + fn manifests_leave_out_what_an_assembly_leaves_out() { + let records = concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"a\",\"size\":600}\n", + "\x1e{\"contents\":[{\"literal\":\"eA==\"}],\"name\":\"link\",\"type\":\"lnk\"}\n", + "\x1e{\"name\":\"sub\",\"sha256\":\"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824\",\"size\":5,\"type\":\"dir\"}\n", + "\x1e{\"name\":\"sub/x\",\"size\":1}\n", + "\x1e{\"name\":\"sub/y\",\"type\":\"dir\"}\n", + "\x1e{\"name\":\"sub/y/z\",\"size\":1}\n", + "\x1e{\"name\":\"z\",\"size\":1}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + let mut plan = Plan::new(options(512, Some(512))); + let mut reader = Reader::open(records.as_bytes()).unwrap(); + assert_eq!( + plan.add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED).unwrap(), + 5 + ); + let e = plan.estimate().unwrap(); + assert_eq!( + (e.files, e.directories, e.bytes, e.data_clusters), + (2, 0, 601, 1 + 2 + 1) + ); + // Without SKIP_UNSUPPORTED the plan fails where the assembly fails. + let mut plan = Plan::new(options(512, Some(512))); + let mut reader = Reader::open(records.as_bytes()).unwrap(); + let e = plan.add_records(&mut reader, AssembleFlags::NONE).unwrap_err(); + assert_eq!(e.errno(), EOPNOTSUPP); + // A file FAT32 cannot hold and one without a size cannot be + // planned, and a manifest out of code point order not at all. + for (records, errno) in [ + ( + concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"big\",\"size\":4294967296}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ), + EFBIG, + ), + ( + concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"b\",\"size\":1}\n", + "\x1e{\"name\":\"a\",\"size\":1}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ), + EBADMSG, + ), + ( + concat!( + "\x1e{\"features\":[],\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"a\"}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ), + EINVAL, + ), + ] { + let mut plan = Plan::new(options(512, None)); + let mut reader = Reader::open(records.as_bytes()).unwrap(); + assert_eq!( + plan.add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED) + .unwrap_err() + .errno(), + errno, + "{}", + records + ); + } + // Nor one that does not declare the order, even with its objects in + // it. Nothing of it is counted. + let undeclared = concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n", + "\x1e{\"name\":\"a\",\"size\":1}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + let mut plan = Plan::new(options(512, None)); + let mut reader = Reader::open(undeclared.as_bytes()).unwrap(); + let e = plan + .add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED) + .unwrap_err(); + assert_eq!(e.errno(), EBADMSG); + assert_eq!( + e.detail(), + Some(&Detail::Manifest { + problem: ManifestProblem::Malformed(uapi16::Problem::NoOrder), + record: Some(0), + name: None, + field: Some("order".to_string()), + }) + ); + assert_eq!(plan.estimate().unwrap().files, 0); + } } diff --git a/src/fat/sha256.rs b/src/fat/sha256.rs deleted file mode 100644 index 253fc76..0000000 --- a/src/fat/sha256.rs +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: LGPL-2.1-or-later -//! SHA-256 (FIPS 180-4), used to verify the contents listed in manifests. -//! The sha2 crate computes it, with the SHA instructions of the CPU where -//! it has them. - -use sha2::Digest; - -/// Size of a digest in bytes. -pub const DIGEST_SIZE: usize = 32; - -/// The digest of the empty string. -pub const EMPTY: [u8; DIGEST_SIZE] = [ - 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, - 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, -]; - -/// A streaming SHA-256 computation. -#[derive(Clone, Debug, Default)] -pub struct Sha256(sha2::Sha256); - -impl Sha256 { - /// Starts a new computation. - pub fn new() -> Sha256 { - Sha256(sha2::Sha256::new()) - } - - /// Feeds data. - pub fn update(&mut self, data: &[u8]) { - self.0.update(data); - } - - /// Finishes the computation and returns the digest. - pub fn finalize(self) -> [u8; DIGEST_SIZE] { - self.0.finalize().into() - } -} - -/// The digest of `data`. -pub fn digest(data: &[u8]) -> [u8; DIGEST_SIZE] { - sha2::Sha256::digest(data).into() -} - -/// Lower case hex encoding. -pub fn to_hex(digest: &[u8]) -> String { - const DIGITS: &[u8; 16] = b"0123456789abcdef"; - let mut hex = String::with_capacity(digest.len() * 2); - for &b in digest { - hex.push(char::from(DIGITS[usize::from(b >> 4)])); - hex.push(char::from(DIGITS[usize::from(b & 0x0f)])); - } - hex -} - -/// Decodes 64 hex digits of either case. -pub fn from_hex(text: &str) -> Option<[u8; DIGEST_SIZE]> { - let bytes = text.as_bytes(); - if bytes.len() != 2 * DIGEST_SIZE { - return None; - } - let mut out = [0u8; DIGEST_SIZE]; - for (i, pair) in bytes.chunks_exact(2).enumerate() { - let hi = (pair[0] as char).to_digit(16)?; - let lo = (pair[1] as char).to_digit(16)?; - out[i] = (hi * 16 + lo) as u8; - } - Some(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The FIPS 180-4 vectors. - #[test] - fn vectors() { - let million = vec![b'a'; 1_000_000]; - for (data, expected) in [ - ( - &b""[..], - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - ), - ( - &b"abc"[..], - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", - ), - ( - &b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"[..], - "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", - ), - ( - &million[..], - "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", - ), - ] { - assert_eq!(to_hex(&digest(data)), expected, "{} bytes", data.len()); - } - assert_eq!(digest(b""), EMPTY); - } - - #[test] - fn streaming_matches_one_shot() { - let data: Vec = (0..1000u32).map(|i| (i * 31 % 251) as u8).collect(); - let expected = digest(&data); - for chunk in [1usize, 7, 63, 64, 65, 100, 999] { - let mut h = Sha256::new(); - for piece in data.chunks(chunk) { - h.update(piece); - } - assert_eq!(h.finalize(), expected, "chunk size {}", chunk); - } - } - - #[test] - fn hex() { - let hex = to_hex(&EMPTY); - assert_eq!(from_hex(&hex), Some(EMPTY)); - assert_eq!(from_hex(&hex.to_uppercase()), Some(EMPTY)); - assert_eq!(from_hex("00"), None); - assert_eq!(from_hex(&"zz".repeat(32)), None); - } -} diff --git a/src/fat/sha512.rs b/src/fat/sha512.rs index 062792f..36e1985 100644 --- a/src/fat/sha512.rs +++ b/src/fat/sha512.rs @@ -1,25 +1,19 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! SHA-512 (FIPS 180-4), for the hash of a whole image a caller may ask -//! for. The hashes inside manifests stay SHA-256, see [`crate::sha256`]. -//! The sha2 crate computes it. +//! for. The sha2 crate computes it. A SHA-256 hash, of an image or of the +//! files of a manifest, is computed with [`crate::manifest::Sha256Context`]. use sha2::Digest; -pub use crate::sha256::to_hex; - /// Size of a digest in bytes. pub const DIGEST_SIZE: usize = 64; -/// A streaming SHA-512 computation. +/// A streaming SHA-512 computation, started with +/// [`Sha512Context::default`]. #[derive(Clone, Debug, Default)] -pub struct Sha512(sha2::Sha512); - -impl Sha512 { - /// Starts a new computation. - pub fn new() -> Sha512 { - Sha512(sha2::Sha512::new()) - } +pub struct Sha512Context(sha2::Sha512); +impl Sha512Context { /// Feeds data. pub fn update(&mut self, data: &[u8]) { self.0.update(data); @@ -36,6 +30,17 @@ pub fn digest(data: &[u8]) -> [u8; DIGEST_SIZE] { sha2::Sha512::digest(data).into() } +/// Lower case hex encoding. +pub fn to_hex(digest: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut hex = String::with_capacity(digest.len() * 2); + for &b in digest { + hex.push(char::from(DIGITS[usize::from(b >> 4)])); + hex.push(char::from(DIGITS[usize::from(b & 0x0f)])); + } + hex +} + #[cfg(test)] mod tests { use super::*; @@ -124,14 +129,14 @@ mod tests { "9001a3f2cd24e4c46c751ab62e0c2f071ef9c319d5a90477d214905270b23d02e8ed527bd332f2dc5d45f7a0c5265f00a45afdf5120ba46709581e81818a57a2" ); for chunk in [1usize, 7, 63, 64, 65, 111, 112, 113, 127, 128, 129, 200, 999] { - let mut h = Sha512::new(); + let mut h = Sha512Context::default(); for piece in data.chunks(chunk) { h.update(piece); } assert_eq!(h.finalize(), expected, "chunk size {}", chunk); } // Pieces of varying size, including empty ones. - let mut h = Sha512::new(); + let mut h = Sha512Context::default(); let mut pos = 0; for (i, step) in [0usize, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] .iter() @@ -151,6 +156,7 @@ mod tests { #[test] fn hex() { assert_eq!(to_hex(&[0, 0x0f, 0xf0, 0xff]), "000ff0ff"); + assert_eq!(to_hex(&[]), ""); assert_eq!(to_hex(&digest(b"")).len(), 2 * DIGEST_SIZE); } } diff --git a/src/fat/volume/file.rs b/src/fat/volume/file.rs index cdd5d26..7274664 100644 --- a/src/fat/volume/file.rs +++ b/src/fat/volume/file.rs @@ -7,7 +7,7 @@ use std::io::{self, Read, Write}; use std::time::SystemTime; -use super::{check_attributes, writable, Located, Placement, Volume, MAX_FILE_SIZE, SETTABLE_ATTRIBUTES}; +use super::{check_attributes, writable, Located, NewEntry, Placement, Volume, MAX_FILE_SIZE, SETTABLE_ATTRIBUTES}; use crate::dir::{DirEntry, Directory}; use crate::dirent::{RawDirEntry, ATTR_ARCHIVE, ATTR_READ_ONLY}; use crate::errno::*; @@ -40,8 +40,12 @@ impl Volume { /// finished. A token that is dropped leaves its clusters allocated until /// the next fsck; [`Volume::create_file`] wraps it in a guard that /// aborts instead. + /// + /// Nothing is written for a file that is refused: a name FAT cannot + /// store or one that is too long, a parent that is missing, damaged or + /// full, too few free clusters for the parent to grow, a directory of + /// the name, or a file of the name without `replace`. pub fn begin_file(&mut self, path: &str, time: SystemTime, replace: bool) -> Result { - self.begin_write()?; let (dir_cluster, name) = self.locate_parent(path)?; let (placement, replaced) = self.with_directory_mut(dir_cluster, |vol, parent| { let replaced = match Self::find(parent, name.as_str()) { @@ -52,7 +56,7 @@ impl Volume { existing => existing, }; let placement = vol - .place_entry(parent, &name, replaced.as_ref()) + .place_entry(parent, &name, replaced.as_ref(), NewEntry::File) .map_err(|e| e.at_path(path))?; if !vol.reserve_slots(parent, placement.start, placement.long.len() + 1) { bail!( diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index 60c7db3..c6f9c9f 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -87,6 +87,26 @@ enum Located { Entry { parent: u32, entry: DirEntry }, } +/// What a new entry is for, which decides the clusters allocated with it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NewEntry { + /// A file. Its clusters come as its data is written. + File, + /// A directory. Its first cluster, which holds its "." and ".." + /// entries, comes with its entry. + Directory, +} + +impl NewEntry { + /// The clusters allocated along with the entry. + fn clusters(self) -> u32 { + match self { + NewEntry::File => 0, + NewEntry::Directory => 1, + } + } +} + /// A placed, not yet written entry: its slot and its names. #[derive(Debug)] struct Placement { @@ -320,6 +340,16 @@ impl Volume { self.durable } + /// Whether the volume is being written: something was written to it + /// since open() or the last sync(), so that it carries the marks of a + /// volume that was not cleanly unmounted until sync() or close() puts + /// back what was there before. A caller that failed before anything was + /// written leaves the volume as it was by not closing it with + /// [`Volume::close_unfinished`]. + pub fn is_writing(&self) -> bool { + self.writing + } + /// Marks the volume as being written, once per session. Linux and /// Windows decide from bit 0 of byte 0x41 in the boot sector whether a /// volume was cleanly unmounted, EDK2 and the specification from bit 27 @@ -764,15 +794,7 @@ impl Volume { fn grow_directory(&mut self, dir: &mut Directory) -> Result<()> { let per_cluster = self.layout.cluster_size() as usize / DIR_ENTRY_SIZE; if dir.slots() + per_cluster > MAX_SLOTS { - bail!( - ENOSPC, - Detail::NoSpace { - reason: NoSpaceReason::DirectoryEntries, - path: None, - }, - "directory is full, it cannot hold more than {} entries", - MAX_SLOTS - ); + return Err(Directory::full()); } let cluster = self.allocate(1)?.first; let zeros = vec![0u8; self.layout.cluster_size() as usize]; @@ -808,11 +830,36 @@ impl Volume { } } + /// The clusters [`Volume::free_run`] adds to `dir` for a run of `count` + /// free slots where it has none. Fails where that takes the directory + /// past [`MAX_SLOTS`]. Nothing is written. + fn growth_for(&self, dir: &Directory, count: usize) -> Result { + // No run of `count` fits, so fewer slots are free at the end, and + // the clusters appended continue them. + let per_cluster = self.layout.cluster_size() as usize / DIR_ENTRY_SIZE; + let clusters = count.saturating_sub(dir.free_at_end()).div_ceil(per_cluster); + if dir.slots() + clusters * per_cluster > MAX_SLOTS { + return Err(Directory::full()); + } + Ok(clusters) + } + /// Picks the short name for `name`, builds its long name entries and /// finds room for them in `dir`, growing it as needed. `replacing` is an - /// entry about to be replaced, whose names do not count as taken. - /// Nothing is written yet. - fn place_entry(&mut self, dir: &mut Directory, name: &LongName, replacing: Option<&DirEntry>) -> Result { + /// entry about to be replaced, whose names do not count as taken. The + /// clusters allocated with a `new` entry have to be free as well. + /// + /// What refuses the entry is checked before anything is written: a + /// damaged directory, a name that is taken, no short name left, a full + /// directory and too few free clusters. Only then does the volume begin + /// a write and grow the directory. The entry itself is not written. + fn place_entry( + &mut self, + dir: &mut Directory, + name: &LongName, + replacing: Option<&DirEntry>, + new: NewEntry, + ) -> Result { writable(dir)?; if dir.name_taken(&name.folded(), replacing) { bail!(EEXIST, "'{}' exists", name.as_str()); @@ -838,7 +885,20 @@ impl Volume { } else { (alias.name, Vec::new()) }; - let start = self.free_run(dir, long.len() + 1)?; + let count = long.len() + 1; + let free = dir.find_free_run(count); + let growth = match free { + Some(_) => 0, + None => self.growth_for(dir, count)?, + }; + if (self.free_clusters() as usize) < growth + new.clusters() as usize { + return Err(Fat::no_free_clusters()); + } + self.begin_write()?; + let start = match free { + Some(start) => start, + None => self.free_run(dir, count)?, + }; Ok(Placement { start, name: short, @@ -874,9 +934,11 @@ impl Volume { /// an entry that was never written, which keeps it out of the cache. fn make_directory(&mut self, parent: &mut Directory, name: &LongName, time: SystemTime) -> Result { let t = FatTimestamp::from_system_time(time); - // The new directory's cluster is allocated before anything else is - // touched, so that running out of space changes nothing. - let cluster = self.allocate(1)?.first; + // place_entry() checks the parent first, also that a cluster is + // free for the new directory, so a refusal writes nothing. The + // cluster is allocated once the parent made room. + let placement = self.place_entry(parent, name, None, NewEntry::Directory)?; + let cluster = self.allocate(NewEntry::Directory.clusters())?.first; let result = (|| { let cs = self.layout.cluster_size() as usize; let mut data = vec![0u8; cs]; @@ -899,7 +961,6 @@ impl Volume { data[..DIR_ENTRY_SIZE].copy_from_slice(&dot.to_bytes()); data[DIR_ENTRY_SIZE..2 * DIR_ENTRY_SIZE].copy_from_slice(&dotdot.to_bytes()); self.device.write_at(self.layout.cluster_offset(cluster)?, &data)?; - let placement = self.place_entry(parent, name, None)?; let mut entry = RawDirEntry { attr: ATTR_DIRECTORY, first_cluster: cluster, @@ -922,9 +983,11 @@ impl Volume { result } - /// Creates a directory. Its parent must exist. + /// Creates a directory. Its parent must exist. Nothing is written for + /// a directory that is refused: a name FAT cannot store or one that is + /// too long, a parent that is missing, damaged or full, too few free + /// clusters, or a name the parent holds. pub fn create_dir(&mut self, path: &str, time: SystemTime) -> Result<()> { - self.begin_write()?; let (parent, name) = self.locate_parent(path)?; let child = self.with_directory_mut(parent, |vol, parent| { if Self::find(parent, name.as_str()).is_some() { @@ -937,14 +1000,19 @@ impl Volume { } /// Creates a directory and any missing parents. Existing directories - /// along the way are fine. + /// along the way are fine, whatever their names. The path is walked to + /// the first directory that is missing without writing anything, and + /// the names of the directories to create are checked before the first + /// of them is, so a name FAT cannot store or one that is too long + /// writes nothing. Nothing is written either when every directory is + /// there. pub fn create_dir_all(&mut self, path: &str, time: SystemTime) -> Result<()> { - self.begin_write()?; let comps = components(path)?; let mut cluster = self.boot.root_cluster; + let mut there = 0; for (i, c) in comps.iter().enumerate() { - cluster = self.with_directory_mut(cluster, |vol, dir| match Self::find(dir, c) { - Some(e) if e.short.is_directory() => Ok(e.short.first_cluster), + match self.with_directory(cluster, |dir| Ok(Self::find(dir, c)))? { + Some(e) if e.short.is_directory() => cluster = e.short.first_cluster, Some(_) => { let p = format!("/{}", comps[..=i].join("/")); bail!( @@ -954,43 +1022,78 @@ impl Volume { p ); } - None => { - let name = LongName::new(c)?; - let child = vol - .make_directory(dir, &name, time) - .map_err(|e| e.at_path(&format!("/{}", comps[..=i].join("/"))))?; - let first = child.first_cluster(); - vol.keep_directory(child); - Ok(first) - } + None => break, + } + there = i + 1; + } + let names = comps[there..] + .iter() + .copied() + .map(LongName::new) + .collect::>>()?; + for (i, name) in (there..).zip(&names) { + cluster = self.with_directory_mut(cluster, |vol, dir| { + let child = vol + .make_directory(dir, name, time) + .map_err(|e| e.at_path(&format!("/{}", comps[..=i].join("/"))))?; + let first = child.first_cluster(); + vol.keep_directory(child); + Ok(first) })?; } Ok(()) } /// Sets the modification and creation time of a file or directory. A - /// directory's "." and ".." entries follow along. + /// directory's "." and ".." entries follow along. Only what changes is + /// written, so setting the time an entry has leaves the volume as it + /// was. A damaged directory where something would change is refused + /// before anything is written. pub fn set_times(&mut self, path: &str, time: SystemTime) -> Result<()> { - self.begin_write()?; let Located::Entry { parent, entry } = self.locate(path)? else { bail!(EINVAL, "the root directory has no timestamps"); }; let t = FatTimestamp::from_system_time(time); let mut raw = entry.short; raw.set_times(t); - self.with_directory(parent, |parent| { - writable(parent)?; - parent.set_slot(entry.slot, &raw.to_bytes()); - self.save_directory(parent) - })?; - if raw.is_directory() { + let entry_changes = raw != entry.short; + if entry_changes { + self.with_directory(parent, |parent| writable(parent))?; + } + // The dot entries whose times change, with what they become. + let dots: Vec<(usize, RawDirEntry)> = if raw.is_directory() { + self.with_directory(raw.first_cluster, |dir| { + let dots: Vec<(usize, RawDirEntry)> = dir + .iter() + .filter(|e| e.is_dot()) + .filter_map(|dot| { + let mut d = dot.short; + d.set_times(t); + (d != dot.short).then_some((dot.slot, d)) + }) + .collect(); + if !dots.is_empty() { + writable(dir)?; + } + Ok(dots) + })? + } else { + Vec::new() + }; + if !entry_changes && dots.is_empty() { + return Ok(()); + } + self.begin_write()?; + if entry_changes { + self.with_directory(parent, |parent| { + parent.set_slot(entry.slot, &raw.to_bytes()); + self.save_directory(parent) + })?; + } + if !dots.is_empty() { self.with_directory(raw.first_cluster, |dir| { - writable(dir)?; - let dots: Vec = dir.iter().filter(|e| e.is_dot()).cloned().collect(); - for dot in dots { - let mut d = dot.short; - d.set_times(t); - dir.set_slot(dot.slot, &d.to_bytes()); + for &(slot, d) in &dots { + dir.set_slot(slot, &d.to_bytes()); } self.save_directory(dir) })?; diff --git a/src/fat/volume/tests.rs b/src/fat/volume/tests.rs index 23c35a3..a875d02 100644 --- a/src/fat/volume/tests.rs +++ b/src/fat/volume/tests.rs @@ -1,10 +1,12 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! Tests of the volume. use super::*; +use crate::dirent::lfn_field; use crate::fat::{END_OF_CHAIN, ENTRY_SIZE}; use crate::format::{self, FormatOptions}; use crate::fsck; use crate::layout::FIRST_CLUSTER; +use crate::name::{LFN_PADDING, LFN_TERMINATOR}; use crate::test_util::{format_options, volume, TempImage}; use std::io::{Read, Write}; use std::time::{Duration, UNIX_EPOCH}; @@ -232,16 +234,25 @@ fn growing_a_directory_without_space_changes_nothing() { w.write_all(&vec![0u8; free as usize * 512]).unwrap(); w.finish().unwrap(); assert_eq!(v.free_clusters(), 0); - // Growing /sub needs a cluster there is not. + // Growing /sub needs a cluster there is not. That is found before + // anything is written. + v.sync().unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); assert_eq!(v.create_file("/sub/F14", t(0), false).unwrap_err().errno(), ENOSPC); assert_eq!(names(&v, "/sub").len(), 14); - // With one free cluster a new directory gets its own cluster but + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); + // With one free cluster a new directory could get its own cluster but // /sub cannot grow to hold its entry: nothing changes either. v.remove_file("/junk").unwrap(); assert_eq!(v.free_clusters(), 1); + v.sync().unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); assert_eq!(v.create_dir("/sub/d", t(0)).unwrap_err().errno(), ENOSPC); assert_eq!(v.free_clusters(), 1); assert_eq!(names(&v, "/sub").len(), 14); + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); // A file without contents only needs the directory to grow. v.create_file("/sub/F14", t(0), false).unwrap().finish().unwrap(); assert_eq!(v.free_clusters(), 0); @@ -253,6 +264,222 @@ fn growing_a_directory_without_space_changes_nothing() { assert_eq!(names(&v, "/sub").len(), 15); } +/// A directory with every one of its MAX_SLOTS entry slots in use takes no +/// more entries, and refusing one writes nothing. The directory is made on +/// the image itself: one entry at a time would take too long. +#[test] +fn a_full_directory_refuses_before_it_writes() { + let cs = 4096; + let per_cluster = cs / DIR_ENTRY_SIZE; + let (img, mut v) = volume(8 << 20, 512, cs as u32); + v.create_dir("/d", t(0)).unwrap(); + let d = v.metadata("/d").unwrap(); + let more = u32::try_from(MAX_SLOTS / per_cluster - 1).unwrap(); + let extent = v.allocate(more).unwrap(); + assert_eq!(extent.count, more); + v.link(d.first_cluster, extent.first).unwrap(); + let layout = *v.layout(); + v.close().unwrap(); + // The dot entries stay; every other slot gets a file of its own name. + let dev = img.device(); + let chain = std::iter::once(d.first_cluster).chain(extent.first..extent.first + more); + for (i, cluster) in chain.enumerate() { + let offset = layout.cluster_offset(cluster).unwrap(); + let mut data = vec![0u8; cs]; + dev.read_at(offset, &mut data).unwrap(); + for (j, slot) in data.chunks_exact_mut(DIR_ENTRY_SIZE).enumerate() { + let n = i * per_cluster + j; + if n < 2 { + continue; + } + let mut name = [b' '; SHORT_NAME_SIZE]; + name[..8].copy_from_slice(format!("{:08X}", n).as_bytes()); + let mut entry = RawDirEntry { + name, + attr: ATTR_ARCHIVE, + ..RawDirEntry::default() + }; + entry.set_times(FatTimestamp::from_system_time(t(0))); + slot.copy_from_slice(&entry.to_bytes()); + } + dev.write_at(offset, &data).unwrap(); + } + drop(dev); + let mut v = Volume::open(img.device()).unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); + assert_eq!(v.read_dir("/d").unwrap().len(), MAX_SLOTS - 2); + for e in [ + v.create_file("/d/x", t(0), false).map(drop).unwrap_err(), + v.create_dir("/d/y", t(0)).unwrap_err(), + v.create_dir_all("/d/y/z", t(0)).unwrap_err(), + ] { + assert_eq!(e.errno(), ENOSPC); + assert!( + matches!( + e.detail(), + Some(Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + .. + }) + ), + "{:?}", + e + ); + } + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); +} + +/// growth_for() counts the clusters free_run() appends from the free +/// slots at the end, which the first cluster appended continues, and +/// refuses growth past MAX_SLOTS slots but not growth up to it. +#[test] +fn growth_for_continues_the_free_slots_at_the_end() { + let cs = 512; + let per_cluster = cs / DIR_ENTRY_SIZE; + let (_img, v) = volume(1 << 20, 512, cs as u32); + // A directory of `clusters` clusters whose first `used` slots hold + // entries, with nothing after them. + let dir = |clusters: usize, used: usize| { + let mut data = vec![0u8; clusters * cs]; + for (n, slot) in data.chunks_exact_mut(DIR_ENTRY_SIZE).take(used).enumerate() { + let mut name = [b' '; SHORT_NAME_SIZE]; + name[..8].copy_from_slice(format!("{:08X}", n).as_bytes()); + let entry = RawDirEntry { + name, + attr: ATTR_ARCHIVE, + ..RawDirEntry::default() + }; + slot.copy_from_slice(&entry.to_bytes()); + } + let first = FIRST_CLUSTER; + Directory::new((first..first + clusters as u32).collect(), data, cs).unwrap() + }; + let full = |e: crate::Error| { + e.errno() == ENOSPC + && matches!( + e.detail(), + Some(Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + .. + }) + ) + }; + // Four slots free at the end: the first cluster appended continues them. + let d = dir(2, 2 * per_cluster - 4); + assert_eq!(d.free_at_end(), 4); + assert_eq!(v.growth_for(&d, 5).unwrap(), 1); + assert_eq!(v.growth_for(&d, 4 + per_cluster).unwrap(), 1); + assert_eq!(v.growth_for(&d, 5 + per_cluster).unwrap(), 2); + // None free at the end: every slot of the run is a new one. + let d = dir(2, 2 * per_cluster); + assert_eq!(d.free_at_end(), 0); + assert_eq!(v.growth_for(&d, per_cluster).unwrap(), 1); + assert_eq!(v.growth_for(&d, per_cluster + 1).unwrap(), 2); + // A cluster short of MAX_SLOTS: growing up to it is fine, past it not. + let most = MAX_SLOTS / per_cluster; + let d = dir(most - 1, (most - 1) * per_cluster - 4); + assert_eq!(d.free_at_end(), 4); + assert_eq!(v.growth_for(&d, 4 + per_cluster).unwrap(), 1); + assert!(full(v.growth_for(&d, 5 + per_cluster).unwrap_err())); + // At MAX_SLOTS the free slots at the end still take a run that fits + // them, and nothing longer. + let d = dir(most, MAX_SLOTS - 4); + assert_eq!(d.find_free_run(4), Some(MAX_SLOTS - 4)); + assert!(full(v.growth_for(&d, 5).unwrap_err())); +} + +/// An entry that continues the free slots at the end of a directory needs +/// the clusters past them only, and exactly that many free clusters do. +/// One less refuses it before anything is written. +#[test] +fn growing_from_the_free_slots_at_the_end_takes_the_clusters_it_needs() { + let (img, mut v) = volume(1 << 20, 512, 512); + v.create_dir("/d", t(0)).unwrap(); + // The dots and 13 one-slot entries leave the last slot of /d free. + for i in 0..13 { + v.create_file(&format!("/d/F{}", i), t(0), false) + .unwrap() + .finish() + .unwrap(); + } + let d = v.metadata("/d").unwrap(); + assert_eq!(v.load_directory(d.first_cluster).unwrap().free_at_end(), 1); + let free = v.free_clusters(); + let mut w = v.create_file("/fill", t(0), false).unwrap(); + w.write_all(&vec![0u8; (free as usize - 1) * 512]).unwrap(); + w.finish().unwrap(); + assert_eq!(v.free_clusters(), 1); + v.sync().unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); + // A name of two slots needs a cluster for /d, and a directory of that + // name one more for itself. + assert_eq!(v.create_dir("/d/abcdefghi", t(0)).unwrap_err().errno(), ENOSPC); + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); + // A file of that name takes the one, and its entry starts in the last + // slot of the first cluster. + v.create_file("/d/abcdefghi", t(0), false).unwrap().finish().unwrap(); + assert_eq!(v.free_clusters(), 0); + let dir = v.load_directory(d.first_cluster).unwrap(); + assert_eq!(dir.chain().len(), 2); + let e = dir.entries().into_iter().find(|e| e.name() == "abcdefghi").unwrap(); + assert_eq!(e.first_slot(), 15); + v.close().unwrap(); + let r = fsck::check(&img.device()).unwrap(); + assert_eq!(r.errors(), 0, "{:?}", r.problems); +} + +/// create_dir_all() walks through directories whatever their names, such +/// as " x", which Linux writes and ufat does not, and checks only the +/// names of the directories it creates. +#[test] +fn create_dir_all_walks_through_names_it_would_not_write() { + let (img, mut v) = volume(1 << 20, 512, 512); + v.create_dir("/abcdefghij", t(0)).unwrap(); + let root = v.boot.root_cluster; + let first_slot = v + .load_directory(root) + .unwrap() + .entries() + .into_iter() + .find(|e| e.name() == "abcdefghij") + .unwrap() + .first_slot(); + let layout = *v.layout(); + v.close().unwrap(); + // Its one long name slot gets the name " x". + let at = layout.cluster_offset(root).unwrap() + (first_slot * DIR_ENTRY_SIZE) as u64; + let dev = img.device(); + let mut slot = [0u8; DIR_ENTRY_SIZE]; + dev.read_at(at, &mut slot).unwrap(); + let units = [u16::from(b' '), u16::from(b'x'), LFN_TERMINATOR] + .into_iter() + .chain(std::iter::repeat(LFN_PADDING)); + let offsets = [lfn_field::NAME1, lfn_field::NAME2, lfn_field::NAME3] + .into_iter() + .flat_map(|field| field.step_by(2)); + for (off, unit) in offsets.zip(units) { + slot[off..off + 2].copy_from_slice(&unit.to_le_bytes()); + } + dev.write_at(at, &slot).unwrap(); + drop(dev); + let mut v = Volume::open(img.device()).unwrap(); + assert_eq!(names(&v, "/"), vec![" x"]); + assert_eq!(LongName::new(" x").unwrap_err().errno(), EINVAL); + v.create_dir_all("/ x/y/z", t(0)).unwrap(); + assert!(v.metadata("/ x/y/z").unwrap().is_dir); + // A name it creates is checked, before anything is written. + v.sync().unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); + assert_eq!(v.create_dir_all("/ x/y/ w/v", t(0)).unwrap_err().errno(), EINVAL); + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); + v.close().unwrap(); + let r = fsck::check(&img.device()).unwrap(); + assert_eq!(r.errors(), 0, "{:?}", r.problems); +} + #[test] fn a_failed_write_discards_the_file() { let (img, mut v) = volume(1 << 20, 512, 512); @@ -369,14 +596,21 @@ fn a_damaged_directory_is_read_but_not_written() { ) .unwrap(); let mut v = Volume::open(img.device()).unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); // Reading stops at the marker, like Linux. assert_eq!(names(&v, "/d"), vec!["x"]); assert!(v.metadata("/d/x").is_ok()); - // Writing is refused in every form. + // Writing is refused in every form, before anything is written: the + // directory's entry in the root does not get the time its dot entries + // cannot. assert_eq!(v.create_file("/d/y", t(0), false).unwrap_err().errno(), EUCLEAN); assert_eq!(v.create_dir("/d/sub", t(0)).unwrap_err().errno(), EUCLEAN); + assert_eq!(v.create_dir_all("/d/sub/deeper", t(0)).unwrap_err().errno(), EUCLEAN); + assert_eq!(v.set_times("/d/x", t(1_700_000_000)).unwrap_err().errno(), EUCLEAN); + assert_eq!(v.set_times("/d", t(1_700_000_000)).unwrap_err().errno(), EUCLEAN); + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); assert_eq!(v.remove_file("/d/x").unwrap_err().errno(), EUCLEAN); - assert_eq!(v.set_times("/d/x", t(1)).unwrap_err().errno(), EUCLEAN); assert_eq!(names(&v, "/d"), vec!["x"]); // The rest of the volume is still usable. v.create_file("/ok", t(0), false).unwrap().finish().unwrap(); @@ -416,6 +650,14 @@ fn set_times() { } assert_eq!(v.set_times("/", t(0)).unwrap_err().errno(), EINVAL); assert_eq!(v.set_times("/missing", t(0)).unwrap_err().errno(), ENOENT); + // The time an entry has already is not written. + v.sync().unwrap(); + v.set_times("/d", t(1_600_000_000)).unwrap(); + v.set_times("/d/f", t(1_700_000_000)).unwrap(); + assert!(!v.is_writing()); + v.set_times("/d", t(1_700_000_000)).unwrap(); + assert!(v.is_writing()); + assert_eq!(v.metadata("/d").unwrap().modified, t(1_700_000_000)); } #[test] @@ -836,9 +1078,50 @@ fn the_volume_is_marked_dirty_while_written() { ); } +/// What the volume refuses before it would write leaves it as it was: a +/// name FAT cannot store, one that is too long, one that is taken or is a +/// directory, a parent that is missing. Nothing is marked, and the image +/// does not change. +#[test] +fn refusals_leave_the_volume_unmarked() { + let (img, mut v) = volume(1 << 20, 512, 512); + v.create_dir("/d", t(0)).unwrap(); + v.create_file("/f", t(0), false).unwrap().finish().unwrap(); + v.sync().unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); + let long = format!("/{}", "x".repeat(256)); + let long_below_missing = format!("/missing/{}", "x".repeat(256)); + for (e, errno) in [ + (v.create_dir("/a:b", t(0)), EINVAL), + (v.create_dir("/d", t(0)), EEXIST), + (v.create_dir("/missing/x", t(0)), ENOENT), + (v.create_dir(&long, t(0)), ENAMETOOLONG), + (v.create_dir_all("/d/a:b", t(0)), EINVAL), + (v.create_dir_all("/f/x", t(0)), ENOTDIR), + (v.create_dir_all("/missing/a:b", t(0)), EINVAL), + (v.create_dir_all(&long_below_missing, t(0)), ENAMETOOLONG), + (v.create_file("/d", t(0), true).map(drop), EISDIR), + (v.create_file("/f", t(0), false).map(drop), EEXIST), + (v.create_file("/a:b", t(0), true).map(drop), EINVAL), + (v.create_file(&long, t(0), true).map(drop), ENAMETOOLONG), + ] { + assert_eq!(e.unwrap_err().errno(), errno); + } + // Directories that are there are no write either. + v.create_dir_all("/d", t(0)).unwrap(); + v.create_dir_all("/", t(0)).unwrap(); + // The image is read while the volume is open: closing it would put back + // marks a refusal set. A writing session lasts until the volume is + // synced, so is_writing() covers every refusal above as well. + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); + assert!(!v.is_writing()); + assert_eq!(v.metadata("/missing").unwrap_err().errno(), ENOENT); +} + /// A volume closed unfinished keeps the marks of a writing session, as a /// crash would leave them, and what was written before is on disk. One -/// that nothing was written to since it was opened gets the marks too. +/// that nothing was written to since it was opened gets the marks too. A +/// volume is being written from its first write on, until it is synced. #[test] fn a_volume_closed_unfinished_stays_marked() { use crate::boot::{field, FsInfo, FSINFO_SIZE, FSINFO_UNKNOWN, NT_FLAG_DIRTY}; @@ -846,11 +1129,16 @@ fn a_volume_closed_unfinished_stays_marked() { let (img, mut v) = volume(1 << 20, 512, 512); let layout = *v.layout(); let fsinfo = usize::from(v.boot_sector().fsinfo_sector) * layout.sector_size as usize; + assert!(!v.is_writing()); if written { let mut w = v.create_file("/f", t(0), false).unwrap(); w.write_all(b"data").unwrap(); w.finish().unwrap(); + v.sync().unwrap(); + assert!(!v.is_writing()); + v.create_dir("/d", t(0)).unwrap(); } + assert_eq!(v.is_writing(), written); v.close_unfinished().unwrap(); let bytes = std::fs::read(img.path()).unwrap(); assert_ne!(bytes[field::NT_FLAGS] & NT_FLAG_DIRTY, 0); @@ -1011,6 +1299,48 @@ fn root_time() { assert_eq!(v.root_time().unwrap(), Some(t(1_650_000_000))); } +/// set_times() writes the dot entries of a directory where only they +/// differ: its entry has the time already and its "." and ".." do not. +#[test] +fn set_times_writes_dot_entries_that_differ() { + let (img, mut v) = volume(1 << 20, 512, 512); + v.create_dir("/e", t(0)).unwrap(); + let e = v.metadata("/e").unwrap(); + let layout = *v.layout(); + v.close().unwrap(); + // The dot entries get another time on the image. + let offset = layout.cluster_offset(e.first_cluster).unwrap(); + let dev = img.device(); + for slot in 0..2u64 { + let at = offset + slot * DIR_ENTRY_SIZE as u64; + let mut bytes = [0u8; DIR_ENTRY_SIZE]; + dev.read_at(at, &mut bytes).unwrap(); + let mut dot = RawDirEntry::from_bytes(&bytes); + dot.set_times(FatTimestamp::from_system_time(t(1_600_000_000))); + dev.write_at(at, &dot.to_bytes()).unwrap(); + } + drop(dev); + let mut v = Volume::open(img.device()).unwrap(); + v.set_times("/e", t(0)).unwrap(); + assert!(v.is_writing()); + let expected = FatTimestamp::from_system_time(t(0)); + let dots: Vec = v + .load_directory(e.first_cluster) + .unwrap() + .entries() + .into_iter() + .filter(|entry| entry.is_dot()) + .collect(); + assert_eq!(dots.len(), 2); + for dot in dots { + assert_eq!( + (dot.short.write_date, dot.short.write_time), + (expected.date, expected.time) + ); + } + assert_eq!(v.metadata("/e").unwrap().modified, e.modified); +} + #[test] fn the_label_entry_grows_a_full_root() { let img = TempImage::new(1 << 20); diff --git a/tests/cli.rs b/tests/cli.rs index 4739759..69e960f 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -26,9 +26,11 @@ fn run(bin: &Path, args: &[&str]) -> Output { .expect("ufat runs") } -/// Runs ufat with `stdin` fed to its standard input. +/// Runs ufat with `stdin` fed to its standard input. ufat may exit before +/// it reads its input, for one when it refuses an argument first or its +/// SOURCE is a tree. fn run_in(bin: &Path, args: &[&str], stdin: &[u8]) -> Output { - use std::io::Write; + use std::io::{ErrorKind, Write}; use std::process::Stdio; let mut child = Command::new(bin) .args(args) @@ -38,10 +40,46 @@ fn run_in(bin: &Path, args: &[&str], stdin: &[u8]) -> Output { .stderr(Stdio::piped()) .spawn() .expect("ufat runs"); - child.stdin.take().unwrap().write_all(stdin).unwrap(); + if let Err(e) = child.stdin.take().unwrap().write_all(stdin) { + assert_eq!(e.kind(), ErrorKind::BrokenPipe, "{}", e); + } child.wait_with_output().expect("ufat runs") } +/// Runs ufat with the file at `path` as its standard input. +fn run_from(bin: &Path, args: &[&str], path: &Path) -> Output { + Command::new(bin) + .args(args) + .env("SOURCE_DATE_EPOCH", "1700000000") + .stdin(fs::File::open(path).unwrap()) + .output() + .expect("ufat runs") +} + +/// Runs ufat with a pipe that holds `stdin` as its standard input, the +/// writing end closed. Returns what ufat left in the pipe as well. `stdin` +/// has to fit into the pipe. +fn run_from_pipe(bin: &Path, args: &[&str], stdin: &[u8]) -> (Output, Vec) { + use std::io::{Read, Write}; + use std::os::fd::FromRawFd; + let mut fds = [0; 2]; + // SAFETY: pipe2() fills in two descriptors, which are owned here. + assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + // SAFETY: both are open and owned by nothing else. + let (mut reader, mut writer) = unsafe { (fs::File::from_raw_fd(fds[0]), fs::File::from_raw_fd(fds[1])) }; + writer.write_all(stdin).unwrap(); + drop(writer); + let out = Command::new(bin) + .args(args) + .env("SOURCE_DATE_EPOCH", "1700000000") + .stdin(reader.try_clone().unwrap()) + .output() + .expect("ufat runs"); + let mut left = Vec::new(); + reader.read_to_end(&mut left).unwrap(); + (out, left) +} + fn ok(bin: &Path, args: &[&str]) -> String { let out = run(bin, args); assert!( @@ -429,8 +467,9 @@ fn assemble_and_populate_take_trees_and_manifests() { tree(&root.join("tree")); let tree_arg = root.join("tree"); let tree_arg = tree_arg.to_str().unwrap(); - let a = root.join("a.img"); - let a = a.to_str().unwrap(); + let image = |name: &str| root.join(name).to_str().unwrap().to_string(); + let a = image("a.img"); + let a = a.as_str(); // A tree: created, formatted and filled in one command. The size is // given so that the replacements below have room: a replacement holds // the old file until the new one is complete, and a volume sized to fit @@ -440,15 +479,16 @@ fn assemble_and_populate_take_trees_and_manifests() { assert!(run(&bin, &["check", a]).status.success()); let tree_size = ok(&bin, &["assemble", "--plan", tree_arg]); // A manifest of the tree, kept outside it, builds the same content; the - // one SOURCE says where the files are. + // one SOURCE says where the files are. assemble reads it twice. let manifest = root.join("tree.manifest"); fs::write(&manifest, ok(&bin, &["manifest", tree_arg])).unwrap(); let m = manifest.to_str().unwrap(); - let b = root.join("b.img"); - let b = b.to_str().unwrap(); + let b = image("b.img"); + let b = b.as_str(); ok(&bin, &["assemble", "--create", "--manifest", m, b, tree_arg]); assert_eq!(ok(&bin, &["list", b, "/loader/entries"]), "x.conf\n"); assert_eq!(ok(&bin, &["cat", b, "/EFI/Linux/linux.efi"]), "kernel"); + assert_eq!(fs::metadata(b).unwrap().len().to_string() + "\n", tree_size); // The planner sees the same size from the manifest, which needs no // SOURCE to be sized. assert_eq!(tree_size, ok(&bin, &["assemble", "--plan", "--manifest", m])); @@ -468,10 +508,124 @@ fn assemble_and_populate_take_trees_and_manifests() { let out = run_in(&bin, &["populate", "--manifest", m, a, "-"], b"kerneltitle x\nmore"); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("goes on after the last file")); + // A populate that fails partway leaves the file system marked as not + // cleanly unmounted, with what was complete. + assert!(ok(&bin, &["check", a]).contains("not cleanly unmounted")); + // One whose manifest is refused at its first object, before anything + // was written, leaves the file system as it was: an object that has + // expired, one that comes before its directory, one FAT cannot store + // under --unsupported fail, a file the stream cannot have without a + // size or at an offset, one that is missing below the SOURCE, one where + // the file system has a directory, a name FAT cannot store or one too + // long, and a name the file system holds with --no-replace. + let clean = image("clean.img"); + let clean = clean.as_str(); + ok(&bin, &["assemble", "--create", "--size", "40M", clean]); + let old = root.join("old.txt"); + fs::write(&old, b"old").unwrap(); + ok(&bin, &["populate", "--path", "/d", clean]); + ok(&bin, &["populate", "--path", "/f", clean, old.to_str().unwrap()]); + let long = format!(r#"{{"name":"{}","size":0}}"#, "x".repeat(256)); + for (object, options, source, message) in [ + ( + r#"{"name":"x","size":0,"validUntilUSec":1}"#, + &[][..], + tree_arg, + "has expired", + ), + (r#"{"name":"d/x","size":0}"#, &[], tree_arg, "does not come right after"), + ( + r#"{"name":"x","type":"fifo"}"#, + &["--unsupported", "fail"], + tree_arg, + "which FAT cannot store", + ), + (r#"{"name":"x"}"#, &[], "-", "cannot be streamed"), + ( + r#"{"contents":[{"file":"x","offset":1}],"name":"x","size":1}"#, + &[], + "-", + "offset cannot be used", + ), + (r#"{"name":"x","size":1}"#, &[], tree_arg, "failed to open x"), + (r#"{"name":"d","size":0}"#, &[], "-", "'/d' is a directory"), + ( + r#"{"name":"a:b","size":0}"#, + &[], + "-", + "contains the invalid character ':'", + ), + (long.as_str(), &[], "-", "is longer than 255 UTF-16 units"), + (r#"{"name":"f","size":0}"#, &["--no-replace"], "-", "'/f' exists"), + ] { + let refused = root.join("refused.manifest"); + fs::write( + &refused, + format!( + "\x1e{{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}}\n\x1e{}\n\x1e{{\"mediaType\":\"application/vnd.uapi.16.trailer\"}}\n", + object + ), + ) + .unwrap(); + let refused = refused.to_str().unwrap(); + let mut args = vec!["populate"]; + args.extend_from_slice(options); + args.extend_from_slice(&["--manifest", refused, clean, source]); + let out = run_in(&bin, &args, b"x"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}: {}", object, stderr); + assert!(stderr.contains(message), "{}: {}", object, stderr); + let report = ok(&bin, &["check", clean]); + assert!(report.ends_with("; 0 errors, 0 warnings\n"), "{}: {}", object, report); + } + assert_eq!(ok(&bin, &["cat", clean, "/f"]), "old"); + let out = run_in(&bin, &["populate", "--manifest", m, clean, "-"], b"kern"); + assert_eq!(out.status.code(), Some(1)); + assert!(ok(&bin, &["check", clean]).contains("not cleanly unmounted")); // --manifest - reads the manifest from standard input, which then - // cannot carry the file contents as well. + // cannot carry the file contents as well. A pipe is read once. + // assemble with a SOURCE plans the content before it writes it, so it + // refuses one before it reads anything of it: all of it is left in the + // pipe. assemble --plan and assemble without a SOURCE read the + // manifest once and take one. assemble --plan takes standard input + // that is the file itself as well. let manifest_bytes = fs::read(&manifest).unwrap(); - let out = run_in(&bin, &["assemble", "--plan", "--manifest", "-"], &manifest_bytes); + let not_a_file = "standard input is not a regular file: assemble with a SOURCE needs the manifest in one"; + let piped = image("piped.img"); + let piped = piped.as_str(); + for args in [ + &["assemble", "--create", "--manifest", "-", piped, tree_arg][..], + &[ + "assemble", + "--create", + "--size", + "40M", + "--manifest", + "-", + piped, + tree_arg, + ], + ] { + let (out, left) = run_from_pipe(&bin, args, &manifest_bytes); + assert_eq!(out.status.code(), Some(1), "{:?}", args); + assert!(String::from_utf8_lossy(&out.stderr).contains(not_a_file), "{:?}", args); + assert_eq!(left, manifest_bytes, "{:?}", args); + assert!(!Path::new(piped).exists()); + } + let (out, left) = run_from_pipe( + &bin, + &["assemble", "--create", "--manifest", "-", piped], + &manifest_bytes, + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(left.is_empty(), "{} bytes left", left.len()); + assert_eq!(fs::metadata(piped).unwrap().len().to_string() + "\n", tree_size); + assert!(run(&bin, &["check", piped]).status.success()); + let (out, left) = run_from_pipe(&bin, &["assemble", "--plan", "--manifest", "-"], &manifest_bytes); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout), tree_size); + assert!(left.is_empty(), "{} bytes left", left.len()); + let out = run_from(&bin, &["assemble", "--plan", "--manifest", "-"], &manifest); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8_lossy(&out.stdout), tree_size); let out = run_in(&bin, &["populate", "--manifest", "-", a, tree_arg], &manifest_bytes); @@ -479,7 +633,15 @@ fn assemble_and_populate_take_trees_and_manifests() { let out = run_in(&bin, &["populate", "--manifest", "-", a, "-"], b""); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("cannot both read standard input")); - let out = run_in(&bin, &["assemble", "--plan", "--manifest", "-"], b"not a manifest"); + fs::write(root.join("not-a-manifest"), b"not a manifest").unwrap(); + let out = run_from( + &bin, + &["assemble", "--plan", "--manifest", "-"], + &root.join("not-a-manifest"), + ); + assert_eq!(out.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&out.stderr).contains("standard input is not a UAPI.16 manifest")); + let out = run_in(&bin, &["populate", "--manifest", "-", a, tree_arg], b"not a manifest"); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("standard input is not a UAPI.16 manifest")); // A SOURCE is a directory, or for populate one file that needs --path; @@ -509,6 +671,19 @@ fn assemble_and_populate_take_trees_and_manifests() { ], "is not a UAPI.16 manifest", ); + // A manifest whose objects are out of order is refused when the object + // that breaks the order comes. + let unsorted = root.join("unsorted.manifest"); + let text = String::from_utf8(manifest_bytes.clone()).unwrap(); + let records: Vec<&str> = text.split_inclusive('\n').collect(); + let mut swapped = records.clone(); + swapped.swap(1, records.len() - 2); + fs::write(&unsorted, swapped.concat()).unwrap(); + fails( + &bin, + &["populate", "--manifest", unsorted.to_str().unwrap(), a, tree_arg], + &format!("{}: manifest object 1 (loader/entries/x.conf):", unsorted.display()), + ); // A manifest takes exactly one SOURCE and no --path. let nowhere = root.join("nowhere"); let nowhere = nowhere.to_str().unwrap(); @@ -535,65 +710,59 @@ fn assemble_and_populate_take_trees_and_manifests() { "unknown option", ); fails(&bin, &["assemble", "--create", "--stream", b, m], "unknown option"); - // The files a manifest names are checked below the SOURCE before an - // image is created, so a wrong tree leaves nothing behind. - let d = root.join("d.img"); - let d = d.to_str().unwrap(); - fs::create_dir(root.join("empty")).unwrap(); - fails( - &bin, - &[ - "assemble", - "--create", - "--manifest", - m, - d, - root.join("empty").to_str().unwrap(), - ], - "linux.efi", - ); - assert!(!Path::new(d).exists()); + // The files a manifest names are found below the SOURCE when they are + // copied, and the messages about them name the SOURCE. A SOURCE that is + // not there leaves nothing behind. A file that is missing, or changed + // since the manifest was written, fails the copy, and the file system + // holds what was complete before it, marked as not cleanly unmounted, + // the way a crash would leave it. A file that grew still has the data + // the manifest describes at its start, and that is what is copied. + let d = image("d.img"); + let d = d.as_str(); fails(&bin, &["assemble", "--create", "--manifest", m, d, nowhere], "nowhere"); assert!(!Path::new(d).exists()); - // A file that grew since the manifest was written is caught the same - // way. - fs::write(root.join("tree/EFI/Linux/linux.efi"), b"kernel and more").unwrap(); + let empty = root.join("empty"); + let empty = empty.to_str().unwrap(); + fs::create_dir(empty).unwrap(); fails( &bin, - &["assemble", "--create", "--manifest", m, d, tree_arg], - ": EFI/Linux/linux.efi: EFI/Linux/linux.efi is 15 bytes, the manifest says 6", + &["assemble", "--create", "--manifest", m, d, empty], + &format!( + "ufat: {}: EFI/Linux/linux.efi: failed to open EFI/Linux/linux.efi", + empty + ), ); - assert!(!Path::new(d).exists()); - // One whose contents changed fails while it is copied. The messages - // name the file the way the manifest does. + assert_eq!(ok(&bin, &["list", d, "/EFI/Linux"]), ""); + fs::write(root.join("tree/EFI/Linux/linux.efi"), b"kernel and more").unwrap(); + ok(&bin, &["assemble", "--force", "--manifest", m, d, tree_arg]); + assert_eq!(ok(&bin, &["cat", d, "/EFI/Linux/linux.efi"]), "kernel"); fs::write(root.join("tree/EFI/Linux/linux.efi"), b"kernal").unwrap(); fails( &bin, - &["assemble", "--create", "--manifest", m, d, tree_arg], - "ufat: 'EFI/Linux/linux.efi' does not match the hash in the manifest", + &["assemble", "--force", "--manifest", m, d, tree_arg], + &format!( + "ufat: {}: 'EFI/Linux/linux.efi' does not match the hash in the manifest", + tree_arg + ), ); fs::write(root.join("tree/EFI/Linux/linux.efi"), b"kernel").unwrap(); - // What a failed assemble wrote is left the way a crash would leave it: - // the files that were complete, in a file system marked as not cleanly - // unmounted. check reports the mark. fs::write(root.join("tree/loader/entries/x.conf"), b"title y\n").unwrap(); - let e = root.join("e.img"); - let e = e.to_str().unwrap(); fails( &bin, - &["assemble", "--create", "--manifest", m, e, tree_arg], + &["assemble", "--force", "--manifest", m, d, tree_arg], "'loader/entries/x.conf' does not match the hash", ); - assert_eq!(ok(&bin, &["cat", e, "/EFI/Linux/linux.efi"]), "kernel"); - let report = ok(&bin, &["check", e]); + assert_eq!(ok(&bin, &["cat", d, "/EFI/Linux/linux.efi"]), "kernel"); + let report = ok(&bin, &["check", d]); assert!(report.contains("marked dirty"), "{}", report); - assert!(report.contains("0 errors, 2 warnings"), "{}", report); + assert!(report.ends_with("; 0 errors, 2 warnings\n"), "{}", report); fs::write(root.join("tree/loader/entries/x.conf"), b"title x\n").unwrap(); // Without a SOURCE assemble makes an empty file system, sized for a // manifest as well, and takes no --fit with it. - let c = root.join("c.img"); - let c = c.to_str().unwrap(); + let c = image("c.img"); + let c = c.as_str(); ok(&bin, &["assemble", "--create", "--manifest", m, c]); + assert_eq!(fs::metadata(c).unwrap().len().to_string() + "\n", tree_size); ok(&bin, &["populate", "--manifest", m, c, tree_arg]); assert!(run(&bin, &["check", c]).status.success()); fails( @@ -668,6 +837,54 @@ fn assemble_and_populate_take_trees_and_manifests() { } } +/// A manifest has to declare the code point order. One that does not is +/// refused before anything is written, also when its objects are sorted, +/// from a file and from standard input. +#[test] +fn manifests_have_to_declare_their_order() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let t = root.join("tree"); + let t = t.to_str().unwrap(); + let declared = ok(&bin, &["manifest", t]); + let undeclared = declared.replacen(r#","order":"codepoint""#, "", 1); + assert_ne!(undeclared, declared); + let manifest = root.join("undeclared.manifest"); + fs::write(&manifest, &undeclared).unwrap(); + let m = manifest.to_str().unwrap(); + let refused = "the manifest does not declare \"order\": \"codepoint\" in its root file object"; + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + fails( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", m, a, t], + &format!("ufat: {}: {}", m, refused), + ); + assert!(!image.exists()); + fails(&bin, &["assemble", "--plan", "--manifest", m], refused); + fails(&bin, &["assemble", "--create", "--manifest", m, a], refused); + assert!(!image.exists()); + ok(&bin, &["assemble", "--create", "--size", "40M", a]); + fails(&bin, &["populate", "--manifest", m, a, t], refused); + let out = run_in(&bin, &["populate", "--manifest", "-", a, t], undeclared.as_bytes()); + assert_eq!(out.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&out.stderr).contains(&format!("ufat: standard input: {}", refused)), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(ok(&bin, &["list", a]), ""); + // With the declaration it is taken. + fs::write(&manifest, &declared).unwrap(); + ok(&bin, &["populate", "--manifest", m, a, t]); + assert_eq!(ok(&bin, &["list", a]), "EFI/\nloader/\n"); +} + /// A volume too small for what goes into it. A copy that runs out of /// clusters says which file did not fit and leaves what came before it in /// a consistent file system. `assemble` with a `--size` the content does @@ -861,6 +1078,47 @@ fn populate_and_remove_work_on_paths() { ); assert!(!ok(&bin, &["list", a, "/"]).contains("fifo-fail")); fails(&bin, &["populate", "--unsupported", "maybe", a, t], "skip or fail"); + // A plan refuses it too, from a tree or a manifest, and so does + // assemble, which plans first, before the image is touched. + fails( + &bin, + &["assemble", "--plan", "--unsupported", "fail", t], + "cannot be stored on FAT", + ); + let manifest = root.join("fifo.manifest"); + fs::write( + &manifest, + concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"a\",\"size\":0}\n", + "\x1e{\"name\":\"f\",\"type\":\"fifo\"}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ), + ) + .unwrap(); + let m = manifest.to_str().unwrap(); + let fifo = "'/f' is a fifo, which FAT cannot store"; + fails( + &bin, + &["assemble", "--plan", "--unsupported", "fail", "--manifest", m], + fifo, + ); + let blank = root.join("blank.img"); + fs::File::create(&blank).unwrap().set_len(40 << 20).unwrap(); + fails( + &bin, + &[ + "assemble", + "--unsupported", + "fail", + "--manifest", + m, + blank.to_str().unwrap(), + t, + ], + fifo, + ); + assert!(fs::read(&blank).unwrap().iter().all(|&b| b == 0)); } /// Creates a FIFO without spawning mkfifo(1). @@ -936,11 +1194,7 @@ fn manifests_of_what_was_written() { ]); assert_eq!(stdout, fs::read(&written).unwrap()); // What --hash sha256 prints for an image sized to fit. - let sha256_line = |image: &str| { - let mut h = fat::sha256::Sha256::new(); - h.update(&fs::read(image).unwrap()); - format!("{}\n", fat::sha256::to_hex(&h.finalize())) - }; + let sha256_line = |image: &str| format!("{}\n", fat::manifest::Sha256::digest(&fs::read(image).unwrap())); assert_eq!(stderr, sha256_line(c)); // --write-hash writes the hash to a file of its own, or for "-" to // standard output, which the manifest then cannot have as well. @@ -1158,9 +1412,10 @@ fn hashes_and_capabilities() { let a = root.join("a.img"); let a = a.to_str().unwrap(); let hash = ok(&bin, &["assemble", "--create", "--hash", "sha256", a, t]); - let mut h = fat::sha256::Sha256::new(); - h.update(&fs::read(a).unwrap()); - assert_eq!(hash, format!("{}\n", fat::sha256::to_hex(&h.finalize()))); + assert_eq!( + hash, + format!("{}\n", fat::manifest::Sha256::digest(&fs::read(a).unwrap())) + ); let hash = ok(&bin, &["assemble", "--force", "--hash", "sha512", a, t]); assert_eq!(hash.trim().len(), 128); fails(&bin, &["assemble", "--hash", "md5", a, t], "sha256 or sha512"); diff --git a/tests/crash/crash.rs b/tests/crash/crash.rs index 84f6b9a..1d98e53 100644 --- a/tests/crash/crash.rs +++ b/tests/crash/crash.rs @@ -37,8 +37,11 @@ use fat::fat::{Entry, Fat, BAD_CLUSTER, END_OF_CHAIN_MIN, ENTRY_MASK, ENTRY_SIZE use fat::format::{self, FormatOptions}; use fat::fsck::{self, ProblemKind, Severity}; use fat::layout::{Layout, FIRST_CLUSTER}; -use fat::name::{join_long_name, parse_long_name_entry, short_name_to_string, LongNameEntry}; -use fat::sha256; +use fat::manifest::Sha256; +use fat::name::{ + join_long_name, parse_long_name_entry, short_name_to_string, LongNameEntry, LFN_MAX_ENTRIES, LFN_UNITS_PER_ENTRY, + MAX_LONG_NAME, +}; use fat::time::FatTimestamp; use fat::volume::Volume; @@ -134,6 +137,12 @@ fn read_trace(path: &Path) -> Vec { enum Op { /// `create_dir_all`. Mkdir(String), + /// `create_dir`, and whether its parent grows a cluster for the entry, + /// which the harness checks. + CreateDir { + path: String, + grows: bool, + }, /// A file written `chunk` bytes per write call, replacing an existing /// file of that name or not. Write { @@ -151,6 +160,11 @@ impl Op { fn describe(&self) -> String { match self { Op::Mkdir(p) => format!("mkdir {}", p), + Op::CreateDir { path, grows } => format!( + "create_dir {}{}", + path, + if *grows { ", growing its parent" } else { "" } + ), Op::Write { path, data, @@ -180,7 +194,8 @@ impl Op { /// A tree with long names, files replaced within one directory cluster and /// across two, a directory grown past its first cluster, a removed file -/// whose slots are reused, nested directories. BOOTX64.EFI is written in +/// whose slots are reused, nested directories, directories made with and +/// without their parent growing for them. BOOTX64.EFI is written in /// small pieces so that its epoch holds many writes; the kernel names take /// four slots each. fn scenario(slots_per_cluster: usize) -> Vec { @@ -226,6 +241,38 @@ fn scenario(slots_per_cluster: usize) -> Vec { // Now the only room is in the directory's second cluster: the old // entry's deletion and the new entry are two cluster writes. file(&mut ops, &kernel(2), 4000, true, whole); + // A directory made where its parent has room, and one made in /full + // after empty files with long names fill the first cluster of /full to + // its last slot, so that /full grows for the entry. The new cluster of + // /full is zeroed and synced before the new directory's cluster is + // allocated and written, and the entry comes last. + ops.push(Op::CreateDir { + path: "/loader/keys".into(), + grows: false, + }); + ops.push(Op::Mkdir("/full".into())); + let mut free = slots_per_cluster - 2; + let mut n = 0; + while free > 0 { + // A name in k slots: k - 1 long name slots of LFN_UNITS_PER_ENTRY + // characters each, MAX_LONG_NAME characters at most, and the short + // entry. A name in one slot is a short name. + let k = free.min(LFN_MAX_ENTRIES + 1); + let name = if k == 1 { + format!("F{}", n) + } else { + let prefix = format!("fill-{}-", n); + let len = (LFN_UNITS_PER_ENTRY * (k - 1)).min(MAX_LONG_NAME); + format!("{}{}", prefix, "x".repeat(len - prefix.len())) + }; + file(&mut ops, &format!("/full/{}", name), 0, false, whole); + free -= k; + n += 1; + } + ops.push(Op::CreateDir { + path: "/full/sub".into(), + grows: true, + }); ops.push(Op::Close); ops } @@ -270,8 +317,8 @@ fn join(dir: &str, name: &str) -> String { } } -fn hash_of(data: &[u8]) -> [u8; 32] { - sha256::digest(data) +fn hash_of(data: &[u8]) -> [u8; Sha256::SIZE] { + Sha256::digest(data).into() } /// The tree the scenario means to leave after `ops`. @@ -287,6 +334,9 @@ fn simulate(ops: &[Op]) -> Tree { tree.insert(cur.clone(), Node::Dir); } } + Op::CreateDir { path, .. } => { + tree.insert(path.clone(), Node::Dir); + } Op::Write { path, data, .. } => { tree.insert( path.clone(), @@ -309,7 +359,7 @@ fn show_node(node: Option<&Node>) -> String { match node { None => "absent".into(), Some(Node::Dir) => "directory".into(), - Some(Node::File { size, hash }) => format!("{} bytes {}", size, &sha256::to_hex(hash)[..12]), + Some(Node::File { size, hash }) => format!("{} bytes {}", size, &Sha256::from(*hash).to_string()[..12]), } } @@ -616,6 +666,7 @@ impl Harness { v.device().trace_note(&op.describe()).unwrap(); match op { Op::Mkdir(path) => v.create_dir_all(path, fixed_time()).unwrap(), + Op::CreateDir { path, .. } => v.create_dir(path, fixed_time()).unwrap(), Op::Write { path, data, @@ -798,6 +849,22 @@ impl Harness { chains.insert(e.path.clone(), e.chain.clone()); } } + if let Some(Op::CreateDir { path, grows }) = j.checked_sub(1).map(|k| &self.ops[k]) { + let parent = parent_of(path); + let clusters = |owners: &HashMap| { + owners.values().filter(|(p, dir)| *dir && p == parent).count() + }; + let (before, after) = (clusters(&self.boundaries[j - 1].owners), clusters(&owners)); + assert_eq!( + after > before, + *grows, + "{}: {} has {} clusters before and {} after", + self.boundary_name(j), + parent, + before, + after + ); + } self.legit.extend(raw.referenced()); self.boundaries.push(Boundary { tree, diff --git a/tests/fixtures.rs b/tests/fixtures.rs index 38d14f2..c815ac4 100644 --- a/tests/fixtures.rs +++ b/tests/fixtures.rs @@ -16,7 +16,10 @@ use fat::dirent::ATTR_READ_ONLY; use fat::errno::{EINVAL, EOPNOTSUPP}; use fat::format::{self, FormatOptions}; use fat::host; -use fat::manifest::{self, AssembleOptions, DirectorySource, Features, HostTree, InodeType, Manifest, StreamSource}; +use fat::manifest::{ + AssembleFlags, AssembleObserver, AssembleOptions, AssembleReport, ContentSource, DirectorySource, Features, + FileObject, HostTree, InodeType, Name, Object, PinnedDirectory, Reader, RootObject, SkipReason, StreamSource, +}; use fat::plan::{Plan, PlanOptions}; use fat::volume::Volume; @@ -24,10 +27,51 @@ fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") } +/// A fixture manifest, read to its end: a test can hold one whole. +struct Manifest { + bytes: Vec, + root: RootObject, + entries: Vec, + signatures: usize, +} + +impl Manifest { + /// A reader of the manifest from its start, which has read the root + /// file object. + fn reader(&self) -> Reader<&[u8]> { + Reader::open(&self.bytes[..]).unwrap() + } + + /// Assembles the manifest into `v`. + fn assemble( + &self, + v: &mut Volume, + source: &mut dyn ContentSource, + options: &AssembleOptions, + ) -> fat::Result { + v.assemble(&mut self.reader(), source, options) + } +} + fn load(case: &str, name: &str) -> Manifest { let path = fixtures().join(case).join(name); let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); - manifest::parse(&bytes).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) + let mut reader = Reader::open(&bytes[..]).unwrap_or_else(|e| panic!("{}: {}", path.display(), e)); + let root = reader.root().clone(); + let mut entries = Vec::new(); + let mut signatures = 0; + for object in &mut reader { + match object.unwrap_or_else(|e| panic!("{}: {}", path.display(), e)) { + Object::File(object) => entries.push(*object), + _ => signatures += 1, + } + } + Manifest { + bytes, + root, + entries, + signatures, + } } fn tree(case: &str) -> PathBuf { @@ -35,8 +79,8 @@ fn tree(case: &str) -> PathBuf { } /// The fixture's tree as a content source: the directory resolved once. -fn source(case: &str) -> DirectorySource { - DirectorySource::new(host::open_dir(&tree(case)).unwrap()) +fn source(case: &str) -> DirectorySource { + DirectorySource::new(PinnedDirectory::new(host::open_dir(&tree(case)).unwrap())) } fn time(nsec: u64) -> SystemTime { @@ -44,16 +88,19 @@ fn time(nsec: u64) -> SystemTime { } fn names(m: &Manifest) -> Vec<&str> { - m.entries.iter().filter_map(|e| e.name.as_deref()).collect() + m.entries.iter().map(|e| e.name.as_str()).collect() } -/// Formats an image of exactly the planned size and returns it open. -fn planned_volume(m: &Manifest) -> (Temp, Volume, Vec) { +/// Formats an image of exactly the planned size and returns it open, with +/// the number of objects the plan left out. +fn planned_volume(m: &Manifest) -> (Temp, Volume, u64) { let mut plan = Plan::new(PlanOptions { allow_small: true, ..PlanOptions::new(512) }); - let skipped = plan.add_manifest(m).unwrap(); + let skipped = plan + .add_records(&mut m.reader(), AssembleFlags::SKIP_UNSUPPORTED) + .unwrap(); let estimate = plan.estimate().unwrap(); let img = Temp::image(estimate.size()); let mut options = FormatOptions { @@ -66,6 +113,15 @@ fn planned_volume(m: &Manifest) -> (Temp, Volume, Vec) { (img, v, skipped) } +/// A log of the objects an assembly leaves out, by name. +struct SkipLog<'a>(&'a mut Vec); + +impl AssembleObserver for SkipLog<'_> { + fn skipped(&mut self, name: &Name, _reason: SkipReason) { + self.0.push(name.to_string()); + } +} + fn read_back(v: &Volume, path: &str) -> Vec { let mut out = Vec::new(); v.open_file(path).unwrap().read_to_end(&mut out).unwrap(); @@ -76,8 +132,8 @@ fn read_back(v: &Volume, path: &str) -> Vec { /// contents and the manifest's time; every directory object is there too. fn check_against_tree(m: &Manifest, v: &Volume, tree: &Path) { for e in &m.entries { - let name = e.name.as_deref().unwrap(); - let path = e.path(); + let name = e.name.as_str(); + let path = format!("/{}", name); match e.inode_type { InodeType::Regular => { let md = v.metadata(&path).unwrap_or_else(|err| panic!("{}: {}", path, err)); @@ -87,15 +143,15 @@ fn check_against_tree(m: &Manifest, v: &Volume, tree: &Path) { if let Some(size) = e.size { assert_eq!(md.size, size, "{}", path); } - if let Some(t) = e.mtime_nsec { + if let Some(t) = e.inode.mtime_nsec { assert_eq!(md.modified, time(t), "{}", path); } - assert_eq!(md.attributes & ATTR_READ_ONLY != 0, e.is_read_only(), "{}", path); + assert_eq!(md.attributes & ATTR_READ_ONLY != 0, e.inode.is_read_only(), "{}", path); } InodeType::Directory => { let md = v.metadata(&path).unwrap_or_else(|err| panic!("{}: {}", path, err)); assert!(md.is_dir, "{}", path); - if let Some(t) = e.mtime_nsec { + if let Some(t) = e.inode.mtime_nsec { assert_eq!(md.modified, time(t), "{}", path); } } @@ -121,8 +177,7 @@ fn every_fixture_parses() { .count(), 6 ); - assert_eq!(esp.root.inode_type, InodeType::Directory); - assert_eq!(esp.root.mtime_nsec, Some(1_699_999_000_000_000_000)); + assert_eq!(esp.root.inode.mtime_nsec, Some(1_699_999_000_000_000_000)); assert_eq!(esp.signatures, 0); assert_eq!( names(&esp), @@ -144,9 +199,9 @@ fn every_fixture_parses() { ); let uki = &esp.entries[4]; assert_eq!(uki.size, Some(6395)); - assert_eq!(uki.mode, Some(0o664)); - assert_eq!(uki.mtime_nsec, Some(1_700_000_002_000_000_000)); - assert!(!uki.is_read_only()); + assert_eq!(uki.inode.mode.map(u32::from), Some(0o664)); + assert_eq!(uki.inode.mtime_nsec, Some(1_700_000_002_000_000_000)); + assert!(!uki.inode.is_read_only()); assert!(uki.contents.is_empty()); // The signature does not change the file objects. @@ -158,18 +213,18 @@ fn every_fixture_parses() { // Fewer fields, same tree. let lean = load("esp", "size-hash-mtime.Uapi16Manifest"); assert_eq!(names(&lean), names(&esp)); - assert!(lean.entries.iter().all(|e| e.mode.is_none())); + assert!(lean.entries.iter().all(|e| e.inode.mode.is_none())); assert!(lean .entries .iter() .zip(&esp.entries) - .all(|(a, b)| a.size == b.size && a.sha256 == b.sha256 && a.mtime_nsec == b.mtime_nsec)); + .all(|(a, b)| a.size == b.size && a.sha256 == b.sha256 && a.inode.mtime_nsec == b.inode.mtime_nsec)); let none = load("esp", "none.Uapi16Manifest"); assert_eq!(names(&none), names(&esp)); assert!(none .entries .iter() - .all(|e| e.size.is_none() && e.sha256.is_none() && e.mtime_nsec.is_none())); + .all(|e| e.size.is_none() && e.sha256.is_none() && e.inode.mtime_nsec.is_none())); let special = load("special", "Uapi16Manifest"); assert_eq!(special.entries.len(), 13); @@ -181,26 +236,22 @@ fn every_fixture_parses() { .iter() .find(|e| e.inode_type == InodeType::Symlink) .unwrap(); - assert_eq!(link.contents[0].literal.as_deref(), Some(&b"a.txt"[..])); + assert_eq!(link.contents[0].literal(), Some(&b"a.txt"[..])); let hardlinks: Vec<&str> = special .entries .iter() .filter(|e| e.inode_token.is_some()) - .filter_map(|e| e.name.as_deref()) + .map(|e| e.name.as_str()) .collect(); assert_eq!(hardlinks, vec!["sub/hl_a", "sub/hl_b"]); - let readonly = special - .entries - .iter() - .find(|e| e.name.as_deref() == Some("sub/readonly.bin")) - .unwrap(); - assert_eq!(readonly.mode, Some(0o444)); - assert!(readonly.is_read_only()); + let readonly = special.entries.iter().find(|e| e.name == "sub/readonly.bin").unwrap(); + assert_eq!(readonly.inode.mode.map(u32::from), Some(0o444)); + assert!(readonly.inode.is_read_only()); assert!(names(&special).contains(&"sub/\u{fc}mlaut \u{221e}.txt")); let empty = load("empty", "Uapi16Manifest"); assert!(empty.entries.is_empty()); - assert_eq!(empty.root.mtime_nsec, Some(1_700_000_200_000_000_000)); + assert_eq!(empty.root.inode.mtime_nsec, Some(1_700_000_200_000_000_000)); } #[test] @@ -212,15 +263,17 @@ fn esp_assembles_from_the_tree_into_the_planned_size() { ] { let m = load("esp", name); let (img, mut v, skipped) = planned_volume(&m); - assert!(skipped.is_empty()); - let report = v.assemble(&m, &mut source("esp"), &AssembleOptions::default()).unwrap(); + assert_eq!(skipped, 0); + let report = m + .assemble(&mut v, &mut source("esp"), &AssembleOptions::default()) + .unwrap(); assert_eq!( (report.files, report.directories, report.bytes), (7, 6, 14718), "{}", name ); - assert!(report.skipped.is_empty()); + assert_eq!(report.skipped, 0); assert_eq!(v.free_clusters(), 0, "{}: the plan was not exact", name); check_against_tree(&m, &v, &tree("esp")); v.close().unwrap(); @@ -233,15 +286,14 @@ fn esp_assembles_from_a_stream() { let m = load("esp", "Uapi16Manifest"); let mut blob = Vec::new(); for e in &m.entries { - if e.is_streamed() { - blob.extend(std::fs::read(tree("esp").join(e.name.as_deref().unwrap())).unwrap()); + if e.has_external_data() { + blob.extend(std::fs::read(tree("esp").join(e.name.as_str())).unwrap()); } } - assert_eq!(m.streamed_bytes().unwrap(), blob.len() as u64); let (img, mut v, _) = planned_volume(&m); let mut reader: &[u8] = &blob; - let report = v - .assemble(&m, &mut StreamSource::new(&mut reader), &AssembleOptions::default()) + let report = m + .assemble(&mut v, &mut StreamSource::new(&mut reader), &AssembleOptions::default()) .unwrap(); assert_eq!((report.files, report.directories, report.bytes), (7, 6, 14718)); assert!(reader.is_empty(), "the stream had bytes left over"); @@ -256,8 +308,8 @@ fn esp_assembles_from_a_stream() { bad[last] ^= 0x80; let (_img, mut v, _) = planned_volume(&m); let mut reader: &[u8] = &bad; - let e = v - .assemble(&m, &mut StreamSource::new(&mut reader), &AssembleOptions::default()) + let e = m + .assemble(&mut v, &mut StreamSource::new(&mut reader), &AssembleOptions::default()) .unwrap_err(); assert!(e.message().contains("hash"), "{}", e); assert!(v.metadata("/loader/random-seed").is_err()); @@ -267,20 +319,29 @@ fn esp_assembles_from_a_stream() { #[test] fn special_skips_what_fat_cannot_hold() { let m = load("special", "Uapi16Manifest"); - assert_eq!(m.check_supported().unwrap_err().errno(), EOPNOTSUPP); let (img, mut v, skipped) = planned_volume(&m); - assert_eq!(skipped, vec!["link", "sub/fifo"]); - let e = v - .assemble(&m, &mut source("special"), &AssembleOptions::default()) + assert_eq!(skipped, 2); + let e = m + .assemble(&mut v, &mut source("special"), &AssembleOptions::default()) .unwrap_err(); assert_eq!(e.errno(), EOPNOTSUPP); assert!(e.message().contains("link"), "{}", e); + // What came before the link is there, and is replaced. let options = AssembleOptions { - skip_unsupported: true, + flags: AssembleFlags::REPLACE | AssembleFlags::SKIP_UNSUPPORTED, ..AssembleOptions::default() }; - let report = v.assemble(&m, &mut source("special"), &options).unwrap(); + let mut left_out = Vec::new(); + let report = v + .assemble_with_observer( + &mut m.reader(), + &mut source("special"), + &options, + &mut SkipLog(&mut left_out), + ) + .unwrap(); assert_eq!(report.skipped, skipped); + assert_eq!(left_out, ["link", "sub/fifo"]); assert_eq!((report.files, report.directories), (8, 3)); assert_eq!(v.free_clusters(), 0); check_against_tree(&m, &v, &tree("special")); @@ -305,8 +366,12 @@ fn names_only_manifests_assemble_but_cannot_be_planned() { allow_small: true, ..PlanOptions::new(512) }); - assert_eq!(plan.add_manifest(&m).unwrap_err().errno(), EINVAL); - assert_eq!(m.streamed_bytes().unwrap_err().errno(), EINVAL); + assert_eq!( + plan.add_records(&mut m.reader(), AssembleFlags::SKIP_UNSUPPORTED) + .unwrap_err() + .errno(), + EINVAL + ); let img = Temp::image(1 << 20); let options = FormatOptions { @@ -318,9 +383,9 @@ fn names_only_manifests_assemble_but_cannot_be_planned() { format::format(&Device::open(img.path(), Access::ReadWrite).unwrap(), &options).unwrap(); let mut v = Volume::open(Device::open(img.path(), Access::ReadWrite).unwrap()).unwrap(); let default_time = UNIX_EPOCH + Duration::from_secs(1_600_000_000); - let report = v + let report = m .assemble( - &m, + &mut v, &mut source("esp"), &AssembleOptions { default_time, @@ -339,12 +404,12 @@ fn names_only_manifests_assemble_but_cannot_be_planned() { fn empty_manifest_is_an_empty_volume() { let m = load("empty", "Uapi16Manifest"); let (img, mut v, skipped) = planned_volume(&m); - assert!(skipped.is_empty()); + assert_eq!(skipped, 0); // Git keeps no empty directory, so the empty tree is made here; the // source is resolved once, before the assembly, like any other. let tree = Temp::dir(); - let mut source = DirectorySource::new(host::open_dir(tree.path()).unwrap()); - let report = v.assemble(&m, &mut source, &AssembleOptions::default()).unwrap(); + let mut source = DirectorySource::new(PinnedDirectory::new(host::open_dir(tree.path()).unwrap())); + let report = m.assemble(&mut v, &mut source, &AssembleOptions::default()).unwrap(); assert_eq!((report.files, report.directories, report.bytes), (0, 0, 0)); assert!(v.read_dir("/").unwrap().is_empty()); v.close().unwrap(); @@ -366,12 +431,12 @@ fn generator_agrees_with_systemd_manifest() { let src = tree("esp"); let mut dirs: Vec<(PathBuf, u64)> = Vec::new(); for e in &m.entries { - let name = e.name.as_deref().unwrap(); + let name = e.name.as_str(); let dest = copy.path().join(name); match e.inode_type { InodeType::Directory => { std::fs::create_dir_all(&dest).unwrap(); - dirs.push((dest, e.mtime_nsec.unwrap())); + dirs.push((dest, e.inode.mtime_nsec.unwrap())); } InodeType::Regular => { std::fs::copy(src.join(name), &dest).unwrap(); @@ -379,14 +444,14 @@ fn generator_agrees_with_systemd_manifest() { .write(true) .open(&dest) .unwrap() - .set_modified(time(e.mtime_nsec.unwrap())) + .set_modified(time(e.inode.mtime_nsec.unwrap())) .unwrap(); } other => panic!("unexpected {:?}", other), } } dirs.sort_by_key(|(p, _)| std::cmp::Reverse(p.components().count())); - dirs.push((copy.path().to_path_buf(), m.root.mtime_nsec.unwrap())); + dirs.push((copy.path().to_path_buf(), m.root.inode.mtime_nsec.unwrap())); for (dir, nsec) in dirs { std::fs::File::open(&dir).unwrap().set_modified(time(nsec)).unwrap(); } @@ -413,7 +478,8 @@ fn generator_agrees_with_systemd_manifest() { fn volume_manifest_agrees_with_systemd_manifest() { let m = load("esp", "size-hash-mtime.Uapi16Manifest"); let (_img, mut v, _) = planned_volume(&m); - v.assemble(&m, &mut source("esp"), &AssembleOptions::default()).unwrap(); + m.assemble(&mut v, &mut source("esp"), &AssembleOptions::default()) + .unwrap(); for (name, features, listed, listed_by_volume) in [ ( "none.Uapi16Manifest", @@ -429,7 +495,7 @@ fn volume_manifest_agrees_with_systemd_manifest() { ), ] { let mut ours = Vec::new(); - v.write_manifest(m.root.mtime(), features, &mut ours).unwrap(); + v.write_manifest(m.root.inode.mtime(), features, &mut ours).unwrap(); let theirs = std::fs::read_to_string(fixtures().join("esp").join(name)).unwrap(); assert!(theirs.contains(listed), "{} does not list {}", name, listed); assert_eq!( @@ -445,14 +511,14 @@ fn volume_manifest_agrees_with_systemd_manifest() { /// root file object, its file objects and its signature objects. #[derive(Debug, PartialEq)] struct ManifestObjects { - root: uapi16::RootObject, - files: Vec, + root: RootObject, + files: Vec, signatures: Vec, } impl ManifestObjects { fn read(bytes: &[u8]) -> Result { - let mut reader = uapi16::Reader::open(bytes)?; + let mut reader = Reader::open(bytes)?; let mut objects = ManifestObjects { root: reader.root().clone(), files: Vec::new(), @@ -460,8 +526,8 @@ impl ManifestObjects { }; for object in &mut reader { match object? { - uapi16::Object::File(file) => objects.files.push(*file), - uapi16::Object::Signature(signature) => objects.signatures.push(signature), + Object::File(file) => objects.files.push(*file), + Object::Signature(signature) => objects.signatures.push(signature), other => panic!("{:?} is neither a file object nor a signature", other), } } diff --git a/tests/fuzz/mutate.py b/tests/fuzz/mutate.py index 03c9dea..3e3a085 100755 --- a/tests/fuzz/mutate.py +++ b/tests/fuzz/mutate.py @@ -666,7 +666,7 @@ def dump_record(obj): return (json.dumps(obj, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8") -ROOT_REC = b'{"mediaType":"application/vnd.uapi.16.manifest"}\n' +ROOT_REC = b'{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}\n' TRAILER_REC = b'{"mediaType":"application/vnd.uapi.16.trailer"}\n' BIG_INTS = [0, 1, -1, 2 ** 31, 2 ** 32 - 1, 2 ** 32, 2 ** 63 - 1, 2 ** 63, 2 ** 64 - 1, 2 ** 64, 2 ** 127 - 1, @@ -854,9 +854,14 @@ def mut_manifest_records(rng, records): elif how == "empty": recs = [rng.choice([b"", b"\n", b" ", b"\t\r\n"])] * rng.choice([1, 10, 1000]) elif how == "many": + # In place of the seed's file objects, which could sort anywhere + # among them, and in code point order: the numbers zero padded, the + # deep names below their directories. n = rng.choice([200, 500, 1000, 2000, 10000]) - body = rng.choice([b'{"name":"f%d","size":0}\n', b'{"name":"d%d","type":"dir"}\n', b'{"name":"f%d","size":1,"sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}\n', b'{"mediaType":"application/x-unknown","n":%d}\n', b'{"name":"a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/%d","size":0}\n']) - recs = [recs[0]] + [body % i for i in range(n)] + recs[1:] + deep = b"a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p" + body = rng.choice([b'{"name":"f%05d","size":0}\n', b'{"name":"d%05d","type":"dir"}\n', b'{"name":"f%05d","size":1,"sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}\n', b'{"mediaType":"application/x-unknown","n":%d}\n', b'{"name":"' + deep + b'/%05d","size":0}\n']) + dirs = [b'{"name":"%s","type":"dir"}\n' % deep[:i] for i in range(1, len(deep) + 1, 2)] if deep in body else [] + recs = [recs[0]] + dirs + [body % i for i in range(n)] + [r for r in recs[1:] if b"trailer" in r] elif how == "sep": recs.insert(rng.randrange(len(recs) + 1), b'{"name":"s\x1ex","size":0}\n') elif how == "nul": diff --git a/tests/fuzz/repro/quadratic-directory.py b/tests/fuzz/repro/quadratic-directory.py index 88cc319..2b0d903 100755 --- a/tests/fuzz/repro/quadratic-directory.py +++ b/tests/fuzz/repro/quadratic-directory.py @@ -16,19 +16,27 @@ source directory; with `lossy` the files share one 8.3 alias prefix, which adds the numeric-tail search on top (2000 files: 7.5 s before the index, 16000 files 0.17 s with it). + +The manifest declares the code point order, which ufat requires, and the +numbers in the names have leading zeros so that the names are in it. """ import sys n = int(sys.argv[1]) if len(sys.argv) > 1 else 16000 kind = sys.argv[2] if len(sys.argv) > 2 else "dir" +digits = len(str(max(n - 1, 0))) out = sys.stdout.buffer RS = b"\x1e" -out.write(RS + b'{"mediaType":"application/vnd.uapi.16.manifest"}\n') +out.write(RS + b'{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}\n') +if kind == "lossy": + out.write(RS + b'{"name":"EFI","type":"dir"}\n') + out.write(RS + b'{"name":"EFI/Linux","type":"dir"}\n') for i in range(n): + number = b"%0*d" % (digits, i) if kind == "dir": - out.write(RS + b'{"name":"d%d","type":"dir"}\n' % i) + out.write(RS + b'{"name":"d%s","type":"dir"}\n' % number) elif kind == "lossy": - out.write(RS + b'{"name":"EFI/Linux/linux-6.12.%d-200.fc41.x86_64.efi","size":0}\n' % i) + out.write(RS + b'{"name":"EFI/Linux/linux-6.12.%s-200.fc41.x86_64.efi","size":0}\n' % number) else: - out.write(RS + b'{"name":"f%d","size":0}\n' % i) + out.write(RS + b'{"name":"f%s","size":0}\n' % number) out.write(RS + b'{"mediaType":"application/vnd.uapi.16.trailer"}\n') diff --git a/tests/fuzz/repro/uuid-char-boundary.sh b/tests/fuzz/repro/uuid-char-boundary.sh index 96dbe3c..030afdf 100755 --- a/tests/fuzz/repro/uuid-char-boundary.sh +++ b/tests/fuzz/repro/uuid-char-boundary.sh @@ -7,7 +7,7 @@ # must exit 1 with "is not a UUID", the script exits 1 otherwise. UFAT=${1:-target/debug/ufat} M=$(mktemp) -printf '\036{"mediaType":"application/vnd.uapi.16.manifest"}\n\036{"name":"x","size":0,"gptUuid":"urn:uuid\303\251\303\251\303\251\303\251"}\n\036{"mediaType":"application/vnd.uapi.16.trailer"}\n' > "$M" +printf '\036{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}\n\036{"name":"x","size":0,"gptUuid":"urn:uuid\303\251\303\251\303\251\303\251"}\n\036{"mediaType":"application/vnd.uapi.16.trailer"}\n' > "$M" "$UFAT" assemble --plan --manifest "$M"; s=$? echo "exit $s" rm -f "$M" diff --git a/tests/fuzz/targeted.py b/tests/fuzz/targeted.py index df0f85e..7cf4236 100755 --- a/tests/fuzz/targeted.py +++ b/tests/fuzz/targeted.py @@ -18,7 +18,7 @@ import mutate # noqa: E402 RS = b"\x1e" -ROOT = b'{"mediaType":"application/vnd.uapi.16.manifest"}\n' +ROOT = b'{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}\n' TRAILER = b'{"mediaType":"application/vnd.uapi.16.trailer"}\n' @@ -180,7 +180,7 @@ def manifests(self): "i128 overflow": [b'{"name":"x","size":170141183460469231731687303715884105728}\n'], "size u64 max": [b'{"name":"x","size":18446744073709551615}\n'], "size 2^32": [b'{"name":"x","size":4294967296}\n'], - "size 2^32-1 x 300": [b'{"name":"f%d","size":4294967295}\n' % i for i in range(300)], + "size 2^32-1 x 300": [b'{"name":"f%03d","size":4294967295}\n' % i for i in range(300)], "mtime u64 max": [b'{"name":"x","size":0,"mTimeNSec":18446744073709551615}\n'], "validSince u64 max": [b'{"name":"x","size":0,"validSinceUSec":18446744073709551615}\n'], "offset u64 max": [b'{"name":"x","size":0,"contents":[{"file":"x","offset":18446744073709551615}]}\n'], @@ -238,7 +238,7 @@ def manifests(self): # Not a manifest at all. for name, data in [("empty", b""), ("rs only", RS), ("rs x 1M", RS * (1 << 20)), ("root only", RS + ROOT), ("4 MiB garbage", bytes(range(256)) * (16 * 1024)), ("binary zeros", b"\0" * 100000), ("utf8 bom", b"\xef\xbb\xbf" + manifest([])), ("CRLF", manifest([]).replace(b"\n", b"\r\n")), - ("nul in record", RS + b'{"name":"a\x00"}' + RS + TRAILER), ("huge valid", manifest([b'{"name":"f%d","size":0}\n' % i for i in range(60000)]))]: + ("nul in record", RS + b'{"name":"a\x00"}' + RS + TRAILER), ("huge valid", manifest([b'{"name":"f%05d","size":0}\n' % i for i in range(60000)]))]: m = os.path.join(self.work, "probe.Uapi16Manifest") with open(m, "wb") as f: f.write(data) diff --git a/tests/reference.rs b/tests/reference.rs index 8907fa1..6fde1de 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -482,7 +482,7 @@ fn matches_sha256sum() { assert_eq!(expected.len(), files.len()); for (name, data) in &files { assert_eq!( - fat::sha256::to_hex(&fat::sha256::digest(data)), + fat::manifest::Sha256::digest(data).to_string(), expected[name], "{}", name @@ -493,11 +493,14 @@ fn matches_sha256sum() { fat::manifest::HostTree::new(dir.as_fd()) .write_manifest(&mut bytes) .unwrap(); - let manifest = fat::manifest::parse(&bytes).unwrap(); let mut hashed = 0; - for entry in &manifest.entries { - if let (Some(name), Some(hash)) = (&entry.name, &entry.sha256) { - assert_eq!(fat::sha256::to_hex(hash), expected[name], "{}", name); + for object in fat::manifest::Reader::open(&bytes[..]).unwrap() { + let fat::manifest::Object::File(entry) = object.unwrap() else { + continue; + }; + if let Some(hash) = &entry.sha256 { + let name = entry.name.as_str(); + assert_eq!(hash.to_string(), expected[name], "{}", name); hashed += 1; } } diff --git a/tests/varlink.rs b/tests/varlink.rs index 805c46b..8a15455 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -379,6 +379,25 @@ fn esp_tree() -> Temp { tree } +/// A manifest read to its end, which a test can hold whole. +struct Manifest { + root: fat::manifest::RootObject, + entries: Vec, +} + +/// Reads the manifest `bytes` to its end. +fn read_manifest(bytes: &[u8]) -> Manifest { + let mut reader = fat::manifest::Reader::open(bytes).unwrap(); + let root = reader.root().clone(); + let mut entries = Vec::new(); + for object in &mut reader { + if let fat::manifest::Object::File(object) = object.unwrap() { + entries.push(*object); + } + } + Manifest { root, entries } +} + /// A manifest of the tree and the contents of its streamed files in /// manifest order. fn manifest_and_blob(tree: &Path) -> (Vec, Vec) { @@ -386,16 +405,66 @@ fn manifest_and_blob(tree: &Path) -> (Vec, Vec) { fat::manifest::HostTree::new(fat::host::open_dir(tree).unwrap().as_fd()) .write_manifest(&mut bytes) .unwrap(); - let m = fat::manifest::parse(&bytes).unwrap(); + let m = read_manifest(&bytes); let mut blob = Vec::new(); for e in &m.entries { - if e.is_streamed() { - blob.extend(std::fs::read(tree.join(e.name.as_ref().unwrap())).unwrap()); + if e.has_external_data() { + blob.extend(std::fs::read(tree.join(e.name.as_str())).unwrap()); } } (bytes, blob) } +/// A pipe with `data` in it and its writing end closed, as a client passes +/// a stream. `data` has to fit into the pipe. +fn pipe_with(data: &[u8]) -> File { + let (reader, mut writer) = pipe(); + writer.write_all(data).unwrap(); + reader +} + +/// Sets the file status flags of `file`, such as O_NONBLOCK. +fn set_status_flags(file: &File, flags: c_int) { + // SAFETY: F_SETFL changes the flags of an open descriptor only. + assert_eq!(unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETFL, flags) }, 0); +} + +/// Writes `data` to the pipe `pipe`, which is set to O_NONBLOCK, until all +/// of it is in or the pipe stays full for `patience`. Returns how much of +/// `data` went in. +fn write_until_full(pipe: &mut File, data: &[u8], patience: Duration) -> usize { + let timeout = c_int::try_from(patience.as_millis()).unwrap(); + let mut written = 0; + while written < data.len() { + match pipe.write(&data[written..]) { + Ok(n) => written += n, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + let mut ready = libc::pollfd { + fd: pipe.as_raw_fd(), + events: libc::POLLOUT, + revents: 0, + }; + // SAFETY: one pollfd, which lives across the call. + let n = unsafe { libc::poll(&mut ready, 1, timeout) }; + assert!(n >= 0, "{}", std::io::Error::last_os_error()); + if n == 0 { + break; + } + } + Err(e) => panic!("writing to the pipe: {}", e), + } + } + written +} + +/// What is left in the pipe whose reading end `pipe` is, its writing end +/// closed. +fn left_in(mut pipe: File) -> Vec { + let mut left = Vec::new(); + pipe.read_to_end(&mut left).unwrap(); + left +} + /// Writes `data` to a fresh file and returns it open read-only. fn file_with(dir: &Path, name: &str, data: &[u8]) -> File { let path = dir.join(name); @@ -404,7 +473,7 @@ fn file_with(dir: &Path, name: &str, data: &[u8]) -> File { } fn sha256_hex(data: &[u8]) -> String { - fat::sha256::to_hex(&fat::sha256::digest(data)) + fat::manifest::Sha256::digest(data).to_string() } fn sha512_hex(data: &[u8]) -> String { @@ -634,6 +703,8 @@ fn capabilities_describe_vfat() { assert_eq!(str_of(caps, "nameUnit"), "utf16Units"); assert_eq!(u64_of(caps, "fileSizeMaxBytes"), 4_294_967_295); assert!(caps.get("features").is_none()); + // A manifest has to declare the code point order. + assert_eq!(str_of(object_of(caps, "manifest"), "order"), "codepoint"); // Any other type is not served, by any method. let e = error_of(&mut c, "GetCapabilities", r#"{"fileSystemType":"ext4"}"#, &[]); assert_eq!(e.name, format!("{}.FileSystemTypeNotSupported", IFACE)); @@ -763,18 +834,35 @@ fn assemble_plans_from_a_tree_and_a_manifest() { assert_eq!(u64_of(&b, "files"), 2); assert_eq!(u64_of(&b, "directories"), 3); assert_eq!(u64_of(&b, "bytes"), 5010); - // With the directory beside the manifest the source is verified first. + // A plan reads the manifest and nothing else: the directory beside it + // is not looked at. let manifest_file = ro(&scratch.path().join("manifest")); let empty = Temp::dir(); let empty_dir = ro(empty.path()); - let e = error_of( + let e = reply(call( &mut c, "Assemble", r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0},"sourceFileDescriptor":1}}"#, &[manifest_file.as_fd(), empty_dir.as_fd()], + )); + assert_eq!( + u64_of(object_of(&e, "description"), "sizeBytes"), + u64_of(d, "sizeBytes") ); - assert_eq!(e.name, format!("{}.SourceMismatch", IFACE)); - assert_eq!(str_of(&e.parameters, "reason"), "missing"); + // It reads the manifest once, so it takes one that comes through a + // pipe, and reads all of it. + let piped = pipe_with(&manifest); + let e = reply(call( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0}}}"#, + &[piped.as_fd()], + )); + assert_eq!( + u64_of(object_of(&e, "description"), "sizeBytes"), + u64_of(d, "sizeBytes") + ); + assert!(left_in(piped).is_empty()); // No content: the smallest volume there is, with 4 KiB sectors too. let m = reply(call(&mut c, "Assemble", r#"{"mode":"plan"}"#, &[])); let md = object_of(&m, "description"); @@ -1123,17 +1211,17 @@ fn assemble_with_a_manifest_and_a_directory() { .size, 10 ); - // A directory that does not hold what the manifest names fails before - // the image is touched: the file the client created stays empty. + // A directory that does not hold what the manifest names fails when the + // file is copied, and leaves the file system unfinished. let manifest_file = ro(&base.path().join("manifest")); let empty = Temp::dir(); let empty_dir = ro(empty.path()); - let (fresh, fresh_img) = fresh_image(); + let (missing, missing_img) = fresh_image(); let e = error_of( &mut c, "Assemble", r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, - &[fresh_img.as_fd(), manifest_file.as_fd(), empty_dir.as_fd()], + &[missing_img.as_fd(), manifest_file.as_fd(), empty_dir.as_fd()], ); assert_eq!( e.name, @@ -1144,30 +1232,81 @@ fn assemble_with_a_manifest_and_a_directory() { assert_eq!(str_of(&e.parameters, "reason"), "missing"); // The file as the manifest names it, not as a path in the volume. assert_eq!(str_of(&e.parameters, "name"), "EFI/BOOT/BOOTX64.EFI"); - assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); - // So does a file that grew since the manifest was written. The manifest - // takes it whole, so it has to have the manifest's size. + assert_eq!(warnings(&mut c, missing.path()), ["dirtyFlag", "fatDirtyFlag"]); + // A file that grew since the manifest was written still holds the + // data the manifest describes at its start, and that is what is copied. std::fs::write(tree.join("loader/loader.conf"), b"timeout 5\nconsole-mode max\n").unwrap(); let manifest_file = ro(&base.path().join("manifest")); + let (grown, grown_img) = fresh_image(); + reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[grown_img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); + let mut data = Vec::new(); + volume(grown.path(), Access::ReadOnly) + .open_file("/loader/loader.conf") + .unwrap() + .read_to_end(&mut data) + .unwrap(); + assert_eq!(data, b"timeout 5\n"); + // One that shrank is too short for the data, and fails when it is + // copied with the size of the file and the size it needs. + std::fs::write(tree.join("loader/loader.conf"), b"timeout\n").unwrap(); + let manifest_file = ro(&base.path().join("manifest")); + let (_shrunk, shrunk_img) = fresh_image(); let e = error_of( &mut c, "Assemble", r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, - &[fresh_img.as_fd(), manifest_file.as_fd(), source.as_fd()], + &[shrunk_img.as_fd(), manifest_file.as_fd(), source.as_fd()], ); assert_eq!( e.name, - format!("{}.SourceMismatch", IFACE), + format!("{}.ContentMismatch", IFACE), "{}", Value::Object(e.parameters.clone()) ); assert_eq!(str_of(&e.parameters, "reason"), "size"); assert_eq!(str_of(&e.parameters, "name"), "loader/loader.conf"); - assert_eq!(u64_of(&e.parameters, "sizeBytes"), 27); + assert_eq!(u64_of(&e.parameters, "sizeBytes"), 8); assert_eq!(u64_of(&e.parameters, "expectedSizeBytes"), 10); - assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); std::fs::write(tree.join("loader/loader.conf"), b"timeout 5\n").unwrap(); - // A broken manifest is InvalidManifest, with nothing written either. + // A file that changes while it is read is reason sourceChanged, without + // sizes. A file of procfs says it is empty when it is opened and has + // data when it is read, which is how a file that grew after it was + // opened looks to the source. Checked against a hash of all of it, it + // is read past its length. + let changing = file_with( + base.path(), + "changing", + format!( + "\x1e{{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}}\n\x1e{{\"contents\":[{{\"originalSha256\":\"{}\"}}],\"name\":\"version\",\"size\":0}}\n\x1e{{\"mediaType\":\"application/vnd.uapi.16.trailer\"}}\n", + sha256_hex(b"hello") + ) + .as_bytes(), + ); + let proc_dir = ro(Path::new("/proc")); + let (_changed, changed_img) = fresh_image(); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[changed_img.as_fd(), changing.as_fd(), proc_dir.as_fd()], + ); + assert_eq!( + e.name, + format!("{}.ContentMismatch", IFACE), + "{}", + Value::Object(e.parameters.clone()) + ); + assert_eq!(str_of(&e.parameters, "reason"), "sourceChanged"); + assert_eq!(str_of(&e.parameters, "name"), "version"); + assert!(e.parameters.get("sizeBytes").is_none()); + assert!(e.parameters.get("expectedSizeBytes").is_none()); + // A broken manifest is InvalidManifest, with nothing written. + let (fresh, fresh_img) = fresh_image(); let garbage = file_with(base.path(), "garbage", b"garbage"); let e = error_of( &mut c, @@ -1178,7 +1317,7 @@ fn assemble_with_a_manifest_and_a_directory() { assert_eq!(e.name, format!("{}.InvalidManifest", IFACE)); assert_eq!(str_of(&e.parameters, "reason"), "recordSeparator"); let bad = file_with(base.path(), "bad", - b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\"}\n\x1e{\"name\":\"x\"}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n\x1e{\"name\":\"x\"}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", ); let e = error_of( &mut c, @@ -1188,8 +1327,24 @@ fn assemble_with_a_manifest_and_a_directory() { ); assert_eq!(e.name, format!("{}.InvalidManifest", IFACE)); assert_eq!(str_of(&e.parameters, "reason"), "noSize"); - assert_eq!(str_of(&e.parameters, "name"), "/x"); + assert_eq!(str_of(&e.parameters, "name"), "x"); + assert_eq!(u64_of(&e.parameters, "record"), 1); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + // A manifest that comes through a pipe can be read once, too little to + // size the file system to fit, which reads the manifest before its + // content is written. + let piped = pipe_with(&manifest); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[fresh_img.as_fd(), piped.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.BadFileDescriptor", IFACE)); + assert_eq!(str_of(&e.parameters, "parameter"), "manifest"); + assert_eq!(str_of(&e.parameters, "reason"), "wrongType"); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + assert_eq!(left_in(piped), manifest); // A manifest needs a source, a stream needs a manifest, a file is no // content for Assemble. let manifest_file = ro(&base.path().join("manifest")); @@ -1219,6 +1374,75 @@ fn assemble_with_a_manifest_and_a_directory() { assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); } +/// A manifest has to declare the code point order: one that does not is +/// InvalidManifest with reason noOrder, also when its objects are sorted, +/// before anything is written, from a file and from a pipe. +#[test] +fn manifests_have_to_declare_their_order() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let tree = esp_tree(); + let (manifest, _) = manifest_and_blob(tree.path()); + let undeclared = String::from_utf8(manifest.clone()) + .unwrap() + .replacen(r#","order":"codepoint""#, "", 1) + .into_bytes(); + assert_ne!(undeclared, manifest); + let scratch = Temp::dir(); + let mut c = connect_fd3(&ufat); + let source = ro(tree.path()); + let no_order = |e: varlink::Error| { + assert_eq!( + e.name, + format!("{}.InvalidManifest", IFACE), + "{}", + Value::Object(e.parameters.clone()) + ); + assert_eq!(str_of(&e.parameters, "reason"), "noOrder"); + assert_eq!(u64_of(&e.parameters, "record"), 0); + assert_eq!(str_of(&e.parameters, "field"), "order"); + }; + let file = file_with(scratch.path(), "undeclared", &undeclared); + no_order(error_of( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0}}}"#, + &[file.as_fd()], + )); + let (fresh, img) = fresh_image(); + let manifest_file = ro(&scratch.path().join("undeclared")); + no_order(error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0,"size":41943040},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + let image = Temp::image(40 << 20); + let img = rw(image.path()); + reply(call(&mut c, "Assemble", IMG, &[img.as_fd()])); + let populate = r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; + for manifest in [ro(&scratch.path().join("undeclared")), pipe_with(&undeclared)] { + no_order(error_of( + &mut c, + "Populate", + populate, + &[img.as_fd(), manifest.as_fd(), source.as_fd()], + )); + } + assert!(volume(image.path(), Access::ReadOnly).read_dir("/").unwrap().is_empty()); + let declared = file_with(scratch.path(), "declared", &manifest); + let r = reply(call( + &mut c, + "Populate", + populate, + &[img.as_fd(), declared.as_fd(), source.as_fd()], + )); + assert_eq!(u64_of(&r, "files"), 2); +} + /// Assemble with a manifest and the contents of its files in a stream. #[test] fn assemble_with_a_manifest_and_a_stream() { @@ -1312,11 +1536,10 @@ fn assemble_with_a_manifest_and_a_stream() { assert_eq!(str_of(&e.parameters, "name"), "EFI/BOOT/BOOTX64.EFI"); // So is a stream that goes on after the last file: that file got more // than the manifest says, by how much is not known. - let last = fat::manifest::parse(&manifest) - .unwrap() + let last = read_manifest(&manifest) .entries .into_iter() - .rfind(|e| e.is_streamed()) + .rfind(|e| e.has_external_data()) .unwrap(); let (_image3, img3) = fresh_image(); let long = file_with(scratch.path(), "long", &[&blob[..], b"more"].concat()); @@ -1334,11 +1557,91 @@ fn assemble_with_a_manifest_and_a_stream() { Value::Object(e.parameters.clone()) ); assert_eq!(str_of(&e.parameters, "reason"), "size"); - assert_eq!(Some(str_of(&e.parameters, "name")), last.name.as_deref()); + assert_eq!(str_of(&e.parameters, "name"), last.name.as_str()); assert_eq!(u64_of(&e.parameters, "expectedSizeBytes"), last.size.unwrap()); assert!(e.parameters.get("sizeBytes").is_none()); } +/// Populate with the manifest and the contents of its files in two pipes +/// reads the two in lockstep: a record of the manifest, then the contents +/// of the file it describes. So the client writes to both at the same time. +/// Until contents come, the service takes no more of a manifest many times +/// larger than a pipe holds than the first records: a client that wrote +/// all of the manifest first would wait for the service forever, and the +/// service for it. +#[test] +fn populate_reads_the_manifest_and_the_contents_in_lockstep() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + // Some 100 bytes of manifest a file, in directories of a thousand. + const DIRECTORIES: usize = 5; + const FILES: usize = 1000; + // What a pipe holds on Linux by default, 16 pages of 4 KiB. + const PIPE_SIZE: c_int = 64 << 10; + // How long the manifest pipe has to stay full. + const PATIENCE: Duration = Duration::from_millis(500); + let mut manifest = b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n".to_vec(); + let mut blob = Vec::new(); + for d in 0..DIRECTORIES { + manifest.extend(format!("\x1e{{\"name\":\"d{}\",\"type\":\"dir\"}}\n", d).bytes()); + for f in 0..FILES { + let data = format!("{:08}", d * FILES + f); + manifest.extend( + format!( + "\x1e{{\"name\":\"d{}/f{:04}\",\"sha256\":\"{}\",\"size\":{}}}\n", + d, + f, + sha256_hex(data.as_bytes()), + data.len() + ) + .bytes(), + ); + blob.extend(data.bytes()); + } + } + manifest.extend(b"\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"); + let image = Temp::image(40 << 20); + let img = rw(image.path()); + let mut c = connect_fd3(&ufat); + reply(call(&mut c, "Assemble", IMG, &[img.as_fd()])); + let (manifest_reader, mut manifest_writer) = pipe(); + let (contents_reader, mut contents_writer) = pipe(); + c.send_with_fds( + &method("Populate"), + params(r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#), + &[img.as_fd(), manifest_reader.as_fd(), contents_reader.as_fd()], + ) + .unwrap(); + drop((manifest_reader, contents_reader)); + // The manifest alone fills its pipe, and the pipe stays full. + // SAFETY: F_SETPIPE_SZ changes the size of an open pipe only. + assert!(unsafe { libc::fcntl(manifest_writer.as_raw_fd(), libc::F_SETPIPE_SZ, PIPE_SIZE) } >= PIPE_SIZE); + set_status_flags(&manifest_writer, libc::O_NONBLOCK); + let written = write_until_full(&mut manifest_writer, &manifest, PATIENCE); + assert!(written < manifest.len() / 2, "{} of {} bytes", written, manifest.len()); + // With the contents written at the same time, the rest goes in. + set_status_flags(&manifest_writer, 0); + let contents = std::thread::spawn(move || contents_writer.write_all(&blob).map(|_| blob.len())); + manifest_writer.write_all(&manifest[written..]).unwrap(); + drop(manifest_writer); + let bytes = contents.join().unwrap().unwrap(); + let r = c.receive().unwrap().unwrap(); + conforms("Populate", &r); + let r = reply(r); + assert_eq!(u64_of(&r, "files"), (DIRECTORIES * FILES) as u64); + assert_eq!(u64_of(&r, "directories"), DIRECTORIES as u64); + assert_eq!(u64_of(&r, "bytes"), bytes as u64); + let mut data = Vec::new(); + volume(image.path(), Access::ReadOnly) + .open_file(&format!("/d{}/f{:04}", DIRECTORIES - 1, FILES - 1)) + .unwrap() + .read_to_end(&mut data) + .unwrap(); + assert_eq!(data, format!("{:08}", DIRECTORIES * FILES - 1).as_bytes()); +} + /// The kinds of the problems Check finds in `image`, which has no errors. fn warnings(c: &mut Client, image: &Path) -> Vec { let img = ro(image); @@ -1359,7 +1662,9 @@ fn warnings(c: &mut Client, image: &Path) -> Vec { /// An Assemble that fails after the format leaves the file system as after /// a crash: with the files that were complete, and marked as not cleanly /// unmounted, which Check reports. It is marked when it fails before the -/// first file as well. Assembling again makes a clean file system. +/// first file as well. Assembling again makes a clean file system, which a +/// Populate refused before it writes anything leaves clean, and a Populate +/// that fails partway leaves marked again. #[test] fn a_failed_assemble_leaves_the_file_system_unfinished() { let _serial = common::serial(); @@ -1378,8 +1683,8 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { let (manifest, _) = manifest_and_blob(&tree); let manifest_file = file_with(base.path(), "manifest", &manifest); // loader.conf keeps its size and changes its contents after the - // manifest was written: it passes the check of the source before the - // format and fails while it is copied, after BOOTX64.EFI. + // manifest was written: it fails while it is copied, after + // BOOTX64.EFI. std::fs::write(tree.join("loader/loader.conf"), b"timeout 9\n").unwrap(); let mut c = connect_fd3(&ufat); let source = ro(&tree); @@ -1409,7 +1714,7 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { let old = file_with( base.path(), "expired", - b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"validUntilUSec\":1}\n\x1e{\"name\":\"x\",\"size\":0}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\",\"validUntilUSec\":1}\n\x1e{\"name\":\"x\",\"size\":0}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", ); let empty = file_with(base.path(), "empty", b""); let e = error_of( @@ -1431,6 +1736,44 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], )); assert!(warnings(&mut c, image.path()).is_empty()); + // A manifest that expired, one whose first object comes before its + // directory, and one whose first file the stream cannot have without a + // size are refused before anything is written, also with parents. + let misplaced = file_with( + base.path(), + "misplaced", + b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n\x1e{\"name\":\"d/x\",\"size\":0}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + let sizeless = file_with( + base.path(), + "sizeless", + b"\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n\x1e{\"name\":\"x\"}\n\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + let old = ro(&base.path().join("expired")); + for (manifest, error) in [ + (old, "EntryNotValid"), + (misplaced, "InvalidManifest"), + (sizeless, "InvalidManifest"), + ] { + let e = error_of( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","parents":true,"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[img.as_fd(), manifest.as_fd(), empty.as_fd()], + ); + assert_eq!(e.name, format!("{}.{}", IFACE, error)); + assert!(warnings(&mut c, image.path()).is_empty()); + } + std::fs::write(tree.join("loader/loader.conf"), b"timeout 9\n").unwrap(); + let manifest_file = ro(&base.path().join("manifest")); + let e = error_of( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"replace":true}}"#, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.ContentMismatch", IFACE)); + assert_eq!(warnings(&mut c, image.path()), ["dirtyFlag", "fatDirtyFlag"]); } /// imageHash: the hash of the whole image window as the call leaves it, @@ -1504,8 +1847,8 @@ fn assemble_writes_a_manifest() { assert_eq!(u64_of(&r, "files"), 2); assert_eq!(u64_of(&r, "omitted"), 0); drop(out_file); - let m = fat::manifest::parse(&std::fs::read(&out).unwrap()).unwrap(); - let mut listed: Vec<&str> = m.entries.iter().map(|e| e.name.as_deref().unwrap()).collect(); + let m = read_manifest(&std::fs::read(&out).unwrap()); + let mut listed: Vec<&str> = m.entries.iter().map(|e| e.name.as_str()).collect(); listed.sort_unstable(); assert_eq!( listed, @@ -1517,13 +1860,13 @@ fn assemble_writes_a_manifest() { "loader/loader.conf" ] ); - assert_eq!(m.root.mtime_nsec, Some(T0 * 1000)); + assert_eq!(m.root.inode.mtime_nsec, Some(T0 * 1000)); for e in &m.entries { if e.inode_type == fat::manifest::InodeType::Regular { - let data = std::fs::read(tree.path().join(e.name.as_deref().unwrap())).unwrap(); + let data = std::fs::read(tree.path().join(e.name.as_str())).unwrap(); assert_eq!(e.size, Some(data.len() as u64)); - assert_eq!(e.sha256, Some(fat::sha256::digest(&data)), "{:?}", e.name); - assert!(e.mtime_nsec.is_some()); + assert_eq!(e.sha256, Some(fat::manifest::Sha256::digest(&data)), "{:?}", e.name); + assert!(e.inode.mtime_nsec.is_some()); } } // A sink that cannot be written to is refused before anything happens. @@ -1562,7 +1905,9 @@ fn manifest_problems_are_those_of_uapi16() { assert_eq!(declared, spelled); } -/// The manifest sink takes the features of UAPI.16, with "_" for "-". +/// The manifest sink takes the features of UAPI.16, with "_" for "-". A +/// refused manifest names the field of a feature it does not list, and a +/// key it has twice is a reason of its own. #[test] fn manifests_record_and_apply_features() { let _serial = common::serial(); @@ -1649,6 +1994,39 @@ fn manifests_record_and_apply_features() { ); assert_eq!(e.name, "org.varlink.service.InvalidParameter"); assert_eq!(str_of(&e.parameters, "parameter"), "manifestSink"); + // A field of a feature the manifest does not list is named, and a key + // twice in an object is duplicateKey. + let declared = "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n"; + let trailer = "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"; + for (record, reason, field) in [ + ( + "\x1e{\"mTimeNSec\":1,\"name\":\"a\",\"size\":0}\n", + "unlistedFeature", + Some("mTimeNSec"), + ), + ( + "\x1e{\"flagHidden\":true,\"name\":\"a\",\"size\":0}\n", + "unlistedFeature", + Some("flagHidden"), + ), + ("\x1e{\"name\":\"a\",\"size\":0,\"size\":0}\n", "duplicateKey", None), + ] { + let bad = file_with( + scratch.path(), + "bad", + format!("{}{}{}", declared, record, trailer).as_bytes(), + ); + let e = error_of( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0}}}"#, + &[bad.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidManifest", IFACE), "{}", record); + assert_eq!(str_of(&e.parameters, "reason"), reason, "{}", record); + assert_eq!(u64_of(&e.parameters, "record"), 1, "{}", record); + assert_eq!(e.parameters.get("field").and_then(Value::as_str), field, "{}", record); + } } /// With the more flag Assemble tells which step it is in, in order. @@ -1831,16 +2209,12 @@ fn describe_with_and_without_a_manifest() { assert_eq!(u64_of(last, "bytes"), 5010); assert_eq!(u64_of(last, "omitted"), 0); drop(out_file); - let m = fat::manifest::parse(&std::fs::read(&out).unwrap()).unwrap(); + let m = read_manifest(&std::fs::read(&out).unwrap()); assert_eq!(m.entries.len(), 5); - assert!(m.root.mtime_nsec.is_none()); - assert!(m.entries.iter().all(|e| e.mtime_nsec.is_none())); - let conf = m - .entries - .iter() - .find(|e| e.name.as_deref() == Some("loader/loader.conf")) - .unwrap(); - assert_eq!(conf.sha256, Some(fat::sha256::digest(b"timeout 5\n"))); + assert!(m.root.inode.mtime_nsec.is_none()); + assert!(m.entries.iter().all(|e| e.inode.mtime_nsec.is_none())); + let conf = m.entries.iter().find(|e| e.name == "loader/loader.conf").unwrap(); + assert_eq!(conf.sha256, Some(fat::manifest::Sha256::digest(b"timeout 5\n"))); // Images that hold no FAT32 volume say why. let blank = Temp::image(40 << 20); let blank_ro = ro(blank.path()); @@ -2073,12 +2447,9 @@ fn populate_puts_content_into_a_volume() { assert_eq!(u64_of(r, "files"), 2); assert_eq!(u64_of(r, "omitted"), 0); drop(out_file); - let m = fat::manifest::parse(&std::fs::read(&out).unwrap()).unwrap(); - assert!(m - .entries - .iter() - .any(|e| e.name.as_deref() == Some("EFI/BOOT/BOOTX64.EFI"))); - assert!(m.entries.iter().any(|e| e.name.as_deref() == Some("a/b/c.conf"))); + let m = read_manifest(&std::fs::read(&out).unwrap()); + assert!(m.entries.iter().any(|e| e.name == "EFI/BOOT/BOOTX64.EFI")); + assert!(m.entries.iter().any(|e| e.name == "a/b/c.conf")); assert_eq!( names(&call_more( &mut c, @@ -2554,7 +2925,7 @@ fn passed_descriptors_are_vetted() { const DRAIN_POLL: Duration = Duration::from_millis(1); /// What the manifest of a volume carries for every file at least: the /// hash of its contents in hex. -const MANIFEST_BYTES_PER_FILE: usize = 2 * fat::sha256::DIGEST_SIZE; +const MANIFEST_BYTES_PER_FILE: usize = 2 * fat::manifest::Sha256::SIZE; /// How many times over the manifest of the sink test fills its pipe. const PIPEFULS: usize = 4; /// The size asked for a pipe that is to be as small as a pipe can be: the @@ -2647,10 +3018,12 @@ fn receive(c: &mut Client, name: &str) -> Response { } /// A client keeps a copy of a pipe it passed and sets O_NONBLOCK on it -/// during the call, once the service vetted it: the manifest, the contents -/// of the files and the manifest sink. The read or write that then fails -/// with EAGAIN fails the call with BadFileDescriptor and reason flags, as -/// the vetting does when the flag is set before the call. +/// during the call, once the service vetted it: the manifest, alone or read +/// with the contents of its files, the contents of the files and the +/// manifest sink. The read or write that then fails with EAGAIN fails the +/// call with BadFileDescriptor and reason flags, as the vetting does when +/// the flag is set before the call. The error names the parameter the pipe +/// was passed as. #[test] fn pipes_made_non_blocking_during_the_call_are_refused() { let _serial = common::serial(); @@ -2702,6 +3075,30 @@ fn pipes_made_non_blocking_during_the_call_are_refused() { let client = feed_and_flip(&r, &w, &blob); refused(&mut c, "Assemble", "sourceFileDescriptor"); client.join().unwrap(); + // The manifest, read with the contents of the files from a regular + // file into a volume made before: the manifest is named, not the + // contents it is read with. + let image = Temp::image(40 << 20); + let img = rw(image.path()); + reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0}}"#, + &[img.as_fd()], + )); + let blob_file = file_with(scratch.path(), "blob", &blob); + let (r, w) = pipe(); + c.send_with_fds( + &method("Populate"), + params( + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + ), + &[img.as_fd(), r.as_fd(), blob_file.as_fd()], + ) + .unwrap(); + let client = feed_and_flip(&r, &w, &manifest); + refused(&mut c, "Populate", "manifest"); + client.join().unwrap(); // The manifest sink, a pipe as small as can be, and a volume whose // manifest fills it PIPEFULS times over. let (r, w) = pipe(); @@ -2857,6 +3254,34 @@ fn errors_are_typed() { ); assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + // A plan refuses a manifest's fifo, and so does Assemble before the + // image is touched. + let scratch = Temp::dir(); + let fifo = scratch.path().join("fifo.manifest"); + std::fs::write( + &fifo, + concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"f\",\"type\":\"fifo\"}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ), + ) + .unwrap(); + let e = error_of( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0},"unsupported":"fail"}}"#, + &[ro(&fifo).as_fd()], + ); + assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"unsupported":"fail"}}"#, + &[fresh_img.as_fd(), ro(&fifo).as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); // There is no switch for following links, and no unknown parameter. let e = error_of( &mut c, @@ -3045,6 +3470,20 @@ fn too_small_images_are_reported() { ); assert_eq!(str_of(&e.parameters, "reason"), "blocks"); assert_eq!(str_of(&e.parameters, "path"), "/big.bin"); + // So is the file of a manifest that does not fit. + let (manifest, _) = manifest_and_blob(&tree); + let manifest_file = file_with(base.path(), "manifest", &manifest); + let other = Temp::image(40 << 20); + let other_img = rw(other.path()); + reply(call(&mut c, "Assemble", IMG, &[other_img.as_fd()])); + let e = error_of( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[other_img.as_fd(), manifest_file.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.NoSpaceLeft", IFACE)); + assert_eq!(str_of(&e.parameters, "path"), "/big.bin"); let ck = reply(call(&mut c, "Check", IMG, &[img.as_fd()])); assert_eq!(u64_of(&ck, "errors"), 0); assert!(bool_of(&ck, "clean")); From 7f707d624eb2909414db1dc6d73f6d5b069e28a0 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 13/19] fat: plan the size with counters per open directory Currently the planner keeps every name of every directory it is given, in a BTreeMap per directory keyed by the folded name. Now that a manifest is read record by record that's the last thing that grows with the manifest, about 160 bytes per object. assemble --plan of a manifest of a million files peaks at 153 MiB, and at 41 MiB for a quarter of them. But a tree walk and a manifest in code point order both hand us the entries in tree order: every directory before what is in it, and what is in it right after it. So the planner only has to keep the directories more entries can still go into, the root and the ones on the way to the last entry, with the slots their entries take so far. When the entries of a directory are done we add up the clusters it takes for every cluster size and forget about it. A file only adds its clusters. IOW, the memory a plan takes grows with the depth of the tree and not with the number of its entries. The price is that names aren't compared anymore. Two names FAT doesn't tell apart, such as README.TXT and readme.txt, are two entries to the plan. Where the assembly replaces, which it does by default, the file under the second name replaces the first one. The replaced file stays allocated until its replacement is complete, so the plan has to count both for the peak. The old planner kept one count per folded name, and that was too small: a volume of the size it planned ran out of clusters while a large file that came late replaced an earlier one. Counting both fixes that, and the finished file system keeps the clusters of every replaced file free. That's fine, we're after a size that fits and not the absolute minimum. Both entries also count against the 65536 entry slots of their directory, so the plan of a directory close to the limit can fail although the write would fit. We accept that too. A file and a directory under two such names don't fail the plan anymore either. The write fails on the second one, replacing or not. A directory under two such names is another matter. Its entries come in two runs then, one under each name, and the plan holds each run to the 65536 entry slots of a directory on its own while both together might not fit. So the plan can pass what the write refuses with ENOSPC, "directory is full". Remembering every directory the plan is done with, by its parent and its folded name, would catch the second run. But that grows with every directory, about 180 bytes each and 349 MiB for two million of them, and it still misses a directory that comes back under its 8.3 alias, such as FOOBAR~1 after FOO BAR. The numeric tails depend on the siblings, so catching that needs every name of every directory, which is exactly what we're getting rid of here. So the plan doesn't compare names, and the README and the Varlink documentation say so. The entries of a directory under two such names are held to the slot limit as a whole only when they are written, and a file and a directory under such names, or names that --no-replace refuses, pass a plan as well. The slot limit is checked when a directory takes an entry. So a plan fails at the entry that doesn't fit, and the error names the directory, NoSpaceLeft with reason directoryEntries and its path over Varlink. add_file() and add_dir() count right only in tree order, so they are private now. Nothing outside the planner used them. Plan::add_tree() takes the CopyOptions of the copy it plans for instead of a bare bool for following symbolic links, and the command line and the service build them in one place for the copy and its plan. The planner allocates nothing per record. The open directories share one path buffer, LongName::slots_for() counts the slots of a name from the string with the checks of LongName::new(), Alias::of() puts the parts of the alias in place instead of collecting them in two vectors first, and path::names() hands out the names of a path without collecting them. The path of an object goes into one more buffer, written by the helper that gives the assembly its path, so the plan holds it to the 4095 bytes of a path the way the write does. Most records go into the deepest open directory. So the directory a record is in is compared with the path of the open directories first, and the path of a record is split into names only when it leaves the deepest one. A plan of the same million files now peaks at 3.0 to 3.5 MiB, and so does a plan of a quarter of them, of a million files in sixteen directories, of a million files down a chain of 500 directories, and of a tree of a million files on disk. It runs about half the instructions and takes about half the time, and down the chain it takes 1.5 seconds instead of 45. assemble of a million files from a manifest takes the 101 MiB populate takes, down from 154 MiB, and populate runs 3% fewer instructions. So the README, the Varlink documentation and the manifest module say that memory use doesn't grow with the manifest, for assemble and its plan as well. The tests pin what the old planner said for a synthetic tree of 885 entries with every shape of name the slots depend on, for 512 and 4096 byte sectors and every cluster size. The new one agrees, fed from a walk and from a manifest. That tree fills a volume of the planned size to the last cluster, copied from a walk and assembled from a manifest. A tree with names FAT doesn't tell apart fits with the clusters of the replaced file and of the second directory free, a file and a directory under such names pass the plan and fail the write, names of 4094 and 4095 bytes are planned the way they are assembled, and the command line passes a plan of a directory under two names and fails to write it. Signed-off-by: Christian Brauner (Amutable) --- README.md | 37 +- docs/varlink.md | 22 +- src/bin/ufat/cli.rs | 19 +- src/bin/ufat/service.rs | 20 +- src/fat/manifest/mod.rs | 24 +- src/fat/name.rs | 131 ++++-- src/fat/path.rs | 115 ++++- src/fat/plan.rs | 983 +++++++++++++++++++++++++++++++++------- tests/cli.rs | 47 ++ tests/reference.rs | 6 +- 10 files changed, 1159 insertions(+), 245 deletions(-) diff --git a/README.md b/README.md index 4abe557..f3fa812 100644 --- a/README.md +++ b/README.md @@ -178,14 +178,13 @@ contents then have to come from a directory. ufat reads a manifest one record at a time, and writes each file and directory when its record comes. So `populate` takes a manifest of any -size, also through a pipe, and its memory use does not grow with the -manifest. To size the file system to fit, ufat reads the manifest once -before it writes anything, and keeps the name of every file and -directory while it does. So `assemble` with a SOURCE needs the manifest -in a regular file, and the memory `assemble` and `assemble --plan` use -grows with the manifest. `assemble --plan` and `assemble` without a -SOURCE read the manifest only once, so they take one through a pipe as -well. +size, also through a pipe. To size the file system to fit, ufat reads +the manifest once before it writes anything. So `assemble` with a SOURCE +needs the manifest in a regular file. `assemble --plan` and `assemble` +without a SOURCE read the manifest only once, so they take one through a +pipe as well. While it sizes, ufat keeps the path of the deepest open +directory, and a count for each directory on that path. Memory use does +not grow with the manifest. The objects of a manifest have to be in code point order: every directory before what is in it, and the names of a directory sorted by @@ -266,6 +265,28 @@ An existing image file is grown when needed and never shrunk. A smaller volume made by another tool can still be read, filled and checked. `ufat check` reports that it is below the minimum. +A plan does not compare names. Two names that FAT does not tell apart +are two names to the plan: names that differ in case only, such as +`A.TXT` and `a.txt`, and a name and the short name FAT gives another +one, such as `FOOBAR~1` for `FOO BAR`. + +When a file replaces another one under such a name, the plan counts +both. The file system keeps the clusters of every replaced file free +then. Both also count against the 65536 directory entries a FAT +directory holds, so the plan of a directory close to that limit can +fail although the write would fit. A long name takes up to 21 of these +entries. + +The entries of a directory under two such names, such as `FOO BAR/a` +and `FOOBAR~1/b`, go into one directory. The plan holds the entries +under each name to the limit on their own, and only the write sees them +all in one directory. When they do not fit, `assemble` fails with +"directory is full". + +A file and a directory under two such names pass the plan, and +`assemble` fails on the second one, with or without `--no-replace`. +Names that `--no-replace` refuses pass the plan too. + ## Sector size The sector size of the file system has to be at least the logical block diff --git a/docs/varlink.md b/docs/varlink.md index 8977bb6..fb2fce9 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -128,7 +128,18 @@ What the fields mean for vfat: `features` and `discard` are missing. Asking for them fails with `OperationNotSupported`. - `sizeToFit` is `exact`. A plan gives the size the content needs, to the - sector. + sector. A plan does not compare names. Names that FAT does not tell + apart, such as `A.TXT` and `a.txt`, or `FOOBAR~1` and `FOO BAR`, whose + short name it is, are two names to it. Content with such names, + assembled with `replace`, leaves the clusters of every file that was + replaced free, and the plan of a directory close to the limit of 65536 + entries can fail although the assembly would fit. The entries of a + directory under two such names go into one directory. A plan holds the + entries under each name to the limit on their own, and the assembly + fails with `NoSpaceLeft` and reason `directoryEntries` when they do not + fit together. A file and a directory under two such names pass a plan + and fail the assembly, with `replace` or without it, and so do names + that an assembly without `replace` refuses. - `minimalSizeBytes` is the smallest volume: 65525 clusters of 512 bytes plus the reserved sectors and two FATs. With 4096 byte sectors the minimum is 269045760 bytes. `maximalSizeBytes` is 2^32 - 1 sectors of @@ -402,8 +413,8 @@ a pipe, unless it is planned before its content is written: `Assemble` in mode `assemble` plans its content first, so there it has to be a regular file. A pipe fails with `BadFileDescriptor` and reason `wrongType` then. Mode `plan` reads the manifest once and takes a pipe. A plan keeps the -name of every file and directory of the manifest, so the memory -`Assemble` uses grows with the manifest. +path of the deepest open directory, and a count for each directory on +that path, so the memory `Assemble` uses does not grow with the manifest. When the file contents come from a stream, the manifest and the stream are read in lockstep: a record of the manifest, then the contents of the @@ -687,9 +698,8 @@ Notes: - Files below a passed directory are opened with the service's credentials. This is why only root and the service's own user may connect. -- Memory use does not grow with the volume, and not with a manifest that - `Populate` writes. `Assemble` keeps the names of a manifest while it - plans it. 512M leaves room for several connections. +- Memory use does not grow with the volume or with a manifest. 512M + leaves room for several connections. - `DynamicUser=yes` works. Only root can then connect. - Do not set `LimitFSIZE=`. A write past the limit kills the process with SIGXFSZ. diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index 00eb67b..0b3d2a7 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -583,7 +583,7 @@ impl Source { match self { Source::None => Ok(0), Source::Tree { path, dir } => { - let skipped = plan.add_tree(dir.as_fd(), dest(args), true)?; + let skipped = plan.add_tree(dir.as_fd(), dest(args), ©_options(args)?)?; if let (Some(skipped), true) = (skipped.first(), fail_unsupported(args)?) { bail!( errno::EINVAL, @@ -615,11 +615,7 @@ impl Source { /// manifest assembled while it is read, which takes the contents of its /// files. fn fill(&mut self, volume: &mut Volume, args: &Args) -> Result<()> { - let copy = CopyOptions { - times: time_policy(args)?, - replace: !args.flag("no-replace"), - follow_symlinks: true, - }; + let copy = copy_options(args)?; match self { Source::None => {} Source::Tree { path, dir } => { @@ -682,6 +678,17 @@ impl AssembleObserver for SkipNotes { } } +/// How the command line asks a copy of a tree, and the plan of one, to +/// take it: following symbolic links, and replacing what is there unless +/// `--no-replace`. +fn copy_options(args: &Args) -> Result { + Ok(CopyOptions { + times: time_policy(args)?, + replace: !args.flag("no-replace"), + follow_symlinks: true, + }) +} + /// How the command line asks an assembly, and the plan of one, to store a /// manifest's objects: replacing what is there unless `--no-replace`, and /// leaving out what FAT cannot store unless `--unsupported fail`. diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index ee31d97..4eb30c4 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -1094,7 +1094,7 @@ impl Content { fn plan(&self, plan: &mut Plan) -> fat::Result<()> { match &self.fill { Some(Fill::Tree(dir)) => { - let skipped = plan.add_tree(dir.as_fd(), "/", true)?; + let skipped = plan.add_tree(dir.as_fd(), "/", &self.copy_options())?; if self.fail_unsupported { refuse_skipped(&skipped)?; } @@ -1131,11 +1131,21 @@ impl Content { fn check_tree(&self, dest: &str) -> Outcome<()> { if let (true, Some(Fill::Tree(dir))) = (self.fail_unsupported, &self.fill) { let mut plan = Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)); - refuse_skipped(&plan.add_tree(dir.as_fd(), dest, true)?)?; + refuse_skipped(&plan.add_tree(dir.as_fd(), dest, &self.copy_options())?)?; } Ok(()) } + /// How a copy of the tree, and its plan, take it: following symbolic + /// links, and replacing what is there with replace. + fn copy_options(&self) -> CopyOptions { + CopyOptions { + times: self.times, + replace: self.replace, + follow_symlinks: true, + } + } + /// How an assembly of the manifest, and its plan, store its objects: /// replacing what is there with replace, and leaving out what FAT /// cannot store unless UnsupportedPolicy fail. @@ -1148,11 +1158,7 @@ impl Content { /// Puts the content into the volume at `dest`: the directory a tree goes /// below, the path of one file. A manifest's tree goes below the root. fn write_into(&mut self, v: &mut Volume, dest: &str, progress: &mut dyn FnMut(&Progress)) -> Outcome { - let copy = CopyOptions { - times: self.times, - replace: self.replace, - follow_symlinks: true, - }; + let copy = self.copy_options(); let assembly = AssembleOptions { default_time: self.time, flags: self.assemble_flags(), diff --git a/src/fat/manifest/mod.rs b/src/fat/manifest/mod.rs index 6370aaa..1d9f45f 100644 --- a/src/fat/manifest/mod.rs +++ b/src/fat/manifest/mod.rs @@ -9,11 +9,11 @@ //! directories, no file of 4 GiB or more, and no two names that differ in //! case only. //! -//! An assembly reads one record at a time and writes what it describes -//! right away. It never holds a whole manifest, so a manifest of any size -//! can come through a pipe. The planner in [`crate::plan`] takes the -//! records as they come too, but it keeps the name of every file and -//! directory it is given. +//! Nothing here holds a whole manifest. An assembly reads one record at a +//! time and writes what it describes right away, so a manifest of any size +//! can come through a pipe. The planner in [`crate::plan`] counts what the +//! records take as they come. It keeps the path of the deepest open +//! directory, and a count for each directory on that path. //! //! Signatures are recognised but not verified: that needs an X.509 stack. //! Callers who need authenticated manifests must verify them before handing @@ -50,8 +50,18 @@ pub(crate) use error::SizePurpose; /// The path inside a volume of the file object with the name `name`: the /// name below the root directory. -pub(crate) fn path_in_volume(name: &str) -> String { - crate::path::join("/", name) +fn path_in_volume(name: &str) -> String { + let mut path = String::with_capacity(SEPARATOR.len_utf8() + name.len()); + path_in_volume_into(name, &mut path); + path +} + +/// Puts [`path_in_volume`] of `name` into `path`, in place of what `path` +/// held, so that the paths of all objects can share one buffer. +pub(crate) fn path_in_volume_into(name: &str, path: &mut String) { + path.clear(); + path.push(SEPARATOR); + path.push_str(name); } /// What a file object becomes in a FAT volume. diff --git a/src/fat/name.rs b/src/fat/name.rs index 1805c95..274c57d 100644 --- a/src/fat/name.rs +++ b/src/fat/name.rs @@ -87,6 +87,10 @@ const LFN_UNIT_OFFSETS: [usize; LFN_UNITS_PER_ENTRY] = { offsets }; +/// The short entries of a directory entry: one, after its long name +/// entries if it has any. +const SHORT_ENTRIES: usize = 1; + /// A validated long file name. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LongName { @@ -100,6 +104,19 @@ impl LongName { /// `" * / : < > ? \ |`, must not start with a space and must not end /// with a space or a dot, and must not be "." or "..". pub fn new(name: &str) -> Result { + let len = LongName::check(name)?; + // The units take one allocation of the size check() counted. + let mut units = Vec::with_capacity(len); + units.extend(name.encode_utf16()); + Ok(LongName { + text: name.to_string(), + units, + }) + } + + /// Checks `name` the way [`LongName::new`] does and returns its length + /// in UTF-16 units. Nothing is allocated unless it fails. + fn check(name: &str) -> Result { let bad = |problem: NameProblem| Detail::Name { name: name.to_string(), problem, @@ -115,6 +132,7 @@ impl LongName { name ); } + let mut len = 0; for c in name.chars() { if c.is_ascii_control() { bail!( @@ -143,6 +161,7 @@ impl LongName { c ); } + len += c.len_utf16(); } if name.starts_with(' ') { bail!( @@ -160,13 +179,7 @@ impl LongName { name ); } - // A name has no more UTF-16 units than UTF-8 bytes, so this is the - // only allocation. collect() would size the vector from the - // iterator's lower bound, a third of that, and reallocate as it - // grows. - let mut units = Vec::with_capacity(name.len()); - units.extend(name.encode_utf16()); - if units.len() > MAX_LONG_NAME { + if len > MAX_LONG_NAME { bail!( ENAMETOOLONG, bad(NameProblem::TooLong), @@ -175,10 +188,20 @@ impl LongName { MAX_LONG_NAME ); } - Ok(LongName { - text: name.to_string(), - units, - }) + Ok(len) + } + + /// The directory slots an entry named `name` takes: its long name + /// entries, if it needs any, and its short entry. Fails where + /// [`LongName::new`] fails, and allocates nothing. + pub(crate) fn slots_for(name: &str) -> Result { + let len = LongName::check(name)?; + let long = if Alias::from_name(name).needs_long_name { + len.div_ceil(LFN_UNITS_PER_ENTRY) + } else { + 0 + }; + Ok(long + SHORT_ENTRIES) } /// The name as a string. @@ -275,11 +298,11 @@ impl Case { } } -/// Converts one part (base or extension) of a name into at most `max` -/// alias bytes. Returns the bytes, whether information was lost and the -/// case of the letters seen. -fn convert_part(part: &str, max: usize) -> (Vec, bool, Case) { - let mut out = Vec::with_capacity(max); +/// Converts one part (base or extension) of a name into the alias bytes +/// `out`, as many as fit. Returns how many it wrote, whether information +/// was lost and the case of the letters seen. +fn convert_part(part: &str, out: &mut [u8]) -> (usize, bool, Case) { + let mut len = 0; let mut lossy = false; let mut case = Case::NoLetters; for c in part.chars() { @@ -287,21 +310,22 @@ fn convert_part(part: &str, max: usize) -> (Vec, bool, Case) { lossy = true; continue; } - if out.len() == max { + let Some(byte) = out.get_mut(len) else { lossy = true; break; - } + }; if c.is_ascii_alphabetic() { case = case.add(c.is_ascii_lowercase()); - out.push(c.to_ascii_uppercase() as u8); + *byte = c.to_ascii_uppercase() as u8; } else if c.is_ascii() && valid_short_char(c as u8) { - out.push(c as u8); + *byte = c as u8; } else { lossy = true; - out.push(b'_'); + *byte = b'_'; } + len += 1; } - (out, lossy, case) + (len, lossy, case) } /// The 8.3 alias derived from a long name, before any numeric tail. @@ -322,17 +346,23 @@ pub struct Alias { impl Alias { /// Derives the alias of a long name. pub fn of(name: &LongName) -> Alias { - let text = name.as_str(); - let trimmed = text.trim_start_matches(['.', ' ']); - let mut lossy = trimmed.len() != text.len(); + Alias::from_name(name.as_str()) + } + + /// Derives the alias of `name`, a name [`LongName::new`] takes, + /// without allocating. + fn from_name(name: &str) -> Alias { + let trimmed = name.trim_start_matches(['.', ' ']); + let mut lossy = trimmed.len() != name.len(); let (base, ext) = match trimmed.rfind('.') { Some(i) => (&trimmed[..i], &trimmed[i + 1..]), None => (trimmed, ""), }; - let (base_bytes, base_lossy, base_case) = convert_part(base, NAME_BASE.len()); - let (ext_bytes, ext_lossy, ext_case) = convert_part(ext, NAME_EXT.len()); + let mut alias = [b' '; SHORT_NAME_SIZE]; + let (base_len, base_lossy, base_case) = convert_part(base, &mut alias[NAME_BASE]); + let (_, ext_lossy, ext_case) = convert_part(ext, &mut alias[NAME_EXT]); lossy |= base_lossy || ext_lossy; - if base_bytes.is_empty() || RESERVED_NAMES.contains(&base_bytes.as_slice()) { + if base_len == 0 || RESERVED_NAMES.contains(&&alias[..base_len]) { lossy = true; } let mixed = base_case == Case::Mixed || ext_case == Case::Mixed; @@ -346,12 +376,9 @@ impl Alias { case_flags |= CASE_LOWER_EXT; } } - let mut alias = [b' '; SHORT_NAME_SIZE]; - alias[..base_bytes.len()].copy_from_slice(&base_bytes); - alias[NAME_EXT.start..NAME_EXT.start + ext_bytes.len()].copy_from_slice(&ext_bytes); Alias { name: alias, - base_len: base_bytes.len(), + base_len, lossy, needs_long_name, case_flags, @@ -533,6 +560,46 @@ mod tests { assert_eq!(LongName::new(&astral).unwrap_err().errno(), ENAMETOOLONG); } + /// The slots counted from a name are those of its long name entries, + /// where its alias needs them, and its short entry. A name that + /// LongName::new() refuses is refused alike. + #[test] + fn slots_of_names() { + let longest: String = std::iter::repeat_n('x', MAX_LONG_NAME).collect(); + let astral: String = std::iter::repeat_n('\u{1F600}', 7).collect(); + for (name, slots) in [ + ("README.TXT", 1), + ("readme.txt", 1), + ("loader", 1), + ("Readme.txt", 2), + ("thirteen_char", 2), + ("linux-6.12.efi", 3), + ("\u{fc}n\u{ef}c\u{f6}d\u{e9}", 2), + (astral.as_str(), 3), + (longest.as_str(), 21), + ] { + assert_eq!(LongName::slots_for(name).unwrap(), slots, "{:?}", name); + let long_name = LongName::new(name).unwrap(); + let entries = if Alias::of(&long_name).needs_long_name { + long_name.entry_count() + } else { + 0 + }; + assert_eq!(entries + SHORT_ENTRIES, slots, "{:?}", name); + } + let too_long: String = std::iter::repeat_n('x', MAX_LONG_NAME + 1).collect(); + for bad in ["", ".", "..", "a/b", "a:b", "a\tb", "a ", " a", "a.", too_long.as_str()] { + let refused = LongName::slots_for(bad).unwrap_err(); + let expected = LongName::new(bad).unwrap_err(); + assert_eq!( + (refused.errno(), refused.detail()), + (expected.errno(), expected.detail()), + "{:?}", + bad + ); + } + } + #[test] fn plain_short_names() { let a = alias("README.TXT"); diff --git a/src/fat/path.rs b/src/fat/path.rs index 039cd0d..7756365 100644 --- a/src/fat/path.rs +++ b/src/fat/path.rs @@ -7,8 +7,8 @@ //! stores them as entries of their own. use crate::errno::*; -use crate::Result; use crate::{Detail, NameProblem}; +use crate::{Error, Result}; /// What separates the names of a path. pub(crate) const SEPARATOR: char = '/'; @@ -20,35 +20,77 @@ pub(crate) const MAX_PATH: usize = 4095; /// Splits `path` into its names. pub(crate) fn components(path: &str) -> Result> { - let bad = |problem: NameProblem| Detail::Name { - name: path.to_string(), - problem, - }; - if path.len() > MAX_PATH { + check_length(path)?; + let mut out = Vec::new(); + for name in path.split(SEPARATOR).filter(|name| !name.is_empty()) { + if is_dot_name(name) { + return Err(dot_component(path, name)); + } + out.push(name); + } + Ok(out) +} + +/// The names of `path`, the first one first, checked as [`components`] +/// checks them but not collected. +pub(crate) fn names(path: &str) -> Result + Clone> { + check_length(path)?; + let names = path.split(SEPARATOR).filter(|name| !name.is_empty()); + if let Some(name) = names.clone().find(|name| is_dot_name(name)) { + return Err(dot_component(path, name)); + } + Ok(names) +} + +/// The path of the directory `path` is in, as `path` spells it, and the +/// last name of `path`, where that is all [`names`] has to check of it: +/// `path` fits [`MAX_PATH`], and its last name is not empty, "." or "..". +/// The names of `path` are then those of the directory and the last name, +/// and [`names`] refuses `path` only where it refuses the directory. None +/// for every other path. +pub(crate) fn parent_and_name(path: &str) -> Option<(&str, &str)> { + let (parent, name) = path.rsplit_once(SEPARATOR)?; + (fits(path) && !name.is_empty() && !is_dot_name(name)).then_some((parent, name)) +} + +/// Whether `path` is not longer than [`MAX_PATH`]. +fn fits(path: &str) -> bool { + path.len() <= MAX_PATH +} + +/// Refuses a path longer than [`MAX_PATH`]. +fn check_length(path: &str) -> Result<()> { + if !fits(path) { bail!( ENAMETOOLONG, - bad(NameProblem::TooLong), + Detail::Name { + name: path.to_string(), + problem: NameProblem::TooLong, + }, "path is longer than {} bytes", MAX_PATH ); } - let mut out = Vec::new(); - for c in path.split(SEPARATOR) { - if c.is_empty() { - continue; - } - if c == "." || c == ".." { - bail!( - EINVAL, - bad(NameProblem::DotComponent), - "path '{}' contains a '{}' component", - path, - c - ); - } - out.push(c); - } - Ok(out) + Ok(()) +} + +/// Whether `name` is "." or "..", which a path must not have. +fn is_dot_name(name: &str) -> bool { + name == "." || name == ".." +} + +/// The error of `path` for its name `name`, "." or "..". +fn dot_component(path: &str, name: &str) -> Error { + err!( + EINVAL, + Detail::Name { + name: path.to_string(), + problem: NameProblem::DotComponent, + }, + "path '{}' contains a '{}' component", + path, + name + ) } /// Appends `name` to the directory path `dir`. @@ -68,6 +110,31 @@ mod tests { assert_eq!(components("EFI/Linux").unwrap(), vec!["EFI", "Linux"]); assert_eq!(components("/EFI/./x").unwrap_err().errno(), EINVAL); assert_eq!(components("../x").unwrap_err().errno(), EINVAL); + assert_eq!(names("/EFI//Linux/").unwrap().next_back(), Some("Linux")); + assert_eq!(names("/EFI/..").err().map(|e| e.errno()), Some(EINVAL)); + let longest = format!("/{}", "x".repeat(MAX_PATH - 1)); + let too_long = format!("{}x", longest); + for (path, split) in [ + ("/EFI/Linux", Some(("/EFI", "Linux"))), + ("/EFI", Some(("", "EFI"))), + ("EFI/Linux", Some(("EFI", "Linux"))), + ("/EFI//Linux", Some(("/EFI/", "Linux"))), + ("/./x", Some(("/.", "x"))), + (longest.as_str(), Some(("", &longest[1..]))), + ("EFI", None), + ("/EFI/", None), + ("/EFI/.", None), + ("/EFI/..", None), + (too_long.as_str(), None), + ] { + assert_eq!(parent_and_name(path), split, "{}", path); + if let Some((parent, name)) = split { + // names() agrees, also where it refuses the directory. + let parent_names = names(parent).map(|names| names.chain([name]).collect::>()); + let path_names = names(path).map(|names| names.collect::>()); + assert_eq!(path_names.ok(), parent_names.ok(), "{}", path); + } + } assert_eq!(join("/", "EFI"), "/EFI"); assert_eq!(join("", "EFI"), "/EFI"); assert_eq!(join("/EFI/", "Linux"), "/EFI/Linux"); diff --git a/src/fat/plan.rs b/src/fat/plan.rs index 84c2674..78608ad 100644 --- a/src/fat/plan.rs +++ b/src/fat/plan.rs @@ -6,10 +6,35 @@ //! [`layout::minimal`] for the smallest volume that offers that many //! clusters. Formatting a volume of that size and copying the planned tree //! into it therefore succeeds, with no cluster to spare beyond what the -//! FAT32 minimum demands. +//! FAT32 minimum demands, as long as FAT tells all names of a directory +//! apart. +//! +//! The entries come in tree order, as a tree walk and a manifest have them: +//! every directory before what is in it, and what is in it right after it. +//! So the planner keeps only the directories more entries can still go +//! into, the root and the ones on the way to the last entry, with the slots +//! their entries take so far. When the entries of a directory are done, +//! the clusters it takes are added up for every cluster size, and the +//! directory is forgotten. A file only adds its clusters. The memory a plan +//! takes grows with the depth of the tree and not with its entries, so a +//! manifest of any size can be planned while it is read. +//! +//! The planner does not compare names. Two names that FAT does not tell +//! apart, such as `A.TXT` and `a.txt`, or `FOO BAR` and `FOOBAR~1`, the +//! short name of `FOO BAR`, are two entries to the planner and one to a +//! copy. A file under the second name replaces the one under the first, +//! or fails without [`CopyOptions::replace`] or [`AssembleFlags::REPLACE`], +//! whichever the copy takes. The plan counts both files, so the volume +//! keeps the clusters of the replaced one free. The entries of a directory +//! under both names go into one directory, which the plan counts as two, +//! each held to the limit of entry slots on its own. The copy can then +//! still run out of entry slots in it. A file and a directory under such +//! names pass the plan, and the copy fails on the second one, replacing or +//! not. -use std::collections::BTreeMap; use std::io::Read; +use std::iter::Peekable; +use std::ops::Range; use std::os::fd::BorrowedFd; use std::path::PathBuf; @@ -21,14 +46,21 @@ use crate::errno::*; use crate::format::{encode_label, FormatOptions}; use crate::host::{walk_tree, HostEntry, UnnamableEntry}; use crate::layout::{self, Layout, LayoutParams, MAX_CLUSTERS, MAX_CLUSTER_SIZE, MAX_SECTORS_PER_CLUSTER}; -use crate::manifest::{path_in_volume, AssembleFlags, EntryKind, ObjectAction, ObjectTriage, SizePurpose}; -use crate::name::{Alias, LongName}; -use crate::path::components; +use crate::manifest::{path_in_volume_into, AssembleFlags, EntryKind, ObjectAction, ObjectTriage, SizePurpose}; +use crate::name::LongName; +use crate::path::{self, SEPARATOR}; +use crate::populate::CopyOptions; use crate::sys; use crate::volume::MAX_FILE_SIZE; use crate::{Context, Error, Result}; use crate::{Detail, NoSpaceReason}; +/// How many cluster sizes a plan counts for: one for every number of +/// sectors per cluster, the powers of two up to [`MAX_SECTORS_PER_CLUSTER`]. +const CLUSTER_SIZES: usize = MAX_SECTORS_PER_CLUSTER.ilog2() as usize + 1; +/// The entries every directory but the root starts with: "." and "..". +const DOT_ENTRIES: u64 = 2; + /// Parameters the size of a volume depends on. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PlanOptions { @@ -84,77 +116,49 @@ impl PlanOptions { label, }) } -} -#[derive(Debug)] -enum Node { - File { size: u64 }, - Dir(Dir), + /// The parameters of the layout of a volume with `cluster_size` byte + /// clusters. + fn layout_params(&self, cluster_size: u32) -> LayoutParams { + LayoutParams { + sector_size: self.sector_size, + sectors_per_cluster: cluster_size.checked_div(self.sector_size), + reserved_sectors: self.reserved_sectors, + fats: self.fats, + align: self.align, + track_sectors: None, + allow_small: self.allow_small, + } + } } -/// A planned entry: the directory slots its name occupies, worked out -/// once when it is added since they do not depend on the cluster size, -/// and what it is. +/// A directory below the root that more entries can still go into. #[derive(Debug)] -struct Entry { +struct OpenDirectory { + /// Where its name is in the path of the open directories. + name: Range, + /// The slots its entries take so far. slots: u64, - node: Node, } -/// A planned directory. Entries are keyed by their case folded name. -#[derive(Debug, Default)] -struct Dir { - entries: BTreeMap, Entry>, +/// The clusters a plan takes with one cluster size. +#[derive(Clone, Copy, Debug)] +struct Tally { + /// The cluster size in bytes. + cluster_size: u64, + /// The clusters the files and the directories that are done take. + clusters: u64, } -/// Number of directory slots an entry named `name` occupies. -pub fn entry_slots(name: &LongName) -> usize { - if Alias::of(name).needs_long_name { - name.entry_count() + 1 - } else { - 1 +impl Tally { + /// The clusters `bytes` of data take. + fn clusters_for(&self, bytes: u64) -> u64 { + bytes.div_ceil(self.cluster_size) } -} - -#[derive(Default)] -struct Totals { - clusters: u64, - files: u64, - directories: u64, - bytes: u64, -} -impl Dir { - fn count(&self, is_root: bool, label: bool, cluster_size: u64, totals: &mut Totals) -> Result<()> { - let mut slots: u64 = if is_root { u64::from(label) } else { 2 }; - for entry in self.entries.values() { - slots += entry.slots; - match &entry.node { - Node::File { size } => { - totals.files += 1; - totals.bytes += size; - totals.clusters += size.div_ceil(cluster_size); - } - Node::Dir(d) => { - totals.directories += 1; - d.count(false, label, cluster_size, totals)?; - } - } - } - if slots > MAX_SLOTS as u64 { - bail!( - ENOSPC, - Detail::NoSpace { - reason: NoSpaceReason::DirectoryEntries, - path: None, - }, - "a directory needs {} entry slots, FAT32 directories hold at most {}", - slots, - MAX_SLOTS - ); - } - totals.clusters += (slots * DIR_ENTRY_SIZE as u64).div_ceil(cluster_size).max(1); - Ok(()) + /// The clusters a directory with `slots` slots takes: one at least. + fn directory_clusters(&self, slots: u64) -> u64 { + self.clusters_for(slots.saturating_mul(DIR_ENTRY_SIZE as u64)).max(1) } } @@ -187,19 +191,53 @@ impl Estimate { } } -/// A set of files and directories whose minimal volume size is wanted. +/// A set of files and directories whose minimal volume size is wanted, +/// added in tree order, see the [module documentation](self). #[derive(Debug)] pub struct Plan { + /// The parameters the plan is made with. options: PlanOptions, - root: Dir, + /// What the plan takes with every cluster size it can be estimated + /// for, the smallest first. Empty for a sector size the layout does not + /// take. + tallies: Vec, + /// The slots the entries of the root take so far. + root_slots: u64, + /// The open directories below the root, each in the one before it. + open: Vec, + /// The path of the deepest open directory: a slash and the name of + /// every open directory. Empty for the root. + open_path: String, + /// The files added. + files: u64, + /// The directories added below the root. + directories: u64, + /// The bytes of the files added. + bytes: u64, } impl Plan { /// An empty plan. pub fn new(options: PlanOptions) -> Plan { + let tallies = if layout::valid_sector_size(options.sector_size) { + (0..CLUSTER_SIZES) + .map(|shift| Tally { + cluster_size: u64::from(options.sector_size) << shift, + clusters: 0, + }) + .collect() + } else { + Vec::new() + }; Plan { options, - root: Dir::default(), + tallies, + root_slots: u64::from(options.label), + open: Vec::new(), + open_path: String::new(), + files: 0, + directories: 0, + bytes: 0, } } @@ -208,34 +246,124 @@ impl Plan { &self.options } - /// Finds or creates the directory at `comps`. - fn dir_mut(&mut self, comps: &[&str]) -> Result<&mut Dir> { - let mut dir = &mut self.root; - for (i, c) in comps.iter().enumerate() { - let name = LongName::new(c)?; - let entry = dir.entries.entry(name.folded()).or_insert_with(|| Entry { - slots: entry_slots(&name) as u64, - node: Node::Dir(Dir::default()), - }); - dir = match &mut entry.node { - Node::Dir(d) => d, - Node::File { .. } => { - let p = format!("/{}", comps[..=i].join("/")); - bail!(ENOTDIR, Detail::Path(p.clone()), "'{}' is a file", p) - } - }; + /// The path of the deepest open directory, as messages show it. + fn deepest_path(&self) -> &str { + if self.open_path.is_empty() { + "/" + } else { + &self.open_path + } + } + + /// The name of the entry `path` names in the deepest open directory. + /// None unless [`path::parent_and_name`] splits `path`, which it does + /// where `path` fits [`path::MAX_PATH`] and its last name is one that + /// [`path::names`] lets through, and the directory `path` is in is the + /// deepest open one, as [`Plan::open_path`] has it. The directories on + /// the way were checked when they were opened. + fn name_in_deepest<'p>(&self, path: &'p str) -> Option<&'p str> { + let (parent, name) = path::parent_and_name(path)?; + (parent == self.open_path).then_some(name) + } + + /// Takes the names off the front of `names` that lead from the root + /// through open directories, and returns how many it took. + fn skip_open<'n>(&self, names: &mut Peekable>) -> usize { + let mut kept = 0; + for dir in &self.open { + let open = &self.open_path[dir.name.clone()]; + if names.next_if_eq(&open).is_none() { + break; + } + kept += 1; + } + kept + } + + /// Takes `slots` more slots in the deepest open directory, the one the + /// next entry goes into. A directory cannot take more than + /// [`MAX_SLOTS`], so beyond that the plan fails with ENOSPC, naming the + /// directory. + fn take_slots(&mut self, slots: u64) -> Result<()> { + let taken = match self.open.last_mut() { + Some(dir) => &mut dir.slots, + None => &mut self.root_slots, + }; + let total = *taken + slots; + if total <= MAX_SLOTS as u64 { + *taken = total; + return Ok(()); + } + let path = self.deepest_path(); + bail!( + ENOSPC, + Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + path: Some(path.to_string()), + }, + "'{}' needs more than the {} entry slots a FAT32 directory holds", + path, + MAX_SLOTS + ) + } + + /// Makes the directory that `dirs` lead to from the root the deepest + /// open one: closes the open directories that are not on the way to + /// it, and opens those on the way that are not open as new + /// directories. + fn descend<'n>(&mut self, dirs: impl Iterator) -> Result<()> { + let mut dirs = dirs.peekable(); + let kept = self.skip_open(&mut dirs); + self.descend_from(kept, dirs) + } + + /// [`Plan::descend`] where the first `kept` open directories are on + /// the way: closes the others, and opens `dirs`, the rest of the way, + /// as new directories. + fn descend_from<'n>(&mut self, kept: usize, mut dirs: impl Iterator) -> Result<()> { + self.close_below(kept); + dirs.try_for_each(|name| self.open_directory(name)) + } + + /// Closes the open directories but the first `kept`: the clusters they + /// take are counted for every cluster size, and they are forgotten. + fn close_below(&mut self, kept: usize) { + let Some(first) = self.open.get(kept) else { + return; + }; + self.open_path.truncate(first.name.start - SEPARATOR.len_utf8()); + for dir in self.open.drain(kept..) { + for tally in &mut self.tallies { + tally.clusters = tally.clusters.saturating_add(tally.directory_clusters(dir.slots)); + } } - Ok(dir) } - /// Adds a file of `size` bytes at `path`, creating parent directories. - /// A file already planned under that name is replaced. - pub fn add_file(&mut self, path: &str, size: u64) -> Result<()> { + /// Opens a new directory named `name` in the deepest open one. + fn open_directory(&mut self, name: &str) -> Result<()> { + self.take_slots(LongName::slots_for(name)? as u64)?; + self.open_path.push(SEPARATOR); + let start = self.open_path.len(); + self.open_path.push_str(name); + self.open.push(OpenDirectory { + name: start..self.open_path.len(), + slots: DOT_ENTRIES, + }); + self.directories += 1; + Ok(()) + } + + /// Adds a file of `size` bytes at `path`, from the root of the volume. + /// Parent directories that are not open are added too. It counts right + /// only in tree order, see the [module documentation](self): out of + /// order, a directory is counted once for every run of its entries. + fn add_file(&mut self, path: &str, size: u64) -> Result<()> { if size > MAX_FILE_SIZE { + let path = path::join("/", path.trim_start_matches(SEPARATOR)); bail!( EFBIG, Detail::TooLarge { - path: Some(path.to_string()), + path: Some(path.clone()), size, maximum: MAX_FILE_SIZE, }, @@ -244,44 +372,50 @@ impl Plan { MAX_FILE_SIZE ); } - let comps = components(path)?; - let Some((last, parents)) = comps.split_last() else { - bail!( - EISDIR, - Detail::Path(path.to_string()), - "'{}' is the root directory", - path - ) - }; - let name = LongName::new(last)?; - let dir = self.dir_mut(parents)?; - let key = name.folded(); - if let Some(Entry { node: Node::Dir(_), .. }) = dir.entries.get(&key) { - bail!(EISDIR, Detail::Path(path.to_string()), "'{}' is a directory", path); - } - let entry = Entry { - slots: entry_slots(&name) as u64, - node: Node::File { size }, + let name = match self.name_in_deepest(path) { + Some(name) => name, + None => { + let mut names = path::names(path)?; + let Some(name) = names.next_back() else { + bail!(EISDIR, Detail::Path("/".to_string()), "'/' is the root directory") + }; + self.descend(names)?; + name + } }; - dir.entries.insert(key, entry); + self.take_slots(LongName::slots_for(name)? as u64)?; + for tally in &mut self.tallies { + tally.clusters = tally.clusters.saturating_add(tally.clusters_for(size)); + } + self.files += 1; + self.bytes = self.bytes.saturating_add(size); Ok(()) } - /// Adds a directory at `path`, creating parents. Existing directories - /// are fine. - pub fn add_dir(&mut self, path: &str) -> Result<()> { - let comps = components(path)?; - self.dir_mut(&comps)?; - Ok(()) + /// Adds a directory at `path`, from the root of the volume. Parent + /// directories that are not open are added too, and a directory that + /// is open is there already. It counts right only in tree order, as + /// [`Plan::add_file`] does. + fn add_dir(&mut self, path: &str) -> Result<()> { + if let Some(name) = self.name_in_deepest(path) { + return self.open_directory(name); + } + let mut names = path::names(path)?.peekable(); + let kept = self.skip_open(&mut names); + // A directory that is open is there already. + if names.peek().is_none() { + return Ok(()); + } + self.descend_from(kept, names) } /// Adds the tree below the open directory `source` under `dest`, the way - /// the populator would copy it. The descriptor is what the caller - /// resolved its path to, with [`crate::host::open_dir`] when it has a - /// path, and may be O_PATH; nothing below it is looked up by path. - /// Returns the entries that would be skipped because they are neither - /// regular files nor directories, relative to `source`. - pub fn add_tree(&mut self, source: BorrowedFd<'_>, dest: &str, follow_symlinks: bool) -> Result> { + /// the populator would copy it with `options`. The descriptor is what + /// the caller resolved its path to, with [`crate::host::open_dir`] when + /// it has a path, and may be O_PATH; nothing below it is looked up by + /// path. Returns the entries that would be skipped because they are + /// neither regular files nor directories, relative to `source`. + pub fn add_tree(&mut self, source: BorrowedFd<'_>, dest: &str, options: &CopyOptions) -> Result> { let md = sys::fstat(source).with_context(|| "failed to stat the source directory")?; if !md.is_dir() { bail!(ENOTDIR, "the source is not a directory"); @@ -301,7 +435,7 @@ impl Plan { Ok(false) } }; - walk_tree(source, dest, follow_symlinks, UnnamableEntry::Fail, &mut visit)?; + walk_tree(source, dest, options.follow_symlinks, UnnamableEntry::Fail, &mut visit)?; Ok(skipped) } @@ -316,12 +450,16 @@ impl Plan { reader.root().require_order(Order::CodePoint)?; let mut triage = ObjectTriage::default(); let mut skipped = 0; + // The path of each object in the volume, the one the assembly + // opens, in one buffer. + let mut path = String::new(); while let Some(object) = reader.next() { let Object::File(object) = object? else { continue; }; - let path = path_in_volume(&object.name); - match triage.decide(&object, flags)? { + let action = triage.decide(&object, flags)?; + path_in_volume_into(&object.name, &mut path); + match action { ObjectAction::Skip(_) => skipped += 1, ObjectAction::Store(EntryKind::Directory) => self.add_dir(&path)?, ObjectAction::Store(EntryKind::File) => { @@ -342,7 +480,7 @@ impl Plan { /// The smallest volume for the plan with a given cluster size. pub fn estimate_for(&self, cluster_size: u32) -> Result { let ss = self.options.sector_size; - if cluster_size == 0 || cluster_size % ss != 0 { + if cluster_size == 0 || cluster_size.checked_rem(ss) != Some(0) { bail!( EINVAL, Detail::InvalidOption("clusterSize"), @@ -351,8 +489,13 @@ impl Plan { ss ); } - let spc = cluster_size / ss; - if !spc.is_power_of_two() || spc > MAX_SECTORS_PER_CLUSTER { + let params = self.options.layout_params(cluster_size); + params.validate()?; + let Some(tally) = self + .tallies + .iter() + .find(|tally| tally.cluster_size == u64::from(cluster_size)) + else { bail!( EINVAL, Detail::InvalidOption("clusterSize"), @@ -360,40 +503,37 @@ impl Plan { cluster_size, MAX_SECTORS_PER_CLUSTER ); - } - let mut totals = Totals::default(); - self.root - .count(true, self.options.label, u64::from(cluster_size), &mut totals)?; - if totals.clusters > u64::from(MAX_CLUSTERS) { + }; + // The open directories are done as far as the plan goes. + let clusters = self + .open + .iter() + .map(|dir| dir.slots) + .chain([self.root_slots]) + .fold(tally.clusters, |clusters, slots| { + clusters.saturating_add(tally.directory_clusters(slots)) + }); + let Some(clusters) = u32::try_from(clusters).ok().filter(|&c| c <= MAX_CLUSTERS) else { bail!( EFBIG, Detail::TooLarge { path: None, - size: totals.clusters * u64::from(cluster_size), + size: clusters.saturating_mul(u64::from(cluster_size)), maximum: u64::from(MAX_CLUSTERS) * u64::from(cluster_size), }, "{} clusters of {} bytes exceed the FAT32 maximum of {}", - totals.clusters, + clusters, cluster_size, MAX_CLUSTERS ); - } - let params = LayoutParams { - sector_size: ss, - sectors_per_cluster: Some(spc), - reserved_sectors: self.options.reserved_sectors, - fats: self.options.fats, - align: self.options.align, - track_sectors: None, - allow_small: self.options.allow_small, }; - let layout = layout::minimal(¶ms, totals.clusters as u32)?; + let layout = layout::minimal(¶ms, clusters)?; Ok(Estimate { layout, - data_clusters: totals.clusters as u32, - files: totals.files, - directories: totals.directories, - bytes: totals.bytes, + data_clusters: clusters, + files: self.files, + directories: self.directories, + bytes: self.bytes, }) } @@ -430,7 +570,14 @@ impl Plan { #[cfg(test)] mod tests { use super::*; + use crate::manifest::{AssembleOptions, DirectorySource, PinnedDirectory, StreamSource}; + use crate::path::MAX_PATH; + use crate::test_util::{TempDir, TempImage}; + use crate::volume::Volume; use crate::ManifestProblem; + use std::os::fd::AsFd; + use std::path::Path; + use uapi16::{Features, FileObject, InodeType, Name, RootObject, Writer}; fn options(ss: u32, cs: Option) -> PlanOptions { PlanOptions { @@ -440,6 +587,25 @@ mod tests { } } + /// The clusters the plan takes for every cluster size from one sector + /// to [`MAX_SECTORS_PER_CLUSTER`] sectors. + fn clusters(plan: &Plan) -> Vec { + let ss = plan.options().sector_size; + (0..CLUSTER_SIZES) + .map(|shift| plan.estimate_for(ss << shift).unwrap().data_clusters) + .collect() + } + + /// The options of a copy that leaves symbolic links alone and replaces + /// what is there. + fn no_links() -> CopyOptions { + CopyOptions { + replace: true, + follow_symlinks: false, + ..CopyOptions::default() + } + } + #[test] fn counts_slots_and_clusters() { let mut p = Plan::new(options(512, Some(512))); @@ -455,14 +621,36 @@ mod tests { // Files: 2 + 10 clusters. assert_eq!(e.data_clusters, 6 + 12); assert_eq!((e.files, e.directories, e.bytes), (2, 5, 1000 + 5120)); - // Replacing a file does not double count it. - p.add_file("/EFI/boot/bootx64.efi", 100).unwrap(); - assert_eq!(p.estimate().unwrap().data_clusters, 6 + 11); - assert_eq!(p.add_file("/EFI", 1).unwrap_err().errno(), EISDIR); - assert_eq!(p.add_file("/EFI/BOOT/BOOTX64.EFI/x", 1).unwrap_err().errno(), ENOTDIR); - assert_eq!(p.add_dir("/EFI/BOOT/BOOTX64.EFI").unwrap_err().errno(), ENOTDIR); - assert_eq!(p.add_file("/x", MAX_FILE_SIZE + 1).unwrap_err().errno(), EFBIG); + // A directory that is open is there; one that was done is counted + // again, and so is a name that comes twice. + p.add_dir("/loader").unwrap(); + assert_eq!(p.estimate().unwrap().data_clusters, 6 + 12); + p.add_file("/loader/entries/a.conf", 1).unwrap(); + assert_eq!(p.estimate().unwrap().data_clusters, 6 + 12 + 1); + p.add_file("/EFI/Linux/linux-6.12.efi", 512 * 10).unwrap(); + assert_eq!(p.estimate().unwrap().data_clusters, 8 + 12 + 1 + 10); + assert_eq!(p.add_file("/", 1).unwrap_err().errno(), EISDIR); + for path in ["/x", "x"] { + let e = p.add_file(path, MAX_FILE_SIZE + 1).unwrap_err(); + assert_eq!(e.errno(), EFBIG); + assert!( + matches!(e.detail(), Some(Detail::TooLarge { path: Some(p), .. }) if p == "/x"), + "{:?}", + e + ); + } assert_eq!(p.add_file("/bad:name", 1).unwrap_err().errno(), EINVAL); + assert_eq!(p.add_dir("/bad:name/x").unwrap_err().errno(), EINVAL); + assert_eq!(p.add_file("/EFI/../x", 1).unwrap_err().errno(), EINVAL); + // A last name of "." or ".." is the path's, not the directory's. + for dots in [".", ".."] { + let path = format!("/{}", dots); + let refused = format!("path '{}' contains a '{}' component", path, dots); + let e = Plan::new(options(512, None)).add_dir(&path).unwrap_err(); + assert_eq!((e.errno(), e.to_string()), (EINVAL, refused.clone())); + let e = Plan::new(options(512, None)).add_file(&path, 1).unwrap_err(); + assert_eq!((e.errno(), e.to_string()), (EINVAL, refused)); + } } #[test] @@ -488,6 +676,36 @@ mod tests { assert_eq!(p.estimate().unwrap().data_clusters, 2); } + /// The entry that a directory has no slots left for fails the plan, + /// which names the directory. + #[test] + fn full_directories_are_refused() { + let full = |path: &str| Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + path: Some(path.to_string()), + }; + // The dot entries and 65534 short names fill a directory. + let mut p = Plan::new(options(512, None)); + let names = MAX_SLOTS - DOT_ENTRIES as usize; + for i in 0..names { + p.add_file(&format!("/d/F{}", i), 0).unwrap(); + } + let e = p.add_file(&format!("/d/F{}", names), 0).unwrap_err(); + assert_eq!(e.errno(), ENOSPC); + assert_eq!(e.detail(), Some(&full("/d"))); + assert_eq!(p.estimate().unwrap().files, names as u64); + // The label and 65535 short names fill the root. + let mut p = Plan::new(PlanOptions { + label: true, + ..options(512, None) + }); + for i in 0..MAX_SLOTS - 1 { + p.add_file(&format!("/F{}", i), 0).unwrap(); + } + let e = p.add_dir("/d").unwrap_err(); + assert_eq!((e.errno(), e.detail()), (ENOSPC, Some(&full("/")))); + } + #[test] fn picks_the_smallest_cluster_size() { let mut p = Plan::new(options(512, None)); @@ -508,6 +726,17 @@ mod tests { let other = p.estimate_for(spc * 512).unwrap(); assert!(other.size() >= e.size()); } + for cs in [0, 256, 768, 3 * 512, 256 * 512] { + assert_eq!(p.estimate_for(cs).unwrap_err().errno(), EINVAL, "{}", cs); + } + for cs in [0, 256, 768] { + assert_eq!( + p.estimate_for(cs).unwrap_err().to_string(), + format!("cluster size {} is not a multiple of the sector size 512", cs) + ); + } + let p = Plan::new(options(1000, None)); + assert_eq!(p.estimate().unwrap_err().errno(), EINVAL); } #[test] @@ -522,6 +751,452 @@ mod tests { assert!(e.size() > 256 << 20); } + /// A tree in tree order: every directory before its entries, and its + /// entries sorted by the bytes of their names right after it, which is + /// also the code point order of a manifest. None is a directory, + /// Some(size) a file. No two names in a directory differ in case only. + fn synthetic_tree() -> Vec<(String, Option)> { + enum Node { + File(String, u64), + Dir(String, Vec), + } + const SIZES: [u64; 15] = [ + 0, + 1, + 511, + 512, + 513, + 1023, + 4095, + 4096, + 4097, + 32767, + 32768, + 32769, + 65537, + 100_000, + 1 << 20, + ]; + // Names of every shape the slots depend on: 8.3 in upper and in + // lower case, mixed case, spaces, a character outside ASCII, long + // names of up to 255 units, more than one dot. + fn name(i: usize) -> String { + match i % 7 { + 0 => format!("F{:05}.BIN", i), + 1 => format!("f{:05}.txt", i), + 2 => format!("Mixed{}.Txt", i), + 3 => format!("{}{}", "long name ".repeat(i % 5 + 1), i), + 4 => format!("\u{fc}{}.dat", i), + 5 => format!("{}{}", "x".repeat((13 * (i % 19 + 1)).min(250)), i), + _ => format!("{}.tar.gz", i), + } + } + fn files(from: usize, count: usize) -> Vec { + (from..from + count) + .map(|i| Node::File(name(i), SIZES[i % SIZES.len()])) + .collect() + } + fn emit(prefix: &str, mut nodes: Vec, out: &mut Vec<(String, Option)>) { + let key = |node: &Node| match node { + Node::File(name, _) | Node::Dir(name, _) => name.clone().into_bytes(), + }; + nodes.sort_by_key(key); + for node in nodes { + match node { + Node::File(name, size) => out.push((format!("{}{}", prefix, name), Some(size))), + Node::Dir(name, children) => { + let path = format!("{}{}", prefix, name); + out.push((path.clone(), None)); + emit(&format!("{}/", path), children, out); + } + } + } + } + // A chain of 26 directories, each with two files. + let mut chain = Node::Dir("deep25".into(), files(5000, 2)); + for level in (0..25).rev() { + let mut inside = files(5100 + 2 * level, 2); + inside.push(chain); + chain = Node::Dir(format!("deep{:02}", level), inside); + } + let mut root = files(0, 40); + root.extend([ + chain, + // 700 files: many clusters of entries for every cluster size. + Node::Dir("many".into(), files(1000, 700)), + // 14 short names and the dot entries fill a cluster of 512 + // bytes, 15 need a second one. + Node::Dir( + "SIXTEEN".into(), + (0..14).map(|i| Node::File(format!("S{:02}", i), 1)).collect(), + ), + Node::Dir( + "SEVENTEEN".into(), + (0..15).map(|i| Node::File(format!("S{:02}", i), 1)).collect(), + ), + Node::Dir("empty".into(), Vec::new()), + Node::Dir( + "Mixed Dir".into(), + vec![ + Node::Dir("EMPTY".into(), Vec::new()), + Node::Dir("sub".into(), files(3000, 30)), + Node::File("x".into(), 3), + ], + ), + ]); + let mut out = Vec::new(); + emit("", root, &mut out); + out + } + + /// Creates `tree` below `dir`: its directories, and its files as sparse + /// files of their sizes. + fn make_tree(dir: &Path, tree: &[(String, Option)]) { + for (path, size) in tree { + let path = dir.join(path); + match size { + Some(size) => std::fs::File::create(&path).unwrap().set_len(*size).unwrap(), + None => std::fs::create_dir(&path).unwrap(), + } + } + } + + /// A manifest of `tree` that gives the size of every file. + fn manifest_of(tree: &[(String, Option)]) -> Vec { + let mut root = RootObject::default(); + root.features = Some(Features::SIZE); + root.order = Some(Order::CodePoint); + let mut writer = Writer::begin(Vec::new(), &root).unwrap(); + for (name, size) in tree { + let mut object = FileObject::new(Name::new(name.as_str()).unwrap()); + match size { + Some(size) => object.size = Some(*size), + None => object.inode_type = InodeType::Directory, + } + writer.file(&object).unwrap(); + } + writer.finish().unwrap() + } + + /// What the planner said for the synthetic tree when it kept every name + /// of a directory, for 512 and 4096 byte sectors and every number of + /// sectors per cluster, with the entries below the root, and below + /// /below/here. + const SYNTHETIC_512: [u32; CLUSTER_SIZES] = [140547, 70467, 35485, 18021, 9317, 4992, 2830, 1749]; + const SYNTHETIC_4096: [u32; CLUSTER_SIZES] = [18021, 9317, 4992, 2830, 1749, 1208, 992, 884]; + const BELOW_512: [u32; CLUSTER_SIZES] = [140549, 70469, 35487, 18023, 9319, 4994, 2832, 1751]; + const BELOW_4096: [u32; CLUSTER_SIZES] = [18023, 9319, 4994, 2832, 1751, 1210, 994, 886]; + /// And the smallest volumes it found, with their cluster sizes. + const BEST_512: (u64, u32) = (72739840, 1024); + const BEST_4096: (u64, u32) = (74092544, 4096); + const BEST_BELOW_512: u64 = 72741888; + const BEST_BELOW_4096: u64 = 74100736; + + /// Checks a plan of the synthetic tree against the planner that kept + /// every name. + fn agrees(plan: &Plan, expected: &[u32; CLUSTER_SIZES], best: u64, directories: u64) { + assert_eq!(clusters(plan), expected); + let e = plan.estimate().unwrap(); + assert_eq!(e.size(), best); + assert_eq!((e.files, e.directories, e.bytes), (852, directories, 71680534)); + } + + #[test] + fn agrees_with_the_planner_that_kept_every_name() { + let tree = synthetic_tree(); + assert_eq!(tree.len(), 885); + for (ss, label, expected, best) in [ + (512, false, SYNTHETIC_512, BEST_512), + (512, true, SYNTHETIC_512, BEST_512), + (4096, false, SYNTHETIC_4096, BEST_4096), + (4096, true, SYNTHETIC_4096, BEST_4096), + ] { + let mut plan = Plan::new(PlanOptions { + label, + ..options(ss, None) + }); + for (path, size) in &tree { + let path = format!("/{}", path); + match size { + Some(size) => plan.add_file(&path, *size).unwrap(), + None => plan.add_dir(&path).unwrap(), + } + } + agrees(&plan, &expected, best.0, 33); + assert_eq!(plan.estimate().unwrap().layout.cluster_size(), best.1); + } + } + + #[test] + fn walks_a_tree_in_tree_order() { + let tmp = TempDir::new("plan-walk"); + make_tree(tmp.path(), &synthetic_tree()); + let dir = crate::host::open_dir(tmp.path()).unwrap(); + for (ss, label, expected, below, best, best_below) in [ + (512, false, SYNTHETIC_512, BELOW_512, BEST_512.0, BEST_BELOW_512), + (4096, true, SYNTHETIC_4096, BELOW_4096, BEST_4096.0, BEST_BELOW_4096), + ] { + let plan_options = PlanOptions { + label, + ..options(ss, None) + }; + let mut plan = Plan::new(plan_options); + assert!(plan.add_tree(dir.as_fd(), "/", &no_links()).unwrap().is_empty()); + agrees(&plan, &expected, best, 33); + // The directories on the way to the destination are the same + // however its path is spelled. + for dest in ["/below/here", "below/here", "//below//here/"] { + let mut plan = Plan::new(plan_options); + plan.add_tree(dir.as_fd(), dest, &no_links()).unwrap(); + agrees(&plan, &below, best_below, 35); + } + } + } + + #[test] + fn plans_a_manifest_while_it_is_read() { + let manifest = manifest_of(&synthetic_tree()); + let mut plan = Plan::new(options(512, None)); + let mut reader = Reader::open(&manifest[..]).unwrap(); + assert_eq!( + plan.add_records(&mut reader, AssembleFlags::SKIP_UNSUPPORTED).unwrap(), + 0 + ); + agrees(&plan, &SYNTHETIC_512, BEST_512.0, 33); + } + + /// A volume formatted with `options` and the plan's cluster size, of the + /// size the plan gives. + fn planned_volume(plan: &Plan, options: &FormatOptions) -> (TempImage, Volume) { + let estimate = plan.estimate().unwrap(); + // Clusters to spare would hide a plan that counts too few. + assert_eq!(estimate.layout.clusters, estimate.data_clusters); + let mut options = options.clone(); + estimate.apply(&mut options); + let image = TempImage::new(estimate.size()); + crate::format::format(&image.device(), &options).unwrap(); + let volume = Volume::open(image.device()).unwrap(); + (image, volume) + } + + /// Plans `tree`, which `dir` holds, and puts it into volumes of the + /// planned sizes, formatted with `options`: walked and copied from + /// `dir`, and planned from a manifest of it and assembled with the + /// contents in `dir`. Both replace what is there. + fn fill_planned(dir: &Path, tree: &[(String, Option)], options: &FormatOptions) -> [(TempImage, Volume); 2] { + let plan_options = PlanOptions::from_format_options(options, None).unwrap(); + let source = crate::host::open_dir(dir).unwrap(); + let mut plan = Plan::new(plan_options); + plan.add_tree(source.as_fd(), "/", &no_links()).unwrap(); + let (copied_image, mut copied) = planned_volume(&plan, options); + copied.copy_tree(source.as_fd(), "/", &no_links()).unwrap(); + + let manifest = manifest_of(tree); + let mut plan = Plan::new(plan_options); + plan.add_records(&mut Reader::open(&manifest[..]).unwrap(), AssembleFlags::REPLACE) + .unwrap(); + let (assembled_image, mut assembled) = planned_volume(&plan, options); + let mut contents = DirectorySource::new(PinnedDirectory::new(source)); + let replacing = AssembleOptions { + flags: AssembleFlags::REPLACE, + ..AssembleOptions::default() + }; + assembled + .assemble(&mut Reader::open(&manifest[..]).unwrap(), &mut contents, &replacing) + .unwrap(); + [(copied_image, copied), (assembled_image, assembled)] + } + + /// The synthetic tree fills a volume of the size its plan gives, copied + /// from a walk and assembled from a manifest, to the last cluster. + #[test] + fn the_planned_size_is_filled() { + let tmp = TempDir::new("plan-fill"); + let tree = synthetic_tree(); + make_tree(tmp.path(), &tree); + for (sector_size, cluster_size, label) in [ + (512, None, None), + (512, Some(512), Some("PLANNED")), + (4096, None, Some("PLANNED")), + ] { + let options = FormatOptions { + sector_size: Some(sector_size), + cluster_size, + label: label.map(String::from), + allow_small: true, + ..FormatOptions::default() + }; + for (_image, volume) in fill_planned(tmp.path(), &tree, &options) { + assert_eq!(volume.free_clusters(), 0, "{:?}", options); + } + } + } + + /// Names that FAT does not tell apart are two names to the plan: the + /// file A.TXT and a.txt, which replaces it, and the directory EFI and + /// efi, whose entries go into it. Replacing, the volume of the planned + /// size holds them and keeps the clusters of A.TXT and of efi free. + #[test] + fn names_fat_does_not_tell_apart() { + let tree: Vec<(String, Option)> = [ + ("A.TXT", Some(3000)), + ("EFI", None), + ("EFI/X", Some(1)), + ("a.txt", Some(1000)), + ("efi", None), + ("efi/Y", Some(1)), + ] + .into_iter() + .map(|(path, size)| (path.to_string(), size)) + .collect(); + let tmp = TempDir::new("plan-folded"); + make_tree(tmp.path(), &tree); + let options = FormatOptions { + sector_size: Some(512), + cluster_size: Some(512), + allow_small: true, + ..FormatOptions::default() + }; + let manifest = manifest_of(&tree); + let plan = |flags| { + let mut plan = Plan::new(PlanOptions::from_format_options(&options, None).unwrap()); + plan.add_records(&mut Reader::open(&manifest[..]).unwrap(), flags) + .unwrap(); + plan + }; + for flags in [AssembleFlags::REPLACE, AssembleFlags::NONE] { + let e = plan(flags).estimate().unwrap(); + // The root, EFI and efi take a cluster each, A.TXT 6, X 1, + // a.txt 2 and Y 1. + assert_eq!((e.data_clusters, e.layout.clusters), (3 + 10, 3 + 10)); + assert_eq!((e.files, e.directories), (4, 2)); + } + for (_image, volume) in fill_planned(tmp.path(), &tree, &options) { + // The 6 clusters of A.TXT, which a.txt replaced, and the one of + // efi, whose entries went into EFI. + assert_eq!(volume.free_clusters(), 6 + 1); + assert_eq!(volume.metadata("/A.TXT").unwrap().size, 1000); + assert_eq!(volume.read_dir("/efi").unwrap().len(), 2); + } + // Without replacing, the assembly fails at a.txt, which the plan + // took. + let (_image, mut volume) = planned_volume(&plan(AssembleFlags::NONE), &options); + let mut contents = DirectorySource::new(PinnedDirectory::new(crate::host::open_dir(tmp.path()).unwrap())); + let not_replacing = AssembleOptions { + flags: AssembleFlags::NONE, + ..AssembleOptions::default() + }; + let e = volume + .assemble(&mut Reader::open(&manifest[..]).unwrap(), &mut contents, ¬_replacing) + .unwrap_err(); + assert_eq!(e.errno(), EEXIST); + } + + /// A file and a directory under names that FAT does not tell apart + /// pass the plan, and the assembly fails on the second one, replacing + /// or not: ENOTDIR for the directory after the file, EISDIR for the + /// file after the directory. + #[test] + fn a_file_and_a_directory_under_one_name() { + for (tree, errno) in [ + ([("A", Some(1)), ("a", None), ("a/x", Some(1))], ENOTDIR), + ([("A", None), ("A/x", Some(1)), ("a", Some(1))], EISDIR), + ] { + let tree: Vec<(String, Option)> = + tree.into_iter().map(|(path, size)| (path.to_string(), size)).collect(); + let manifest = manifest_of(&tree); + for flags in [AssembleFlags::REPLACE, AssembleFlags::NONE] { + let mut plan = Plan::new(options(512, Some(512))); + plan.add_records(&mut Reader::open(&manifest[..]).unwrap(), flags) + .unwrap(); + let (_image, mut volume) = crate::test_util::volume(8 << 20, 512, 512); + let options = AssembleOptions { + flags, + ..AssembleOptions::default() + }; + let e = volume + .assemble( + &mut Reader::open(&manifest[..]).unwrap(), + &mut StreamSource::new(&[1u8, 1][..]), + &options, + ) + .unwrap_err(); + assert_eq!(e.errno(), errno, "{:?} {:?}", tree, e); + } + } + } + + /// The plan holds a path to the limit of 4095 bytes as the assembly + /// does, the slash in front of the name included: a name of 4094 bytes + /// is planned and assembled, one of 4095 bytes neither. + #[test] + fn paths_at_the_limit() { + // 15 directories of 255 byte names take 3840 bytes with a slash + // after each, the name of the file the rest. + let mut dirs = String::new(); + let mut tree = Vec::new(); + for i in 0..15 { + dirs.push_str(&format!("{}{:x}", "d".repeat(254), i)); + tree.push((dirs.clone(), None)); + dirs.push(SEPARATOR); + } + for length in [MAX_PATH - 1, MAX_PATH] { + let mut tree = tree.clone(); + tree.push((format!("{}{}", dirs, "f".repeat(length - dirs.len())), Some(0))); + assert_eq!(tree.last().unwrap().0.len(), length); + let manifest = manifest_of(&tree); + let planned = Plan::new(options(512, Some(512))) + .add_records(&mut Reader::open(&manifest[..]).unwrap(), AssembleFlags::NONE) + .map(drop); + let (_image, mut volume) = crate::test_util::volume(8 << 20, 512, 512); + let assembled = volume + .assemble( + &mut Reader::open(&manifest[..]).unwrap(), + &mut StreamSource::new(std::io::empty()), + &AssembleOptions::default(), + ) + .map(drop); + if length < MAX_PATH { + assert!(planned.is_ok() && assembled.is_ok(), "{:?} {:?}", planned, assembled); + } else { + assert_eq!(planned.unwrap_err().errno(), ENAMETOOLONG); + assert_eq!(assembled.unwrap_err().errno(), ENAMETOOLONG); + } + } + } + + /// A directory whose entries come in two runs, under two names FAT does + /// not tell apart, is two directories to the plan, each held to the + /// limit of entry slots on its own. In one run, the plan fails at the + /// entry that the directory has no slots left for, and names the + /// directory. + #[test] + fn directories_in_two_runs() { + // A long name of 255 characters takes 21 slots, so either run of + // 1600 fits a directory, both do not. + let run = |dir: &'static str, files: Range| { + std::iter::once((dir.to_string(), None)) + .chain(files.map(move |i| (format!("{}/{:0>255}", dir, i), Some(0)))) + }; + let plan = |tree: Vec<(String, Option)>| { + let manifest = manifest_of(&tree); + let mut plan = Plan::new(options(512, None)); + plan.add_records(&mut Reader::open(&manifest[..]).unwrap(), AssembleFlags::REPLACE) + .map(|_| plan) + }; + let split = plan(run("EFI", 0..1600).chain(run("efi", 1600..3200)).collect()).unwrap(); + assert_eq!(split.estimate().unwrap().directories, 2); + let e = plan(run("EFI", 0..3200).collect()).unwrap_err(); + assert_eq!(e.errno(), ENOSPC); + assert_eq!( + e.detail(), + Some(&Detail::NoSpace { + reason: NoSpaceReason::DirectoryEntries, + path: Some("/EFI".to_string()), + }) + ); + } + #[test] fn manifests_leave_out_what_an_assembly_leaves_out() { let records = concat!( diff --git a/tests/cli.rs b/tests/cli.rs index 69e960f..653a828 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -952,6 +952,53 @@ fn too_small_volumes_fail_cleanly() { assert_eq!(ok(&bin, &["cat", l, "/sub/c.txt"]), "last\n"); } +/// A plan does not compare names. The entries of a directory under two +/// names that FAT does not tell apart go into one directory. The plan holds +/// the entries under each name to the 65536 entries of a FAT directory on +/// their own, and only the write sees them all in one directory. In two +/// runs of 1600 names of 255 characters, which take 21 entries each, the +/// plan passes and `assemble` fails. In one run the plan fails. +#[test] +fn directories_under_two_names_fill_up_when_written() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + let manifest = |runs: &[(&str, std::ops::Range)]| { + let mut text = String::from( + "\x1e{\"features\":[\"size\"],\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + ); + for (name, files) in runs { + text.push_str(&format!("\x1e{{\"name\":\"{}\",\"type\":\"dir\"}}\n", name)); + for i in files.clone() { + text.push_str(&format!("\x1e{{\"name\":\"{}/{:0>255}\",\"size\":0}}\n", name, i)); + } + } + text.push_str("\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"); + text + }; + let split = root.join("split.manifest"); + fs::write(&split, manifest(&[("EFI", 0..1600), ("efi", 1600..3200)])).unwrap(); + let s = split.to_str().unwrap(); + ok(&bin, &["assemble", "--plan", "--manifest", s]); + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + fails( + &bin, + &["assemble", "--create", "--manifest", s, a, "-"], + "directory is full", + ); + let whole = root.join("whole.manifest"); + fs::write(&whole, manifest(&[("EFI", 0..3200)])).unwrap(); + fails( + &bin, + &["assemble", "--plan", "--manifest", whole.to_str().unwrap()], + "'/EFI' needs more than the 65536 entry slots a FAT32 directory holds", + ); +} + /// Paths on the host are taken as the bytes they are, UTF-8 or not. Paths /// inside the volume are Unicode, and one that is not UTF-8 is refused. #[test] diff --git a/tests/reference.rs b/tests/reference.rs index 6fde1de..54e9a24 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -386,7 +386,11 @@ fn planner_is_exact() { ..FormatOptions::default() }; let mut plan = fat::plan::Plan::new(fat::plan::PlanOptions::from_format_options(&options, None).unwrap()); - plan.add_tree(source(tree.path()).as_fd(), "/", false).unwrap(); + let no_links = CopyOptions { + follow_symlinks: false, + ..CopyOptions::default() + }; + plan.add_tree(source(tree.path()).as_fd(), "/", &no_links).unwrap(); let estimate = plan.estimate().unwrap(); estimate.apply(&mut options); From c9b15b00cb830a06d0728cc7fc096cffcc8f9370 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 14/19] bench: add a workload that reads a large manifest The manifests bench/compare.sh hands to the binaries are the ones of the ESP, a few dozen records each. A slower reader or planner wouldn't show up in what bench/compare.py reports. So let's add plan/wide-manifest: assemble --plan on the manifest of the wide tree, ten thousand records, with nothing else to do. The head binary writes that manifest once with the other inputs, and an input directory that doesn't have it yet is built again. Signed-off-by: Christian Brauner (Amutable) --- HACKING.md | 19 +++++++++++++------ bench/compare.sh | 5 ++++- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/HACKING.md b/HACKING.md index 47c97ca..cdec898 100644 --- a/HACKING.md +++ b/HACKING.md @@ -225,12 +225,19 @@ bench/compare.sh compares two ufat binaries, BASE and HEAD: bench/compare.sh BASE HEAD bench/compare.py "$BENCH_DIR/out" -It runs ten small workloads: assemble, populate, check and manifest with -trees of 10000 files and with an ESP, and two Varlink calls. Every -workload runs once under cachegrind, which counts the instructions, and -once under strace, which counts the system calls. Then it runs nine -times with each binary, alternating, for the wall time, the peak RSS and -the bytes read and written. It needs valgrind and strace. +It runs eleven small workloads: assemble, populate, check and manifest +with trees of 10000 files and with an ESP, a plan from the manifest of +such a tree, and two Varlink calls. Every workload runs once under +cachegrind, which counts the instructions, and once under strace, which +counts the system calls. Then it runs nine times with each binary, +alternating, for the wall time, the peak RSS and the bytes read and +written. It needs valgrind and strace. + +HEAD writes the manifests of the workloads that read a manifest, +assemble/esp-stream, plan/wide-manifest and varlink/Assemble-esp-stream, +and BASE reads them too. So BASE has to read what HEAD writes. That +holds as long as both binaries have the same manifest reader. Against an +older BASE those workloads can fail. bench/compare.py prints the results of HEAD and their change from BASE. It fails when HEAD exceeds BASE on a workload by more than a limit: diff --git a/bench/compare.sh b/bench/compare.sh index e84210a..63b5946 100755 --- a/bench/compare.sh +++ b/bench/compare.sh @@ -71,7 +71,7 @@ RAW=$OUT/compare.tsv # valgrind. Inputs depend on FILES and UKI only, and are built once. make_inputs() { local stamp=$IN/.ready-$FILES-$UKI - [ -e "$stamp" ] && return + [ -e "$stamp" ] && [ -e "$IN/wide.manifest" ] && return say "building inputs under $IN (FILES=$FILES UKI=$UKI)" rm -rf "$IN"; mkdir -p "$IN" # A subshell that stops at the first failure, so the stamp is only set @@ -116,6 +116,8 @@ make_inputs() { tr '\036' '\n' < "$IN/esp.manifest" | grep '"size":' | sed -E 's/.*"name":"([^"]*)".*/\1/' | while IFS= read -r n; do cat "$e/$n"; done > "$IN/esp.blob" [ -s "$IN/esp.blob" ] || { say "empty blob"; exit 1; } + # The manifest of the wide tree, for a plan that reads nothing else. + "$HEAD" manifest "$IN/wide" > "$IN/wide.manifest" # An empty file system of 256 MiB, the target of populate, and one # holding the wide tree, the input of check. Both are made once, by # the head binary, so that both binaries see the same bytes. @@ -153,6 +155,7 @@ workloads() { $r check/wide nothing -- @UFAT@ check "$IN/wide.img" $r manifest/esp nothing -- @UFAT@ manifest "$IN/esp" $r manifest/wide nothing -- @UFAT@ manifest "$IN/wide" + $r plan/wide-manifest nothing -- @UFAT@ assemble --plan --sector-size 512 --manifest "$IN/wide.manifest" $r varlink/Populate-wide fresh_image --ufat @UFAT@ --method org.uapi-group.FileSystem.Populate \ --fd "rw:$IMG/target.img" --fd "$IN/wide" --params "$POPULATE" $r varlink/Assemble-esp-stream empty_image --ufat @UFAT@ --method org.uapi-group.FileSystem.Assemble \ From 0efb1bf43897f7609fb8e1870b09aae057281cc0 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 15/19] ufat: size volumes to fit only when asked to Currently assemble sizes a file system to fit its content unless --size is given, and even with --size it plans the content first to see that it fits. Now that a manifest is read while its content is written, a plan means reading the manifest twice. A regular file can be read twice but a pipe can't, so assemble with a SOURCE refuses a manifest that comes through a pipe altogether. Let's make sizing to fit opt-in instead, like repart's Minimize=. With --minimize, minimize in the FormatOptions of Assemble, the file system is as small as its content allows, and a size given is the most it may take. Without it the file system takes the size given, or else all of the image behind the offset, the way mkfs.fat does. An empty image without a size fails with SizeRequired. --fit and --manifest without a SOURCE take the size given as well, which the --fit directory or what the manifest describes has to fit, and without one they make the file system as small as that allows. A file system that takes the size given gets the cluster size the formatter picks for that size, also when --fit or --manifest plans its content first. So the plan uses that cluster size, and only a file system sized to fit is formatted with the cluster size of its plan. Taking the plan's cluster size for a size given would turn --size 1G --fit DIR into 512 byte clusters where --size 1G alone gets 4 KiB ones, and above about 128 GiB 512 byte clusters are more than FAT32 can count. Whether the content fits that file system has to be counted in clusters. The formatter's layout doesn't grow with the size in every step: one sector more can take one more sector for each FAT and leave one cluster less. With 512 byte clusters 66590 sectors hold 65534 clusters, and 66591 sectors only 65533. So --fit and --manifest compare the clusters the plan counts with the clusters of the file system of the size given, and say so in clusters when the content doesn't fit. A file system sized to fit is made at the size of its plan, which holds what the plan counts, so with --minimize comparing sizes is fine. assemble --plan --size has to follow, since it answers for assemble with the same options. Until now both planned with the cluster size of the smallest file system. Now assemble --size gets the cluster size the formatter picks for that size, so --plan --size plans with that one and counts clusters as well. With --minimize it compares the smallest size with --size as before. Without --minimize a SOURCE isn't planned. Its content is written right away, and content that doesn't fit fails with ENOSPC while it is written and leaves the file system marked as not cleanly unmounted. So a manifest can come through a pipe again. Only --minimize with a SOURCE plans before it writes, so only it needs the manifest in a regular file. It refuses a pipe before it reads anything from it, and over Varlink so does minimize. What can be found before the image is touched still is. A size no file system of the options fits in, such as --size 1M, is refused before the image grows, so a file that --create made is removed again. So is a size of 0, whether it is given or what an --offset at the end of the image leaves. SizeRequired is only for an empty image and no size at all. The service checks the block size against the sector size before it sizes anything, also for a size given. Both front ends walk a tree under unsupported fail before they touch the image, in the plan with minimize and on its own without it. An --offset beyond the end of the image without a size says so. --hash hashes the file system that was written, also where --size is only the most --minimize may take. Whether a manifest is planned before its content is written and how the file system is sized are one decision now, util::SizeMode, so the two can't disagree. Over Varlink Assemble only has a planning phase with minimize. Its reply said in exact whether the size was planned, which the caller knows from its own call, so exact goes. Capabilities.sizeToFit says in the words of repart's Minimize= what a plan finds: best, the smallest size, for vfat, or guess, a size with room to spare. That changes org.uapi-group.FileSystem incompatibly: exact goes, SizeToFit's values are renamed and without minimize an omitted size no longer means sized to fit, which is only fine because the interface isn't released yet. The README, the Varlink documentation and interface, the help and the benchmark scripts follow. The fuzzers pass --minimize where they relied on the plan, and they get cases that plan nothing: a --size, a manifest through a pipe, and an Assemble over Varlink with image.size. So a manifest that breaks while the volume is written is fuzzed as well. bench/compare.sh gives the file systems it assembles a size, so that a binary that sizes to fit on its own and one that doesn't make the same ones. Signed-off-by: Christian Brauner (Amutable) --- README.md | 49 ++- bench/compare.sh | 6 +- bench/run.sh | 8 +- docs/org.uapi-group.FileSystem.varlink | 71 ++-- docs/varlink.md | 63 ++-- src/bin/ufat/cli.rs | 173 ++++++---- src/bin/ufat/service.rs | 117 ++++--- src/bin/ufat/util.rs | 302 +++++++++++++---- tests/cli.rs | 418 ++++++++++++++++++++---- tests/fuzz/mutate.py | 67 +++- tests/fuzz/repro/quadratic-directory.py | 2 +- tests/fuzz/targeted.py | 20 +- tests/fuzz/varlink_fuzz.py | 16 +- tests/reference.rs | 3 +- tests/varlink.rs | 193 ++++++----- 15 files changed, 1089 insertions(+), 419 deletions(-) diff --git a/README.md b/README.md index f3fa812..fdc769a 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,12 @@ This recording uses the tool to make, change and check an ESP image: Make an image that fits a directory tree and copy the tree into it: - ufat assemble --create --label ESP esp.img tree/ + ufat assemble --create --minimize --label ESP esp.img tree/ + +Without `--minimize` the file system takes the size given with `--size`, +or the whole image, as mkfs.fat does: + + ufat assemble --create --size 1G --label ESP esp.img tree/ Copy more files into an existing file system, a directory tree or one file: @@ -95,7 +100,7 @@ The commands are: | Command | What it does | |---|---| -| `assemble IMAGE [SOURCE]` | Create a file system sized to fit SOURCE or what `--manifest` describes, and fill it with that. Without a SOURCE, create an empty file system. | +| `assemble IMAGE [SOURCE]` | Create a file system and fill it with SOURCE or what `--manifest` describes. Without a SOURCE, create an empty file system. | | `assemble --plan [SOURCE]` | Print the smallest file system size that holds SOURCE or what `--manifest` describes. | | `populate IMAGE [SOURCE]` | Copy a directory tree, one file, or what `--manifest` describes into an existing file system. Without a SOURCE, create a directory. | | `remove IMAGE PATH...` | Remove files and empty directories. `-r` removes directories with everything in them. | @@ -121,6 +126,8 @@ The most common ones: - `--path PATH` copies the directory tree below PATH instead of the root. For `populate` it is also the path of a single file, or the directory to create. +- `--minimize` makes the file system of `assemble` as small as its + content allows. A `--size` is then the most it may take. - `--no-replace` fails instead of replacing files that exist. - `--unsupported fail` fails on files FAT cannot store, such as FIFOs and device nodes. By default they are left out with a message. @@ -161,8 +168,8 @@ derived from the time stamp and the label instead of drawn at random. `assemble`, `populate` and `assemble --plan` can work from a UAPI.16 manifest instead of a tree: - ufat assemble --create --manifest m.json esp.img tree/ - ufat assemble --create --manifest m.json esp.img - < contents + ufat assemble --create --minimize --manifest m.json esp.img tree/ + ufat assemble --create --minimize --manifest m.json esp.img - < contents ufat assemble --plan --manifest m.json With `--manifest`, the one SOURCE is the directory that the manifest's @@ -177,14 +184,15 @@ paths from the root of the file system, so `--path` does not apply. contents then have to come from a directory. ufat reads a manifest one record at a time, and writes each file and -directory when its record comes. So `populate` takes a manifest of any -size, also through a pipe. To size the file system to fit, ufat reads -the manifest once before it writes anything. So `assemble` with a SOURCE -needs the manifest in a regular file. `assemble --plan` and `assemble` -without a SOURCE read the manifest only once, so they take one through a -pipe as well. While it sizes, ufat keeps the path of the deepest open -directory, and a count for each directory on that path. Memory use does -not grow with the manifest. +directory when its record comes. So a manifest of any size can come +through a pipe on standard input, with `--manifest -`. A `--manifest` +PATH names a regular file. To size the file system to fit, ufat reads +the manifest once before it writes anything. So `--minimize` with a +SOURCE needs the manifest in a regular file, also on standard input. +`assemble --plan` and `assemble` without a SOURCE read the manifest only +once, so they take one through a pipe as well. While it sizes, ufat +keeps the path of the deepest open directory, and a count for each +directory on that path. Memory use does not grow with the manifest. The objects of a manifest have to be in code point order: every directory before what is in it, and the names of a directory sorted by @@ -260,10 +268,19 @@ smaller volumes. ufat never creates a volume below that limit: | 4096 bytes | 269045760 bytes, about 257 MiB | `ufat assemble --plan` prints the smallest size for a tree or a manifest. -`assemble` creates an image of exactly that size unless `--size` is given. -An existing image file is grown when needed and never shrunk. A smaller -volume made by another tool can still be read, filled and checked. -`ufat check` reports that it is below the minimum. +`assemble --minimize` creates a file system of exactly that size, and +fails when it is more than `--size`. Without `--minimize` the file system +takes `--size`, or the whole image, and an empty image without `--size` +is refused. An empty file system made with `--fit DIR`, or with +`--manifest` and no SOURCE, takes `--size` too, which DIR or what the +manifest describes has to fit. Without `--size` it gets the smallest size +that holds them. `--plan` with `--size` answers for `assemble` with the +same options: without `--minimize` the content has to fit a file system +of that size, in the clusters that size gets, and with `--minimize` the +smallest file system has to fit in `--size`. An existing image file is +grown when needed and never shrunk. A smaller volume made by another +tool can still be read, filled and checked. `ufat check` reports that it +is below the minimum. A plan does not compare names. Two names that FAT does not tell apart are two names to the plan: names that differ in case only, such as diff --git a/bench/compare.sh b/bench/compare.sh index 63b5946..b0d2136 100755 --- a/bench/compare.sh +++ b/bench/compare.sh @@ -142,9 +142,11 @@ fresh_image() { cp --sparse=always "$IN/empty.img" "$IMG/target.img"; } no_image() { rm -f "$IMG/target.img"; } empty_image() { rm -f "$IMG/target.img" && : > "$IMG/target.img"; } nothing() { :; } -ASM=(assemble --create --sector-size 512 --identifier 1234abcd --label ESP) +# The file systems get a size: one both binaries make the same way whether +# or not they size to fit on their own. +ASM=(assemble --create --size 64M --sector-size 512 --identifier 1234abcd --label ESP) POPULATE='{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1}}' -ASSEMBLE='{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2},"options":{"sectorSize":512,"identifier":"1234-ABCD","label":"ESP"}}' +ASSEMBLE='{"image":{"fileDescriptor":0,"size":67108864},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2},"options":{"sectorSize":512,"identifier":"1234-ABCD","label":"ESP"}}' workloads() { local r=$1 $r assemble/esp no_image -- @UFAT@ "${ASM[@]}" "$IMG/target.img" "$IN/esp" diff --git a/bench/run.sh b/bench/run.sh index 8584e85..7002d7c 100755 --- a/bench/run.sh +++ b/bench/run.sh @@ -347,10 +347,10 @@ bench "sha256/esp/ufat-manifest" ":" -- "$UFAT" manifest "$IN/esp" [ -n "$SHA256SUM" ] && bench "sha256/esp/sha256sum" ":" -- "$SHA256SUM" "${ESP_FILES[@]}" for ss in 512 4096; do W=$IMG/asm-$ss.img - # --create without --size sizes the image to fit the manifest. - bench "assemble/$ss/esp/dir-fit" "rm -f $W" -- "$UFAT" assemble --create --sector-size "$ss" --identifier 1234abcd --label ESP \ + # --minimize sizes the image to fit the manifest, which it reads twice. + bench "assemble/$ss/esp/dir-fit" "rm -f $W" -- "$UFAT" assemble --create --minimize --sector-size "$ss" --identifier 1234abcd --label ESP \ --manifest "$IN/esp.manifest" "$W" "$IN/esp" - bench "assemble/$ss/esp/stream-fit" "rm -f $W" --stdin "$IN/esp.blob" -- "$UFAT" assemble --create --sector-size "$ss" --identifier 1234abcd --label ESP \ + bench "assemble/$ss/esp/stream-fit" "rm -f $W" --stdin "$IN/esp.blob" -- "$UFAT" assemble --create --minimize --sector-size "$ss" --identifier 1234abcd --label ESP \ --manifest "$IN/esp.manifest" "$W" - # Into a formatted 1 GiB image, like populate above: the difference to # populate is the manifest handling and the SHA-256 verification. @@ -377,7 +377,7 @@ for ss in 512 4096; do --params '{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2},"timestampUSec":1700000000000000}' bench "varlink/$ss/esp/Assemble-manifest-stream-fit" "rm -f $W; : > $W" --ufat "$UFAT" --method org.uapi-group.FileSystem.Assemble \ --fd "rw:$W" --fd "$IN/esp.manifest" --fd "$IN/esp.blob" \ - --params "{\"image\":{\"fileDescriptor\":0},\"content\":{\"manifest\":{\"fileDescriptor\":1},\"sourceFileDescriptor\":2},\"options\":{\"sectorSize\":$ss,\"identifier\":\"1234-ABCD\",\"label\":\"ESP\",\"timestampUSec\":1700000000000000}}" + --params "{\"image\":{\"fileDescriptor\":0},\"content\":{\"manifest\":{\"fileDescriptor\":1},\"sourceFileDescriptor\":2},\"options\":{\"minimize\":true,\"sectorSize\":$ss,\"identifier\":\"1234-ABCD\",\"label\":\"ESP\",\"timestampUSec\":1700000000000000}}" rm -f "$W" for tree in esp wide-flat wide-flat83 wide-deep; do rm -f "$IMG/pop-$tree-$ss.img"; done done diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index 9032497..f87bd23 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -36,16 +36,16 @@ interface org.uapi-group.FileSystem # Where a filesystem lives: an image file or block device and the byte range # inside it. A block device written to is claimed exclusively while the call # runs, the way a mount claims it; a mounted device is refused with ImageBusy. A -# regular file is grown to the size the filesystem needs when the call makes -# one and no size is given; it is never shrunk. +# regular file is grown to the size of a filesystem the call makes; it is never +# shrunk. type Image( # Index of the descriptor of the image file or block device fileDescriptor: int, # Byte offset of the filesystem inside the image, 0 by default offset: ?int, - # Size of the filesystem in bytes, the rest of the image by default; with - # content and no size the filesystem is sized to fit when the - # implementation can (Capabilities.sizeToFit), else SizeRequired + # Size of the filesystem in bytes, the rest of the image by default; an + # empty image without a size is SizeRequired, unless FormatOptions.minimize + # is set. With FormatOptions.minimize the most the filesystem may take. size: ?int ) @@ -79,13 +79,14 @@ type LabelRules( charset: LabelCharset ) -# How well plan finds the smallest filesystem for given content. +# How well plan finds the smallest filesystem for given content, in the +# words of systemd-repart's Minimize=. type SizeToFit( - # An estimate that holds the content with room to spare (ext4, xfs) - estimate, - # The exact size, the filesystem full to the last block (vfat, erofs, + # A guess that holds the content with room to spare (ext4, xfs) + guess, + # The best size, the filesystem full to the last block (vfat, erofs, # squashfs, btrfs) - exact + best ) # A feature the filesystem can be made with or without, by its name in the @@ -117,7 +118,8 @@ type TimeRules( # asked for and is not in it. A set is an array of an enum because Varlink # has no flags type. type Operation( - # Assemble with mode plan (Capabilities.sizeToFit says how exactly) + # Assemble with mode plan and with FormatOptions.minimize + # (Capabilities.sizeToFit says how well) plan, # Content at Assemble time assembleWithContent, @@ -193,7 +195,7 @@ type Capabilities( readOnly: bool, # What a caller can ask for; anything else is OperationNotSupported operations: []Operation, - # Whether plan answers exactly or estimates; absent without plan + # Whether plan finds the best size or guesses; absent without plan sizeToFit: ?SizeToFit, # The smallest and largest filesystem the implementation makes, and the # granularity sizes are rounded to @@ -297,10 +299,10 @@ type ManifestFeature( # the source directory, or back to back in manifest order from the source # stream. A manifest and a source stream are read in lockstep, a record and # then the contents of the file it describes, so a client that passes both as -# pipes writes to both at the same time. Assemble in mode assemble plans the -# content first: it reads the whole manifest before it writes and needs it in -# a regular file; a pipe is BadFileDescriptor with reason wrongType then. In -# mode plan the manifest is read once, and a pipe will do. +# pipes writes to both at the same time. Assemble with FormatOptions.minimize +# plans the content first: it reads the whole manifest before it writes and +# needs it in a regular file; a pipe is BadFileDescriptor with reason wrongType +# then. In mode plan the manifest is read once, and a pipe will do. type Manifest( # Index of the descriptor, open read-only fileDescriptor: int, @@ -399,6 +401,9 @@ type FormatOptions( zero: ?bool, # Format the image whatever it holds, false by default force: ?bool, + # Make the filesystem the smallest that holds the content, false by + # default; Image.size is then the most it may take + minimize: ?bool, # Make the bytes a function of the inputs alone: requires identifier and # timestampUSec and pins everything else the implementation knows to # vary (seeds, worker counts, walk order) @@ -515,14 +520,14 @@ method GetCapabilities( # Lays out a filesystem and reports it. With mode assemble the image is # written: formatted, and filled with the content when there is one, in one # step, which is the only way for a read-only filesystem. With mode plan -# nothing is written: the geometry, the size the content needs and whether -# that size is exact are computed, from the content and the options, and -# from the image's size when one is given. A regular image file without a -# size is grown to the fit when content is given. With mode assemble, an -# image that holds a filesystem, a partition table or other data that -# formatting would destroy is refused with ImageNotEmpty, unless -# FormatOptions.force is set. With offset and size, only that part of the -# image counts. The reply contains the label and identifier as stored. +# nothing is written: the geometry and the size the content needs are +# computed, from the content and the options, and from the image's size +# when one is given. With FormatOptions.minimize a regular image file is +# grown to the size the content needs. With mode assemble, an image that +# holds a filesystem, a partition table or other data that formatting would +# destroy is refused with ImageNotEmpty, unless FormatOptions.force is set. +# With offset and size, only that part of the image counts. The reply +# contains the label and identifier as stored. # [Supports 'more' flag]: intermediate replies carry the phase and the # counts so far. method Assemble( @@ -532,17 +537,15 @@ method Assemble( mode: ?AssembleMode, options: ?FormatOptions, content: ?Content, - # Hash the filesystem as it is in the image after the call, all size bytes - # from offset: the written bytes and the rest, which the implementation - # knows to be zero when the call sized or zeroed the image, and reads back - # otherwise + # Hash the filesystem as it is in the image after the call, the bytes from + # offset to the end of the filesystem: the written bytes and the rest, + # which the implementation knows to be zero when the call sized or zeroed + # the image, and reads back otherwise imageHash: ?HashAlgorithm ) -> ( # The step in progress, in intermediate replies only phase: ?Phase, description: ?Description, - # Whether the size is the exact minimum (plan, or assemble sized to fit) - exact: ?bool, # What was written, when content was given files: ?int, directories: ?int, @@ -674,7 +677,8 @@ error OperationNotSupported(operation: Operation) # A read-only filesystem is made with its content, and none was given. error ContentRequired() -# The filesystem cannot be sized to fit and no size was given. +# Nothing says how large the filesystem is to be: no size was given, the image +# is empty, and FormatOptions.minimize is not set. error SizeRequired() # The image holds no filesystem of this type: nothing (blank), another @@ -699,7 +703,10 @@ error Corrupt(where: CorruptPlace, field: ?string, path: ?string, block: ?int) type NoSpaceReason(blocks, directoryEntries, names, inodes, volume) error NoSpaceLeft(reason: NoSpaceReason, path: ?string) -# The image is smaller than the content needs. +# The image is smaller than the content needs: the smallest filesystem that +# holds the content, minimalSizeBytes, is larger than sizeBytes, the Image.size +# given with FormatOptions.minimize or what a block device has behind the +# offset. error TooSmall(minimalSizeBytes: int, sizeBytes: int) # A file or the filesystem is larger than the filesystem allows. diff --git a/docs/varlink.md b/docs/varlink.md index fb2fce9..6da9bf1 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -66,7 +66,7 @@ Every method except `GetCapabilities` works on an `Image`: |---|---| | `fileDescriptor` | Index of the passed image file or block device. | | `offset` | Byte offset of the file system in the image. 0 by default. | -| `size` | Size of the file system in bytes. The rest of the image by default. | +| `size` | Size of the file system in bytes. The rest of the image by default. With `minimize`, the most the file system may take. | Paths inside the file system are absolute. `/` is the root. Times are microseconds since the UNIX epoch, in UTC. @@ -96,7 +96,7 @@ The reply does not depend on the call. It is: "operations" : [ "plan", "assembleWithContent", "populate", "remove", "list", "check", "label", "identifier", "reproducible", "manifest", "writeManifest" ], - "sizeToFit" : "exact", + "sizeToFit" : "best", "minimalSizeBytes" : 34089472, "maximalSizeBytes" : 2199023255040, "sizeGranularityBytes" : 512, @@ -127,7 +127,7 @@ What the fields mean for vfat: - `operations` lists what the implementation can do. `repair`, `features` and `discard` are missing. Asking for them fails with `OperationNotSupported`. -- `sizeToFit` is `exact`. A plan gives the size the content needs, to the +- `sizeToFit` is `best`. A plan gives the size the content needs, to the sector. A plan does not compare names. Names that FAT does not tell apart, such as `A.TXT` and `a.txt`, or `FOOBAR~1` and `FOO BAR`, whose short name it is, are two names to it. Content with such names, @@ -189,21 +189,25 @@ formats any image. How the image is sized: -- With content and without `size`, a regular image file is grown to the - exact size the content needs. It is never shrunk. -- With a `size`, the file system gets that size. Content that does not - fit fails with `TooSmall` before anything is written. -- Content is planned first. A manifest is read twice then, so it has to - be a regular file. -- Without content, a regular image file is grown to `size`. An empty - image file without a `size` fails with `SizeRequired`. -- A block device is never resized. +- Without `minimize`, the file system gets `size`, or the rest of the + image behind `offset`, as mkfs.fat does. A regular image file is grown + to `size`. An empty image file without a `size` fails with + `SizeRequired`. A size too small for a FAT32 file system fails with + `NoSpaceLeft` and reason `volume` before anything is written, also a + `size` of 0 and an `offset` at the end of the image. The content is + written right away. Content that does not fit fails with `NoSpaceLeft` + while it is written. +- With `minimize`, the file system is as small as the content allows. A + regular image file is grown to that size. Content that does not fit + `size` or the block device fails with `TooSmall` before anything is + written. The content is planned first. A manifest is read twice then, + so it has to be a regular file. +- An image file is never shrunk, and a block device is never resized. The reply carries a `description` with the label and the serial number as stored, the sector size, the cluster size (`blockSize`), the size and the free space. With content, the counts `files`, `directories`, `bytes` -and `skipped` follow, and with a `manifestSink` also `omitted`. `exact` -is true when the size was computed to fit the content. +and `skipped` follow, and with a `manifestSink` also `omitted`. Mode `plan` answers with `minimalSizeBytes` in place of `freeBytes`: @@ -220,7 +224,6 @@ Mode `plan` answers with `minimalSizeBytes` in place of `freeBytes`: "minimalSizeBytes" : 34089472, "label" : "ESP" }, - "exact" : true, "files" : 2, "directories" : 3, "bytes" : 5010 @@ -250,6 +253,7 @@ see "Passing file descriptors". | `blockSize` | The cluster size: a power of two from the sector size up to 32768, at most 128 sectors. Chosen from the volume size by default, like mkfs.fat does. | | `zero` | Overwrites the whole data area with zeros. Off by default. | | `force` | Formats the image whatever it holds. Off by default. | +| `minimize` | Makes the file system as small as the content allows. Off by default. | | `reproducible` | Makes the image depend on the inputs only. Requires `identifier` and `timestampUSec`, and fails with `NotReproducible` without them. Set `times` to `fixed` or `clamp` to make the file times reproducible too. | | `discard` | `false` is accepted. `true` fails with `OperationNotSupported`. | | `enableFeatures`, `disableFeatures` | FAT has none. Setting them fails with `OperationNotSupported`. | @@ -410,11 +414,12 @@ Other combinations fail with `InvalidParameter`. A manifest is read one record at a time, and what a record describes is written when the record comes. So a manifest of any size can come through a pipe, unless it is planned before its content is written: `Assemble` in -mode `assemble` plans its content first, so there it has to be a regular -file. A pipe fails with `BadFileDescriptor` and reason `wrongType` then. -Mode `plan` reads the manifest once and takes a pipe. A plan keeps the -path of the deepest open directory, and a count for each directory on -that path, so the memory `Assemble` uses does not grow with the manifest. +mode `assemble` with `minimize` plans its content first, so there it has +to be a regular file. A pipe fails with `BadFileDescriptor` and reason +`wrongType` then. Mode `plan` reads the manifest once and takes a pipe. +A plan keeps the path of the deepest open directory, and a count for +each directory on that path, so the memory `Assemble` uses does not grow +with the manifest. When the file contents come from a stream, the manifest and the stream are read in lockstep: a record of the manifest, then the contents of the @@ -534,7 +539,7 @@ reply. Without it, only the final reply is sent. | Method | Phases | |---|---| -| `Assemble` | `planning` (with content), `formatting`, `populating` (with content), `reading` (with a `manifestSink`, and again with `imageHash`). Mode `plan` sends `planning` only. | +| `Assemble` | `planning` (with `minimize`), `formatting`, `populating` (with content), `reading` (with a `manifestSink`, and again with `imageHash`). Mode `plan` sends `planning` only. | | `Describe` | `reading`, with a `manifestSink` only. | | `Populate` | `populating`, then `reading` with a `manifestSink`. | | `Remove` | `removing`, for a recursive removal only. | @@ -557,7 +562,7 @@ Each parameter needs a descriptor of a certain kind: |---|---| | `image.fileDescriptor` | A regular file or a block device. Open read-write for `Assemble` in mode `assemble`, `Populate` and `Remove`. Read-only or read-write for `Describe`, `List` and `Check`. | | `content.sourceFileDescriptor` | A directory, a regular file or a pipe, open read-only. | -| `content.manifest.fileDescriptor` | A regular file or a pipe, open read-only. A manifest of any size can be passed this way. `Assemble` in mode `assemble` needs a regular file. | +| `content.manifest.fileDescriptor` | A regular file or a pipe, open read-only. A manifest of any size can be passed this way. `Assemble` with `minimize` needs a regular file. | | `manifestSink.fileDescriptor` | A regular file or a pipe, open for writing. `O_APPEND` is allowed. | The service checks every descriptor before it uses it. The call fails @@ -573,12 +578,12 @@ descriptor: - is not open read-only for a source or a manifest (`notReadOnly`), - is not open for writing for a manifest sink (`notWritable`), - is not of the type the parameter needs (`wrongType`), also a manifest - on a pipe for `Assemble` in mode `assemble`. + on a pipe for `Assemble` with `minimize`. All descriptors are checked, and the first record of a manifest is read, -before the image is opened. `Assemble` in mode `assemble` reads the -whole manifest before the image is changed. A call that fails this way -leaves the image unchanged. +before the image is opened. With `minimize` the whole manifest is read +before the image is changed. A call that fails this way leaves the image +unchanged. A pipe that is made non-blocking during the call fails it with `BadFileDescriptor` and the reason `flags` once the service has to wait @@ -605,12 +610,12 @@ The service returns no text. Every error is a name with typed fields. | `BadFileDescriptor` | A passed descriptor does not meet the requirements. | `parameter`, `reason`, `flags` | | `FileSystemTypeNotSupported` | A `fileSystemType` other than `vfat`. | `fileSystemType` | | `OperationNotSupported` | `discard`, features or `repair` were requested. | `operation` | -| `SizeRequired` | `Assemble` without content into an empty file without a `size`. | none | +| `SizeRequired` | `Assemble` without `minimize` into an empty file without a `size`. | none | | `NotFileSystem` | The image holds no FAT32 file system. | `reason` (`blank`, `foreignImageType`, `sectorSize`, `tooSmall`, `unknown`), `found`, `sectorSize` | | `ImageNotEmpty` | `Assemble` without `force` into an image that holds a file system, a partition table or other data. | `found` | | `Corrupt` | The file system is damaged where the operation needs it. | `where` (`superblock`, `allocation`, `chain`, `directory`), `field`, `path`, `block` | -| `NoSpaceLeft` | The file system is full, or the cluster size leaves fewer than 65525 clusters. | `reason` (`blocks`, `directoryEntries`, `names`, `volume`), `path` | -| `TooSmall` | The content does not fit the `size` given to `Assemble`. | `minimalSizeBytes`, `sizeBytes` | +| `NoSpaceLeft` | The file system is full, or the size or the cluster size leaves fewer than 65525 clusters. | `reason` (`blocks`, `directoryEntries`, `names`, `volume`), `path` | +| `TooSmall` | With `minimize`, the content does not fit the `size` given to `Assemble` or the block device. `minimalSizeBytes` is the smallest file system that holds it, `sizeBytes` that `size` or what the block device has behind `offset`. | `minimalSizeBytes`, `sizeBytes` | | `TooLarge` | A file is larger than FAT allows, or a volume has more clusters than FAT32 can address. | `path`, `sizeBytes`, `sizeMaxBytes` | | `NoSuchFile` | A path does not exist. | `path` | | `FileExists` | A file exists and `replace` is false, or a directory exists and `parents` is false. | `path` | diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index 0b3d2a7..0d52f01 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -20,13 +20,12 @@ use fat::manifest::{ }; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, TimePolicy}; -use fat::probe::Prober; use fat::time::civil_from_days; use fat::volume::Volume; use fat::{bail, err, Context, DescriptorProblem, Detail, Error, ManifestProblem, Result}; use crate::service; -use crate::util::{self, ImageFlags, ManifestInput, ManifestUse}; +use crate::util::{self, GivenSize, ImageFlags, ManifestInput, ManifestUse, SizeMode, SizeRequest}; const USAGE: &str = "\ Usage: ufat COMMAND [OPTIONS...] ARGS... @@ -34,9 +33,9 @@ Usage: ufat COMMAND [OPTIONS...] ARGS... ufat --version Commands: - assemble [OPTIONS] IMAGE [SOURCE] Create a FAT32 file system sized to fit - SOURCE or what --manifest describes, - and fill it with that + assemble [OPTIONS] IMAGE [SOURCE] Create a FAT32 file system and fill it + with SOURCE or what --manifest + describes assemble --plan [OPTIONS] [SOURCE] Print the smallest file system size for SOURCE or what --manifest describes populate [OPTIONS] IMAGE [SOURCE] Fill an existing FAT32 file system @@ -52,8 +51,11 @@ Commands: The commands are the methods of the org.uapi-group.FileSystem Varlink interface that ufat serves; cat and manifest have no method. -assemble without a SOURCE creates an empty file system of the size of IMAGE or ---size, or sized to hold the --fit directory or what --manifest describes. +assemble makes the file system as large as --size, or else as large as the +part of IMAGE behind --offset. --minimize makes it the smallest that holds the +content, and --size is then the most it may take. Without a SOURCE it is +empty. The --fit directory or what --manifest describes then has to fit +--size, and without --size the file system is the smallest that holds it. assemble refuses an IMAGE that holds a file system, a partition table or other data libblkid recognizes, or without libblkid anything that is not blank. --force formats it anyway. @@ -64,9 +66,9 @@ A SOURCE is a directory tree, or for populate one file. With --manifest the one SOURCE is the tree the manifest describes, where its file contents are read, or - for the contents on standard input, back to back in manifest order. The manifest has to declare \"order\": \"codepoint\" and be in that order. -assemble with a SOURCE reads the manifest twice, to plan the file system and -to fill it, and needs it in a regular file. populate, assemble --plan and -assemble without a SOURCE read it once and take a pipe: +assemble --minimize with a SOURCE reads the manifest twice, to plan the file +system and to fill it, and needs it in a regular file. Everything else reads +it once and takes a pipe: --manifest PATH Build what the UAPI.16 manifest at PATH, or on standard input for -, describes --no-check-validity Accept revoked and expired manifest entries @@ -75,12 +77,15 @@ assemble without a SOURCE read it once and take a pipe: Options common to commands taking IMAGE: --offset BYTES Byte offset of the file system inside IMAGE - --size BYTES Size of the file system inside IMAGE (assemble: instead - of the size that fits the content; assemble --plan: - fail when the content does not fit this size) + --size BYTES Size of the file system inside IMAGE, or with + --minimize the most it may take (--minimize, --plan, + --fit and --manifest without a SOURCE fail when the + content does not fit this size) Options for assemble: --plan Print the size the content needs and write nothing + --minimize Make the file system the smallest that holds the + content --sector-size BYTES Logical sector size, 512 or 4096 (1024 and 2048 work) --cluster-size BYTES Cluster size --identifier ID Volume serial number, XXXX-XXXX or 8 hex digits @@ -93,11 +98,12 @@ Options for assemble: --fats N FAT copies (default 2) --mkfs-fat-compat Reproduce mkfs.fat's layout quirks exactly --zero Zero the whole data area - --create Create IMAGE if it does not exist (without a SOURCE it - needs --size, --fit or --manifest for that) + --create Create IMAGE if it does not exist (it then needs --size, + --minimize, --fit, or --manifest without a SOURCE) --force, -f Format IMAGE whatever it holds - --fit DIR Size IMAGE to the smallest file system holding DIR - and leave it empty (no SOURCE) + --fit DIR Size IMAGE for DIR and leave it empty (no SOURCE): + --size, which DIR has to fit, or else the smallest + file system holding DIR --hash ALGORITHM Print the sha256 or sha512 hash of the file system written --write-hash PATH Write that hash to PATH instead, or to standard output @@ -336,7 +342,15 @@ const FILL_VALUES: &[&str] = &[ "write-manifest", ]; const FILL_FLAGS: &[&str] = &["no-replace", "no-check-validity", "verbose"]; -const FORMAT_FLAGS: &[&str] = &["no-align", "mkfs-fat-compat", "zero", "create", "force", "verbose"]; +const FORMAT_FLAGS: &[&str] = &[ + "no-align", + "mkfs-fat-compat", + "zero", + "create", + "force", + "minimize", + "verbose", +]; fn with(a: &[&'static str], b: &[&'static str]) -> Vec<&'static str> { a.iter().chain(b).copied().collect() @@ -484,7 +498,7 @@ fn read_manifest(path: &Path, manifest_use: ManifestUse) -> Result<(ManifestInpu .. }) => err!( errno::EINVAL, - "{} is not a regular file: assemble with a SOURCE needs the manifest in one", + "{} is not a regular file: --minimize with a SOURCE needs the manifest in one", name ), _ if e.is_manifest() => e.context(format_args!("{} is not a UAPI.16 manifest", name)), @@ -814,13 +828,27 @@ fn image_arg<'a>(args: &'a Args, command: &str) -> Result<&'a Path> { } } -/// `assemble --plan`: the size the content needs, with nothing written. +/// `assemble --plan`: the size the content needs, with nothing written. It +/// answers for `assemble` with the same options. With `--size` and without +/// `--minimize` that makes a file system of that size, so the content is +/// planned with the cluster size the formatter picks for it and has to fit +/// its clusters. Otherwise the plan is of the smallest file system, which +/// with `--minimize` has to fit in `--size`. fn plan(args: &Args) -> Result<()> { if args.positional.is_empty() && args.path("manifest").is_none() { bail!(errno::EINVAL, "assemble --plan needs a SOURCE or --manifest"); } let options = format_options(args)?; - let mut plan = Plan::new(PlanOptions::from_format_options(&options, None)?); + let mut plan_options = PlanOptions::from_format_options(&options, None)?; + let size = args.size("size")?; + let given = match size { + Some(size) if !args.flag("minimize") => Some(GivenSize::new(&options, size, None)?), + _ => None, + }; + if let Some(given) = &given { + plan_options.cluster_size = Some(given.layout.cluster_size()); + } + let mut plan = Plan::new(plan_options); // Nothing is written after a plan, so it reads the manifest on from its // root file object, and the manifest is read once. A pipe will do. let source = Source::open(args, &args.positional_paths(), Sourcing::Size)?; @@ -832,15 +860,17 @@ fn plan(args: &Args) -> Result<()> { ); } let e = plan.estimate()?; - if let Some(size) = args.size("size")? { - if e.size() > size { - bail!( - errno::ENOSPC, - "the content needs a {} byte file system, more than --size {}", - e.size(), - size - ); - } + match (&given, size) { + (Some(given), _) => given + .check(&e) + .map_err(|shortfall| err!(errno::ENOSPC, "{}", shortfall))?, + (None, Some(size)) if e.size() > size => bail!( + errno::ENOSPC, + "the content needs a {} byte file system, more than --size {}", + e.size(), + size + ), + _ => {} } println!("{}", e.size()); if args.flag("verbose") { @@ -855,60 +885,64 @@ fn plan(args: &Args) -> Result<()> { Ok(()) } -/// `assemble` without a SOURCE: an empty file system, of the size of the -/// image or `--size`, or sized for the `--fit` directory or what -/// `--manifest` describes. +/// `assemble` without a SOURCE: an empty file system of the size of +/// `--size` or of the image, or with `--minimize` the smallest one. The +/// `--fit` directory or what `--manifest` describes has to fit a size +/// given, and without one the file system is the smallest that holds it. fn assemble_empty(args: &Args, path: &Path) -> Result { let mut options = format_options(args)?; - let offset = args.size("offset")?.unwrap_or(0); - let size = args.size("size")?; let fit = args.paths("fit"); let target = util::Target { path, - offset, - size, + offset: args.size("offset")?.unwrap_or(0), + size: args.size("size")?, flags: args.image_flags(), }; - if fit.is_empty() && args.path("manifest").is_none() { - let mut device = util::open_target(&target)?; - if !target.flags.contains(ImageFlags::FORCE) { - Prober::new().ensure_empty(&device, offset, size)?; - } - if target.flags.contains(ImageFlags::CREATE) { - let size = size.ok_or_else(|| err!(errno::EINVAL, "--create needs --size, --fit or --manifest"))?; - util::size_image(&mut device, offset, size)?; - } - let device = device.window(offset, size)?; - format::format(&device, &options)?; - return Volume::open(device); - } // Nothing of the content is written, so a manifest is planned on from // its root file object, through the reader that read it, and is read - // once: a pipe will do. fit_and_format() plans the content once. - let mut source = Some(Source::open(args, &fit, Sourcing::Size)?); + // once: a pipe will do. fit_and_format() plans the content at most once. + let source = Source::open(args, &fit, Sourcing::Size)?; + let mode = if args.flag("minimize") { + SizeMode::Minimize + } else if matches!(source, Source::None) { + SizeMode::Given + } else { + SizeMode::Fit + }; + let mut source = Some(source); let mut add = |plan: &mut Plan| match source.take() { Some(source) => source.into_plan(plan, args).map(drop), None => bail!(errno::EINVAL, "the content is planned once"), }; - let (volume, estimate) = util::fit_and_format(&target, &mut options, &mut add).map_err(|e| e.into_error(path))?; - report_estimate(args, path, &estimate); + let (volume, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add)) + .map_err(|e| e.into_error(path))?; + if let Some(estimate) = estimate { + report_estimate(args, path, &estimate); + } Ok(volume) } -/// `assemble` with a SOURCE: the file system sized to fit it, unless -/// `--size` says otherwise, and filled with it. +/// `assemble` with a SOURCE: the file system of the size of `--size` or of +/// the image, or with `--minimize` the smallest that holds it, filled with +/// it. fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result { if !args.paths("fit").is_empty() { bail!( errno::EINVAL, - "--fit sizes an empty file system; with a SOURCE the file system is sized for it" + "--fit sizes an empty file system; with a SOURCE --minimize sizes it for the SOURCE" ); } - // The manifest is planned before its content is written. - let mut source = Source::open(args, paths, Sourcing::Write(ManifestUse::Plan))?; + let mode = if args.flag("minimize") { + SizeMode::Minimize + } else { + SizeMode::Given + }; + let mut source = Source::open(args, paths, Sourcing::Write(mode.manifest_use()))?; // Better to learn about a tree FAT cannot hold before an image is sized - // and formatted. - source.check(args)?; + // and formatted. With --minimize the plan finds it. + if mode == SizeMode::Given { + source.check(args)?; + } let mut options = format_options(args)?; let target = util::Target { path, @@ -916,10 +950,12 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result size: args.size("size")?, flags: args.image_flags(), }; - let (mut v, estimate) = - util::fit_and_format(&target, &mut options, &mut |plan| source.add_to(plan, args).map(drop)) - .map_err(|e| e.into_error(path))?; - report_estimate(args, path, &estimate); + let mut add = |plan: &mut Plan| source.add_to(plan, args).map(drop); + let (mut v, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add)) + .map_err(|e| e.into_error(path))?; + if let Some(estimate) = estimate { + report_estimate(args, path, &estimate); + } match source.fill(&mut v, args) { Ok(()) => Ok(v), Err(e) => Err(unfinished(v, e)), @@ -1008,10 +1044,15 @@ fn cmd_assemble(argv: &[OsString]) -> Result<()> { } } let layout = *v.layout(); + // The hash is of the file system's own bytes, which with --minimize can + // end before --size does. + let window = v.device().len(); v.close()?; report_layout(path, &layout, args.flag("verbose")); if let Some(hash) = hash { - let digest = hash.of(&open_image(&args, path, Access::ReadOnly)?, &mut |_| {})?; + let offset = args.size("offset")?.unwrap_or(0); + let image = util::open_image(path, offset, Some(window), Access::ReadOnly)?; + let digest = hash.of(&image, &mut |_| {})?; match hash_path { Some(p) if p != Path::new("-") => { std::fs::write(p, format!("{}\n", digest)).with_context(|| format!("cannot write {}", p.display()))? diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index 4eb30c4..172455b 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -41,7 +41,7 @@ use fat::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason, UnsupportedKind}; use json::{Object, Value}; use varlink::{Activation, Call, Connection, Info, Reply, Server, Service}; -use crate::util::{self, ManifestInput, ManifestUse}; +use crate::util::{self, ImageFlags, ManifestInput, ManifestUse, SizeMode, SizeRequest}; /// The interface description, served verbatim. pub(crate) const INTERFACE: &str = include_str!("../../../docs/org.uapi-group.FileSystem.varlink"); @@ -344,7 +344,17 @@ fn fail(f: Failure) -> varlink::Error { /// The error of the fit, as a failure of the call. fn fit_error(e: util::FitError) -> Failure { match e { + util::FitError::SizeRequired => Failure::SizeRequired, util::FitError::TooSmall { minimal, actual } => Failure::TooSmall { minimal, actual }, + // Only the command line asks for SizeMode::Fit, with --fit and with + // --manifest without a SOURCE. The service makes no such call. This + // is the room that writing the content would run out of. + util::FitError::TooFewClusters(shortfall) => Failure::Other( + fat::Error::new(errno::ENOSPC, shortfall.to_string()).with(Detail::NoSpace { + reason: NoSpaceReason::Clusters, + path: None, + }), + ), util::FitError::Other(e) => Failure::Other(e), } } @@ -588,8 +598,10 @@ struct Options { format: FormatOptions, /// `timestampUSec` as given; None when the current time stands in. time: Option, - /// `force`: format the image whatever it holds. - force: bool, + /// `force`: what may be done to the image. + image: ImageFlags, + /// `minimize`: how large the file system is made. + size_mode: SizeMode, } fn format_options(p: Option>) -> Outcome { @@ -605,7 +617,8 @@ fn format_options(p: Option>) -> Outcome { return Ok(Options { format: o, time: None, - force: false, + image: ImageFlags::default(), + size_mode: SizeMode::Given, }); }; // What FAT has no notion of is refused, not ignored. @@ -654,10 +667,18 @@ fn format_options(p: Option>) -> Outcome { o.hidden_sectors = v.u32("hiddenSectors")?; o.mkfs_fat_compat = v.bool("mkfsFatCompatible", false); } + let mut image = ImageFlags::default(); + image.set(ImageFlags::FORCE, p.bool("force", false)); + let size_mode = if p.bool("minimize", false) { + SizeMode::Minimize + } else { + SizeMode::Given + }; Ok(Options { format: o, time, - force: p.bool("force", false), + image, + size_mode, }) } @@ -759,7 +780,7 @@ pub(crate) fn capabilities() -> fat::Result { "manifest", "writeManifest", ], - "sizeToFit" => "exact", + "sizeToFit" => "best", "minimalSizeBytes" => minimal, // 0xFFFFFFFF sectors of 512 bytes, the total sectors field's limit. "maximalSizeBytes" => u64::from(u32::MAX) * u64::from(MIN_SECTOR_SIZE), @@ -1237,13 +1258,13 @@ impl FileSystemService { }; let options = format_options(p.object("options"))?; let content_time = options.format.timestamp.unwrap_or_else(util::now); - // The content is planned. A plan alone reads a manifest once, on - // from its root file object; an assembly reads it for the plan from - // its start, and once more while its content is written. + // A plan alone reads a manifest once, on from its root file object. + // An assembly that sizes the file system to fit reads it for the + // plan from its start, and once more while its content is written. let (taker, manifest_use) = if plan_only { (Taker::Plan, ManifestUse::PlanOnly) } else { - (Taker::Assemble, ManifestUse::Plan) + (Taker::Assemble, options.size_mode.manifest_use()) }; let content = match p.object("content") { None => None, @@ -1469,7 +1490,6 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more optional(&mut d, "label", stored_label(&options.format)?); Ok(json::object! { "description" => d, - "exact" => true, "files" => e.files, "directories" => e.directories, "bytes" => e.bytes, @@ -1519,13 +1539,15 @@ fn fill_image( } /// Assemble with mode assemble: the image written, filled with the content -/// when there is one, sized to fit when no size is given. Everything that -/// can be checked before the image is touched has been checked by now: -/// the descriptors vetted, the manifest parsed and its source verified, -/// the options validated. Without force in the options, an image that -/// holds a file system, a partition table or other data is ImageNotEmpty. -/// A call that fails after the format leaves the file system marked as not -/// cleanly unmounted. +/// when there is one. The file system takes the size given or the rest of +/// the image, or with minimize the size the content needs. Everything that +/// can be checked before the image is touched has been checked by now: the +/// descriptors vetted, the root file object of a manifest read, the options +/// validated. With minimize the content is planned before the image is +/// touched. Without force in the options, an image that holds a file +/// system, a partition table or other data is ImageNotEmpty. A call that +/// fails after the format leaves the file system marked as not cleanly +/// unmounted. fn assemble_image( image: Image, mut options: Options, @@ -1539,38 +1561,33 @@ fn assemble_image( None => None, }; let (mut device, offset, size) = image.device(Access::ReadWrite)?; - let (mut volume, exact) = match &content { - Some(ct) => { - phase(c, more, "planning")?; - let (estimate, fit) = util::plan_fit(&mut device, offset, size, &mut options.format, true, &mut |plan| { - ct.plan(plan) - }) - .map_err(fit_error)?; - if !options.force { - Prober::new().ensure_empty(&device, offset, Some(fit))?; - } - phase(c, more, "formatting")?; - let (volume, _) = util::format_fit(device, offset, fit, estimate, &options.format).map_err(fit_error)?; - (volume, size.is_none()) - } - None => { - if !options.force { - Prober::new().ensure_empty(&device, offset, size)?; - } - // A regular file is grown to a size given. An image with no - // bytes in it has no size at all. - if let Some(s) = size { - util::size_image(&mut device, offset, s)?; - } - let device = device.window(offset, size)?; - if device.is_empty() { - return Err(Failure::SizeRequired); - } - check_block_size(&options.format, &device)?; - phase(c, more, "formatting")?; - (Volume::create(device, &options.format)?, false) - } + check_block_size(&options.format, &device)?; + // Without a plan a tree is walked here, so that under UnsupportedPolicy + // fail what FAT cannot hold is refused before the image is touched. + let mode = options.size_mode; + match (mode, &content) { + (SizeMode::Given, Some(ct)) => ct.check_tree("/")?, + (SizeMode::Given, None) => {} + (SizeMode::Fit | SizeMode::Minimize, _) => phase(c, more, "planning")?, + } + let mut add = |plan: &mut Plan| match &content { + Some(ct) => ct.plan(plan), + None => Ok(()), }; + let decision = util::decide_size( + &mut device, + offset, + size, + &mut options.format, + true, + SizeRequest::new(mode, &mut add), + ) + .map_err(fit_error)?; + if !options.image.contains(ImageFlags::FORCE) { + Prober::new().ensure_empty(&device, offset, Some(decision.size))?; + } + phase(c, more, "formatting")?; + let mut volume = util::format_sized(device, offset, decision.size, &options.format)?; let (counts, omitted, description) = match fill_image(&mut volume, content, options.time, c, more) { Ok(filled) => filled, Err(e) => { @@ -1584,7 +1601,7 @@ fn assemble_image( }; let window = volume.device().len(); volume.close()?; - let mut o = json::object! { "description" => description, "exact" => exact }; + let mut o = json::object! { "description" => description }; if let Some(counts) = counts { counts.put(&mut o); } diff --git a/src/bin/ufat/util.rs b/src/bin/ufat/util.rs index 4271d05..3934cdc 100644 --- a/src/bin/ufat/util.rs +++ b/src/bin/ufat/util.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! Helpers shared by the command line interface and the Varlink service. +use std::fmt; use std::fs::File; use std::io::{self, Read, Seek}; use std::os::fd::AsFd; @@ -11,6 +12,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use fat::device::{Access, Device}; use fat::errno; use fat::format::FormatOptions; +use fat::layout::Layout; use fat::manifest::{Order, Reader, RootObject}; use fat::plan::{Estimate, Plan, PlanOptions}; use fat::probe::Prober; @@ -71,8 +73,9 @@ pub(crate) enum ManifestUse { /// It is planned and none of its content is written: it is read once, /// on from its root file object. A pipe will do. PlanOnly, - /// It is planned before its content is written, and has to be in a - /// regular file for that: the plan reads it once more from its start. + /// It is planned before its content is written, with `--minimize` or + /// `minimize`, and has to be in a regular file for that: the plan reads + /// it once more from its start. Plan, } @@ -286,10 +289,19 @@ pub(crate) struct Target<'a> { pub flags: ImageFlags, } -/// Why [`fit_and_format`] could not fit the content. +/// Why the size of a new file system could not be decided. pub(crate) enum FitError { - /// The image is fixed in size and smaller than the content needs. + /// Nothing says how large the file system is to be: no size was given + /// and the image is empty. + SizeRequired, + /// The smallest file system that holds the content, `minimal` bytes, + /// is larger than the most it may take, `actual` bytes: the size given + /// with a file system sized to fit, or the block device behind the + /// offset. TooSmall { minimal: u64, actual: u64 }, + /// The file system of the size given holds fewer clusters than the + /// content takes. + TooFewClusters(ClusterShortfall), /// Anything else. Other(Error), } @@ -304,6 +316,11 @@ impl FitError { /// The error as the command line tool reports it. pub(crate) fn into_error(self, image: &Path) -> Error { match self { + FitError::SizeRequired => err!( + errno::EINVAL, + "{} is empty: give --size, or --minimize to make the file system as small as its content allows", + image.display() + ), FitError::TooSmall { minimal, actual } => { err!( errno::ENOSPC, @@ -313,32 +330,145 @@ impl FitError { minimal ) } + FitError::TooFewClusters(shortfall) => err!(errno::ENOSPC, "{}: {}", image.display(), shortfall), FitError::Other(e) => e, } } } -/// Sizes, formats and opens a file system that fits what `add` puts into -/// the plan: the one way mkfs --fit and assemble make a volume, and what -/// the Varlink Assemble method does in two steps with [`plan_fit`] and -/// [`format_fit`]. The image is opened once; a block device -/// is planned for its logical block size, a regular image file is grown, -/// never shrunk, to the size given or to the fit, and created first with -/// [`ImageFlags::CREATE`]. Everything that can go wrong before the first -/// write, a source that cannot be read, content that does not fit the -/// size given, is found out while the image is untouched, and a file created -/// for the file system is removed again then, so a failed command leaves -/// nothing behind. Without [`ImageFlags::FORCE`], an image that holds a -/// file system, a partition table or other data is not formatted over -/// ([`Prober::ensure_empty`]). +/// The partition start [`fat::format::prepare`] is given where only the +/// layout of a file system is wanted. It goes into the hidden sectors field +/// of the boot sector, and the layout does not depend on it. +const PARTITION_START_FOR_LAYOUT: u64 = 0; + +/// A size given for a new file system, with the layout the formatter makes +/// of it. What goes into that file system is planned with the cluster size +/// of the layout, and has to fit its clusters. +pub(crate) struct GivenSize { + pub size: u64, + pub layout: Layout, +} + +impl GivenSize { + /// Lays out a file system of `size` bytes the way the formatter does + /// with `options` on a device of `block_size`, and writes nothing. A + /// size no file system of the options fits in, 0 among them, fails as + /// the formatter fails on it. + pub(crate) fn new(options: &FormatOptions, size: u64, block_size: Option) -> Result { + let layout = fat::format::prepare(options, size, block_size, PARTITION_START_FOR_LAYOUT)?.layout; + Ok(GivenSize { size, layout }) + } + + /// Whether the clusters a plan counts, `estimate`, fit the file system. + pub(crate) fn check(&self, estimate: &Estimate) -> std::result::Result<(), ClusterShortfall> { + if self.layout.clusters < estimate.data_clusters { + return Err(ClusterShortfall { + size: self.size, + cluster_size: self.layout.cluster_size(), + clusters: self.layout.clusters, + needed: estimate.data_clusters, + }); + } + Ok(()) + } +} + +/// A file system of a size given that holds fewer clusters than the content +/// takes. The clusters do not grow with the size in every step: one sector +/// more can take one more sector for each FAT and leave one cluster less. +/// So this is counted in clusters. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ClusterShortfall { + size: u64, + cluster_size: u32, + clusters: u32, + needed: u32, +} + +impl fmt::Display for ClusterShortfall { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "a file system of {} bytes holds {} clusters of {} bytes, the content needs {}", + self.size, self.clusters, self.cluster_size, self.needed + ) + } +} + +/// How large a new file system is made, decided before its content is +/// looked at. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SizeMode { + /// The size given, or else the rest of the image behind the offset, as + /// mkfs.fat does. The content is not planned. + Given, + /// The size given, which the content has to fit, or else the smallest + /// size that holds it. + Fit, + /// The smallest size that holds the content. A size given is the most + /// it may take. + Minimize, +} + +impl SizeMode { + /// What it asks of the manifest of the content: everything but the + /// size given plans it before its content is written. + pub(crate) fn manifest_use(self) -> ManifestUse { + match self { + SizeMode::Given => ManifestUse::Write, + SizeMode::Fit | SizeMode::Minimize => ManifestUse::Plan, + } + } +} + +/// How large a new file system is made, see [`SizeMode`], with the closure +/// that puts its content into the plan. +pub(crate) enum SizeRequest<'a> { + Given, + Fit(&'a mut dyn FnMut(&mut Plan) -> Result<()>), + Minimize(&'a mut dyn FnMut(&mut Plan) -> Result<()>), +} + +impl<'a> SizeRequest<'a> { + /// The request for `mode`, with `add` to put the content into the + /// plan. + pub(crate) fn new(mode: SizeMode, add: &'a mut dyn FnMut(&mut Plan) -> Result<()>) -> SizeRequest<'a> { + match mode { + SizeMode::Given => SizeRequest::Given, + SizeMode::Fit => SizeRequest::Fit(add), + SizeMode::Minimize => SizeRequest::Minimize(add), + } + } +} + +/// The size decided for a new file system, and the estimate of the plan +/// when the content was planned. +pub(crate) struct SizeDecision { + pub size: u64, + pub estimate: Option, +} + +/// Makes and opens a file system the way `request` says: the one way the +/// command line makes a volume, and what the Varlink Assemble method does +/// in two steps with [`decide_size`] and [`format_sized`]. The image is +/// opened once; a block device is planned for its logical block size, a +/// regular image file is grown, never shrunk, to the size, and created +/// first with [`ImageFlags::CREATE`]. What can be found out before the +/// first write is found out while the image is untouched: a size no file +/// system fits in and, when the content is planned, a source tree that +/// cannot be read, a manifest that cannot be planned, and content that +/// does not fit a size given. A file created for the file system is +/// removed again then, so a failed command leaves nothing behind. Without +/// [`ImageFlags::FORCE`], an image that holds a file system, a partition +/// table or other data is not formatted over ([`Prober::ensure_empty`]). pub(crate) fn fit_and_format( target: &Target<'_>, options: &mut FormatOptions, - add: &mut dyn FnMut(&mut Plan) -> Result<()>, -) -> std::result::Result<(Volume, Estimate), FitError> { + request: SizeRequest<'_>, +) -> std::result::Result<(Volume, Option), FitError> { let mut device = open_target(target)?; - let (estimate, size) = match plan_fit(&mut device, target.offset, target.size, options, false, add) { - Ok(fit) => fit, + let decision = match decide_size(&mut device, target.offset, target.size, options, false, request) { + Ok(decision) => decision, Err(e) => { // Nothing has been written. The error of the removal, if any, // is not the one the user needs to hear about. @@ -347,63 +477,113 @@ pub(crate) fn fit_and_format( } }; if !target.flags.contains(ImageFlags::FORCE) { - Prober::new().ensure_empty(&device, target.offset, Some(size))?; + Prober::new().ensure_empty(&device, target.offset, Some(decision.size))?; } - format_fit(device, target.offset, size, estimate, options) + let volume = format_sized(device, target.offset, decision.size, options)?; + Ok((volume, decision.estimate)) } -/// Plans the content and decides the size of the file system: the size -/// given, or the smallest that fits. Nothing is written; the image is only -/// asked for its type, block size and length, so that content that does -/// not fit is reported while the image is as it was. `device` covers the -/// whole image, a descriptor the service was handed or the file the -/// command line tool opened or created; the file system goes to `offset` -/// and takes `size` bytes, or what fits when there is no size. With -/// `label_slot` the root directory is planned with a volume label entry -/// whether or not a label is given, for a caller that stamps the root's -/// time on one afterwards ([`Volume::set_root_time`]). -pub(crate) fn plan_fit( +/// Decides the size of a new file system the way `request` says. Nothing +/// is written; the image is only asked for its type, block size and +/// length. `device` covers the whole image, a descriptor the service was +/// handed or the file the command line tool opened or created; the file +/// system goes to `offset` and takes `size` bytes. With `label_slot` the +/// root directory is planned with a volume label entry whether or not a +/// label is given, for a caller that stamps the root's time on one +/// afterwards ([`Volume::set_root_time`]). +/// +/// [`SizeRequest::Given`] without a size takes the rest of the image, and +/// an empty image is [`FitError::SizeRequired`] then. A size the file +/// system is to take that no file system of the options fits in, 0 among +/// them, fails as the formatter fails on it. [`SizeRequest::Fit`] plans the +/// content of a file system that takes the size given with the cluster +/// size the formatter picks for that size, and the content has to fit the +/// clusters the formatter lays out for it ([`FitError::TooFewClusters`]). +/// A file system sized to fit has to fit a size given and a block device +/// ([`FitError::TooSmall`]), and only it gets the sector and the cluster +/// size it was planned with in `options`. Content that does not fit is +/// reported while the image is as it was. +pub(crate) fn decide_size( device: &mut Device, offset: u64, size: Option, options: &mut FormatOptions, label_slot: bool, - add: &mut dyn FnMut(&mut Plan) -> Result<()>, -) -> std::result::Result<(Estimate, u64), FitError> { + request: SizeRequest<'_>, +) -> std::result::Result { let block_size = device.logical_block_size()?; + // The size the file system keeps when the content fits it. + let (add, kept) = match request { + SizeRequest::Given => { + let size = match size { + Some(size) => size, + None if device.is_empty() => return Err(FitError::SizeRequired), + None => device.len().checked_sub(offset).ok_or_else(|| { + err!( + errno::EINVAL, + "offset {} is beyond the end of the device ({} bytes)", + offset, + device.len() + ) + })?, + }; + // A size no file system of the options fits in is found before + // the image is grown. + GivenSize::new(options, size, block_size)?; + return Ok(SizeDecision { size, estimate: None }); + } + SizeRequest::Fit(add) => (add, size), + SizeRequest::Minimize(add) => (add, None), + }; let mut plan_options = PlanOptions::from_format_options(options, block_size)?; plan_options.label |= label_slot; + // The content of a file system of the size kept is planned with the + // cluster size the formatter picks for that size. A size no file system + // of the options fits in is found before the image is grown. + let kept = kept.map(|size| GivenSize::new(options, size, block_size)).transpose()?; + if let Some(kept) = &kept { + plan_options.cluster_size = Some(kept.layout.cluster_size()); + } let mut plan = Plan::new(plan_options); add(&mut plan)?; let estimate = plan.estimate()?; - estimate.apply(options); - let size = size.unwrap_or(estimate.size()); - // A block device cannot grow: what lies behind the offset is all there - // is. A regular file is grown to the size, so the size is the limit. - let available = if device.is_block_device() { - size.min(device.len().saturating_sub(offset)) - } else { - size + let size = match kept { + // The content has to fit the clusters of that file system. + Some(kept) => { + kept.check(&estimate).map_err(FitError::TooFewClusters)?; + kept.size + } + // Sized to fit, the file system is formatted as it was planned. A + // size given is the most it may take, and a block device cannot + // grow: what lies behind the offset is all there is. + None => { + let room = device.is_block_device().then(|| device.len().saturating_sub(offset)); + if let Some(actual) = [size, room] + .into_iter() + .flatten() + .min() + .filter(|&actual| actual < estimate.size()) + { + return Err(FitError::TooSmall { + minimal: estimate.size(), + actual, + }); + } + estimate.apply(options); + estimate.size() + } }; - if available < estimate.size() { - return Err(FitError::TooSmall { - minimal: estimate.size(), - actual: available, - }); - } - Ok((estimate, size)) + Ok(SizeDecision { + size, + estimate: Some(estimate), + }) } -/// Sizes the image for a planned file system, formats it and opens it: -/// the second step of [`fit_and_format`], after [`plan_fit`]. -pub(crate) fn format_fit( - mut device: Device, - offset: u64, - size: u64, - estimate: Estimate, - options: &FormatOptions, -) -> std::result::Result<(Volume, Estimate), FitError> { +/// Sizes the image for a new file system of `size` bytes at `offset`, +/// formats it and opens it: the second step of [`fit_and_format`], after +/// [`decide_size`]. +pub(crate) fn format_sized(mut device: Device, offset: u64, size: u64, options: &FormatOptions) -> Result { size_image(&mut device, offset, size)?; let device = device.window(offset, Some(size))?; - Ok((Volume::create(device, options)?, estimate)) + Volume::create(device, options) } diff --git a/tests/cli.rs b/tests/cli.rs index 653a828..aea1acc 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -412,7 +412,7 @@ fn assemble_refuses_to_format_over_what_is_there() { let t = t.to_str().unwrap(); let a = root.join("a.img"); let a = a.to_str().unwrap(); - ok(&bin, &["assemble", "--create", a, t]); + ok(&bin, &["assemble", "--create", "--minimize", a, t]); let refused = "the image holds a FAT file system, use --force to format it anyway"; fails(&bin, &["assemble", a, t], refused); fails(&bin, &["assemble", "--create", "--size", "40M", a], refused); @@ -424,7 +424,7 @@ fn assemble_refuses_to_format_over_what_is_there() { // Empty and zeros. let empty = root.join("empty.img"); fs::File::create(&empty).unwrap(); - ok(&bin, &["assemble", empty.to_str().unwrap(), t]); + ok(&bin, &["assemble", "--minimize", empty.to_str().unwrap(), t]); let zeros = root.join("zeros.img"); fs::File::create(&zeros).unwrap().set_len(40 << 20).unwrap(); ok(&bin, &["assemble", zeros.to_str().unwrap()]); @@ -437,6 +437,16 @@ fn assemble_refuses_to_format_over_what_is_there() { ok(&bin, &["assemble", "--size", "40M", d]); fails(&bin, &["assemble", "--offset", "60M", d], refused); fails(&bin, &["assemble", "--offset", "60M", "--size", "40M", d, t], refused); + // An offset beyond the end of the image leaves no size to take. One at + // its end leaves 0 bytes, too few for any file system, like a size of 0. + fails( + &bin, + &["assemble", "--offset", "200M", d], + "offset 209715200 is beyond the end of the device (104857600 bytes)", + ); + let no_room = "0 sectors are not enough for the 32 reserved sectors"; + fails(&bin, &["assemble", "--offset", "100M", d], no_room); + fails(&bin, &["assemble", "--size", "0", d], no_room); // Another file system, which libblkid names. let ext4 = root.join("ext4.img"); let mkfs_ext4 = common::Maker::of("ext4"); @@ -479,13 +489,16 @@ fn assemble_and_populate_take_trees_and_manifests() { assert!(run(&bin, &["check", a]).status.success()); let tree_size = ok(&bin, &["assemble", "--plan", tree_arg]); // A manifest of the tree, kept outside it, builds the same content; the - // one SOURCE says where the files are. assemble reads it twice. + // one SOURCE says where the files are. --minimize reads it twice. let manifest = root.join("tree.manifest"); fs::write(&manifest, ok(&bin, &["manifest", tree_arg])).unwrap(); let m = manifest.to_str().unwrap(); let b = image("b.img"); let b = b.as_str(); - ok(&bin, &["assemble", "--create", "--manifest", m, b, tree_arg]); + ok( + &bin, + &["assemble", "--create", "--minimize", "--manifest", m, b, tree_arg], + ); assert_eq!(ok(&bin, &["list", b, "/loader/entries"]), "x.conf\n"); assert_eq!(ok(&bin, &["cat", b, "/EFI/Linux/linux.efi"]), "kernel"); assert_eq!(fs::metadata(b).unwrap().len().to_string() + "\n", tree_size); @@ -584,34 +597,21 @@ fn assemble_and_populate_take_trees_and_manifests() { assert!(ok(&bin, &["check", clean]).contains("not cleanly unmounted")); // --manifest - reads the manifest from standard input, which then // cannot carry the file contents as well. A pipe is read once. - // assemble with a SOURCE plans the content before it writes it, so it - // refuses one before it reads anything of it: all of it is left in the - // pipe. assemble --plan and assemble without a SOURCE read the - // manifest once and take one. assemble --plan takes standard input - // that is the file itself as well. + // assemble --minimize with a SOURCE plans the content before it writes + // it, so it refuses one before it reads anything of it: all of it is + // left in the pipe. assemble --plan, assemble without a SOURCE and + // assemble with a size given read the manifest once and take one. + // assemble --plan takes standard input that is the file itself as well. let manifest_bytes = fs::read(&manifest).unwrap(); - let not_a_file = "standard input is not a regular file: assemble with a SOURCE needs the manifest in one"; + let not_a_file = "standard input is not a regular file: --minimize with a SOURCE needs the manifest in one"; let piped = image("piped.img"); let piped = piped.as_str(); - for args in [ - &["assemble", "--create", "--manifest", "-", piped, tree_arg][..], - &[ - "assemble", - "--create", - "--size", - "40M", - "--manifest", - "-", - piped, - tree_arg, - ], - ] { - let (out, left) = run_from_pipe(&bin, args, &manifest_bytes); - assert_eq!(out.status.code(), Some(1), "{:?}", args); - assert!(String::from_utf8_lossy(&out.stderr).contains(not_a_file), "{:?}", args); - assert_eq!(left, manifest_bytes, "{:?}", args); - assert!(!Path::new(piped).exists()); - } + let minimized = ["assemble", "--create", "--minimize", "--manifest", "-", piped, tree_arg]; + let (out, left) = run_from_pipe(&bin, &minimized, &manifest_bytes); + assert_eq!(out.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&out.stderr).contains(not_a_file)); + assert_eq!(left, manifest_bytes); + assert!(!Path::new(piped).exists()); let (out, left) = run_from_pipe( &bin, &["assemble", "--create", "--manifest", "-", piped], @@ -621,6 +621,7 @@ fn assemble_and_populate_take_trees_and_manifests() { assert!(left.is_empty(), "{} bytes left", left.len()); assert_eq!(fs::metadata(piped).unwrap().len().to_string() + "\n", tree_size); assert!(run(&bin, &["check", piped]).status.success()); + fs::remove_file(piped).unwrap(); let (out, left) = run_from_pipe(&bin, &["assemble", "--plan", "--manifest", "-"], &manifest_bytes); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8_lossy(&out.stdout), tree_size); @@ -628,6 +629,22 @@ fn assemble_and_populate_take_trees_and_manifests() { let out = run_from(&bin, &["assemble", "--plan", "--manifest", "-"], &manifest); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(String::from_utf8_lossy(&out.stdout), tree_size); + let out = run_in( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + "--manifest", + "-", + piped, + tree_arg, + ], + &manifest_bytes, + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(ok(&bin, &["cat", piped, "/loader/entries/x.conf"]), "title x\n"); let out = run_in(&bin, &["populate", "--manifest", "-", a, tree_arg], &manifest_bytes); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let out = run_in(&bin, &["populate", "--manifest", "-", a, "-"], b""); @@ -719,14 +736,18 @@ fn assemble_and_populate_take_trees_and_manifests() { // the manifest describes at its start, and that is what is copied. let d = image("d.img"); let d = d.as_str(); - fails(&bin, &["assemble", "--create", "--manifest", m, d, nowhere], "nowhere"); + fails( + &bin, + &["assemble", "--create", "--minimize", "--manifest", m, d, nowhere], + "nowhere", + ); assert!(!Path::new(d).exists()); let empty = root.join("empty"); let empty = empty.to_str().unwrap(); fs::create_dir(empty).unwrap(); fails( &bin, - &["assemble", "--create", "--manifest", m, d, empty], + &["assemble", "--create", "--minimize", "--manifest", m, d, empty], &format!( "ufat: {}: EFI/Linux/linux.efi: failed to open EFI/Linux/linux.efi", empty @@ -765,6 +786,25 @@ fn assemble_and_populate_take_trees_and_manifests() { assert_eq!(fs::metadata(c).unwrap().len().to_string() + "\n", tree_size); ok(&bin, &["populate", "--manifest", m, c, tree_arg]); assert!(run(&bin, &["check", c]).status.success()); + // With --size it takes that size, which the --fit directory or what the + // manifest describes has to fit. A size no file system fits in is + // refused as it is without them. + let e = image("e.img"); + let e = e.as_str(); + for sized in [["--fit", tree_arg], ["--manifest", m]] { + ok( + &bin, + &[&["assemble", "--create", "--size", "64M", e][..], &sized].concat(), + ); + assert_eq!(fs::metadata(e).unwrap().len(), 64 << 20); + fs::remove_file(e).unwrap(); + fails( + &bin, + &[&["assemble", "--create", "--size", "1M", e][..], &sized].concat(), + "FAT32 needs at least 65525", + ); + assert!(!Path::new(e).exists()); + } fails( &bin, &["assemble", "--create", "--fit", tree_arg, "--manifest", nowhere, c], @@ -866,18 +906,23 @@ fn manifests_have_to_declare_their_order() { &format!("ufat: {}: {}", m, refused), ); assert!(!image.exists()); - fails(&bin, &["assemble", "--plan", "--manifest", m], refused); - fails(&bin, &["assemble", "--create", "--manifest", m, a], refused); - assert!(!image.exists()); - ok(&bin, &["assemble", "--create", "--size", "40M", a]); - fails(&bin, &["populate", "--manifest", m, a, t], refused); - let out = run_in(&bin, &["populate", "--manifest", "-", a, t], undeclared.as_bytes()); + let out = run_in( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", "-", a, t], + undeclared.as_bytes(), + ); assert_eq!(out.status.code(), Some(1)); assert!( String::from_utf8_lossy(&out.stderr).contains(&format!("ufat: standard input: {}", refused)), "{}", String::from_utf8_lossy(&out.stderr) ); + assert!(!image.exists()); + fails(&bin, &["assemble", "--plan", "--manifest", m], refused); + fails(&bin, &["assemble", "--create", "--manifest", m, a], refused); + assert!(!image.exists()); + ok(&bin, &["assemble", "--create", "--size", "40M", a]); + fails(&bin, &["populate", "--manifest", m, a, t], refused); assert_eq!(ok(&bin, &["list", a]), ""); // With the declaration it is taken. fs::write(&manifest, &declared).unwrap(); @@ -887,10 +932,13 @@ fn manifests_have_to_declare_their_order() { /// A volume too small for what goes into it. A copy that runs out of /// clusters says which file did not fit and leaves what came before it in -/// a consistent file system. `assemble` with a `--size` the content does -/// not fit says so before it sizes or formats anything: a file `--create` -/// made is gone again and an existing file is as it was. Without a size an -/// existing file is grown to the fit and never shrunk. +/// a consistent file system. `assemble --minimize` with a `--size` the +/// content does not fit says so before it sizes or formats anything: a +/// file `--create` made is gone again and an existing file is as it was. +/// So do `--fit` and `--manifest` without a SOURCE, and a size of 0, which +/// no file system fits in. With `--minimize` and without a size an +/// existing file is grown to the fit and never shrunk. Without +/// `--minimize` the file system takes the size given or the whole file. #[test] fn too_small_volumes_fail_cleanly() { let _serial = common::serial(); @@ -918,38 +966,256 @@ fn too_small_volumes_fail_cleanly() { let n = new.to_str().unwrap(); fails( &bin, - &["assemble", "--create", "--size", "1M", n, t], + &["assemble", "--create", "--minimize", "--size", "1M", n, t], "holds 1048576 bytes but the content needs", ); assert!(!new.exists(), "a failed assemble left its image behind"); + fails( + &bin, + &["assemble", "--create", n, t], + "is empty: give --size, or --minimize", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + fails( + &bin, + &["assemble", "--create", "--size", "1M", n, t], + "FAT32 needs at least 65525", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + fails( + &bin, + &["assemble", "--create", "--size", "0", n, t], + "0 sectors are not enough for the 32 reserved sectors", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + // An empty file system that the tree or its manifest has to fit is + // refused the same way, in the clusters --size 34M gets. + let manifest = root.join("tree.manifest"); + fs::write(&manifest, ok(&bin, &["manifest", t])).unwrap(); + let m = manifest.to_str().unwrap(); + for content in [["--fit", t], ["--manifest", m]] { + fails( + &bin, + &[&["assemble", "--create", "--size", "34M", n][..], &content].concat(), + "a file system of 35651584 bytes holds 68528 clusters of 512 bytes, the content needs 73732", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + } let existing = root.join("existing.img"); let e = existing.to_str().unwrap(); fs::write(&existing, b"").unwrap(); fails( &bin, - &["assemble", "--size", "1M", e, t], + &["assemble", "--minimize", "--size", "1M", e, t], "holds 1048576 bytes but the content needs", ); assert_eq!(fs::metadata(&existing).unwrap().len(), 0); let size: u64 = ok(&bin, &["assemble", "--plan", t]).trim().parse().unwrap(); - // A plan against a size says whether the tree fits it. - fails(&bin, &["assemble", "--plan", "--size", "1M", t], "more than --size"); + // A plan against a size says whether the tree fits it, the way + // assemble with the same options would: 1M is too small for any file + // system, and too small for the smallest one --minimize makes. + fails( + &bin, + &["assemble", "--plan", "--size", "1M", t], + "FAT32 needs at least 65525", + ); + fails( + &bin, + &["assemble", "--plan", "--minimize", "--size", "1M", t], + "more than --size", + ); assert_eq!( ok(&bin, &["assemble", "--plan", "--size", "64M", t]), format!("{}\n", size) ); fs::File::create(&existing).unwrap().set_len(4096).unwrap(); - ok(&bin, &["assemble", e, t]); + ok(&bin, &["assemble", "--minimize", e, t]); assert_eq!(fs::metadata(&existing).unwrap().len(), size); assert_eq!(ok(&bin, &["cat", e, "/sub/c.txt"]), "last\n"); let large = root.join("large.img"); let l = large.to_str().unwrap(); fs::File::create(&large).unwrap().set_len(64 << 20).unwrap(); - ok(&bin, &["assemble", l, t]); + ok(&bin, &["assemble", "--minimize", l, t]); assert_eq!(fs::metadata(&large).unwrap().len(), 64 << 20); + assert!(ok(&bin, &["describe", l]).contains(&format!("size: {}\n", size))); assert!(run(&bin, &["check", l]).status.success()); assert_eq!(ok(&bin, &["cat", l, "/sub/c.txt"]), "last\n"); + ok(&bin, &["assemble", "--force", l, t]); + assert!(ok(&bin, &["describe", l]).contains(&format!("size: {}\n", 64 << 20))); + assert_eq!(ok(&bin, &["cat", l, "/sub/c.txt"]), "last\n"); + // Without --minimize nothing is planned: what does not fit fails while + // it is written, and leaves the file system unfinished. + fs::File::create(&large).unwrap().set_len(36 << 20).unwrap(); + fails(&bin, &["assemble", l, t], "copying big.bin: no free clusters left"); + assert!(ok(&bin, &["check", l]).contains("marked dirty")); +} + +/// A file system of the size given gets the cluster size that size gets, +/// also where `--fit` or `--manifest` without a SOURCE plans what it has to +/// hold. A plan of a small tree picks 512 byte clusters, and 200 GiB of +/// them are more than FAT32 can count. The images are sparse. +#[test] +fn a_size_given_keeps_its_cluster_size() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let t = root.join("tree"); + let t = t.to_str().unwrap(); + let manifest = root.join("tree.manifest"); + fs::write(&manifest, ok(&bin, &["manifest", t])).unwrap(); + let m = manifest.to_str().unwrap(); + let sized = ["assemble", "--create", "--size", "200G", "--identifier", "1234abcd"]; + let alone = root.join("alone.img"); + let alone = alone.to_str().unwrap(); + ok(&bin, &[&sized[..], &[alone]].concat()); + let geometry = ok(&bin, &["describe", alone]); + assert!(geometry.contains("cluster size: 32768\n"), "{}", geometry); + let image = root.join("sized.img"); + let i = image.to_str().unwrap(); + for content in [["--fit", t], ["--manifest", m]] { + ok(&bin, &[&sized[..], &content, &[i]].concat()); + assert_eq!(fs::metadata(&image).unwrap().len(), 200 << 30); + assert_eq!(ok(&bin, &["describe", i]), geometry); + assert!(run(&bin, &["check", i]).status.success()); + fs::remove_file(&image).unwrap(); + } +} + +/// Whether the content fits a size given is counted in clusters. One +/// sector more can take one more sector for each FAT and hold one cluster +/// less: with 512 byte clusters a file system of 66590 sectors holds 65534 +/// clusters, one of 66591 sectors 65533. A tree that takes 65534 clusters +/// fills the smaller one to the last cluster. Its plan, the smallest file +/// system for it, has 66590 sectors, fewer than 66591, so comparing sizes +/// would let `--fit` and `--manifest` pass there and the copy run out of +/// clusters. The images are sparse. +#[test] +fn one_sector_more_can_hold_one_cluster_less() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + // A cluster for the root directory and 65533 for the file. + let tree = root.join("tree"); + fs::create_dir(&tree).unwrap(); + fs::File::create(tree.join("big")) + .unwrap() + .set_len(65533 * 512) + .unwrap(); + let t = tree.to_str().unwrap(); + let manifest = root.join("tree.manifest"); + fs::write(&manifest, ok(&bin, &["manifest", t])).unwrap(); + let m = manifest.to_str().unwrap(); + let sectors = |n: u64| (n * 512).to_string(); + let clusters = |free: u64, clusters: u64| format!("clusters: {} ({} free)", clusters, free); + assert_eq!(ok(&bin, &["assemble", "--plan", t]), sectors(66590) + "\n"); + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + for (n, held) in [(66590, 65534), (66591, 65533), (66592, 65534)] { + ok(&bin, &["assemble", "--create", "--size", §ors(n), a]); + assert!(ok(&bin, &["describe", a]).contains(&clusters(held - 1, held))); + fs::remove_file(&image).unwrap(); + } + for content in [["--fit", t], ["--manifest", m]] { + for n in [66590, 66592] { + ok( + &bin, + &[&["assemble", "--create", "--size", §ors(n), a][..], &content].concat(), + ); + fs::remove_file(&image).unwrap(); + } + fails( + &bin, + &[&["assemble", "--create", "--size", §ors(66591), a][..], &content].concat(), + "a file system of 34094592 bytes holds 65533 clusters of 512 bytes, the content needs 65534", + ); + assert!(!image.exists(), "a failed assemble left its image behind"); + } + // The copy agrees: the tree fills 66590 sectors to the last cluster and + // does not go into 66591. + ok( + &bin, + &["assemble", "--create", "--size", §ors(66590), "--fit", t, a], + ); + ok(&bin, &["populate", a, t]); + assert!(ok(&bin, &["describe", a]).contains(&clusters(0, 65534))); + fs::remove_file(&image).unwrap(); + ok(&bin, &["assemble", "--create", "--size", §ors(66591), a]); + fails(&bin, &["populate", a, t], "copying big: no free clusters left"); +} + +/// `assemble --plan --size` answers for `assemble` with the same options. +/// Without `--minimize` that is a file system of the size given, with the +/// cluster size the formatter picks for it: 80000 files of one byte fit 512 +/// byte clusters in about 44 MB, but take 80000 of the 4 KiB clusters that +/// 300 MiB gets, and it has fewer. With `--minimize` the smallest file +/// system, with 512 byte clusters, has to fit in `--size`. The files come +/// from standard input, after a manifest. +#[test] +fn a_plan_against_a_size_answers_for_assemble() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + // 100 directories of 800 files, which keeps every directory below the + // 65536 entries FAT allows. + let mut text = String::from( + "\x1e{\"features\":[\"size\"],\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + ); + for d in 0..100 { + text.push_str(&format!("\x1e{{\"name\":\"d{:02}\",\"type\":\"dir\"}}\n", d)); + for f in 0..800 { + text.push_str(&format!("\x1e{{\"name\":\"d{:02}/f{:03}\",\"size\":1}}\n", d, f)); + } + } + text.push_str("\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"); + let manifest = root.join("small.manifest"); + fs::write(&manifest, text).unwrap(); + let m = manifest.to_str().unwrap(); + let contents = vec![b'x'; 80_000]; + let smallest: u64 = ok(&bin, &["assemble", "--plan", "--manifest", m]) + .trim() + .parse() + .unwrap(); + assert!(smallest < 300 << 20, "{}", smallest); + ok( + &bin, + &["assemble", "--plan", "--minimize", "--size", "300M", "--manifest", m], + ); + fails( + &bin, + &["assemble", "--plan", "--size", "300M", "--manifest", m], + "a file system of 314572800 bytes holds 76646 clusters of 4096 bytes, the content needs 80701", + ); + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + let out = run_in( + &bin, + &["assemble", "--create", "--size", "300M", "--manifest", m, a, "-"], + &contents, + ); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(stderr.contains("no free clusters left"), "{}", stderr); + fs::remove_file(&image).unwrap(); + // 400 MiB holds them, and the plan says so. + ok(&bin, &["assemble", "--plan", "--size", "400M", "--manifest", m]); + let out = run_in( + &bin, + &["assemble", "--create", "--size", "400M", "--manifest", m, a, "-"], + &contents, + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(ok(&bin, &["cat", a, "/d99/f799"]), "x"); } /// A plan does not compare names. The entries of a directory under two @@ -987,7 +1253,7 @@ fn directories_under_two_names_fill_up_when_written() { let a = image.to_str().unwrap(); fails( &bin, - &["assemble", "--create", "--manifest", s, a, "-"], + &["assemble", "--create", "--minimize", "--manifest", s, a, "-"], "directory is full", ); let whole = root.join("whole.manifest"); @@ -1024,6 +1290,7 @@ fn host_paths_need_not_be_utf8() { let out = ufat(&[ "assemble".as_ref(), "--create".as_ref(), + "--minimize".as_ref(), image.as_ref(), tree_dir.as_ref(), ]); @@ -1126,7 +1393,7 @@ fn populate_and_remove_work_on_paths() { assert!(!ok(&bin, &["list", a, "/"]).contains("fifo-fail")); fails(&bin, &["populate", "--unsupported", "maybe", a, t], "skip or fail"); // A plan refuses it too, from a tree or a manifest, and so does - // assemble, which plans first, before the image is touched. + // --minimize before the image is touched. fails( &bin, &["assemble", "--plan", "--unsupported", "fail", t], @@ -1156,6 +1423,7 @@ fn populate_and_remove_work_on_paths() { &bin, &[ "assemble", + "--minimize", "--unsupported", "fail", "--manifest", @@ -1193,7 +1461,10 @@ fn manifests_of_what_was_written() { let a = a.to_str().unwrap(); let written = root.join("written.manifest"); let w = written.to_str().unwrap(); - ok(&bin, &["assemble", "--create", "--write-manifest", w, a, t]); + ok( + &bin, + &["assemble", "--create", "--minimize", "--write-manifest", w, a, t], + ); let described = root.join("described.manifest"); let d = described.to_str().unwrap(); ok(&bin, &["describe", "--write-manifest", d, a]); @@ -1203,7 +1474,7 @@ fn manifests_of_what_was_written() { // The manifest builds the same files from the tree. let b = root.join("b.img"); let b = b.to_str().unwrap(); - ok(&bin, &["assemble", "--create", "--manifest", w, b, t]); + ok(&bin, &["assemble", "--create", "--minimize", "--manifest", w, b, t]); assert_eq!(ok(&bin, &["cat", b, "/EFI/Linux/linux.efi"]), "kernel"); let populated = root.join("populated.manifest"); let p = populated.to_str().unwrap(); @@ -1232,6 +1503,7 @@ fn manifests_of_what_was_written() { let (stdout, stderr) = run_here(&[ "assemble", "--create", + "--minimize", "--hash", "sha256", "--write-manifest", @@ -1251,6 +1523,7 @@ fn manifests_of_what_was_written() { let (stdout, stderr) = run_here(&[ "assemble", "--create", + "--minimize", "--hash", "sha256", "--write-hash", @@ -1265,7 +1538,17 @@ fn manifests_of_what_was_written() { assert_eq!(fs::read_to_string(&hash_file).unwrap(), sha256_line(e)); let f = root.join("f.img"); let f = f.to_str().unwrap(); - let (stdout, _) = run_here(&["assemble", "--create", "--hash", "sha256", "--write-hash", "-", f, t]); + let (stdout, _) = run_here(&[ + "assemble", + "--create", + "--minimize", + "--hash", + "sha256", + "--write-hash", + "-", + f, + t, + ]); assert_eq!(String::from_utf8_lossy(&stdout), sha256_line(f)); fails( &bin, @@ -1311,7 +1594,10 @@ fn counts_of_one() { let t = t.to_str().unwrap(); let a = root.join("a.img"); let a = a.to_str().unwrap(); - let out = run(&bin, &["assemble", "--create", "--verbose", "--fats", "1", a, t]); + let out = run( + &bin, + &["assemble", "--create", "--minimize", "--verbose", "--fats", "1", a, t], + ); let stderr = String::from_utf8_lossy(&out.stderr); assert!(out.status.success(), "{}", stderr); assert!( @@ -1340,7 +1626,7 @@ fn counts_of_one() { // FAT entry 0 without the media byte in the first of two FATs is one // error, and the one byte the second FAT differs in is one warning. let b = root.join("b.img"); - ok(&bin, &["assemble", "--create", b.to_str().unwrap(), t]); + ok(&bin, &["assemble", "--create", "--minimize", b.to_str().unwrap(), t]); let image = fs::OpenOptions::new().read(true).write(true).open(&b).unwrap(); let mut sector = [0u8; 512]; image.read_exact_at(&mut sector, 0).unwrap(); @@ -1458,13 +1744,35 @@ fn hashes_and_capabilities() { let t = t.to_str().unwrap(); let a = root.join("a.img"); let a = a.to_str().unwrap(); - let hash = ok(&bin, &["assemble", "--create", "--hash", "sha256", a, t]); + let hash = ok(&bin, &["assemble", "--create", "--minimize", "--hash", "sha256", a, t]); assert_eq!( hash, format!("{}\n", fat::manifest::Sha256::digest(&fs::read(a).unwrap())) ); let hash = ok(&bin, &["assemble", "--force", "--hash", "sha512", a, t]); assert_eq!(hash.trim().len(), 128); + // The hash is of the file system written, also where --size is only + // the most --minimize may take, and when the image is larger. + let size: usize = ok(&bin, &["assemble", "--plan", t]).trim().parse().unwrap(); + let b = root.join("b.img"); + let b = b.to_str().unwrap(); + let minimized = ["assemble", "--minimize", "--size", "50M", "--hash", "sha256"]; + let hash = ok(&bin, &[&minimized[..], &["--create", b, t]].concat()); + assert_eq!( + hash, + format!("{}\n", fat::manifest::Sha256::digest(&fs::read(b).unwrap())) + ); + fs::File::options() + .write(true) + .open(b) + .unwrap() + .set_len(100 << 20) + .unwrap(); + let hash = ok(&bin, &[&minimized[..], &["--force", b, t]].concat()); + assert_eq!( + hash, + format!("{}\n", fat::manifest::Sha256::digest(&fs::read(b).unwrap()[..size])) + ); fails(&bin, &["assemble", "--hash", "md5", a, t], "sha256 or sha512"); let caps = ok(&bin, &["capabilities"]); assert!( diff --git a/tests/fuzz/mutate.py b/tests/fuzz/mutate.py index 3e3a085..7ecceb7 100755 --- a/tests/fuzz/mutate.py +++ b/tests/fuzz/mutate.py @@ -936,13 +936,37 @@ def mutate_manifest(rng, seed_bytes): FSIZE_LIMIT = 1 << 30 # keep runaway images off the tmpfs -def run_local(argv, stdin_path=None, timeout=5.0, stderr_path=None, cwd=None, env=None): +def feed_pipe(path): + """A pipe with the bytes of the file at path in it, which the tool can + read once and not seek: returns its reading end and the process that + writes them. The writer is gone, or gets EPIPE, once the reading end + is closed everywhere.""" + r, w = os.pipe() + pid = os.fork() + if pid == 0: + try: + os.close(r) + with open(path, "rb") as f, os.fdopen(w, "wb") as out: + shutil.copyfileobj(f, out) + except BaseException: + pass + os._exit(0) + os.close(w) + return r, pid + + +def run_local(argv, stdin_path=None, timeout=5.0, stderr_path=None, cwd=None, env=None, stdin_pipe=False): """Runs argv under the resource limits and returns a dict of outcome data: exit status or signal, wall time, peak RSS (ru_maxrss from wait4, the counter /usr/bin/time -v reports as the maximum resident set - size) and the stderr tail.""" + size) and the stderr tail. With stdin_pipe the file at stdin_path comes + through a pipe.""" err_fd = os.open(stderr_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644) if stderr_path else os.open(os.devnull, os.O_WRONLY) - in_fd = os.open(stdin_path, os.O_RDONLY) if stdin_path else os.open(os.devnull, os.O_RDONLY) + feeder = None + if stdin_path and stdin_pipe: + in_fd, feeder = feed_pipe(stdin_path) + else: + in_fd = os.open(stdin_path, os.O_RDONLY) if stdin_path else os.open(os.devnull, os.O_RDONLY) out_fd = os.open(os.devnull, os.O_WRONLY) start = time.monotonic() pid = os.fork() @@ -986,6 +1010,10 @@ def run_local(argv, stdin_path=None, timeout=5.0, stderr_path=None, cwd=None, en time.sleep(delay) delay = min(delay * 1.5, 0.01) elapsed = time.monotonic() - start + if feeder is not None: + # Whatever the tool left in the pipe is not needed any more. + os.kill(feeder, signal.SIGKILL) + os.waitpid(feeder, 0) res = {"secs": round(elapsed, 4), "rss_kb": ru.ru_maxrss, "timeout": timed_out} if os.WIFEXITED(status): res["exit"] = os.WEXITSTATUS(status) @@ -1018,7 +1046,8 @@ def spawner_loop(rfd, wfd): wf = os.fdopen(wfd, "wb") for line in rf: req = json.loads(line) - res = run_local(req["argv"], req.get("stdin"), req.get("timeout", 5.0), req.get("stderr"), req.get("cwd"), req.get("env")) + res = run_local(req["argv"], req.get("stdin"), req.get("timeout", 5.0), req.get("stderr"), req.get("cwd"), req.get("env"), + req.get("stdin_pipe", False)) wf.write(json.dumps(res).encode("utf-8") + b"\n") wf.flush() os._exit(0) @@ -1038,11 +1067,12 @@ def start_spawner(): _SPAWNER = (os.fdopen(w1, "wb"), os.fdopen(r2, "rb"), pid) -def run(argv, stdin_path=None, timeout=5.0, stderr_path=None, cwd=None, env=None): +def run(argv, stdin_path=None, timeout=5.0, stderr_path=None, cwd=None, env=None, stdin_pipe=False): if _SPAWNER is None: - return run_local(argv, stdin_path, timeout, stderr_path, cwd, env) + return run_local(argv, stdin_path, timeout, stderr_path, cwd, env, stdin_pipe) w, r, _ = _SPAWNER - w.write(json.dumps({"argv": argv, "stdin": stdin_path, "timeout": timeout, "stderr": stderr_path, "cwd": cwd, "env": env}).encode("utf-8") + b"\n") + w.write(json.dumps({"argv": argv, "stdin": stdin_path, "timeout": timeout, "stderr": stderr_path, "cwd": cwd, "env": env, + "stdin_pipe": stdin_pipe}).encode("utf-8") + b"\n") w.flush() line = r.readline() if not line: @@ -1216,6 +1246,11 @@ def source_tree_for(seeds_dir, name): return os.path.join(seeds_dir, "trees", "esp") +# The size of the file systems that take the size given: the smallest FAT32 +# volume with 512 byte clusters is about 33 MiB. +SIZE_GIVEN = "64M" + + def worker_manifests(args): (indices, ufat, seed_paths, seeds_dir, out, timeout, mem_mb, base_seed, blob_path) = args work = os.path.join(out, "manifests-work", str(os.getpid())) @@ -1240,19 +1275,23 @@ def worker_manifests(args): n = rng.choice([0, 1, 100, len(blob) // 2, len(blob), len(blob) - 1]) with open(stream_path, "wb") as f: f.write(blob[:n]) + # The size given takes no plan: the manifest is read while the + # volume is written, also when it comes through a pipe. cmds = [ - ("plan", [ufat, "assemble", "--plan", "--manifest", m_path], None), - ("assemble", [ufat, "assemble", "--create", "--unsupported", "fail", "--manifest", m_path, img_path, source], None), - ("assemble-stream", [ufat, "assemble", "--create", "--manifest", m_path, img_path, "-"], stream_path), + ("plan", [ufat, "assemble", "--plan", "--manifest", m_path], None, False), + ("assemble", [ufat, "assemble", "--create", "--minimize", "--unsupported", "fail", "--manifest", m_path, img_path, source], None, False), + ("assemble-stream", [ufat, "assemble", "--create", "--minimize", "--manifest", m_path, img_path, "-"], stream_path, False), + ("assemble-sized", [ufat, "assemble", "--create", "--size", SIZE_GIVEN, "--unsupported", "fail", "--manifest", m_path, img_path, source], None, False), + ("assemble-pipe", [ufat, "assemble", "--create", "--size", SIZE_GIVEN, "--manifest", "-", img_path, source], m_path, True), ] if rng.random() < 0.3: - cmds.append(("assemble-skip", [ufat, "assemble", "--create", "--unsupported", "skip", "--no-check-validity", "--manifest", m_path, img_path, source], None)) - for cmd_name, argv, stdin in cmds: + cmds.append(("assemble-skip", [ufat, "assemble", "--create", "--minimize", "--unsupported", "skip", "--no-check-validity", "--manifest", m_path, img_path, source], None, False)) + for cmd_name, argv, stdin, stdin_pipe in cmds: try: os.unlink(img_path) except FileNotFoundError: pass - res = run(argv, stdin_path=stdin, timeout=timeout, stderr_path=err_path) + res = run(argv, stdin_path=stdin, timeout=timeout, stderr_path=err_path, stdin_pipe=stdin_pipe) res["cmd"] = cmd_name try: res["image_size"] = os.stat(img_path).st_size @@ -1266,7 +1305,7 @@ def worker_manifests(args): if kind: sig = signature(cmd_name, kind, detail, res.get("stderr", "")) saved = save_finding(out, sig, kind, detail, cmd_name, argv, res, variant, seed_name, None, desc, ".Uapi16Manifest", - extra={"stream_bytes": n if stdin else None}) + extra={"stream_bytes": n if stdin == stream_path else None, "manifest_on_stdin": stdin == m_path}) findings.append((sig, kind, detail, cmd_name, seed_name, desc, saved)) try: os.unlink(img_path) diff --git a/tests/fuzz/repro/quadratic-directory.py b/tests/fuzz/repro/quadratic-directory.py index 2b0d903..741897c 100755 --- a/tests/fuzz/repro/quadratic-directory.py +++ b/tests/fuzz/repro/quadratic-directory.py @@ -9,7 +9,7 @@ way. tests/fuzz/repro/quadratic-directory.py 16000 dir > many.Uapi16Manifest - time ufat assemble --create --manifest many.Uapi16Manifest img - < /dev/null + time ufat assemble --create --minimize --manifest many.Uapi16Manifest img - < /dev/null With `dir` every entry is a directory (no contents needed); with `file` every entry is an empty file whose contents come from the stream or from a diff --git a/tests/fuzz/targeted.py b/tests/fuzz/targeted.py index 7cf4236..08f1ee7 100755 --- a/tests/fuzz/targeted.py +++ b/tests/fuzz/targeted.py @@ -37,11 +37,12 @@ def __init__(self, ufat, seeds, work, timeout=20.0, mem_mb=300): self.seed_img = os.path.join(seeds, "images", "ufat-512s-512c-2M.img") self.small_tree = os.path.join(seeds, "trees", "small") - def run(self, name, argv, stdin=None, env=None, expect_exit=None, timeout=None): + def run(self, name, argv, stdin=None, env=None, expect_exit=None, timeout=None, stdin_pipe=False): """Runs argv and records a defect unless it exits with one of - expect_exit: 0 or 1, for fsck the fsck(8) codes 0, 4 and 8.""" + expect_exit: 0 or 1, for fsck the fsck(8) codes 0, 4 and 8. With + stdin_pipe the file stdin comes through a pipe.""" err = os.path.join(self.work, "stderr.txt") - res = mutate.run_local(argv, stdin_path=stdin, timeout=timeout or self.timeout, stderr_path=err, env=env) + res = mutate.run_local(argv, stdin_path=stdin, timeout=timeout or self.timeout, stderr_path=err, env=env, stdin_pipe=stdin_pipe) res["cmd"] = argv[1] if expect_exit is None: expect_exit = mutate.clean_exits(argv[1]) @@ -229,10 +230,19 @@ def manifests(self): self.run("manifest %s: plan" % name, [self.ufat, "assemble", "--plan", "--manifest", m], timeout=60) if os.path.exists(img): os.unlink(img) - self.run("manifest %s: assemble" % name, [self.ufat, "assemble", "--create", "--manifest", m, img, src], timeout=120) + self.run("manifest %s: assemble" % name, [self.ufat, "assemble", "--create", "--minimize", "--manifest", m, img, src], timeout=120) if os.path.exists(img): os.unlink(img) - self.run("manifest %s: assemble from a stream" % name, [self.ufat, "assemble", "--create", "--manifest", m, img, "-"], stdin=os.devnull, timeout=120) + self.run("manifest %s: assemble from a stream" % name, [self.ufat, "assemble", "--create", "--minimize", "--manifest", m, img, "-"], stdin=os.devnull, timeout=120) + if os.path.exists(img): + os.unlink(img) + # Into a size given nothing is planned: the manifest is read + # while the volume is written, also through a pipe. + self.run("manifest %s: assemble into a size given" % name, [self.ufat, "assemble", "--create", "--size", mutate.SIZE_GIVEN, "--manifest", m, img, src], timeout=120) + if os.path.exists(img): + os.unlink(img) + self.run("manifest %s: assemble through a pipe" % name, [self.ufat, "assemble", "--create", "--size", mutate.SIZE_GIVEN, "--manifest", "-", img, src], + stdin=m, stdin_pipe=True, timeout=120) if os.path.exists(img): os.unlink(img) # Not a manifest at all. diff --git a/tests/fuzz/varlink_fuzz.py b/tests/fuzz/varlink_fuzz.py index 95fbe26..7b6e83b 100755 --- a/tests/fuzz/varlink_fuzz.py +++ b/tests/fuzz/varlink_fuzz.py @@ -512,6 +512,10 @@ def method_cases(rng, seeds, work, small_tree, img): return cases +# The size of the file systems that take the size given, 64 MiB. +SIZE_GIVEN = 64 << 20 + + def manifest_cases(rng, seeds, work, img, count): """Assemble, written and planned, with mutated manifests.""" cases = [] @@ -533,8 +537,14 @@ def manifest_cases(rng, seeds, work, img, count): if rng.random() < 0.3: content["unsupported"] = "skip" content["manifest"]["checkValidity"] = False - params = {"image": {"fileDescriptor": 0}, "options": {}, "content": content} - cases.append(("Assemble-manifest[%s]" % desc[:40], [fdcall(IFACE + "Assemble", params, [(fimg, "rw"), mpath, (source, "dir")])], + # Half of them into a size given, which takes no plan: the + # manifest is read while the volume is written. + if rng.random() < 0.5: + image, options, label = {"fileDescriptor": 0}, {"minimize": True}, "Assemble-manifest" + else: + image, options, label = {"fileDescriptor": 0, "size": SIZE_GIVEN}, {}, "Assemble-sized" + params = {"image": image, "options": options, "content": content} + cases.append(("%s[%s]" % (label, desc[:40]), [fdcall(IFACE + "Assemble", params, [(fimg, "rw"), mpath, (source, "dir")])], {"manifest": variant, "cleanup": fimg})) elif kind < 0.65: cases.append(("Plan-manifest[%s]" % desc[:40], [fdcall(IFACE + "Assemble", {"mode": "plan", "content": {"manifest": {"fileDescriptor": 0}}}, [mpath])], @@ -544,7 +554,7 @@ def manifest_cases(rng, seeds, work, img, count): # directory: too short, too long, or just right by accident. blob = os.path.join(work, "case.blob") n = rng.choice([0, 1, 1000, 100000, 1 << 20]) - params = {"image": {"fileDescriptor": 0}, "options": {}, "content": {"manifest": {"fileDescriptor": 1}, "sourceFileDescriptor": 2}} + params = {"image": {"fileDescriptor": 0}, "options": {"minimize": True}, "content": {"manifest": {"fileDescriptor": 1}, "sourceFileDescriptor": 2}} cases.append(("Assemble-stream[%s]" % desc[:40], [fdcall(IFACE + "Assemble", params, [(fimg, "rw"), mpath, blob])], {"manifest": variant, "cleanup": fimg, "blob": bytes([0x5A]) * n, "blob_path": blob})) return cases diff --git a/tests/reference.rs b/tests/reference.rs index 54e9a24..2a7c0fb 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -632,7 +632,7 @@ fn an_assembled_tree_comes_back_through_mtools() { let img = image.0.to_str().unwrap(); let out = std::process::Command::new(&ufat) - .args(["assemble", "--create", "--verbose", img, src]) + .args(["assemble", "--create", "--minimize", "--verbose", img, src]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); @@ -731,6 +731,7 @@ fn fsck_fat_sees_a_failed_assemble() { .args([ "assemble", "--create", + "--minimize", "--manifest", manifest.0.to_str().unwrap(), img, diff --git a/tests/varlink.rs b/tests/varlink.rs index 8a15455..f140ef0 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -662,7 +662,7 @@ fn capabilities_describe_vfat() { "writeManifest" ] ); - assert_eq!(str_of(caps, "sizeToFit"), "exact"); + assert_eq!(str_of(caps, "sizeToFit"), "best"); // The smallest volume: 65525 clusters of one 512 byte sector, two // FATs of 512 sectors and 32 reserved sectors. let mut params = fat::layout::LayoutParams::new(512); @@ -730,7 +730,7 @@ fn methods_on_an_image_take_the_file_system_type() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); // Each method with what it needs besides the type and the image. @@ -807,7 +807,6 @@ fn assemble_plans_from_a_tree_and_a_manifest() { r#"{"mode":"plan","options":{"label":"esp","identifier":"1234-abcd"},"content":{"sourceFileDescriptor":0}}"#, &[source.as_fd()], )); - assert!(bool_of(&a, "exact")); assert_eq!(u64_of(&a, "files"), 2); assert_eq!(u64_of(&a, "directories"), 3); assert_eq!(u64_of(&a, "bytes"), 5010); @@ -880,7 +879,7 @@ fn assemble_plans_from_a_tree_and_a_manifest() { let r = reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"options":{"label":"esp","identifier":"1234-abcd"},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"label":"esp","identifier":"1234-abcd"},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); let rd = object_of(&r, "description"); @@ -895,7 +894,6 @@ fn assemble_plans_from_a_tree_and_a_manifest() { &[source.as_fd()], ); assert_eq!(phases(&replies), vec!["planning"]); - assert!(bool_of(replies.last().unwrap(), "exact")); } /// Assemble with a tree: the image sized to fit, the root stamped with the @@ -915,12 +913,11 @@ fn assemble_with_a_tree() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"label":"ESP","identifier":"1234-ABCD","timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"times":"clamp"}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"label":"ESP","identifier":"1234-ABCD","timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"times":"clamp"}}}}"#, T0 ), &[img.as_fd(), source.as_fd()], )); - assert!(bool_of(&r, "exact")); assert_eq!(u64_of(&r, "files"), 2); assert_eq!(u64_of(&r, "directories"), 3); assert_eq!(u64_of(&r, "bytes"), 5010); @@ -957,13 +954,23 @@ fn assemble_with_a_tree() { assert_eq!(data, vec![1u8; 5000]); assert_eq!(v.root_time().unwrap(), Some(UNIX_EPOCH + Duration::from_micros(T0))); drop(v); + // Without minimize the file system takes the size of the image, and + // an empty one has none. + let (_unsized, unsized_img) = fresh_image(); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + &[unsized_img.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.SizeRequired", IFACE)); // Without a timestamp the root takes the source directory's time, // which build_tree fixed. let (image2, img2) = fresh_image(); reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img2.as_fd(), source.as_fd()], )); let v = volume(image2.path(), Access::ReadOnly); @@ -1002,7 +1009,6 @@ fn assemble_without_content() { r#"{"image":{"fileDescriptor":0},"options":{"label":"ESP","blockSize":4096,"vfat":{"oemName":"ufat","fats":1}}}"#, &[img.as_fd()], )); - assert!(!bool_of(&r, "exact")); assert!(r.get("files").is_none()); let d = object_of(&r, "description"); assert_eq!(u64_of(d, "sizeBytes"), 320 << 20); @@ -1039,9 +1045,20 @@ fn assemble_without_content() { )); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 40 << 20); // An empty file without a size and without content has no size to take. - let (_fresh2, fresh_img2) = fresh_image(); + let (fresh2, fresh_img2) = fresh_image(); let e = error_of(&mut c, "Assemble", IMG, &[fresh_img2.as_fd()]); assert_eq!(e.name, format!("{}.SizeRequired", IFACE)); + // A size of 0 is too small for any file system, and so are the 0 bytes + // an offset at the end of an image that holds something leaves. + for (params, image) in [ + (r#"{"image":{"fileDescriptor":0,"size":0}}"#, &fresh_img2), + (r#"{"image":{"fileDescriptor":0,"offset":335544320}}"#, &img), + ] { + let e = error_of(&mut c, "Assemble", params, &[image.as_fd()]); + assert_eq!(e.name, format!("{}.NoSpaceLeft", IFACE), "{}", params); + assert_eq!(str_of(&e.parameters, "reason"), "volume"); + } + assert_eq!(std::fs::metadata(fresh2.path()).unwrap().len(), 0); // Options the library refuses are named as the interface spells them, // with force set, since the image holds a file system by now. let e = error_of( @@ -1052,6 +1069,13 @@ fn assemble_without_content() { ); assert_eq!(e.name, "org.varlink.service.InvalidParameter"); assert_eq!(str_of(&e.parameters, "parameter"), "blockSize"); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"options":{"blockSize":512,"sectorSize":4096,"force":true}}"#, + &[img.as_fd()], + ); + assert_eq!(str_of(&e.parameters, "parameter"), "blockSize"); let e = error_of( &mut c, "Assemble", @@ -1130,7 +1154,7 @@ fn assemble_refuses_what_is_there_without_force() { let r = reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"options":{"force":true},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"force":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); assert_eq!(u64_of(&r, "files"), 2); @@ -1185,7 +1209,7 @@ fn assemble_with_a_manifest_and_a_directory() { let r = reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"options":{"label":"ESP"},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"label":"ESP"},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], )); assert_eq!(u64_of(&r, "files"), 2); @@ -1200,7 +1224,7 @@ fn assemble_with_a_manifest_and_a_directory() { let r = reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img2.as_fd(), source.as_fd()], )); assert_eq!(u64_of(&r, "files"), 3); @@ -1213,6 +1237,7 @@ fn assemble_with_a_manifest_and_a_directory() { ); // A directory that does not hold what the manifest names fails when the // file is copied, and leaves the file system unfinished. + let minimized = r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; let manifest_file = ro(&base.path().join("manifest")); let empty = Temp::dir(); let empty_dir = ro(empty.path()); @@ -1220,7 +1245,7 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[missing_img.as_fd(), manifest_file.as_fd(), empty_dir.as_fd()], ); assert_eq!( @@ -1241,7 +1266,7 @@ fn assemble_with_a_manifest_and_a_directory() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[grown_img.as_fd(), manifest_file.as_fd(), source.as_fd()], )); let mut data = Vec::new(); @@ -1259,7 +1284,7 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[shrunk_img.as_fd(), manifest_file.as_fd(), source.as_fd()], ); assert_eq!( @@ -1292,7 +1317,7 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[changed_img.as_fd(), changing.as_fd(), proc_dir.as_fd()], ); assert_eq!( @@ -1311,7 +1336,7 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[fresh_img.as_fd(), garbage.as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.InvalidManifest", IFACE)); @@ -1330,14 +1355,14 @@ fn assemble_with_a_manifest_and_a_directory() { assert_eq!(str_of(&e.parameters, "name"), "x"); assert_eq!(u64_of(&e.parameters, "record"), 1); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); - // A manifest that comes through a pipe can be read once, too little to - // size the file system to fit, which reads the manifest before its - // content is written. + // A manifest that comes through a pipe can be read once. That is + // enough when the image has its size, and too little to size it to + // fit, which reads the manifest before its content is written. let piped = pipe_with(&manifest); let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + minimized, &[fresh_img.as_fd(), piped.as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.BadFileDescriptor", IFACE)); @@ -1351,7 +1376,7 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1}}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1}}}"#, &[fresh_img.as_fd(), manifest_file.as_fd()], ); assert_eq!(e.name, "org.varlink.service.InvalidParameter"); @@ -1360,18 +1385,27 @@ fn assemble_with_a_manifest_and_a_directory() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[fresh_img.as_fd(), conf.as_fd()], ); assert_eq!(str_of(&e.parameters, "parameter"), "content"); let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{}}"#, &[fresh_img.as_fd()], ); assert_eq!(str_of(&e.parameters, "parameter"), "content"); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + let piped = pipe_with(&manifest); + let r = reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0,"size":41943040},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[fresh_img.as_fd(), piped.as_fd(), source.as_fd()], + )); + assert_eq!((u64_of(&r, "files"), u64_of(&r, "directories")), (2, 3)); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 40 << 20); } /// A manifest has to declare the code point order: one that does not is @@ -1412,26 +1446,27 @@ fn manifests_have_to_declare_their_order() { &[file.as_fd()], )); let (fresh, img) = fresh_image(); - let manifest_file = ro(&scratch.path().join("undeclared")); - no_order(error_of( - &mut c, - "Assemble", - r#"{"image":{"fileDescriptor":0,"size":41943040},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, - &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], - )); - assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); - let image = Temp::image(40 << 20); - let img = rw(image.path()); - reply(call(&mut c, "Assemble", IMG, &[img.as_fd()])); - let populate = r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; + let sized = r#"{"image":{"fileDescriptor":0,"size":41943040},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; for manifest in [ro(&scratch.path().join("undeclared")), pipe_with(&undeclared)] { no_order(error_of( &mut c, - "Populate", - populate, + "Assemble", + sized, &[img.as_fd(), manifest.as_fd(), source.as_fd()], )); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); } + let image = Temp::image(40 << 20); + let img = rw(image.path()); + reply(call(&mut c, "Assemble", IMG, &[img.as_fd()])); + let populate = r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; + let manifest_file = ro(&scratch.path().join("undeclared")); + no_order(error_of( + &mut c, + "Populate", + populate, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); assert!(volume(image.path(), Access::ReadOnly).read_dir("/").unwrap().is_empty()); let declared = file_with(scratch.path(), "declared", &manifest); let r = reply(call( @@ -1484,7 +1519,7 @@ fn assemble_with_a_manifest_and_a_stream() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"label":"ESP","identifier":"00000001","timestampUSec":{}}},"content":{{"manifest":{{"fileDescriptor":1}},"sourceFileDescriptor":2}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"label":"ESP","identifier":"00000001","timestampUSec":{}}},"content":{{"manifest":{{"fileDescriptor":1}},"sourceFileDescriptor":2}}}}"#, T0 ), &[img.as_fd(), manifest_file.as_fd(), reader.as_fd()], @@ -1523,7 +1558,7 @@ fn assemble_with_a_manifest_and_a_stream() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[img2.as_fd(), manifest_file.as_fd(), short.as_fd()], ); assert_eq!( @@ -1547,7 +1582,7 @@ fn assemble_with_a_manifest_and_a_stream() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[img3.as_fd(), manifest_file.as_fd(), long.as_fd()], ); assert_eq!( @@ -1689,8 +1724,7 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { let mut c = connect_fd3(&ufat); let source = ro(&tree); let (image, img) = fresh_image(); - let assemble = - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; + let assemble = r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#; let e = error_of( &mut c, "Assemble", @@ -1732,7 +1766,7 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"options":{"force":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"force":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], )); assert!(warnings(&mut c, image.path()).is_empty()); @@ -1796,7 +1830,7 @@ fn assemble_hashes_the_image() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"content":{{"sourceFileDescriptor":1}},"imageHash":"{}"}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true}},"content":{{"sourceFileDescriptor":1}},"imageHash":"{}"}}"#, algorithm ), &[img.as_fd(), source.as_fd()], @@ -1839,7 +1873,7 @@ fn assemble_writes_a_manifest() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"manifestSink":{{"fileDescriptor":2,"features":["size","sha256","mtime"]}}}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1,"manifestSink":{{"fileDescriptor":2,"features":["size","sha256","mtime"]}}}}}}"#, T0 ), &[img.as_fd(), source.as_fd(), out_file.as_fd()], @@ -1875,7 +1909,7 @@ fn assemble_writes_a_manifest() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1,"manifestSink":{"fileDescriptor":2}}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1,"manifestSink":{"fileDescriptor":2}}}"#, &[fresh_img.as_fd(), source.as_fd(), readable.as_fd()], ); assert_eq!(e.name, format!("{}.BadFileDescriptor", IFACE)); @@ -1934,7 +1968,7 @@ fn manifests_record_and_apply_features() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); // The features a manifest lists in its root file object. @@ -2045,7 +2079,7 @@ fn assemble_reports_its_phases() { let replies = call_more( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1,"manifestSink":{"fileDescriptor":2}},"imageHash":"sha256"}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1,"manifestSink":{"fileDescriptor":2}},"imageHash":"sha256"}"#, &[img.as_fd(), source.as_fd(), out_file.as_fd()], ); // A phase that lasts repeats itself; the order is what counts, and the @@ -2105,7 +2139,7 @@ fn long_phases_report_progress() { let replies = call_more( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[img.as_fd(), manifest_file.as_fd(), reader.as_fd()], ); writer.join().unwrap(); @@ -2136,7 +2170,7 @@ fn reproducible_images_are_identical() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"reproducible":true,"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"reproducible":true,"timestampUSec":{}}},"content":{{"sourceFileDescriptor":1}}}}"#, T0 ), &[img.as_fd(), source.as_fd()], @@ -2146,13 +2180,13 @@ fn reproducible_images_are_identical() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"options":{"reproducible":true,"identifier":"1234-ABCD"},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"reproducible":true,"identifier":"1234-ABCD"},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.NotReproducible", IFACE)); assert_eq!(str_of(&e.parameters, "reason"), "timestampRequired"); let options = format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"reproducible":true,"identifier":"1234-ABCD","timestampUSec":{},"label":"ESP"}},"content":{{"sourceFileDescriptor":1,"times":"clamp"}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"reproducible":true,"identifier":"1234-ABCD","timestampUSec":{},"label":"ESP"}},"content":{{"sourceFileDescriptor":1,"times":"clamp"}}}}"#, T0 ); let (a, a_img) = fresh_image(); @@ -2179,7 +2213,7 @@ fn describe_with_and_without_a_manifest() { &mut c, "Assemble", &format!( - r#"{{"image":{{"fileDescriptor":0}},"options":{{"label":"ESP","identifier":"1234-ABCD","timestampUSec":{}}},"content":{{"sourceFileDescriptor":1}}}}"#, + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"label":"ESP","identifier":"1234-ABCD","timestampUSec":{}}},"content":{{"sourceFileDescriptor":1}}}}"#, T0 ), &[img.as_fd(), source.as_fd()], @@ -2313,7 +2347,7 @@ fn describe_of_a_directory_whose_chain_loops_is_corrupt() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); drop(img); @@ -2542,7 +2576,7 @@ fn remove_files_and_directories() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); reply(call( @@ -2622,7 +2656,7 @@ fn list_streams_entries() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); reply(call( @@ -2728,7 +2762,7 @@ fn check_finds_damage() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); let img_ro = ro(image.path()); @@ -3067,7 +3101,7 @@ fn pipes_made_non_blocking_during_the_call_are_refused() { c.send_with_fds( &method("Assemble"), params( - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, ), &[img.as_fd(), manifest_file.as_fd(), r.as_fd()], ) @@ -3117,7 +3151,7 @@ fn pipes_made_non_blocking_during_the_call_are_refused() { reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], )); let img_ro = ro(image.path()); @@ -3245,17 +3279,18 @@ fn errors_are_typed() { assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); assert_eq!(str_of(&e.parameters, "what"), "inodeType"); assert_eq!(str_of(&e.parameters, "name"), "sock"); + // Assemble refuses it before the image is touched, with the size given + // and with the size planned. A plan refuses a manifest's fifo, and so + // does Assemble with minimize before the image is touched. let (fresh, fresh_img) = fresh_image(); - let e = error_of( - &mut c, - "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"sourceFileDescriptor":1,"unsupported":"fail"}}"#, - &[fresh_img.as_fd(), source.as_fd()], - ); - assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); - assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); - // A plan refuses a manifest's fifo, and so does Assemble before the - // image is touched. + for parameters in [ + r#"{"image":{"fileDescriptor":0,"size":40000000},"content":{"sourceFileDescriptor":1,"unsupported":"fail"}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1,"unsupported":"fail"}}"#, + ] { + let e = error_of(&mut c, "Assemble", parameters, &[fresh_img.as_fd(), source.as_fd()]); + assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); + assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); + } let scratch = Temp::dir(); let fifo = scratch.path().join("fifo.manifest"); std::fs::write( @@ -3277,7 +3312,7 @@ fn errors_are_typed() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"unsupported":"fail"}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"unsupported":"fail"}}"#, &[fresh_img.as_fd(), ro(&fifo).as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); @@ -3494,15 +3529,15 @@ fn too_small_images_are_reported() { "{:?}", listed ); - // Sized into a window of 1 MiB the content does not fit: TooSmall, and - // the fresh file the client made is still empty. + // Sized to fit into a window of 1 MiB the content does not fit: + // TooSmall, and the fresh file the client made is still empty. let (manifest, _) = manifest_and_blob(&tree); let manifest_file = file_with(base.path(), "manifest", &manifest); let (fresh, fresh_img) = fresh_image(); let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0,"size":1048576},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0,"size":1048576},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[fresh_img.as_fd(), manifest_file.as_fd(), source.as_fd()], ); assert_eq!( @@ -3517,22 +3552,21 @@ fn too_small_images_are_reported() { let e = error_of( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0,"size":1048576},"content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0,"size":1048576},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, &[fresh_img.as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.TooSmall", IFACE)); assert_eq!(std::fs::metadata(fresh.path()).unwrap().len(), 0); // Without a size the file is grown to the fit and the same call - // succeeds; the size was not the exact minimum when it was given. + // succeeds. Without minimize the file system takes the size given. let manifest_file = ro(&base.path().join("manifest")); let r = reply(call( &mut c, "Assemble", - r#"{"image":{"fileDescriptor":0},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, &[fresh_img.as_fd(), manifest_file.as_fd(), source.as_fd()], )); assert_eq!((u64_of(&r, "files"), u64_of(&r, "directories")), (3, 1)); - assert!(bool_of(&r, "exact")); assert!(std::fs::metadata(fresh.path()).unwrap().len() > 48 << 20); let (big_image, big_img) = fresh_image(); let r = reply(call( @@ -3541,7 +3575,6 @@ fn too_small_images_are_reported() { r#"{"image":{"fileDescriptor":0,"size":67108864},"content":{"sourceFileDescriptor":1}}"#, &[big_img.as_fd(), source.as_fd()], )); - assert!(!bool_of(&r, "exact")); assert_eq!(u64_of(object_of(&r, "description"), "sizeBytes"), 64 << 20); assert_eq!(std::fs::metadata(big_image.path()).unwrap().len(), 64 << 20); } From 8fbc347702461801b972be1658b701e06b5bb625 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 16/19] ufat: refuse existing files unless asked to replace them Currently assemble and populate replace a file that is there already unless --no-replace is given, and replace in the Content of the Varlink interface is true by default. Two names FAT doesn't tell apart, such as README.TXT and readme.txt, are taken as one name: the second file replaces the first one and the second directory takes the entries of the first one. The reader refuses a manifest that names a file twice, as UAPI.16 asks. To FAT two names it doesn't tell apart are one name, so they should be refused just the same. assemble makes a new file system, so a name that is there already comes from its content: a name FAT doesn't tell apart from an earlier one. And populate usually fills an empty file system, or one that doesn't hold the files it is given. So let's refuse existing files by default. assemble and populate take --replace now and --no-replace goes. replace in the Varlink Content is false by default for Assemble and Populate. Without it a file that is there fails with EEXIST, FileExists over Varlink. A name FAT doesn't tell apart from one that is there fails with EEXIST as well, and with InvalidName and reason caseCollision over Varlink, for files and directories, from a manifest or a tree. A directory that is there under the same name takes the entries either way. The error of a case collision is Error::case_collision(). It names the entry that is there by its path as the volume spells it. So with /EFI/x in the volume, populate with --path /efi/X says that '/efi/X' and '/EFI/x' are names FAT cannot tell apart. begin_file() raises it for files and the new Volume::find_or_create_dir() for the directories of the populator and the assembly, before anything else about the entry. So a file under a name FAT doesn't tell apart from a directory's is a case collision as well. The assembly creates a file once the source has its first data. So an error the source finds before the data, such as a file that is missing below the source directory, still comes first, and EEXIST comes before one in the data, such as a hash that doesn't match. begin_file(), create_file() and write_file() took a bare bool for replacing, and CopyOptions kept one in replace. They take a NameCollision now, Fail or Replace, and so does find_or_create_dir(). CopyOptions keeps it in name_collision. find_or_create_dir() returns a DirectoryOrigin: Created, or Existing with the attributes of the directory that is there. The populator and the assembly looked a directory up from the root to see whether it is there, and walked from the root once more to create it. find_or_create_dir() does both in one walk. Signed-off-by: Christian Brauner (Amutable) --- README.md | 40 +-- docs/org.uapi-group.FileSystem.varlink | 5 +- docs/varlink.md | 20 +- src/bin/ufat/cli.rs | 30 ++- src/bin/ufat/service.rs | 12 +- src/fat/error.rs | 15 ++ src/fat/fsck.rs | 14 +- src/fat/manifest/assemble.rs | 59 +++-- src/fat/manifest/tests.rs | 63 +++-- src/fat/manifest/volume.rs | 3 +- src/fat/path.rs | 20 ++ src/fat/plan.rs | 57 +++-- src/fat/populate.rs | 36 +-- src/fat/volume/file.rs | 31 ++- src/fat/volume/mod.rs | 102 +++++++- src/fat/volume/tests.rs | 329 +++++++++++++++++++------ tests/cli.rs | 187 ++++++++++++-- tests/crash/crash.rs | 57 +++-- tests/fuzz/mutate.py | 2 +- tests/fuzz/targeted.py | 4 +- tests/reference.rs | 23 +- tests/varlink.rs | 141 +++++++++-- 22 files changed, 967 insertions(+), 283 deletions(-) diff --git a/README.md b/README.md index fdc769a..608197d 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,10 @@ The most common ones: to create. - `--minimize` makes the file system of `assemble` as small as its content allows. A `--size` is then the most it may take. -- `--no-replace` fails instead of replacing files that exist. +- `--replace` lets `populate` replace a file that is there already, and + lets `assemble` and `populate` take names that FAT does not tell apart, + such as `A.TXT` and `a.txt`, as one name. Without it they fail on + them. - `--unsupported fail` fails on files FAT cannot store, such as FIFOs and device nodes. By default they are left out with a message. - `--write-manifest PATH` writes a UAPI.16 manifest of what the file @@ -202,7 +205,8 @@ with `"order": "codepoint"`. `ufat manifest` writes manifests that way. since systemd commit 330fab5e90, which is not in a release yet. ufat refuses a manifest that does not declare the order, that is out of that order, or that names a file twice. Two names that FAT does not tell -apart, such as `A.TXT` and `a.txt`, are taken as one name. +apart, such as `A.TXT` and `a.txt`, make `assemble` and `populate` fail +unless `--replace` is given. While copying, ufat verifies the size and the SHA-256 hash of every file. The data of a file is the part of its file below the SOURCE that starts @@ -285,24 +289,24 @@ is below the minimum. A plan does not compare names. Two names that FAT does not tell apart are two names to the plan: names that differ in case only, such as `A.TXT` and `a.txt`, and a name and the short name FAT gives another -one, such as `FOOBAR~1` for `FOO BAR`. - -When a file replaces another one under such a name, the plan counts -both. The file system keeps the clusters of every replaced file free -then. Both also count against the 65536 directory entries a FAT -directory holds, so the plan of a directory close to that limit can -fail although the write would fit. A long name takes up to 21 of these -entries. - -The entries of a directory under two such names, such as `FOO BAR/a` -and `FOOBAR~1/b`, go into one directory. The plan holds the entries -under each name to the limit on their own, and only the write sees them -all in one directory. When they do not fit, `assemble` fails with -"directory is full". +one, such as `FOOBAR~1` for `FOO BAR`. So they pass the plan also where +`assemble` refuses them without `--replace`. + +With `--replace` a file under such a name replaces the other one, and +the plan counts both. The file system keeps the clusters of every +replaced file free then. Both also count against the 65536 directory +entries a FAT directory holds, so the plan of a directory close to that +limit can fail although the write would fit. A long name takes up to 21 +of these entries. + +With `--replace` the entries of a directory under two such names, such +as `FOO BAR/a` and `FOOBAR~1/b`, go into one directory. The plan holds +the entries under each name to the limit on their own, and only the +write sees them all in one directory. When they do not fit, `assemble` +fails with "directory is full". A file and a directory under two such names pass the plan, and -`assemble` fails on the second one, with or without `--no-replace`. -Names that `--no-replace` refuses pass the plan too. +`assemble` fails on the second one, with or without `--replace`. ## Sector size diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index f87bd23..9984491 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -347,7 +347,10 @@ type Content( times: ?TimePolicy, # What to do with what cannot be stored, skip by default unsupported: ?UnsupportedPolicy, - # Replace files that exist, true by default + # Replace files that exist, and take a name the filesystem does not tell + # apart from an existing one as that name, false by default. Without it + # that is FileExists, or InvalidName with reason caseCollision. A + # directory that exists under the same name takes the entries either way replace: ?bool, # Copy extended attributes where the filesystem keeps them, true by default extendedAttributes: ?bool, diff --git a/docs/varlink.md b/docs/varlink.md index 6da9bf1..fa5e68c 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -133,13 +133,13 @@ What the fields mean for vfat: short name it is, are two names to it. Content with such names, assembled with `replace`, leaves the clusters of every file that was replaced free, and the plan of a directory close to the limit of 65536 - entries can fail although the assembly would fit. The entries of a - directory under two such names go into one directory. A plan holds the - entries under each name to the limit on their own, and the assembly - fails with `NoSpaceLeft` and reason `directoryEntries` when they do not - fit together. A file and a directory under two such names pass a plan - and fail the assembly, with `replace` or without it, and so do names - that an assembly without `replace` refuses. + entries can fail although the assembly would fit. With `replace` the + entries of a directory under two such names go into one directory. A + plan holds the entries under each name to the limit on their own, and + the assembly fails with `NoSpaceLeft` and reason `directoryEntries` + when they do not fit together. A file and a directory under two such + names pass a plan and fail the assembly, with `replace` or without it, + and so do names that an assembly without `replace` refuses. - `minimalSizeBytes` is the smallest volume: 65525 clusters of 512 bytes plus the reserved sectors and two FATs. With 4096 byte sectors the minimum is 269045760 bytes. `maximalSizeBytes` is 2^32 - 1 sectors of @@ -460,7 +460,7 @@ The other fields of `Content`: | `manifest` | A UAPI.16 manifest: `fileDescriptor` names it. `checkValidity`, true by default, rejects revoked entries and entries outside their validity window with `EntryNotValid`. | | `times` | `preserve` keeps modification times. This is the default. `fixed` sets every entry to the time stamp. `clamp` keeps times up to the time stamp and sets later ones to it. | | `unsupported` | `skip`, the default, leaves out what FAT cannot store and counts it in `skipped`. `fail` fails with `ContentNotSupported`: for a tree before anything is written, for a manifest when the object's record comes. | -| `replace` | Replaces existing files. True by default. With `false`, an existing file fails with `FileExists`. | +| `replace` | Replaces existing files, and takes a name FAT does not tell apart from one that exists as that name. False by default. With `false`, an existing file fails with `FileExists`, and a name FAT does not tell apart from an existing one, such as `a.txt` for `A.TXT`, fails with `InvalidName` and reason `caseCollision`. A directory that exists under the same name takes the entries in any case. | | `extendedAttributes`, `uid`, `gid` | Accepted and ignored. FAT stores none of them. | | `manifestSink` | Writes a UAPI.16 manifest of the whole volume after the content is in. | @@ -620,9 +620,9 @@ The service returns no text. Every error is a name with typed fields. | `NoSuchFile` | A path does not exist. | `path` | | `FileExists` | A file exists and `replace` is false, or a directory exists and `parents` is false. | `path` | | `NotADirectory` | A path component is a file. | `path` | -| `IsADirectory` | `Populate` of a single file at a path that is a directory. | `path` | +| `IsADirectory` | A file where the file system has a directory: under the same name, as for `Populate` of a single file at a path that is a directory, or with `replace` under a name FAT does not tell apart from the directory's. | `path` | | `DirectoryNotEmpty` | `Remove` of a directory with entries, without `recursive`. | `path` | -| `InvalidName` | A name FAT cannot store. | `name`, `reason` (`empty`, `dotComponent`, `invalidCharacter`, `leadingSpace`, `trailingSpaceOrDot`, `tooLong`) | +| `InvalidName` | A name FAT cannot store, or with `replace` false a name FAT does not tell apart from one that exists. | `name`, `reason` (`empty`, `dotComponent`, `invalidCharacter`, `leadingSpace`, `trailingSpaceOrDot`, `tooLong`, `caseCollision`) | | `InvalidLabel` | A label that breaks the label rules. | `label`, `reason` (`tooLong`, `invalidCharacter`) | | `InvalidIdentifier` | A serial number that is not `XXXX-XXXX` or eight hex digits. | `identifier`, `reason` (`malformed`) | | `InvalidManifest` | The manifest cannot be parsed or is inconsistent. A key twice in an object is reason `duplicateKey`. With reason `unlistedFeature`, `field` names the field of a feature the manifest does not list, such as `mTimeNSec`. | `reason`, `record`, `name`, `field` | diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index 0d52f01..b5f8fad 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -21,7 +21,7 @@ use fat::manifest::{ use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, TimePolicy}; use fat::time::civil_from_days; -use fat::volume::Volume; +use fat::volume::{NameCollision, Volume}; use fat::{bail, err, Context, DescriptorProblem, Detail, Error, ManifestProblem, Result}; use crate::service; @@ -114,7 +114,9 @@ Options for assemble and populate: for a manifest the time of entries that carry none --times POLICY preserve (default), fixed or clamp (clamp is the default when $SOURCE_DATE_EPOCH is set; trees and files) - --no-replace Fail on existing files instead of replacing them + --replace Replace a file that is there already, and take a name + FAT does not tell apart from one that is there as that + name, instead of failing --path PATH The directory a SOURCE tree goes below (default /), the path of a SOURCE file, or the directory to create --parents Create missing parent directories of --path, and @@ -341,7 +343,7 @@ const FILL_VALUES: &[&str] = &[ "unsupported", "write-manifest", ]; -const FILL_FLAGS: &[&str] = &["no-replace", "no-check-validity", "verbose"]; +const FILL_FLAGS: &[&str] = &["no-check-validity", "replace", "verbose"]; const FORMAT_FLAGS: &[&str] = &[ "no-align", "mkfs-fat-compat", @@ -692,23 +694,33 @@ impl AssembleObserver for SkipNotes { } } +/// What a copy does with a name the volume holds already: it takes what is +/// there with `--replace` and fails without. +fn name_collision(args: &Args) -> NameCollision { + if args.flag("replace") { + NameCollision::Replace + } else { + NameCollision::Fail + } +} + /// How the command line asks a copy of a tree, and the plan of one, to -/// take it: following symbolic links, and replacing what is there unless -/// `--no-replace`. +/// take it: following symbolic links, and replacing what is there with +/// `--replace`. fn copy_options(args: &Args) -> Result { Ok(CopyOptions { times: time_policy(args)?, - replace: !args.flag("no-replace"), + name_collision: name_collision(args), follow_symlinks: true, }) } /// How the command line asks an assembly, and the plan of one, to store a -/// manifest's objects: replacing what is there unless `--no-replace`, and +/// manifest's objects: replacing what is there with `--replace`, and /// leaving out what FAT cannot store unless `--unsupported fail`. fn assemble_flags(args: &Args) -> Result { Ok(AssembleFlags::NONE - .with(AssembleFlags::REPLACE, !args.flag("no-replace")) + .with(AssembleFlags::REPLACE, args.flag("replace")) .with(AssembleFlags::SKIP_UNSUPPORTED, !fail_unsupported(args)?)) } @@ -1116,7 +1128,7 @@ fn cmd_populate(argv: &[OsString]) -> Result<()> { } let options = CopyOptions { times: time_policy(&args)?, - replace: !args.flag("no-replace"), + name_collision: name_collision(&args), ..CopyOptions::default() }; let mut v = open_volume(&args, image, Access::ReadWrite)?; diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index 172455b..f5bc58a 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -36,7 +36,7 @@ use fat::populate::{CopyOptions, CopyReport, TimePolicy}; use fat::probe::Prober; use fat::progress::Progress; use fat::sha512::Sha512Context; -use fat::volume::{Metadata, Volume}; +use fat::volume::{Metadata, NameCollision, Volume}; use fat::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason, UnsupportedKind}; use json::{Object, Value}; use varlink::{Activation, Call, Connection, Info, Reply, Server, Service}; @@ -1085,7 +1085,9 @@ impl Content { fill, time, times, - replace: p.bool("replace", true), + // Neither method replaces a file that is there, or takes a name + // FAT does not tell apart from one that is, unless asked to. + replace: p.bool("replace", false), fail_unsupported, check_validity, sink, @@ -1162,7 +1164,11 @@ impl Content { fn copy_options(&self) -> CopyOptions { CopyOptions { times: self.times, - replace: self.replace, + name_collision: if self.replace { + NameCollision::Replace + } else { + NameCollision::Fail + }, follow_symlinks: true, } } diff --git a/src/fat/error.rs b/src/fat/error.rs index 51f4423..bc49d63 100644 --- a/src/fat/error.rs +++ b/src/fat/error.rs @@ -29,6 +29,9 @@ pub enum NameProblem { TrailingSpaceOrDot, /// More than 255 UTF-16 units, or a path longer than PATH_MAX. TooLong, + /// The directory has an entry whose name FAT does not tell apart from + /// this one, as it does not tell `A` from `a`. + CaseCollision, } impl NameProblem { @@ -41,6 +44,7 @@ impl NameProblem { NameProblem::LeadingSpace => "leadingSpace", NameProblem::TrailingSpaceOrDot => "trailingSpaceOrDot", NameProblem::TooLong => "tooLong", + NameProblem::CaseCollision => "caseCollision", } } } @@ -486,6 +490,17 @@ struct Inner { } impl Error { + /// The error for the path `path` when its directory holds the entry + /// at the path `existing`, whose name FAT does not tell apart from the + /// last name of `path`, as it does not tell `A` from `a`. + pub(crate) fn case_collision(path: &str, existing: &str) -> Error { + let message = format!("'{}' and '{}' are names FAT cannot tell apart", path, existing); + Error::new(EEXIST, message).with(Detail::Name { + name: path.to_string(), + problem: NameProblem::CaseCollision, + }) + } + /// Creates an error from a positive errno value and a message. pub fn new(errno: i32, message: impl Into) -> Self { Error(Box::new(Inner { diff --git a/src/fat/fsck.rs b/src/fat/fsck.rs index 0dedc4d..34915b7 100644 --- a/src/fat/fsck.rs +++ b/src/fat/fsck.rs @@ -1957,6 +1957,7 @@ mod tests { use crate::name::LFN_LAST_ENTRY; use crate::test_util::{volume, TempImage}; use crate::time::FatTimestamp; + use crate::volume::NameCollision; use std::io::Write; use std::time::{Duration, UNIX_EPOCH}; @@ -1969,12 +1970,16 @@ mod tests { v.create_dir_all("/EFI/Linux", t(1_700_000_000)).unwrap(); for i in 0..3 { let mut w = v - .create_file(&format!("/EFI/Linux/kernel {}.efi", i), t(1_700_000_000), false) + .create_file( + &format!("/EFI/Linux/kernel {}.efi", i), + t(1_700_000_000), + NameCollision::Fail, + ) .unwrap(); w.write_all(&vec![i as u8; 2000 + i * 300]).unwrap(); w.finish().unwrap(); } - v.create_file("/empty", t(1_700_000_000), false) + v.create_file("/empty", t(1_700_000_000), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -2288,7 +2293,10 @@ mod tests { // A subdirectory whose ".." entry was deleted. let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/sub", t(0)).unwrap(); - v.create_file("/sub/F", t(0), false).unwrap().finish().unwrap(); + v.create_file("/sub/F", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); let sub = v.metadata("/sub").unwrap().first_cluster; let layout = *v.layout(); v.close().unwrap(); diff --git a/src/fat/manifest/assemble.rs b/src/fat/manifest/assemble.rs index c3dab77..7f7f830 100644 --- a/src/fat/manifest/assemble.rs +++ b/src/fat/manifest/assemble.rs @@ -16,8 +16,8 @@ use super::{path_in_volume, EntryKind, ObjectAction, ObjectTriage}; use crate::errno::*; use crate::progress::Progress; use crate::sys; -use crate::volume::{FileWriter, Volume}; -use crate::{Detail, Error, Result}; +use crate::volume::{DirectoryOrigin, FileWriter, NameCollision, Volume}; +use crate::{Error, Result}; /// The directory on the host the files of a manifest are taken from: the /// one the manifest lives in, or the one the caller chose instead. It is @@ -84,16 +84,19 @@ impl Directory for PinnedDirectory { } /// What an assembly does where it could also fail. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct AssembleFlags(u8); impl AssembleFlags { - /// Replace files that exist in the volume instead of failing. + /// Use what the volume holds under a name FAT does not tell apart from + /// the name of an object, and an existing file of the object's name: + /// replace a file, and put the entries of a directory into the one that + /// is there. pub const REPLACE: AssembleFlags = AssembleFlags(1 << 0); /// Skip entries this crate cannot store (see [`EntryKind`]) instead of /// failing. pub const SKIP_UNSUPPORTED: AssembleFlags = AssembleFlags(1 << 1); - /// No flag: an assembly fails in both cases. + /// No flag: an assembly fails in both cases. This is the default. pub const NONE: AssembleFlags = AssembleFlags(0); /// Every single flag with its name. @@ -117,12 +120,15 @@ impl AssembleFlags { AssembleFlags(self.0 & !flags.0) } } -} -impl Default for AssembleFlags { - /// [`AssembleFlags::REPLACE`]. - fn default() -> AssembleFlags { - AssembleFlags::REPLACE + /// What an assembly does where the name of an object collides with an + /// entry the volume holds, as [`AssembleFlags::REPLACE`] says. + fn name_collision(self) -> NameCollision { + if self.contains(AssembleFlags::REPLACE) { + NameCollision::Replace + } else { + NameCollision::Fail + } } } @@ -289,8 +295,8 @@ impl PendingFile<'_> { fn create(&mut self) -> Result<()> { if let Some(volume) = self.volume.take() { let time = self.object.inode.mtime().unwrap_or(self.options.default_time); - let replace = self.options.flags.contains(AssembleFlags::REPLACE); - let mut writer = volume.create_file(self.path, time, replace)?; + let collision = self.options.flags.name_collision(); + let mut writer = volume.create_file(self.path, time, collision)?; writer.set_read_only(self.object.inode.is_read_only()); self.writer = Some(writer); } @@ -373,16 +379,12 @@ impl Assembly<'_> { fn store_directory(&mut self, object: &FileObject) -> Result<()> { let path = path_in_volume(&object.name); let time = object.inode.mtime().unwrap_or(self.options.default_time); - match self.volume.metadata(&path) { - Ok(md) if md.is_dir => self.volume.set_times(&path, time)?, - Ok(_) => bail!( - ENOTDIR, - Detail::Path(path.clone()), - "'{}' exists in the volume and is not a directory", - path - ), - Err(e) if e.errno() == ENOENT => self.volume.create_dir(&path, time)?, - Err(e) => return Err(e), + match self + .volume + .find_or_create_dir(&path, time, self.options.flags.name_collision())? + { + DirectoryOrigin::Created => {} + DirectoryOrigin::Existing { .. } => self.volume.set_times(&path, time)?, } self.report.directories += 1; self.observer.progress(&self.report.progress()); @@ -450,11 +452,14 @@ impl Volume { /// the last file it supplies, which is found after the trailer of the /// manifest. /// - /// A file the volume holds under the same name, or under a name FAT - /// does not tell apart from it, is replaced with - /// [`AssembleFlags::REPLACE`] and fails with EEXIST without it. A - /// directory the volume holds under such a name gets the directory - /// object's time. + /// A name FAT does not tell apart from one the volume holds fails with + /// EEXIST, and so does a file the volume holds under the same name, + /// unless [`AssembleFlags::REPLACE`] is set. A file fails so when its + /// first data comes, or at its end when it has none: after the errors + /// `source` finds before the data, such as a missing file, and before + /// those in the data, such as a hash that does not match. A directory + /// the volume holds under the same name gets the directory object's + /// time. pub fn assemble( &mut self, reader: &mut Reader, diff --git a/src/fat/manifest/tests.rs b/src/fat/manifest/tests.rs index d020e59..a753ba7 100644 --- a/src/fat/manifest/tests.rs +++ b/src/fat/manifest/tests.rs @@ -3,8 +3,8 @@ use super::*; use crate::populate::CopyOptions; use crate::progress::Progress; use crate::test_util::{volume, TempDir, TempImage}; -use crate::volume::Volume; -use crate::{ContentProblem, Error, ManifestProblem, SourceProblem}; +use crate::volume::{NameCollision, Volume}; +use crate::{ContentProblem, Error, ManifestProblem, NameProblem, SourceProblem}; use std::io::{Read, Write}; use std::os::fd::AsFd; use std::path::Path; @@ -228,7 +228,7 @@ fn refusals_at_the_first_object_write_nothing() { let (_img, mut v) = volume(8 << 20, 512, 512); let t0 = UNIX_EPOCH + Duration::from_secs(1_600_000_000); v.create_dir("/d", t0).unwrap(); - v.write_file("/f", &mut &b"old"[..], t0, false).unwrap(); + v.write_file("/f", &mut &b"old"[..], t0, NameCollision::Fail).unwrap(); v.sync().unwrap(); let keep = AssembleOptions { flags: AssembleFlags::NONE, @@ -802,9 +802,9 @@ fn files_that_change_while_they_are_read() { } /// Names FAT does not tell apart, the second of which an assembly finds -/// in the volume: taken as the same name. +/// in the volume: refused by default, taken as the same name with REPLACE. #[test] -fn case_collisions_are_one_name() { +fn case_collisions_are_refused_unless_replaced() { let m = seq(&[ ROOT, r#"{"name":"A.TXT","size":1}"#, @@ -815,10 +815,44 @@ fn case_collisions_are_one_name() { r#"{"name":"efi/y","size":1}"#, TRAILER, ]); - // A file replaces the one it collides with, under its own name, and a - // directory takes the entries of the one it collides with. let (_img, mut v) = volume(8 << 20, 512, 512); - let r = assemble_stream(&mut v, &m, b"Axyyz", &AssembleOptions::default()).unwrap(); + let e = assemble_stream(&mut v, &m, b"Axyyz", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EEXIST); + assert!( + matches!( + e.detail(), + Some(Detail::Name { + name, + problem: NameProblem::CaseCollision, + }) if name == "/a.txt" + ), + "{:?}", + e + ); + assert_eq!(e.message(), "'/a.txt' and '/A.TXT' are names FAT cannot tell apart"); + assert_eq!(contents(&v, "/A.TXT"), b"A"); + // A directory collides the same way. + let dirs = seq(&[ + ROOT, + r#"{"name":"EFI","type":"dir"}"#, + r#"{"name":"efi","type":"dir"}"#, + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + let e = assemble_stream(&mut v, &dirs, b"", &AssembleOptions::default()).unwrap_err(); + assert!( + matches!(e.detail(), Some(Detail::Name { name, problem: NameProblem::CaseCollision }) if name == "/efi"), + "{:?}", + e + ); + // With REPLACE a file replaces the one it collides with, under its own + // name, and a directory takes the entries of the one it collides with. + let (_img, mut v) = volume(8 << 20, 512, 512); + let replace = AssembleOptions { + flags: AssembleFlags::REPLACE, + ..AssembleOptions::default() + }; + let r = assemble_stream(&mut v, &m, b"Axyyz", &replace).unwrap(); assert_eq!((r.files, r.directories, r.bytes), (4, 2, 5)); let names = |v: &Volume, path: &str| { let mut names: Vec = v.read_dir(path).unwrap().into_iter().map(|md| md.name).collect(); @@ -881,7 +915,8 @@ fn entries_of_the_same_name_that_are_there() { let (_img, mut v) = volume(8 << 20, 512, 512); let t0 = UNIX_EPOCH + Duration::from_secs(1_600_000_000); v.create_dir("/EFI", t0).unwrap(); - v.write_file("/EFI/x", &mut &b"old"[..], t0, false).unwrap(); + v.write_file("/EFI/x", &mut &b"old"[..], t0, NameCollision::Fail) + .unwrap(); let m = seq(&[ ROOT_MTIME, r#"{"mTimeNSec":1700000000000000000,"name":"EFI","type":"dir"}"#, @@ -889,11 +924,7 @@ fn entries_of_the_same_name_that_are_there() { r#"{"name":"EFI/y","size":1}"#, TRAILER, ]); - let keep = AssembleOptions { - flags: AssembleFlags::NONE, - ..AssembleOptions::default() - }; - let e = assemble_stream(&mut v, &m, b"newy", &keep).unwrap_err(); + let e = assemble_stream(&mut v, &m, b"newy", &AssembleOptions::default()).unwrap_err(); assert_eq!(e.errno(), EEXIST); assert_eq!(e.detail(), Some(&Detail::Path("/EFI/x".into()))); assert_eq!( @@ -1340,8 +1371,8 @@ fn long_operations_report_progress() { #[test] fn assemble_flags() { let both = AssembleFlags::REPLACE | AssembleFlags::SKIP_UNSUPPORTED; - assert_eq!(AssembleFlags::default(), AssembleFlags::REPLACE); - assert_eq!(AssembleOptions::default().flags, AssembleFlags::REPLACE); + assert_eq!(AssembleFlags::default(), AssembleFlags::NONE); + assert_eq!(AssembleOptions::default().flags, AssembleFlags::NONE); assert!(both.contains(AssembleFlags::REPLACE) && both.contains(AssembleFlags::SKIP_UNSUPPORTED)); assert!(both.contains(both) && both.contains(AssembleFlags::NONE)); assert!(!AssembleFlags::REPLACE.contains(AssembleFlags::SKIP_UNSUPPORTED)); diff --git a/src/fat/manifest/volume.rs b/src/fat/manifest/volume.rs index 8544aff..a6df4ab 100644 --- a/src/fat/manifest/volume.rs +++ b/src/fat/manifest/volume.rs @@ -361,6 +361,7 @@ mod tests { use crate::manifest::HostTree; use crate::populate::CopyOptions; use crate::test_util::{volume, TempDir, TempImage}; + use crate::volume::NameCollision; use json::Object; use std::os::fd::AsFd; use std::time::{Duration, UNIX_EPOCH}; @@ -372,7 +373,7 @@ mod tests { /// Creates a file with `data`. fn put(v: &mut Volume, path: &str, data: &[u8], time: SystemTime, read_only: bool) { - let mut w = v.create_file(path, time, false).unwrap(); + let mut w = v.create_file(path, time, NameCollision::Fail).unwrap(); w.write_all(data).unwrap(); w.set_read_only(read_only); w.finish().unwrap(); diff --git a/src/fat/path.rs b/src/fat/path.rs index 7756365..7b54d97 100644 --- a/src/fat/path.rs +++ b/src/fat/path.rs @@ -98,6 +98,14 @@ pub(crate) fn join(dir: &str, name: &str) -> String { format!("{}{}{}", dir.trim_end_matches(SEPARATOR), SEPARATOR, name) } +/// The path of the directory `path` is in: "/a/b" and "/a/b/" are in +/// "/a", "/b" and "b" in "", which is the root to [`join`]. +pub(crate) fn parent(path: &str) -> &str { + path.trim_end_matches(SEPARATOR) + .rsplit_once(SEPARATOR) + .map_or("", |(parent, _)| parent) +} + #[cfg(test)] mod tests { use super::*; @@ -139,6 +147,18 @@ mod tests { assert_eq!(join("", "EFI"), "/EFI"); assert_eq!(join("/EFI/", "Linux"), "/EFI/Linux"); assert_eq!(join("/EFI", "Linux"), "/EFI/Linux"); + for (path, parent_path) in [ + ("/EFI/Linux", "/EFI"), + ("/EFI/Linux/", "/EFI"), + ("EFI/Linux", "EFI"), + ("/EFI", ""), + ("/EFI/", ""), + ("EFI", ""), + ("", ""), + ] { + assert_eq!(parent(path), parent_path, "{}", path); + } + assert_eq!(join(parent("/EFI/"), "efi"), "/efi"); let long = format!("/{}", "x".repeat(MAX_PATH - 1)); assert_eq!(components(&long).unwrap().len(), 1); assert_eq!(components(&format!("{}x", long)).unwrap_err().errno(), ENAMETOOLONG); diff --git a/src/fat/plan.rs b/src/fat/plan.rs index 78608ad..5d55c81 100644 --- a/src/fat/plan.rs +++ b/src/fat/plan.rs @@ -22,15 +22,17 @@ //! The planner does not compare names. Two names that FAT does not tell //! apart, such as `A.TXT` and `a.txt`, or `FOO BAR` and `FOOBAR~1`, the //! short name of `FOO BAR`, are two entries to the planner and one to a -//! copy. A file under the second name replaces the one under the first, -//! or fails without [`CopyOptions::replace`] or [`AssembleFlags::REPLACE`], -//! whichever the copy takes. The plan counts both files, so the volume -//! keeps the clusters of the replaced one free. The entries of a directory -//! under both names go into one directory, which the plan counts as two, -//! each held to the limit of entry slots on its own. The copy can then -//! still run out of entry slots in it. A file and a directory under such -//! names pass the plan, and the copy fails on the second one, replacing or -//! not. +//! copy. The second name fails the copy unless +//! [`CopyOptions::name_collision`] is +//! [`NameCollision::Replace`](crate::volume::NameCollision::Replace) or the +//! assembly has [`AssembleFlags::REPLACE`]. Then a file under the second +//! name replaces the one under the first, and the plan counts both files, +//! so the volume keeps the clusters of the replaced one free. The entries +//! of a directory under both names go into one directory then, which the +//! plan counts as two, each held to the limit of entry slots on its own. +//! The copy can then still run out of entry slots in it. A file and a +//! directory under such names pass the plan, and the copy fails on the +//! second one, replacing or not. use std::io::Read; use std::iter::Peekable; @@ -573,8 +575,8 @@ mod tests { use crate::manifest::{AssembleOptions, DirectorySource, PinnedDirectory, StreamSource}; use crate::path::MAX_PATH; use crate::test_util::{TempDir, TempImage}; - use crate::volume::Volume; - use crate::ManifestProblem; + use crate::volume::{NameCollision, Volume}; + use crate::{ManifestProblem, NameProblem}; use std::os::fd::AsFd; use std::path::Path; use uapi16::{Features, FileObject, InodeType, Name, RootObject, Writer}; @@ -600,7 +602,7 @@ mod tests { /// what is there. fn no_links() -> CopyOptions { CopyOptions { - replace: true, + name_collision: NameCollision::Replace, follow_symlinks: false, ..CopyOptions::default() } @@ -1079,7 +1081,7 @@ mod tests { assert_eq!(volume.read_dir("/efi").unwrap().len(), 2); } // Without replacing, the assembly fails at a.txt, which the plan - // took. + // took, as a case collision. let (_image, mut volume) = planned_volume(&plan(AssembleFlags::NONE), &options); let mut contents = DirectorySource::new(PinnedDirectory::new(crate::host::open_dir(tmp.path()).unwrap())); let not_replacing = AssembleOptions { @@ -1090,15 +1092,23 @@ mod tests { .assemble(&mut Reader::open(&manifest[..]).unwrap(), &mut contents, ¬_replacing) .unwrap_err(); assert_eq!(e.errno(), EEXIST); + assert_eq!( + e.detail(), + Some(&Detail::Name { + name: "/a.txt".to_string(), + problem: NameProblem::CaseCollision, + }) + ); } /// A file and a directory under names that FAT does not tell apart /// pass the plan, and the assembly fails on the second one, replacing - /// or not: ENOTDIR for the directory after the file, EISDIR for the - /// file after the directory. + /// or not: as a case collision without replacing, and with it ENOTDIR + /// for the directory after the file, EISDIR for the file after the + /// directory. #[test] fn a_file_and_a_directory_under_one_name() { - for (tree, errno) in [ + for (tree, replacing) in [ ([("A", Some(1)), ("a", None), ("a/x", Some(1))], ENOTDIR), ([("A", None), ("A/x", Some(1)), ("a", Some(1))], EISDIR), ] { @@ -1121,7 +1131,20 @@ mod tests { &options, ) .unwrap_err(); - assert_eq!(e.errno(), errno, "{:?} {:?}", tree, e); + if flags.contains(AssembleFlags::REPLACE) { + assert_eq!(e.errno(), replacing, "{:?} {:?}", tree, e); + } else { + assert_eq!(e.errno(), EEXIST, "{:?} {:?}", tree, e); + assert_eq!( + e.detail(), + Some(&Detail::Name { + name: "/a".to_string(), + problem: NameProblem::CaseCollision, + }), + "{:?}", + tree + ); + } } } } diff --git a/src/fat/populate.rs b/src/fat/populate.rs index a77e3fc..228218b 100644 --- a/src/fat/populate.rs +++ b/src/fat/populate.rs @@ -16,7 +16,7 @@ use crate::errno::*; use crate::host::{walk_tree, FromStart, HostEntry, UnnamableEntry}; use crate::progress::Progress; use crate::sys; -use crate::volume::{Volume, MAX_FILE_SIZE}; +use crate::volume::{NameCollision, Volume, MAX_FILE_SIZE}; use crate::Detail; use crate::{Context, Error, Result}; @@ -51,9 +51,13 @@ impl TimePolicy { pub struct CopyOptions { /// Timestamp handling. pub times: TimePolicy, - /// Replace files that already exist in the volume instead of failing - /// with EEXIST. - pub replace: bool, + /// What the copy does with an entry the volume holds under a name it + /// writes, or under a name FAT does not tell apart from it: + /// [`NameCollision::Fail`], the default, fails with EEXIST, and + /// [`NameCollision::Replace`] replaces a file and takes a directory as + /// the one of that name. A directory of the same name takes the + /// entries either way. + pub name_collision: NameCollision, /// Follow symbolic links in the source tree instead of skipping them. pub follow_symlinks: bool, } @@ -62,7 +66,7 @@ impl Default for CopyOptions { fn default() -> Self { CopyOptions { times: TimePolicy::Preserve, - replace: true, + name_collision: NameCollision::Fail, follow_symlinks: false, } } @@ -121,9 +125,16 @@ impl Read for Counted<'_> { impl Volume { /// Copies the contents of `source` into a new file at `dest` and returns - /// how many bytes it copied. - pub fn write_file(&mut self, dest: &str, source: &mut dyn Read, time: SystemTime, replace: bool) -> Result { - let mut file = self.begin_file(dest, time, replace).map_err(|e| e.at_path(dest))?; + /// how many bytes it copied. `collision` says what happens to an entry + /// the volume holds under that name, see [`Volume::begin_file`]. + pub fn write_file( + &mut self, + dest: &str, + source: &mut dyn Read, + time: SystemTime, + collision: NameCollision, + ) -> Result { + let mut file = self.begin_file(dest, time, collision).map_err(|e| e.at_path(dest))?; // The volume keeps one copy buffer, allocated on first use; the // file token lets us hold it while the file is open. let mut buf = std::mem::take(&mut self.copy_buffer); @@ -212,7 +223,7 @@ impl Volume { done, progress, }; - self.write_file(dest, &mut counted, time, options.replace) + self.write_file(dest, &mut counted, time, options.name_collision) } /// Copies the tree below the open directory `source` into the directory @@ -244,12 +255,7 @@ impl Volume { let mut visit = |target: &str, entry: &HostEntry| -> Result { if entry.is_dir() { let time = options.times.resolve(source_mtime(&entry.metadata)); - match self.metadata(target) { - Ok(m) if m.is_dir => {} - Ok(_) => bail!(ENOTDIR, "'{}' exists in the volume and is not a directory", target), - Err(e) if e.errno() == ENOENT => self.create_dir(target, time)?, - Err(e) => return Err(e), - } + self.find_or_create_dir(target, time, options.name_collision)?; report.directories += 1; progress(&report.progress()); Ok(true) diff --git a/src/fat/volume/file.rs b/src/fat/volume/file.rs index 7274664..ef60dbe 100644 --- a/src/fat/volume/file.rs +++ b/src/fat/volume/file.rs @@ -7,7 +7,9 @@ use std::io::{self, Read, Write}; use std::time::SystemTime; -use super::{check_attributes, writable, Located, NewEntry, Placement, Volume, MAX_FILE_SIZE, SETTABLE_ATTRIBUTES}; +use super::{ + check_attributes, writable, Located, NameCollision, NewEntry, Placement, Volume, MAX_FILE_SIZE, SETTABLE_ATTRIBUTES, +}; use crate::dir::{DirEntry, Directory}; use crate::dirent::{RawDirEntry, ATTR_ARCHIVE, ATTR_READ_ONLY}; use crate::errno::*; @@ -30,9 +32,12 @@ impl Volume { /// written to the directory until the file is finished: its slots are /// reserved in memory and the entry goes in, complete, after the data /// and the FAT. So a crash while the file is written leaves the - /// directory as it was, never an empty file. With `replace` an existing - /// file of the same name stays in place until the new one is complete - /// and is removed then; without it an existing file is an EEXIST error. + /// directory as it was, never an empty file. With + /// [`NameCollision::Replace`] an existing file of the same name, or of a + /// name FAT does not tell apart from it, stays in place until the new + /// one is complete and is removed then. With [`NameCollision::Fail`] an + /// existing file is an EEXIST error, which for a name of another + /// spelling says that FAT does not tell the two apart. /// /// The token borrows nothing, so any number of files can be open at /// once and the volume stays usable in between; whether another @@ -44,15 +49,23 @@ impl Volume { /// Nothing is written for a file that is refused: a name FAT cannot /// store or one that is too long, a parent that is missing, damaged or /// full, too few free clusters for the parent to grow, a directory of - /// the name, or a file of the name without `replace`. - pub fn begin_file(&mut self, path: &str, time: SystemTime, replace: bool) -> Result { + /// the name, or under [`NameCollision::Fail`] a file of the name or one + /// FAT does not tell apart from it. + pub fn begin_file(&mut self, path: &str, time: SystemTime, collision: NameCollision) -> Result { let (dir_cluster, name) = self.locate_parent(path)?; let (placement, replaced) = self.with_directory_mut(dir_cluster, |vol, parent| { + // A name of another spelling is a case collision first, as for + // a directory, see Volume::find_or_create_dir. let replaced = match Self::find(parent, name.as_str()) { + Some(existing) if collision == NameCollision::Fail && existing.name() != name.as_str() => { + return Err(vol.case_collision(path, &existing)); + } Some(existing) if existing.short.is_directory() => { bail!(EISDIR, Detail::Path(path.to_string()), "'{}' is a directory", path); } - Some(_) if !replace => bail!(EEXIST, Detail::Path(path.to_string()), "'{}' exists", path), + Some(_) if collision == NameCollision::Fail => { + bail!(EEXIST, Detail::Path(path.to_string()), "'{}' exists", path) + } existing => existing, }; let placement = vol @@ -98,8 +111,8 @@ impl Volume { /// Creates a file and returns a writer for its contents; see /// [`Volume::begin_file`] for what happens when and [`FileWriter`] for /// the guard that aborts an unfinished file on drop. - pub fn create_file(&mut self, path: &str, time: SystemTime, replace: bool) -> Result> { - let file = self.begin_file(path, time, replace)?; + pub fn create_file(&mut self, path: &str, time: SystemTime, collision: NameCollision) -> Result> { + let file = self.begin_file(path, time, collision)?; Ok(FileWriter { volume: self, file: Some(file), diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index c6f9c9f..63a0133 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -34,11 +34,11 @@ use crate::errno::*; use crate::fat::{Entry, Extent, Fat, FatStore, CACHE_BYTES, ENTRY1_CLEAN_SHUTDOWN}; use crate::layout::Layout; use crate::name::{fold_str, long_name_entries, short_name_to_string, Alias, LongName}; -use crate::path::components; +use crate::path::{components, SEPARATOR}; use crate::probe::Prober; use crate::time::FatTimestamp; use crate::Result; -use crate::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason}; +use crate::{CorruptPlace, Detail, Error, NoSpaceReason, NotFat32Reason}; mod file; #[cfg(test)] @@ -80,6 +80,32 @@ pub struct Metadata { pub(crate) name_decoding: NameDecoding, } +/// What creating a file or a directory does where its name collides with +/// an entry the volume holds: one of the same name, or one whose name FAT +/// does not tell apart from it, as it does not tell `A` from `a`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NameCollision { + /// Fail with EEXIST, for an entry of another spelling with + /// [`crate::NameProblem::CaseCollision`]. A directory of the same name + /// is no collision for [`Volume::find_or_create_dir`], which takes it. + Fail, + /// Take what is there: a file is replaced, and a directory under a name + /// of another spelling is the directory of this name. + Replace, +} + +/// The directory [`Volume::find_or_create_dir`] makes sure is there. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DirectoryOrigin { + /// The volume had none, and it was made. + Created, + /// It was there already. + Existing { + /// The attributes of its entry. + attributes: u8, + }, +} + /// Where a path led: the root, or an entry and the first cluster of the /// directory holding it. enum Located { @@ -679,10 +705,19 @@ impl Volume { /// Descends from the root along `comps`, which must all be directories, /// and returns the first cluster of the directory reached. fn walk(&self, comps: &[&str]) -> Result { + self.walk_with(comps, |_| {}) + } + + /// [`Volume::walk`], handing `visit` the entry of every directory it + /// descends into. + fn walk_with(&self, comps: &[&str], mut visit: impl FnMut(&DirEntry)) -> Result { let mut cluster = self.boot.root_cluster; for (i, name) in comps.iter().enumerate() { cluster = match self.with_directory(cluster, |dir| Ok(Self::find(dir, name)))? { - Some(e) if e.short.is_directory() => e.short.first_cluster, + Some(e) if e.short.is_directory() => { + visit(&e); + e.short.first_cluster + } Some(_) => { let p = format!("/{}", comps[..=i].join("/")); bail!(ENOTDIR, Detail::Path(p.clone()), "'{}' is not a directory", p); @@ -696,6 +731,28 @@ impl Volume { Ok(cluster) } + /// The path of the directory `dir` as the volume spells the names on + /// it: "/efi" is "/EFI" where the volume holds EFI, and the root is "". + fn stored_path(&self, dir: &str) -> Result { + let mut stored = String::new(); + self.walk_with(&components(dir)?, |entry| { + stored.push(SEPARATOR); + stored.push_str(&entry.name()); + })?; + Ok(stored) + } + + /// The error of a case collision of `path` with `existing`, the entry + /// its directory holds under a name FAT does not tell apart from the + /// last name of `path`. It names `existing` by its path as the volume + /// spells it. + fn case_collision(&self, path: &str, existing: &DirEntry) -> Error { + match self.stored_path(crate::path::parent(path)) { + Ok(dir) => Error::case_collision(path, &crate::path::join(&dir, &existing.name())), + Err(e) => e, + } + } + fn locate(&self, path: &str) -> Result { let comps = components(path)?; let Some((last, parents)) = comps.split_last() else { @@ -999,6 +1056,45 @@ impl Volume { Ok(()) } + /// Makes sure there is a directory at `path` for content to go into, as + /// a copy or an assembly finds one or makes one with `time`, and says + /// which. A directory of the same name is that one. One under a name FAT + /// does not tell apart from the last name of `path` is that one with + /// [`NameCollision::Replace`], and a case collision with + /// [`NameCollision::Fail`], which comes before anything else about the + /// entry. A file of that name fails with ENOTDIR. The parent has to + /// exist. Only making a directory writes to the volume, and nothing + /// is written for one that is refused, as with [`Volume::create_dir`]. + pub fn find_or_create_dir( + &mut self, + path: &str, + time: SystemTime, + collision: NameCollision, + ) -> Result { + let (parent, name) = self.locate_parent(path)?; + self.with_directory_mut(parent, |vol, parent| { + let Some(existing) = Self::find(parent, name.as_str()) else { + let child = vol.make_directory(parent, &name, time).map_err(|e| e.at_path(path))?; + vol.keep_directory(child); + return Ok(DirectoryOrigin::Created); + }; + if collision == NameCollision::Fail && existing.name() != name.as_str() { + return Err(vol.case_collision(path, &existing)); + } + if !existing.short.is_directory() { + bail!( + ENOTDIR, + Detail::Path(path.to_string()), + "'{}' exists in the volume and is not a directory", + path + ); + } + Ok(DirectoryOrigin::Existing { + attributes: existing.short.attr, + }) + }) + } + /// Creates a directory and any missing parents. Existing directories /// along the way are fine, whatever their names. The path is walked to /// the first directory that is missing without writing anything, and diff --git a/src/fat/volume/tests.rs b/src/fat/volume/tests.rs index a875d02..5e707b7 100644 --- a/src/fat/volume/tests.rs +++ b/src/fat/volume/tests.rs @@ -8,6 +8,7 @@ use crate::fsck; use crate::layout::FIRST_CLUSTER; use crate::name::{LFN_PADDING, LFN_TERMINATOR}; use crate::test_util::{format_options, volume, TempImage}; +use crate::NameProblem; use std::io::{Read, Write}; use std::time::{Duration, UNIX_EPOCH}; @@ -73,7 +74,7 @@ fn files_round_trip() { for (i, &size) in sizes.iter().enumerate() { let path = format!("/file{}.bin", i); let data: Vec = (0..size).map(|j| (j * 7 + i as u64) as u8).collect(); - let mut w = v.create_file(&path, t(1_600_000_000), false).unwrap(); + let mut w = v.create_file(&path, t(1_600_000_000), NameCollision::Fail).unwrap(); // Write in odd sized pieces to exercise the pending buffer. for chunk in data.chunks(1000) { w.write_all(chunk).unwrap(); @@ -100,8 +101,16 @@ fn files_round_trip() { let a = v.metadata("/file3.bin").unwrap().first_cluster; let b = v.metadata("/file4.bin").unwrap().first_cluster; assert_eq!(b, a + 1); - assert_eq!(v.create_file("/file1.bin", t(0), false).unwrap_err().errno(), EEXIST); - assert_eq!(v.create_file("/", t(0), false).unwrap_err().errno(), EEXIST); + assert_eq!( + v.create_file("/file1.bin", t(0), NameCollision::Fail) + .unwrap_err() + .errno(), + EEXIST + ); + assert_eq!( + v.create_file("/", t(0), NameCollision::Fail).unwrap_err().errno(), + EEXIST + ); assert_eq!(v.open_file("/missing").unwrap_err().errno(), ENOENT); assert_eq!(v.open_file("/").unwrap_err().errno(), EISDIR); v.remove_file("/file5.bin").unwrap(); @@ -118,12 +127,12 @@ fn files_round_trip() { fn replace_and_abort() { let (_img, mut v) = volume(8 << 20, 512, 512); let free = v.free_clusters(); - let mut w = v.create_file("/a.txt", t(0), false).unwrap(); + let mut w = v.create_file("/a.txt", t(0), NameCollision::Fail).unwrap(); w.write_all(&[1u8; 2000]).unwrap(); w.finish().unwrap(); // Replacing goes through the case-insensitive match and creates the // entry anew under the new spelling. - let mut w = v.create_file("/A.TXT", t(0), true).unwrap(); + let mut w = v.create_file("/A.TXT", t(0), NameCollision::Replace).unwrap(); w.write_all(&[2u8; 100]).unwrap(); w.finish().unwrap(); assert_eq!(names(&v, "/"), vec!["A.TXT"]); @@ -131,19 +140,81 @@ fn replace_and_abort() { assert_eq!(v.free_clusters(), free - 1); // Dropping an unfinished writer discards the file. { - let mut w = v.create_file("/b.txt", t(0), false).unwrap(); + let mut w = v.create_file("/b.txt", t(0), NameCollision::Fail).unwrap(); w.write_all(&[3u8; 5000]).unwrap(); } assert_eq!(names(&v, "/"), vec!["A.TXT"]); assert_eq!(v.free_clusters(), free - 1); - let mut w = v.create_file("/c.txt", t(0), false).unwrap(); + let mut w = v.create_file("/c.txt", t(0), NameCollision::Fail).unwrap(); w.write_all(&[3u8; 5000]).unwrap(); w.abort().unwrap(); assert_eq!(names(&v, "/"), vec!["A.TXT"]); assert_eq!(v.free_clusters(), free - 1); - assert_eq!(v.create_file("/a.txt/x", t(0), false).unwrap_err().errno(), ENOTDIR); + assert_eq!( + v.create_file("/a.txt/x", t(0), NameCollision::Fail) + .unwrap_err() + .errno(), + ENOTDIR + ); v.create_dir("/d", t(0)).unwrap(); - assert_eq!(v.create_file("/d", t(0), true).unwrap_err().errno(), EISDIR); + assert_eq!( + v.create_file("/d", t(0), NameCollision::Replace).unwrap_err().errno(), + EISDIR + ); +} + +/// find_or_create_dir() makes a directory, or takes the one of the same +/// name, and with NameCollision::Replace one under a name FAT does not +/// tell apart. With NameCollision::Fail that is a case collision, which +/// comes first and names the entry that is there the way the volume spells +/// its path. A file of such a name is ENOTDIR. +#[test] +fn directories_are_found_or_made() { + let (_img, mut v) = volume(8 << 20, 512, 512); + assert_eq!( + v.find_or_create_dir("/EFI", t(0), NameCollision::Fail).unwrap(), + DirectoryOrigin::Created + ); + v.set_attributes("/EFI", ATTR_HIDDEN).unwrap(); + v.create_file("/EFI/x", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); + let existing = DirectoryOrigin::Existing { + attributes: ATTR_DIRECTORY | ATTR_HIDDEN, + }; + assert_eq!( + v.find_or_create_dir("/EFI", t(0), NameCollision::Fail).unwrap(), + existing + ); + assert_eq!( + v.find_or_create_dir("/efi/", t(0), NameCollision::Replace).unwrap(), + existing + ); + let e = v.find_or_create_dir("/efi", t(0), NameCollision::Fail).unwrap_err(); + assert_eq!(e.errno(), EEXIST); + assert_eq!( + e.detail(), + Some(&Detail::Name { + name: "/efi".into(), + problem: NameProblem::CaseCollision, + }) + ); + assert_eq!(e.message(), "'/efi' and '/EFI' are names FAT cannot tell apart"); + let e = v.find_or_create_dir("/efi/X", t(0), NameCollision::Fail).unwrap_err(); + assert_eq!(e.message(), "'/efi/X' and '/EFI/x' are names FAT cannot tell apart"); + for (path, collision, errno) in [ + ("/EFI/x", NameCollision::Fail, ENOTDIR), + ("/EFI/x", NameCollision::Replace, ENOTDIR), + ("/EFI/X", NameCollision::Fail, EEXIST), + ("/EFI/X", NameCollision::Replace, ENOTDIR), + ("/missing/d", NameCollision::Fail, ENOENT), + ] { + let e = v.find_or_create_dir(path, t(0), collision).unwrap_err(); + assert_eq!(e.errno(), errno, "{} {:?}", path, collision); + } + assert_eq!(names(&v, "/"), vec!["EFI"]); + assert_eq!(names(&v, "/EFI"), vec!["x"]); } #[test] @@ -157,7 +228,7 @@ fn short_and_long_names() { "longfilename2.txt", "ünïcödé", ] { - v.create_file(&format!("/{}", name), t(0), false) + v.create_file(&format!("/{}", name), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -182,9 +253,22 @@ fn short_and_long_names() { // Lookups work through either name. assert_eq!(v.metadata("/LONGFI~2.TXT").unwrap().name, "longfilename2.txt"); assert_eq!(v.metadata("/ÜNÏCÖDÉ").unwrap().name, "ünïcödé"); - assert_eq!(v.create_file("/README.TXT", t(0), false).unwrap_err().errno(), EEXIST); - assert_eq!(v.create_file("/bad:name", t(0), false).unwrap_err().errno(), EINVAL); - assert_eq!(v.create_file("/a/../b", t(0), false).unwrap_err().errno(), EINVAL); + assert_eq!( + v.create_file("/README.TXT", t(0), NameCollision::Fail) + .unwrap_err() + .errno(), + EEXIST + ); + assert_eq!( + v.create_file("/bad:name", t(0), NameCollision::Fail) + .unwrap_err() + .errno(), + EINVAL + ); + assert_eq!( + v.create_file("/a/../b", t(0), NameCollision::Fail).unwrap_err().errno(), + EINVAL + ); } #[test] @@ -196,7 +280,7 @@ fn directory_growth() { // one) need 120 slots plus the dot entries, i.e. 8 clusters of 16 // slots. for i in 0..40 { - v.create_file(&format!("/d/Mixed Case File {}.txt", i), t(0), false) + v.create_file(&format!("/d/Mixed Case File {}.txt", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -221,16 +305,16 @@ fn growing_a_directory_without_space_changes_nothing() { v.create_dir("/sub", t(0)).unwrap(); // The dots plus 14 one-slot entries fill the directory's cluster. for i in 0..14 { - v.create_file(&format!("/sub/F{}", i), t(0), false) + v.create_file(&format!("/sub/F{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); } - let mut w = v.create_file("/junk", t(0), false).unwrap(); + let mut w = v.create_file("/junk", t(0), NameCollision::Fail).unwrap(); w.write_all(&[b'A'; 512]).unwrap(); w.finish().unwrap(); let free = v.free_clusters(); - let mut w = v.create_file("/fill", t(0), false).unwrap(); + let mut w = v.create_file("/fill", t(0), NameCollision::Fail).unwrap(); w.write_all(&vec![0u8; free as usize * 512]).unwrap(); w.finish().unwrap(); assert_eq!(v.free_clusters(), 0); @@ -238,7 +322,12 @@ fn growing_a_directory_without_space_changes_nothing() { // anything is written. v.sync().unwrap(); let bytes = std::fs::read(img.path()).unwrap(); - assert_eq!(v.create_file("/sub/F14", t(0), false).unwrap_err().errno(), ENOSPC); + assert_eq!( + v.create_file("/sub/F14", t(0), NameCollision::Fail) + .unwrap_err() + .errno(), + ENOSPC + ); assert_eq!(names(&v, "/sub").len(), 14); assert_eq!(std::fs::read(img.path()).unwrap(), bytes); assert!(!v.is_writing()); @@ -254,7 +343,10 @@ fn growing_a_directory_without_space_changes_nothing() { assert_eq!(std::fs::read(img.path()).unwrap(), bytes); assert!(!v.is_writing()); // A file without contents only needs the directory to grow. - v.create_file("/sub/F14", t(0), false).unwrap().finish().unwrap(); + v.create_file("/sub/F14", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(v.free_clusters(), 0); assert_eq!(names(&v, "/sub").len(), 15); v.close().unwrap(); @@ -309,7 +401,7 @@ fn a_full_directory_refuses_before_it_writes() { let bytes = std::fs::read(img.path()).unwrap(); assert_eq!(v.read_dir("/d").unwrap().len(), MAX_SLOTS - 2); for e in [ - v.create_file("/d/x", t(0), false).map(drop).unwrap_err(), + v.create_file("/d/x", t(0), NameCollision::Fail).map(drop).unwrap_err(), v.create_dir("/d/y", t(0)).unwrap_err(), v.create_dir_all("/d/y/z", t(0)).unwrap_err(), ] { @@ -355,7 +447,7 @@ fn growth_for_continues_the_free_slots_at_the_end() { let first = FIRST_CLUSTER; Directory::new((first..first + clusters as u32).collect(), data, cs).unwrap() }; - let full = |e: crate::Error| { + let full = |e: Error| { e.errno() == ENOSPC && matches!( e.detail(), @@ -398,7 +490,7 @@ fn growing_from_the_free_slots_at_the_end_takes_the_clusters_it_needs() { v.create_dir("/d", t(0)).unwrap(); // The dots and 13 one-slot entries leave the last slot of /d free. for i in 0..13 { - v.create_file(&format!("/d/F{}", i), t(0), false) + v.create_file(&format!("/d/F{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -406,7 +498,7 @@ fn growing_from_the_free_slots_at_the_end_takes_the_clusters_it_needs() { let d = v.metadata("/d").unwrap(); assert_eq!(v.load_directory(d.first_cluster).unwrap().free_at_end(), 1); let free = v.free_clusters(); - let mut w = v.create_file("/fill", t(0), false).unwrap(); + let mut w = v.create_file("/fill", t(0), NameCollision::Fail).unwrap(); w.write_all(&vec![0u8; (free as usize - 1) * 512]).unwrap(); w.finish().unwrap(); assert_eq!(v.free_clusters(), 1); @@ -419,7 +511,10 @@ fn growing_from_the_free_slots_at_the_end_takes_the_clusters_it_needs() { assert!(!v.is_writing()); // A file of that name takes the one, and its entry starts in the last // slot of the first cluster. - v.create_file("/d/abcdefghi", t(0), false).unwrap().finish().unwrap(); + v.create_file("/d/abcdefghi", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(v.free_clusters(), 0); let dir = v.load_directory(d.first_cluster).unwrap(); assert_eq!(dir.chain().len(), 2); @@ -484,11 +579,11 @@ fn create_dir_all_walks_through_names_it_would_not_write() { fn a_failed_write_discards_the_file() { let (img, mut v) = volume(1 << 20, 512, 512); let free = v.free_clusters(); - let mut w = v.create_file("/big", t(0), false).unwrap(); + let mut w = v.create_file("/big", t(0), NameCollision::Fail).unwrap(); let e = w.write_all(&vec![0x5a; (free as usize + 5) * 512]).unwrap_err(); - assert_eq!(crate::Error::from(e).errno(), ENOSPC); + assert_eq!(Error::from(e).errno(), ENOSPC); // From here on the writer refuses to pretend. - assert_eq!(crate::Error::from(w.write_all(b"more").unwrap_err()).errno(), EIO); + assert_eq!(Error::from(w.write_all(b"more").unwrap_err()).errno(), EIO); assert_eq!(w.finish().unwrap_err().errno(), EIO); assert_eq!(v.metadata("/big").unwrap_err().errno(), ENOENT); assert_eq!(v.free_clusters(), free); @@ -510,7 +605,10 @@ fn the_label_is_not_a_name() { assert_eq!(v.label().unwrap().as_deref(), Some("EFI")); assert_eq!(v.metadata("/EFI").unwrap_err().errno(), ENOENT); v.create_dir_all("/EFI/BOOT", t(0)).unwrap(); - v.create_file("/efi.txt", t(0), false).unwrap().finish().unwrap(); + v.create_file("/efi.txt", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(names(&v, "/"), vec!["EFI", "efi.txt"]); assert_eq!(v.label().unwrap().as_deref(), Some("EFI")); v.close().unwrap(); @@ -521,20 +619,20 @@ fn the_label_is_not_a_name() { #[test] fn replacing_keeps_the_old_file_until_the_new_one_is_complete() { let (_img, mut v) = volume(1 << 20, 512, 512); - let mut w = v.create_file("/EFI.efi", t(0), false).unwrap(); + let mut w = v.create_file("/EFI.efi", t(0), NameCollision::Fail).unwrap(); w.write_all(&[7u8; 3000]).unwrap(); w.finish().unwrap(); let free = v.free_clusters(); // A replacement that is dropped half way leaves the old file alone. { - let mut w = v.create_file("/efi.EFI", t(1), true).unwrap(); + let mut w = v.create_file("/efi.EFI", t(1), NameCollision::Replace).unwrap(); w.write_all(&[8u8; 1000]).unwrap(); } assert_eq!(names(&v, "/"), vec!["EFI.efi"]); assert_eq!(v.metadata("/EFI.efi").unwrap().size, 3000); assert_eq!(v.free_clusters(), free); // So does one that is aborted. - let mut w = v.create_file("/efi.EFI", t(1), true).unwrap(); + let mut w = v.create_file("/efi.EFI", t(1), NameCollision::Replace).unwrap(); w.write_all(&[8u8; 1000]).unwrap(); w.abort().unwrap(); assert_eq!(names(&v, "/"), vec!["EFI.efi"]); @@ -548,7 +646,7 @@ fn replacing_keeps_the_old_file_until_the_new_one_is_complete() { (e.first_slot(), e.slot) }; let old = slot_of(&v, "efi.efi"); - let mut w = v.create_file("/efi.EFI", t(1), true).unwrap(); + let mut w = v.create_file("/efi.EFI", t(1), NameCollision::Replace).unwrap(); w.write_all(&[8u8; 1000]).unwrap(); w.finish().unwrap(); assert_eq!(names(&v, "/"), vec!["efi.EFI"]); @@ -558,7 +656,7 @@ fn replacing_keeps_the_old_file_until_the_new_one_is_complete() { assert!(!v.load_directory(root).unwrap().has_reservations()); // A spelling that needs a long name no longer fits into the one slot // and goes elsewhere; the old entry is deleted after it. - let mut w = v.create_file("/Efi.efi", t(1), true).unwrap(); + let mut w = v.create_file("/Efi.efi", t(1), NameCollision::Replace).unwrap(); w.write_all(&[9u8; 500]).unwrap(); w.finish().unwrap(); assert_eq!(names(&v, "/"), vec!["Efi.efi"]); @@ -568,7 +666,7 @@ fn replacing_keeps_the_old_file_until_the_new_one_is_complete() { // And back to one slot. Deleting the two slots of the long form leaves // the deleted slot before them as the end of the directory, so the new // entry goes there and the directory is compact again. - let mut w = v.create_file("/EFI.EFI", t(1), true).unwrap(); + let mut w = v.create_file("/EFI.EFI", t(1), NameCollision::Replace).unwrap(); w.write_all(&[10u8; 500]).unwrap(); w.finish().unwrap(); assert_eq!(slot_of(&v, "efi.efi"), (1, 1)); @@ -583,7 +681,10 @@ fn replacing_keeps_the_old_file_until_the_new_one_is_complete() { fn a_damaged_directory_is_read_but_not_written() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - v.create_file("/d/x", t(0), false).unwrap().finish().unwrap(); + v.create_file("/d/x", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); let d = v.metadata("/d").unwrap(); let layout = *v.layout(); v.close().unwrap(); @@ -603,7 +704,10 @@ fn a_damaged_directory_is_read_but_not_written() { // Writing is refused in every form, before anything is written: the // directory's entry in the root does not get the time its dot entries // cannot. - assert_eq!(v.create_file("/d/y", t(0), false).unwrap_err().errno(), EUCLEAN); + assert_eq!( + v.create_file("/d/y", t(0), NameCollision::Fail).unwrap_err().errno(), + EUCLEAN + ); assert_eq!(v.create_dir("/d/sub", t(0)).unwrap_err().errno(), EUCLEAN); assert_eq!(v.create_dir_all("/d/sub/deeper", t(0)).unwrap_err().errno(), EUCLEAN); assert_eq!(v.set_times("/d/x", t(1_700_000_000)).unwrap_err().errno(), EUCLEAN); @@ -613,7 +717,10 @@ fn a_damaged_directory_is_read_but_not_written() { assert_eq!(v.remove_file("/d/x").unwrap_err().errno(), EUCLEAN); assert_eq!(names(&v, "/d"), vec!["x"]); // The rest of the volume is still usable. - v.create_file("/ok", t(0), false).unwrap().finish().unwrap(); + v.create_file("/ok", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(names(&v, "/"), vec!["d", "ok"]); } @@ -621,7 +728,10 @@ fn a_damaged_directory_is_read_but_not_written() { fn set_times() { let (_img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - v.create_file("/d/f", t(0), false).unwrap().finish().unwrap(); + v.create_file("/d/f", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); v.set_times("/d/f", t(1_700_000_000)).unwrap(); v.set_times("/d", t(1_600_000_000)).unwrap(); assert_eq!(v.metadata("/d/f").unwrap().modified, t(1_700_000_000)); @@ -678,7 +788,10 @@ fn garbage_beyond_the_last_fat_entry_is_ignored() { } let mut v = Volume::open(dev).unwrap(); assert_eq!(v.free_clusters(), free); - v.create_file("/f", t(0), false).unwrap().finish().unwrap(); + v.create_file("/f", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); v.close().unwrap(); let r = fsck::check(&img.device()).unwrap(); assert_eq!(r.errors(), 0, "{:?}", r.problems); @@ -734,7 +847,11 @@ fn reproducible() { v.create_dir_all("/EFI/Linux", t(1_700_000_000)).unwrap(); for i in 0..5 { let mut w = v - .create_file(&format!("/EFI/Linux/kernel-{}.efi", i), t(1_700_000_000 + i), false) + .create_file( + &format!("/EFI/Linux/kernel-{}.efi", i), + t(1_700_000_000 + i), + NameCollision::Fail, + ) .unwrap(); w.write_all(&vec![i as u8; 777 * (i as usize + 1)]).unwrap(); w.finish().unwrap(); @@ -796,10 +913,10 @@ fn durable_mode_runs_the_same_operations() { assert!(!v.durable(), "an image file is not durable by default"); v.set_durable(true); v.create_dir_all("/a/b", t(0)).unwrap(); - let mut w = v.create_file("/a/b/f", t(0), false).unwrap(); + let mut w = v.create_file("/a/b/f", t(0), NameCollision::Fail).unwrap(); w.write_all(b"data").unwrap(); w.finish().unwrap(); - let mut w = v.create_file("/a/b/f", t(0), true).unwrap(); + let mut w = v.create_file("/a/b/f", t(0), NameCollision::Replace).unwrap(); w.write_all(b"newer").unwrap(); w.finish().unwrap(); v.remove_file("/a/b/f").unwrap(); @@ -815,14 +932,14 @@ fn durable_mode_runs_the_same_operations() { #[test] fn a_damaged_file_is_not_replaced() { let (img, mut v) = volume(1 << 20, 512, 512); - let mut w = v.create_file("/f", t(0), false).unwrap(); + let mut w = v.create_file("/f", t(0), NameCollision::Fail).unwrap(); w.write_all(&[7u8; 2000]).unwrap(); w.finish().unwrap(); let first = v.metadata("/f").unwrap().first_cluster; // The chain runs into a free cluster after its first one. v.link(first, 0).unwrap(); let free = v.free_clusters(); - let mut w = v.create_file("/f", t(1), true).unwrap(); + let mut w = v.create_file("/f", t(1), NameCollision::Replace).unwrap(); w.write_all(&[8u8; 1000]).unwrap(); let e = w.finish().unwrap_err(); assert_eq!(e.errno(), EUCLEAN, "{}", e); @@ -853,9 +970,12 @@ fn open_files_keep_their_slots() { n }; // An entry behind a reservation on zero slots. - let mut a = v.begin_file("/a", t(0), false).unwrap(); + let mut a = v.begin_file("/a", t(0), NameCollision::Fail).unwrap(); v.write_file_data(&mut a, b"aaa").unwrap(); - v.create_file("/b", t(0), false).unwrap().finish().unwrap(); + v.create_file("/b", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(sorted(&v), vec!["b"]); let root = v.boot.root_cluster; assert_eq!(v.load_directory(root).unwrap().entries().len(), 2, "label and b"); @@ -863,19 +983,25 @@ fn open_files_keep_their_slots() { assert_eq!(sorted(&v), vec!["a", "b"]); // The same with the reservation given up: a deleted slot stays, not // an end marker. - let c = v.begin_file("/c", t(0), false).unwrap(); - v.create_file("/d", t(0), false).unwrap().finish().unwrap(); + let c = v.begin_file("/c", t(0), NameCollision::Fail).unwrap(); + v.create_file("/d", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); v.abort_file(c).unwrap(); assert_eq!(sorted(&v), vec!["a", "b", "d"]); - v.create_file("/e", t(0), false).unwrap().finish().unwrap(); + v.create_file("/e", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(sorted(&v), vec!["a", "b", "d", "e"]); // A replacement whose old entry is last: deleting it moves the end of // the directory back over a deleted slot that another open file has // reserved; the new entry must go into the old slots instead. v.remove_file("/d").unwrap(); - let mut w = v.begin_file("/w", t(0), false).unwrap(); + let mut w = v.begin_file("/w", t(0), NameCollision::Fail).unwrap(); v.write_file_data(&mut w, b"w").unwrap(); - let mut z = v.create_file("/e", t(1), true).unwrap(); + let mut z = v.create_file("/e", t(1), NameCollision::Replace).unwrap(); z.write_all(b"ee").unwrap(); z.finish().unwrap(); v.finish_file(w).unwrap(); @@ -893,10 +1019,10 @@ fn open_files_keep_their_slots() { fn lookups_keep_the_slots_of_open_files() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - let mut x = v.create_file("/d/x", t(0), false).unwrap(); + let mut x = v.create_file("/d/x", t(0), NameCollision::Fail).unwrap(); x.write_all(b"xx").unwrap(); x.finish().unwrap(); - let mut a = v.begin_file("/d/a", t(0), false).unwrap(); + let mut a = v.begin_file("/d/a", t(0), NameCollision::Fail).unwrap(); v.write_file_data(&mut a, b"aaa").unwrap(); let mut s = String::new(); v.open_file("/d/x").unwrap().read_to_string(&mut s).unwrap(); @@ -917,20 +1043,23 @@ fn a_failed_begin_keeps_the_slots_of_open_files() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); // A whole cluster is written right away, so finishing a needs none. - let mut a = v.begin_file("/d/a", t(0), false).unwrap(); + let mut a = v.begin_file("/d/a", t(0), NameCollision::Fail).unwrap(); v.write_file_data(&mut a, &[b'a'; 512]).unwrap(); // The dots, a's slot and 13 more entries fill the cluster of /d. for i in 0..13 { - v.create_file(&format!("/d/f{}", i), t(0), false) + v.create_file(&format!("/d/f{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); } let free = v.free_clusters(); - let mut fill = v.create_file("/fill", t(0), false).unwrap(); + let mut fill = v.create_file("/fill", t(0), NameCollision::Fail).unwrap(); fill.write_all(&vec![0u8; free as usize * 512]).unwrap(); fill.finish().unwrap(); - assert_eq!(v.create_file("/d/b", t(0), false).unwrap_err().errno(), ENOSPC); + assert_eq!( + v.create_file("/d/b", t(0), NameCollision::Fail).unwrap_err().errno(), + ENOSPC + ); v.finish_file(a).unwrap(); assert_eq!(v.metadata("/d/a").unwrap().size, 512); v.close().unwrap(); @@ -944,17 +1073,20 @@ fn a_failed_begin_keeps_the_slots_of_open_files() { fn reservations_survive_a_reread_of_the_directory() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - let mut a = v.begin_file("/d/a", t(0), false).unwrap(); + let mut a = v.begin_file("/d/a", t(0), NameCollision::Fail).unwrap(); v.write_file_data(&mut a, b"aaa").unwrap(); v.forget_directory(v.metadata("/d").unwrap().first_cluster); // b must not land in the slots kept for a. - v.create_file("/d/b", t(0), false).unwrap().finish().unwrap(); + v.create_file("/d/b", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); v.finish_file(a).unwrap(); let mut n = names(&v, "/d"); n.sort(); assert_eq!(n, ["a", "b"]); // An aborted file gives its slots back for good. - let c = v.begin_file("/d/c", t(0), false).unwrap(); + let c = v.begin_file("/d/c", t(0), NameCollision::Fail).unwrap(); v.abort_file(c).unwrap(); assert!(v.dirs.borrow().reserved.is_empty()); v.close().unwrap(); @@ -969,7 +1101,7 @@ fn reading_files_does_not_reread_their_directory() { let (_img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); for i in 0..20 { - v.create_file(&format!("/d/f{}", i), t(0), false) + v.create_file(&format!("/d/f{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -997,13 +1129,13 @@ fn durable_mode_puts_a_barrier_before_every_publishing_write() { let syncs = || counter.load(Ordering::SeqCst); let before = syncs(); // A new file: chain, barrier, entry. - let mut w = v.create_file("/f", t(0), false).unwrap(); + let mut w = v.create_file("/f", t(0), NameCollision::Fail).unwrap(); w.write_all(b"data").unwrap(); w.finish().unwrap(); assert_eq!(syncs() - before, 1); // Replacing it: chain, barrier, entry, barrier, old chain freed. let before = syncs(); - let mut w = v.create_file("/f", t(0), true).unwrap(); + let mut w = v.create_file("/f", t(0), NameCollision::Replace).unwrap(); w.write_all(b"newer").unwrap(); w.finish().unwrap(); assert_eq!(syncs() - before, 2); @@ -1019,14 +1151,17 @@ fn durable_mode_puts_a_barrier_before_every_publishing_write() { // cluster is synced before the FAT links it, then the file's barrier. let before = syncs(); for i in 0..14 { - v.create_file(&format!("/g{}", i), t(0), false) + v.create_file(&format!("/g{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); } assert_eq!(syncs() - before, 14); let before = syncs(); - v.create_file("/g14", t(0), false).unwrap().finish().unwrap(); + v.create_file("/g14", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(syncs() - before, 2, "growing the directory adds a barrier"); v.close().unwrap(); } @@ -1050,7 +1185,7 @@ fn the_volume_is_marked_dirty_while_written() { assert_eq!(std::fs::read(img.path()).unwrap(), bytes, "reading marks nothing"); // While a file is being written the marks are on disk: the boot // sector bit, bit 27 of FAT entry 1 in every copy, unknown counts. - let mut w = v.create_file("/f", t(0), false).unwrap(); + let mut w = v.create_file("/f", t(0), NameCollision::Fail).unwrap(); w.write_all(b"data").unwrap(); let bytes = std::fs::read(img.path()).unwrap(); assert_ne!(bytes[field::NT_FLAGS] & NT_FLAG_DIRTY, 0); @@ -1080,13 +1215,17 @@ fn the_volume_is_marked_dirty_while_written() { /// What the volume refuses before it would write leaves it as it was: a /// name FAT cannot store, one that is too long, one that is taken or is a -/// directory, a parent that is missing. Nothing is marked, and the image -/// does not change. +/// directory, one FAT does not tell apart from a name that is there, a +/// parent that is missing. Nothing is marked, and the image does not +/// change. A directory that is there is no write either. #[test] fn refusals_leave_the_volume_unmarked() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - v.create_file("/f", t(0), false).unwrap().finish().unwrap(); + v.create_file("/f", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); v.sync().unwrap(); let bytes = std::fs::read(img.path()).unwrap(); let long = format!("/{}", "x".repeat(256)); @@ -1100,16 +1239,35 @@ fn refusals_leave_the_volume_unmarked() { (v.create_dir_all("/f/x", t(0)), ENOTDIR), (v.create_dir_all("/missing/a:b", t(0)), EINVAL), (v.create_dir_all(&long_below_missing, t(0)), ENAMETOOLONG), - (v.create_file("/d", t(0), true).map(drop), EISDIR), - (v.create_file("/f", t(0), false).map(drop), EEXIST), - (v.create_file("/a:b", t(0), true).map(drop), EINVAL), - (v.create_file(&long, t(0), true).map(drop), ENAMETOOLONG), + (v.create_file("/d", t(0), NameCollision::Replace).map(drop), EISDIR), + (v.create_file("/f", t(0), NameCollision::Fail).map(drop), EEXIST), + (v.create_file("/a:b", t(0), NameCollision::Replace).map(drop), EINVAL), + ( + v.create_file(&long, t(0), NameCollision::Replace).map(drop), + ENAMETOOLONG, + ), + (v.create_file("/F", t(0), NameCollision::Fail).map(drop), EEXIST), + (v.create_file("/D", t(0), NameCollision::Fail).map(drop), EEXIST), + (v.find_or_create_dir("/D", t(0), NameCollision::Fail).map(drop), EEXIST), + ( + v.find_or_create_dir("/f", t(0), NameCollision::Replace).map(drop), + ENOTDIR, + ), ] { assert_eq!(e.unwrap_err().errno(), errno); } // Directories that are there are no write either. v.create_dir_all("/d", t(0)).unwrap(); v.create_dir_all("/", t(0)).unwrap(); + for (path, collision) in [("/d", NameCollision::Fail), ("/D", NameCollision::Replace)] { + let origin = v.find_or_create_dir(path, t(0), collision).unwrap(); + assert!( + matches!(origin, DirectoryOrigin::Existing { .. }), + "{} {:?}", + path, + origin + ); + } // The image is read while the volume is open: closing it would put back // marks a refusal set. A writing session lasts until the volume is // synced, so is_writing() covers every refusal above as well. @@ -1131,7 +1289,7 @@ fn a_volume_closed_unfinished_stays_marked() { let fsinfo = usize::from(v.boot_sector().fsinfo_sector) * layout.sector_size as usize; assert!(!v.is_writing()); if written { - let mut w = v.create_file("/f", t(0), false).unwrap(); + let mut w = v.create_file("/f", t(0), NameCollision::Fail).unwrap(); w.write_all(b"data").unwrap(); w.finish().unwrap(); v.sync().unwrap(); @@ -1163,7 +1321,10 @@ fn a_volume_closed_unfinished_stays_marked() { #[test] fn remove_tree() { let (img, mut v) = volume(1 << 20, 512, 512); - v.create_file("/keep", t(0), false).unwrap().finish().unwrap(); + v.create_file("/keep", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); let free = v.free_clusters(); v.create_dir_all("/a/b/c", t(0)).unwrap(); v.create_dir("/a/d", t(0)).unwrap(); @@ -1173,14 +1334,14 @@ fn remove_tree() { .into_iter() .enumerate() { - let mut w = v.create_file(path, t(0), false).unwrap(); + let mut w = v.create_file(path, t(0), NameCollision::Fail).unwrap(); w.write_all(&vec![i as u8; 700 * (i + 1)]).unwrap(); w.finish().unwrap(); files += 1; } // Enough long names to take /a/b/c past its first cluster. for i in 0..20 { - v.create_file(&format!("/a/b/c/Mixed Case File {}.txt", i), t(0), false) + v.create_file(&format!("/a/b/c/Mixed Case File {}.txt", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -1238,7 +1399,10 @@ fn root_time() { let mut v = Volume::open(img.device()).unwrap(); assert_eq!(v.root_time().unwrap(), None); assert_eq!(v.label().unwrap(), None); - v.create_file("/f", t(0), false).unwrap().finish().unwrap(); + v.create_file("/f", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); // Modification times go in two second steps. v.set_root_time(t(1_700_000_001)).unwrap(); assert_eq!(v.root_time().unwrap(), Some(t(1_700_000_000))); @@ -1352,7 +1516,7 @@ fn the_label_entry_grows_a_full_root() { let mut v = Volume::open(img.device()).unwrap(); // Sixteen one-slot entries fill the root's cluster. for i in 0..16 { - v.create_file(&format!("/F{}", i), t(0), false) + v.create_file(&format!("/F{}", i), t(0), NameCollision::Fail) .unwrap() .finish() .unwrap(); @@ -1375,7 +1539,10 @@ fn the_label_entry_grows_a_full_root() { fn set_attributes() { let (img, mut v) = volume(1 << 20, 512, 512); v.create_dir("/d", t(0)).unwrap(); - v.create_file("/d/f", t(0), false).unwrap().finish().unwrap(); + v.create_file("/d/f", t(0), NameCollision::Fail) + .unwrap() + .finish() + .unwrap(); assert_eq!(v.metadata("/d/f").unwrap().attributes, ATTR_ARCHIVE); assert_eq!(v.metadata("/d").unwrap().attributes, ATTR_DIRECTORY); // The four bits are replaced as a whole: the archive bit goes unless it @@ -1412,7 +1579,7 @@ fn set_attributes() { v.set_attributes("/d/f", 0).unwrap(); assert_eq!(v.metadata("/d/f").unwrap().attributes, 0); // A writer sets them for the entry it is going to write. - let mut w = v.create_file("/d/g", t(0), false).unwrap(); + let mut w = v.create_file("/d/g", t(0), NameCollision::Fail).unwrap(); assert_eq!(w.set_attributes(ATTR_DIRECTORY).unwrap_err().errno(), EINVAL); w.set_attributes(ATTR_SYSTEM | ATTR_ARCHIVE).unwrap(); w.finish().unwrap(); diff --git a/tests/cli.rs b/tests/cli.rs index aea1acc..ffc8350 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -505,20 +505,34 @@ fn assemble_and_populate_take_trees_and_manifests() { // The planner sees the same size from the manifest, which needs no // SOURCE to be sized. assert_eq!(tree_size, ok(&bin, &["assemble", "--plan", "--manifest", m])); - // populate fills an existing volume, from a manifest too, replacing. - ok(&bin, &["populate", "--manifest", m, a, tree_arg]); + // populate fills an existing volume, from a manifest too. A file the + // volume holds already it replaces only with --replace. + fails( + &bin, + &["populate", "--manifest", m, a, tree_arg], + "'/EFI/Linux/linux.efi' exists", + ); + ok(&bin, &["populate", "--replace", "--manifest", m, a, tree_arg]); ok(&bin, &["populate", "--path", "/second", a, tree_arg]); assert_eq!(ok(&bin, &["list", a, "/second/EFI/Linux"]), "linux.efi\n"); assert!(run(&bin, &["check", a]).status.success()); // "-" takes the file contents from standard input, back to back in // manifest order: linux.efi sorts before x.conf. - let out = run_in(&bin, &["populate", "--manifest", m, a, "-"], b"kerneltitle x\n"); + let out = run_in( + &bin, + &["populate", "--replace", "--manifest", m, a, "-"], + b"kerneltitle x\n", + ); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(ok(&bin, &["cat", a, "/loader/entries/x.conf"]), "title x\n"); - let out = run_in(&bin, &["populate", "--manifest", m, a, "-"], b"kern"); + let out = run_in(&bin, &["populate", "--replace", "--manifest", m, a, "-"], b"kern"); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("ended")); - let out = run_in(&bin, &["populate", "--manifest", m, a, "-"], b"kerneltitle x\nmore"); + let out = run_in( + &bin, + &["populate", "--replace", "--manifest", m, a, "-"], + b"kerneltitle x\nmore", + ); assert_eq!(out.status.code(), Some(1)); assert!(String::from_utf8_lossy(&out.stderr).contains("goes on after the last file")); // A populate that fails partway leaves the file system marked as not @@ -530,7 +544,7 @@ fn assemble_and_populate_take_trees_and_manifests() { // under --unsupported fail, a file the stream cannot have without a // size or at an offset, one that is missing below the SOURCE, one where // the file system has a directory, a name FAT cannot store or one too - // long, and a name the file system holds with --no-replace. + // long, and a name the file system holds already. let clean = image("clean.img"); let clean = clean.as_str(); ok(&bin, &["assemble", "--create", "--size", "40M", clean]); @@ -569,7 +583,7 @@ fn assemble_and_populate_take_trees_and_manifests() { "contains the invalid character ':'", ), (long.as_str(), &[], "-", "is longer than 255 UTF-16 units"), - (r#"{"name":"f","size":0}"#, &["--no-replace"], "-", "'/f' exists"), + (r#"{"name":"f","size":0}"#, &[], "-", "'/f' exists"), ] { let refused = root.join("refused.manifest"); fs::write( @@ -645,7 +659,11 @@ fn assemble_and_populate_take_trees_and_manifests() { ); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert_eq!(ok(&bin, &["cat", piped, "/loader/entries/x.conf"]), "title x\n"); - let out = run_in(&bin, &["populate", "--manifest", "-", a, tree_arg], &manifest_bytes); + let out = run_in( + &bin, + &["populate", "--replace", "--manifest", "-", a, tree_arg], + &manifest_bytes, + ); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let out = run_in(&bin, &["populate", "--manifest", "-", a, "-"], b""); assert_eq!(out.status.code(), Some(1)); @@ -727,6 +745,11 @@ fn assemble_and_populate_take_trees_and_manifests() { "unknown option", ); fails(&bin, &["assemble", "--create", "--stream", b, m], "unknown option"); + fails( + &bin, + &["assemble", "--no-replace", "--create", b, tree_arg], + "unknown option", + ); // The files a manifest names are found below the SOURCE when they are // copied, and the messages about them name the SOURCE. A SOURCE that is // not there leaves nothing behind. A file that is missing, or changed @@ -786,6 +809,27 @@ fn assemble_and_populate_take_trees_and_manifests() { assert_eq!(fs::metadata(c).unwrap().len().to_string() + "\n", tree_size); ok(&bin, &["populate", "--manifest", m, c, tree_arg]); assert!(run(&bin, &["check", c]).status.success()); + // Populating it with the same manifest once more fails at its first + // file, which is there, before anything is written, with the contents + // from the SOURCE and from standard input. So does the tree. The image + // stays as it was, byte for byte. + let image_before = fs::read(c).unwrap(); + for (args, stdin) in [ + (&["populate", "--manifest", m, c, tree_arg][..], &b""[..]), + (&["populate", "--manifest", m, c, "-"], b"kerneltitle x\n"), + (&["populate", c, tree_arg], b""), + ] { + let out = run_in(&bin, args, stdin); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{:?}: {}", args, stderr); + assert!( + stderr.contains("'/EFI/Linux/linux.efi' exists"), + "{:?}: {}", + args, + stderr + ); + assert!(fs::read(c).unwrap() == image_before, "{:?} changed the image", args); + } // With --size it takes that size, which the --fit directory or what the // manifest describes has to fit. A size no file system fits in is // refused as it is without them. @@ -930,6 +974,95 @@ fn manifests_have_to_declare_their_order() { assert_eq!(ok(&bin, &["list", a]), "EFI/\nloader/\n"); } +/// Names FAT does not tell apart are one name: assemble and populate refuse +/// a second one, in a manifest as well as in a tree, a directory's as well +/// as a file's, unless --replace says to take it as the first. A tree is +/// copied in the order of the bytes of its names, as a manifest has them. +#[test] +fn names_fat_does_not_tell_apart() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + let both = root.join("both"); + fs::create_dir_all(&both).unwrap(); + fs::write(both.join("README.TXT"), "upper\n").unwrap(); + fs::write(both.join("readme.txt"), "lower\n").unwrap(); + let path = |name: &str| root.join(name).to_str().unwrap().to_string(); + let both = path("both"); + let manifest = root.join("both.manifest"); + fs::write(&manifest, ok(&bin, &["manifest", &both])).unwrap(); + let m = manifest.to_str().unwrap(); + let a = path("a.img"); + fails( + &bin, + &["assemble", "--create", "--size", "40M", &a, &both], + "'/readme.txt' and '/README.TXT' are names FAT cannot tell apart", + ); + ok(&bin, &["assemble", "--force", "--replace", &a, &both]); + assert_eq!(ok(&bin, &["list", &a]), "readme.txt\n"); + assert_eq!(ok(&bin, &["cat", &a, "/README.TXT"]), "lower\n"); + fails( + &bin, + &["assemble", "--force", "--manifest", m, &a, &both], + "'/readme.txt' and '/README.TXT' are names FAT cannot tell apart", + ); + ok(&bin, &["assemble", "--force", "--replace", "--manifest", m, &a, &both]); + assert_eq!(ok(&bin, &["list", &a]), "readme.txt\n"); + fails( + &bin, + &["populate", "--manifest", m, &a, &both], + "'/README.TXT' and '/readme.txt' are names FAT cannot tell apart", + ); + ok(&bin, &["populate", "--replace", "--manifest", m, &a, &both]); + // A tree's efi is its EFI only with --replace, and takes the entries of + // the EFI then. + for name in ["EFI/a", "efi/b"] { + let file = root.join("dirs").join(name); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, "x\n").unwrap(); + } + let (dirs, d) = (path("dirs"), path("d.img")); + fails( + &bin, + &["assemble", "--create", "--size", "40M", &d, &dirs], + "'/efi' and '/EFI' are names FAT cannot tell apart", + ); + ok(&bin, &["assemble", "--force", "--replace", &d, &dirs]); + assert_eq!(ok(&bin, &["list", &d, "/EFI"]), "a\nb\n"); + // A trailing slash means nothing, also to the message, which spells the + // path that is there the way the file system does. + fails( + &bin, + &["populate", "--path", "/efi/", &d, &path("dirs/EFI/a")], + "'/efi/' and '/EFI' are names FAT cannot tell apart", + ); + fails( + &bin, + &["populate", "--path", "/efi/A", &d, &path("dirs/EFI/a")], + "'/efi/A' and '/EFI/a' are names FAT cannot tell apart", + ); + // A file whose name FAT does not tell apart from a directory's is that + // as well, before anything else, and with --replace it cannot take the + // directory's place. + let mixed = root.join("mixed"); + fs::create_dir_all(mixed.join("EFI")).unwrap(); + fs::write(mixed.join("efi"), "x\n").unwrap(); + let (mixed, e) = (path("mixed"), path("e.img")); + fails( + &bin, + &["assemble", "--create", "--size", "40M", &e, &mixed], + "'/efi' and '/EFI' are names FAT cannot tell apart", + ); + fails( + &bin, + &["assemble", "--force", "--replace", &e, &mixed], + "'/efi' is a directory", + ); +} + /// A volume too small for what goes into it. A copy that runs out of /// clusters says which file did not fit and leaves what came before it in /// a consistent file system. `assemble --minimize` with a `--size` the @@ -1218,12 +1351,14 @@ fn a_plan_against_a_size_answers_for_assemble() { assert_eq!(ok(&bin, &["cat", a, "/d99/f799"]), "x"); } -/// A plan does not compare names. The entries of a directory under two -/// names that FAT does not tell apart go into one directory. The plan holds -/// the entries under each name to the 65536 entries of a FAT directory on -/// their own, and only the write sees them all in one directory. In two -/// runs of 1600 names of 255 characters, which take 21 entries each, the -/// plan passes and `assemble` fails. In one run the plan fails. +/// A plan does not compare names. With --replace the entries of a +/// directory under two names that FAT does not tell apart go into one +/// directory. The plan holds the entries under each name to the 65536 +/// entries of a FAT directory on their own, and only the write sees them +/// all in one directory. In two runs of 1600 names of 255 characters, +/// which take 21 entries each, the plan passes and `assemble --replace` +/// fails. Without --replace the second name fails before. In one run the +/// plan fails. #[test] fn directories_under_two_names_fill_up_when_written() { let _serial = common::serial(); @@ -1253,9 +1388,25 @@ fn directories_under_two_names_fill_up_when_written() { let a = image.to_str().unwrap(); fails( &bin, - &["assemble", "--create", "--minimize", "--manifest", s, a, "-"], + &[ + "assemble", + "--create", + "--minimize", + "--replace", + "--manifest", + s, + a, + "-", + ], "directory is full", ); + let image = root.join("b.img"); + let b = image.to_str().unwrap(); + fails( + &bin, + &["assemble", "--create", "--minimize", "--manifest", s, b, "-"], + "'/efi' and '/EFI' are names FAT cannot tell apart", + ); let whole = root.join("whole.manifest"); fs::write(&whole, manifest(&[("EFI", 0..3200)])).unwrap(); fails( @@ -1345,10 +1496,10 @@ fn populate_and_remove_work_on_paths() { &["populate", "--parents", "--path", "/EFI/BOOT/BOOTX64.EFI", a, f], ); assert_eq!(ok(&bin, &["cat", a, "/EFI/BOOT/BOOTX64.EFI"]), "loader"); - fails( + fails(&bin, &["populate", "--path", "/EFI/BOOT/BOOTX64.EFI", a, f], "exists"); + ok( &bin, - &["populate", "--no-replace", "--path", "/EFI/BOOT/BOOTX64.EFI", a, f], - "exists", + &["populate", "--replace", "--path", "/EFI/BOOT/BOOTX64.EFI", a, f], ); // No SOURCE: the directory --path, which may exist only with --parents. ok(&bin, &["populate", "--path", "/loader", a]); diff --git a/tests/crash/crash.rs b/tests/crash/crash.rs index 1d98e53..1d1cce3 100644 --- a/tests/crash/crash.rs +++ b/tests/crash/crash.rs @@ -43,7 +43,7 @@ use fat::name::{ MAX_LONG_NAME, }; use fat::time::FatTimestamp; -use fat::volume::Volume; +use fat::volume::{NameCollision, Volume}; /// Subsets enumerated per epoch before the generator samples instead. /// UFAT_CRASH_FULL=1 lifts the cap. @@ -148,7 +148,7 @@ enum Op { Write { path: String, data: Vec, - replace: bool, + collision: NameCollision, chunk: usize, }, Remove(String), @@ -168,11 +168,14 @@ impl Op { Op::Write { path, data, - replace, + collision, chunk, } => format!( "{} {} ({} bytes, {} per write)", - if *replace { "replace" } else { "write" }, + match collision { + NameCollision::Replace => "replace", + NameCollision::Fail => "write", + }, path, data.len(), chunk @@ -185,7 +188,9 @@ impl Op { fn replaces(&self) -> Option<&str> { match self { Op::Write { - path, replace: true, .. + path, + collision: NameCollision::Replace, + .. } => Some(path), _ => None, } @@ -202,45 +207,51 @@ fn scenario(slots_per_cluster: usize) -> Vec { let mut rng = Rng(SEED); let mut ops: Vec = Vec::new(); let whole = 1 << 20; - let mut file = |ops: &mut Vec, path: &str, len: usize, replace: bool, chunk: usize| { + let mut file = |ops: &mut Vec, path: &str, len: usize, collision: NameCollision, chunk: usize| { ops.push(Op::Write { path: path.to_string(), data: rng.bytes(len), - replace, + collision, chunk, }); }; let kernel = |n: usize| format!("/EFI/Linux/linux-6.12.{}-200.fc41.x86_64+3.efi", n); ops.push(Op::Mkdir("/EFI/BOOT".into())); - file(&mut ops, "/EFI/BOOT/BOOTX64.EFI", 70_000, false, 4096); + file(&mut ops, "/EFI/BOOT/BOOTX64.EFI", 70_000, NameCollision::Fail, 4096); ops.push(Op::Mkdir("/EFI/Linux".into())); // More clusters than a 512 byte FAT sector has entries go to a file // before /EFI/Linux grows. So with 512 byte sectors the FAT entries of // its first cluster and of the one it grows by are in different // sectors. - file(&mut ops, "/EFI/BOOT/mmx64.efi", 300_000, false, whole); + file(&mut ops, "/EFI/BOOT/mmx64.efi", 300_000, NameCollision::Fail, whole); // Enough long names to grow the directory past its first cluster. let kernels = slots_per_cluster / 4 + 2; for i in 0..kernels { - file(&mut ops, &kernel(i + 1), 1500 + 700 * i, false, whole); + file(&mut ops, &kernel(i + 1), 1500 + 700 * i, NameCollision::Fail, whole); } ops.push(Op::Mkdir("/loader/entries".into())); - file(&mut ops, "/loader/entries/fedora.conf", 300, false, whole); - file(&mut ops, "/loader/loader.conf", 40, false, whole); - file(&mut ops, "/loader/random-seed", 32, false, whole); - file(&mut ops, "/loader/entries.srel", 5, false, whole); - file(&mut ops, "/EFI/BOOT/BOOTX64.EFI", 72_000, true, 4096); + file(&mut ops, "/loader/entries/fedora.conf", 300, NameCollision::Fail, whole); + file(&mut ops, "/loader/loader.conf", 40, NameCollision::Fail, whole); + file(&mut ops, "/loader/random-seed", 32, NameCollision::Fail, whole); + file(&mut ops, "/loader/entries.srel", 5, NameCollision::Fail, whole); + file(&mut ops, "/EFI/BOOT/BOOTX64.EFI", 72_000, NameCollision::Replace, 4096); ops.push(Op::Remove(kernel(4))); - file(&mut ops, "/loader/loader.conf", 60, true, whole); + file(&mut ops, "/loader/loader.conf", 60, NameCollision::Replace, whole); // The new entry goes into the slots the removed kernel left, which // straddle a sector boundary with 512 byte sectors. - file(&mut ops, &kernel(3), 5000, true, whole); + file(&mut ops, &kernel(3), 5000, NameCollision::Replace, whole); ops.push(Op::Mkdir("/EFI/systemd/drop-ins/deep".into())); - file(&mut ops, "/EFI/systemd/systemd-bootx64.efi", 9000, false, whole); - file(&mut ops, &kernel(kernels + 1), 2048, false, whole); + file( + &mut ops, + "/EFI/systemd/systemd-bootx64.efi", + 9000, + NameCollision::Fail, + whole, + ); + file(&mut ops, &kernel(kernels + 1), 2048, NameCollision::Fail, whole); // Now the only room is in the directory's second cluster: the old // entry's deletion and the new entry are two cluster writes. - file(&mut ops, &kernel(2), 4000, true, whole); + file(&mut ops, &kernel(2), 4000, NameCollision::Replace, whole); // A directory made where its parent has room, and one made in /full // after empty files with long names fill the first cluster of /full to // its last slot, so that /full grows for the entry. The new cluster of @@ -265,7 +276,7 @@ fn scenario(slots_per_cluster: usize) -> Vec { let len = (LFN_UNITS_PER_ENTRY * (k - 1)).min(MAX_LONG_NAME); format!("{}{}", prefix, "x".repeat(len - prefix.len())) }; - file(&mut ops, &format!("/full/{}", name), 0, false, whole); + file(&mut ops, &format!("/full/{}", name), 0, NameCollision::Fail, whole); free -= k; n += 1; } @@ -670,10 +681,10 @@ impl Harness { Op::Write { path, data, - replace, + collision, chunk, } => { - let mut w = v.create_file(path, fixed_time(), *replace).unwrap(); + let mut w = v.create_file(path, fixed_time(), *collision).unwrap(); for piece in data.chunks(*chunk) { w.write_all(piece).unwrap(); } diff --git a/tests/fuzz/mutate.py b/tests/fuzz/mutate.py index 7ecceb7..c080672 100755 --- a/tests/fuzz/mutate.py +++ b/tests/fuzz/mutate.py @@ -1140,7 +1140,7 @@ def image_commands(ufat, img_path, seed_info, small_tree, rng): ("describe", [ufat, "describe", img_path], False), ("populate-dir", [ufat, "populate", "--path", rng.choice(["/new", "/EFI/new", "/new dir with long name", "/deep/er/new"]), img_path], True), ("remove", [ufat, "remove", img_path, rm_target], True), - ("populate", [ufat, "populate", img_path, small_tree], True), + ("populate", [ufat, "populate", "--replace", img_path, small_tree], True), ] if rng.random() < 0.2: cmds.append(("populate-parents", [ufat, "populate", "--parents", "--path", "/a/b/c/d/e/f", img_path], True)) diff --git a/tests/fuzz/targeted.py b/tests/fuzz/targeted.py index 08f1ee7..1e8cb7f 100755 --- a/tests/fuzz/targeted.py +++ b/tests/fuzz/targeted.py @@ -70,7 +70,7 @@ def timestamps(self): for t in ["18446744073709551615", "9223372036854775808", "9223372036854775807", "-1", "1e3", "4354819199", "99999999999999999"]: self.run("populate --timestamp %s" % t, [self.ufat, "populate", "--timestamp", t, "--path", "/t" + t[:3], img]) for t in ["18446744073709551615", "9223372036854775808", "abc", "", " 1700000000", "1700000000.5"]: - self.run("populate SOURCE_DATE_EPOCH=%r" % t, [self.ufat, "populate", img, self.small_tree], env={"SOURCE_DATE_EPOCH": t}) + self.run("populate SOURCE_DATE_EPOCH=%r" % t, [self.ufat, "populate", "--replace", img, self.small_tree], env={"SOURCE_DATE_EPOCH": t}) for t in ["18446744073709551615", "9223372036854775808"]: self.run("assemble --timestamp %s" % t, [self.ufat, "assemble", "--create", "--size", "40M", "--timestamp", t, os.path.join(self.work, "ts.img")]) self.run("assemble --plan SOURCE_DATE_EPOCH=%s" % t, [self.ufat, "assemble", "--plan", self.small_tree], env={"SOURCE_DATE_EPOCH": t}) @@ -164,7 +164,7 @@ def big_directory(self): open(os.path.join(tree, "f%d" % i), "wb").close() img = os.path.join(self.work, "big-%d.img" % n) self.run("populate %d files in one dir" % n, [self.ufat, "assemble", "--create", "--fit", tree, img], timeout=60) - self.run("populate %d files in one dir (2)" % n, [self.ufat, "populate", img, tree], timeout=300) + self.run("populate %d files in one dir (2)" % n, [self.ufat, "populate", "--replace", img, tree], timeout=300) shutil.rmtree(tree) def manifests(self): diff --git a/tests/reference.rs b/tests/reference.rs index 2a7c0fb..f3371f8 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -16,7 +16,7 @@ use fat::device::{Access, Device}; use fat::format::{self, FormatOptions}; use fat::host; use fat::populate::{CopyOptions, TimePolicy}; -use fat::volume::Volume; +use fat::volume::{NameCollision, Volume}; /// A source tree resolved once, the way the tool resolves its arguments. fn source(path: &Path) -> OwnedFd { @@ -128,14 +128,21 @@ fn populate(image: &Path, source: &Path, sector_size: u32, cluster_size: Option< v.copy_tree(self::source(source).as_fd(), "/", &CopyOptions::default()) .unwrap(); // Some churn: a deleted file and a replaced one. - v.create_file("/deleted.tmp", UNIX_EPOCH + Duration::from_secs(1_700_000_000), false) - .unwrap() - .finish() - .unwrap(); + v.create_file( + "/deleted.tmp", + UNIX_EPOCH + Duration::from_secs(1_700_000_000), + NameCollision::Fail, + ) + .unwrap() + .finish() + .unwrap(); v.remove_file("/deleted.tmp").unwrap(); let readme = host::open_file(&source.join("readme.txt")).unwrap(); - v.copy_file(readme.as_fd(), "/readme.txt", &CopyOptions::default()) - .unwrap(); + let replace = CopyOptions { + name_collision: NameCollision::Replace, + ..CopyOptions::default() + }; + v.copy_file(readme.as_fd(), "/readme.txt", &replace).unwrap(); v.close().unwrap(); } @@ -342,7 +349,7 @@ fn matches_mtools_byte_for_byte() { "/", &CopyOptions { times: TimePolicy::Preserve, - replace: true, + name_collision: NameCollision::Replace, follow_symlinks: false, }, ) diff --git a/tests/varlink.rs b/tests/varlink.rs index f140ef0..ecb35c7 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -1478,6 +1478,79 @@ fn manifests_have_to_declare_their_order() { assert_eq!(u64_of(&r, "files"), 2); } +/// Names FAT does not tell apart: Assemble and Populate refuse the second +/// one unless replace is set. +#[test] +fn assemble_refuses_names_fat_does_not_tell_apart() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let tree = Temp::dir(); + build_tree(tree.path(), &[("README.TXT", b"upper\n"), ("readme.txt", b"lower\n")]); + let (manifest, _) = manifest_and_blob(tree.path()); + let scratch = Temp::dir(); + let mut c = connect_fd3(&ufat); + let source = ro(tree.path()); + let (_image, img) = fresh_image(); + let e = error_of( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"sourceFileDescriptor":1}}"#, + &[img.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidName", IFACE)); + assert_eq!(str_of(&e.parameters, "name"), "/readme.txt"); + assert_eq!(str_of(&e.parameters, "reason"), "caseCollision"); + let manifest_file = file_with(scratch.path(), "manifest", &manifest); + let (image, img) = fresh_image(); + let with_manifest = |replace: bool| { + format!( + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"force":true}},"content":{{"manifest":{{"fileDescriptor":1}},"sourceFileDescriptor":2,"replace":{}}}}}"#, + replace + ) + }; + let e = error_of( + &mut c, + "Assemble", + &with_manifest(false), + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidName", IFACE)); + assert_eq!(str_of(&e.parameters, "name"), "/readme.txt"); + assert_eq!(str_of(&e.parameters, "reason"), "caseCollision"); + let manifest_file = ro(&scratch.path().join("manifest")); + let r = reply(call( + &mut c, + "Assemble", + &with_manifest(true), + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); + assert_eq!(u64_of(&r, "files"), 2); + let img_ro = ro(image.path()); + assert_eq!( + names(&call_more(&mut c, "List", IMG, &[img_ro.as_fd()])), + ["readme.txt"] + ); + let manifest_file = ro(&scratch.path().join("manifest")); + let e = error_of( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidName", IFACE)); + assert_eq!(str_of(&e.parameters, "reason"), "caseCollision"); + let manifest_file = ro(&scratch.path().join("manifest")); + let r = reply(call( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"replace":true}}"#, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); + assert_eq!(u64_of(&r, "files"), 2); +} + /// Assemble with a manifest and the contents of its files in a stream. #[test] fn assemble_with_a_manifest_and_a_stream() { @@ -1697,9 +1770,11 @@ fn warnings(c: &mut Client, image: &Path) -> Vec { /// An Assemble that fails after the format leaves the file system as after /// a crash: with the files that were complete, and marked as not cleanly /// unmounted, which Check reports. It is marked when it fails before the -/// first file as well. Assembling again makes a clean file system, which a -/// Populate refused before it writes anything leaves clean, and a Populate -/// that fails partway leaves marked again. +/// first file as well. Assembling again makes a clean file system. A +/// Populate refused before it writes anything leaves it clean. A Populate +/// of the manifest it was assembled from, or of its tree, fails at the +/// first file, which is there, and leaves the image as it was, byte for +/// byte. A Populate that fails partway leaves the file system marked again. #[test] fn a_failed_assemble_leaves_the_file_system_unfinished() { let _serial = common::serial(); @@ -1798,6 +1873,28 @@ fn a_failed_assemble_leaves_the_file_system_unfinished() { assert_eq!(e.name, format!("{}.{}", IFACE, error)); assert!(warnings(&mut c, image.path()).is_empty()); } + // The manifest it was assembled from, and its tree, fail at the first + // file, which is there, before anything is written: the directories + // have the times of the manifest already. + let manifest_file = ro(&base.path().join("manifest")); + let image_before = std::fs::read(image.path()).unwrap(); + for (content, fds) in [ + ( + r#"{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}"#, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()][..], + ), + (r#"{"sourceFileDescriptor":1}"#, &[img.as_fd(), source.as_fd()]), + ] { + let e = error_of( + &mut c, + "Populate", + &format!(r#"{{"image":{{"fileDescriptor":0}},"path":"/","content":{}}}"#, content), + fds, + ); + assert_eq!(e.name, format!("{}.FileExists", IFACE), "{}", content); + assert_eq!(str_of(&e.parameters, "path"), "/EFI/BOOT/BOOTX64.EFI"); + assert!(std::fs::read(image.path()).unwrap() == image_before, "{}", content); + } std::fs::write(tree.join("loader/loader.conf"), b"timeout 9\n").unwrap(); let manifest_file = ro(&base.path().join("manifest")); let e = error_of( @@ -2433,21 +2530,21 @@ fn populate_puts_content_into_a_volume() { &[img.as_fd(), conf.as_fd()], ); assert_eq!(e.name, format!("{}.NoSuchFile", IFACE)); - // An existing file is replaced unless replace says otherwise. - reply(call( - &mut c, - "Populate", - r#"{"image":{"fileDescriptor":0},"path":"/a/b/c.conf","content":{"sourceFileDescriptor":1}}"#, - &[img.as_fd(), conf.as_fd()], - )); + // An existing file is replaced only with replace. let e = error_of( &mut c, "Populate", - r#"{"image":{"fileDescriptor":0},"path":"/a/b/c.conf","content":{"sourceFileDescriptor":1,"replace":false}}"#, + r#"{"image":{"fileDescriptor":0},"path":"/a/b/c.conf","content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), conf.as_fd()], ); assert_eq!(e.name, format!("{}.FileExists", IFACE)); assert_eq!(str_of(&e.parameters, "path"), "/a/b/c.conf"); + reply(call( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/a/b/c.conf","content":{"sourceFileDescriptor":1,"replace":true}}"#, + &[img.as_fd(), conf.as_fd()], + )); // A manifest names its paths from the root and goes nowhere else. let manifest_file = file_with(scratch.path(), "manifest", &manifest); let e = error_of( @@ -2465,15 +2562,15 @@ fn populate_puts_content_into_a_volume() { &[img_ro.as_fd()], ); assert_eq!(e.name, format!("{}.NoSuchFile", IFACE)); - // A manifest's tree, with the manifest of the whole volume written - // afterwards. + // A manifest's tree over the one that is there, with the manifest of + // the whole volume written afterwards. let manifest_file = ro(&scratch.path().join("manifest")); let out = scratch.path().join("out.manifest"); let out_file = sink(&out); let replies = call_more( &mut c, "Populate", - r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"manifestSink":{"fileDescriptor":3}}}"#, + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"replace":true,"manifestSink":{"fileDescriptor":3}}}"#, &[img.as_fd(), manifest_file.as_fd(), source.as_fd(), out_file.as_fd()], ); assert_eq!(phases(&replies), vec!["populating", "reading"]); @@ -2551,12 +2648,20 @@ fn populate_puts_content_into_a_volume() { ); assert_eq!(e.name, "org.varlink.service.InvalidParameter"); assert_eq!(str_of(&e.parameters, "parameter"), "content"); - // A tree into the root of a volume that has things already. - let r = reply(call( + // A tree into the root of a volume that has its files already, which + // it takes only with replace. + let e = error_of( &mut c, "Populate", r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1}}"#, &[img.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.FileExists", IFACE)); + let r = reply(call( + &mut c, + "Populate", + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1,"replace":true}}"#, + &[img.as_fd(), source.as_fd()], )); assert_eq!(u64_of(&r, "files"), 2); } @@ -3266,14 +3371,14 @@ fn errors_are_typed() { let r = reply(call( &mut c, "Populate", - r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1}}"#, + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1,"replace":true}}"#, &[img.as_fd(), source.as_fd()], )); assert_eq!(u64_of(&r, "skipped"), 1); let e = error_of( &mut c, "Populate", - r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1,"unsupported":"fail"}}"#, + r#"{"image":{"fileDescriptor":0},"path":"/","content":{"sourceFileDescriptor":1,"replace":true,"unsupported":"fail"}}"#, &[img.as_fd(), source.as_fd()], ); assert_eq!(e.name, format!("{}.ContentNotSupported", IFACE)); From 3882d9115b0d7a7fe9542b1117bf0489917f40ba Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 17/19] ufat: create new images with O_TMPFILE Currently, assemble --create creates the image right away and removes it again only when it fails before the format, because the content doesn't fit the size given or a source can't be read. When filling the file system fails the image stays, marked as not cleanly unmounted. Without --minimize the content is written right away and a size that is too small is only found while it is written. So a failed assemble --create --size leaves a half-written image behind. We could remove the image by its name after any failure. But no unlink is conditional on the inode, so whatever has the name by then would go. Instead, let's not give the image a name before everything succeeded. Device::create() makes the image with O_TMPFILE in the parent directory it looked up, and it has no name while it is formatted and filled. Once the manifest of --write-manifest and the hash are written the image gets its name with linkat(fd, "", dir, name, AT_EMPTY_PATH). Since 42bd2af59504 ("vfs: relax linkat() AT_EMPTY_PATH - aka flink() - requirements") the opener can do that without CAP_DAC_READ_SEARCH. Where it fails with ENOENT we link through /proc/self/fd/ with AT_SYMLINK_FOLLOW, as systemd's link_fd() does. A failure, a kill, or SIGPIPE while the manifest goes to standard output leave no name behind. A name that something else took meanwhile stays as it is since the link fails with EEXIST. The cost is that --create only claims the name at the end. A file system that makes files without a name but can't link them, say a FUSE server with FUSE_TMPFILE but without FUSE_LINK, fails only then, and we say so. Where O_TMPFILE is refused (EOPNOTSUPP from a file system without it, EISDIR from a kernel that doesn't know it) the image is made under a temporary name in the same directory: ".#", the name and 16 random hex digits, as systemd's tempfn_random() does it. At the end it is renamed with RENAME_NOREPLACE. NFS, CephFS and 9p refuse that flag with EINVAL, and a kernel without renameat2() says ENOSYS. There we link the image by its descriptor and remove the temporary name afterwards. We call renameat2() through syscall(), since the musl that Rust links its musl targets with has no wrapper for it. A kill leaves the temporary name behind, as a crash would. A rename moves whatever has the temporary name by then. So right before each rename we check by device and inode number that the temporary name still refers to our file, and after it that the name does, and fail otherwise. A file that takes the temporary name between that check and the rename still ends up under the image's name, and we leave it there. When the check after the link fails for another reason, say EMFILE, the image keeps its name and we say that it has its name but couldn't be checked. Which of the two works is found out right when the image is made, before anything is written to it, by renaming the temporary file to another temporary name with RENAME_NOREPLACE, or else by linking it to one. A file system without hard links refuses the link with EPERM (vfs_link()). Where both are refused, as on vboxsf and orangefs, the image is created under its name with O_CREAT|O_EXCL as main does it, and removed by that name after any failure, where main removes it only when sizing it fails before the format. Note that this last resort can't avoid the window between checking that the name still refers to the image and removing it. A rename onto the name in between gets the other file removed. That crosses no privilege boundary though, whoever can rename onto the name could unlink it anyway. The new file takes the exclusive lock the device takes as soon as it exists. A file another process locked first keeps its name and we fail with EBUSY. Where the lock can't be had at all, say ENOLCK from NFS without lockd, we remove the fresh name after the same check and fail with that error. Otherwise a name is only ever removed while we hold the lock. fat::host::NewFile is a file that waits for its name. Dropping it gives it up, and giving it up removes a temporary name, or the name of the last resort, after checking by device and inode number that it still refers to the file. NewFile::discard() says what became of the name and NewFile::give_up() says what of the file stays, if anything. The tool collects that in Leftovers, and prints it after the error: what failed, then what that left behind. The device gets a descriptor of its own that shares the open file description with the new file, so the lock is held until the new file is gone. The hash has to be taken before the link, so we take it through the volume's device after syncing it instead of opening the image by path again. A failure there goes through NewVolume::abandon() like any other one, and the hash is printed only once the image has its name. abandon() drops the volume with Volume::abandon(), which writes nothing. So a half-filled file system that somebody linked meanwhile isn't marked clean. NewVolume is a guard as well. A NewVolume that is dropped before link() or abandon(), say by an early return added later, gives up an image made for it and closes an image that was there as not cleanly unmounted, or writes nothing at all while a panic unwinds. The files of --write-manifest and --write-hash are made the same way and get their names after the image, in place of what has them. So a failed run doesn't leave a manifest of an image that doesn't exist. Since such a file is replaced and not written over, other hard links to it keep what it held. A pipe, a device or a symbolic link at their path is written to as we go, as standard output is, and that can't be taken back. An image that has its name keeps it when one of these files can't get its own. Since the names are made last now, a power cut right after a reported success could lose them although the data was synced. So, as systemd's LINK_TMPFILE_SYNC does, each file is synced before it gets its name, the image by closing the volume, and each directory is synced once after the last link, also when something fails after the image got its name, so that a crash can't take the name of a complete image we said we kept. vboxsf, orangefs, AFS and 9p without 9P2000.L have no fsync for directories and vfs_fsync_range() gives EINVAL there, so we skip the sync. We skip it as well for a directory we may write to but not read, mode 0300 say, since it can't be opened for the fsync. That's also why the directory is only opened once the names are given and not before. Any other failure of the sync fails the command, but the names stay and we say so. Note that an image that was there before keeps what was written, marked as not cleanly unmounted, the way a crash would leave it. Signed-off-by: Christian Brauner (Amutable) --- README.md | 57 ++- src/bin/ufat/cli.rs | 169 ++++--- src/bin/ufat/util.rs | 629 +++++++++++++++++++++++- src/fat/device.rs | 202 +++++--- src/fat/host.rs | 1064 ++++++++++++++++++++++++++++++++++++++++- src/fat/sys.rs | 275 ++++++++++- src/fat/volume/mod.rs | 12 +- tests/cli.rs | 1003 +++++++++++++++++++++++++++++++++++++- tests/reference.rs | 4 +- 9 files changed, 3225 insertions(+), 190 deletions(-) diff --git a/README.md b/README.md index 608197d..57512c5 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,8 @@ While copying, ufat verifies the size and the SHA-256 hash of every file. The data of a file is the part of its file below the SOURCE that starts at the offset the manifest gives and is as long as the manifest says, whatever else that file holds. A file that is missing below the SOURCE, -too short for the data, or does not match fails the command, and the file +too short for the data, or does not match fails the command. If +`--create` made the image, nothing is left of it. Otherwise the file system is left marked as not cleanly unmounted, with the files that were complete. @@ -303,7 +304,8 @@ With `--replace` the entries of a directory under two such names, such as `FOO BAR/a` and `FOOBAR~1/b`, go into one directory. The plan holds the entries under each name to the limit on their own, and only the write sees them all in one directory. When they do not fit, `assemble` -fails with "directory is full". +fails with "directory is full", and nothing is left of an image that +`--create` made. A file and a directory under two such names pass the plan, and `assemble` fails on the second one, with or without `--replace`. @@ -359,12 +361,51 @@ unmounted, the way Linux, Windows and EDK2 expect. ufat removes the mark when it closes the volume. After a crash, the mark tells readers and `ufat check` to look at the volume. -When `assemble` fails after it has formatted the file system, ufat -leaves the file system marked as not cleanly unmounted, as after a -crash. It holds the files that were complete when the command failed. -`ufat check` and fsck.fat report the mark, and Linux warns about it when -it mounts the file system read-write. Running `assemble --force` again -formats the file system anew. +An image that `assemble --create` makes gets its name only when +everything else succeeded, its hash included. Until then it has no name, +so a failed `assemble` leaves nothing of it. If a file takes the name +meanwhile, `assemble` fails and leaves that file as it is. On a file +system that cannot make a file without a name, such as NFS or FAT, the +image has a temporary name in the same directory until then: `.#` +followed by its name and 16 hex digits. A kill or a crash leaves that +file behind. Once the image and the files written next to it have their +names, ufat syncs their directories, so that a power cut does not lose +the names. It does that also when `assemble` fails after the image got +its name. It does not sync a directory on a file system that cannot sync +directories, such as vboxsf, or a directory it may not read. + +There are exceptions. A file system that can neither rename a file +without replacing another one nor make hard links, such as vboxsf, does +not let the image wait for its name. There the image gets its name right +away, and a failed `assemble` removes it again, but a kill or a crash +leaves it. ufat removes such a name only while it still refers to the +image, but another file can take the name between that check and the +removal, and is removed then. Another file that takes the temporary name +of the image just before ufat renames the image gets the name of the +image, and `assemble` fails and leaves it there. When another process +locks the new image first, `assemble` fails and leaves the image to that +process: under its temporary name where it has one, or under its name on +a file system such as vboxsf. A file system that makes files without a +name but cannot give them one, such as a FUSE file system without hard +links, fails `assemble` at its very end. An image that has its name +keeps it when a file written next to it cannot get its own, and when +syncing its directory or checking its name fails, which ufat says. A +name that cannot be removed stays, and ufat says so after the error. + +The files that `--write-manifest` and `--write-hash` write get their +names after the image, and a failed `assemble` leaves what is at their +paths as it was. A regular file there is replaced, not written over, so +other hard links to it keep what it held. A pipe, a device or a symbolic +link at such a path is written to as `assemble` goes, like standard +output. A hash that `--hash` prints is printed once the image has its +name. + +When `assemble` fails after it has formatted the file system in an image +that was there before, ufat leaves the file system marked as not cleanly +unmounted, as after a crash. It holds the files that were complete when +the command failed. `ufat check` and fsck.fat report the mark, and Linux +warns about it when it mounts the file system read-write. Running +`assemble --force` again formats the file system anew. When `populate` fails while it writes a tree or a manifest, ufat leaves the file system marked the same way, unless nothing was written yet. A diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index b5f8fad..ad85066 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -25,7 +25,7 @@ use fat::volume::{NameCollision, Volume}; use fat::{bail, err, Context, DescriptorProblem, Detail, Error, ManifestProblem, Result}; use crate::service; -use crate::util::{self, GivenSize, ImageFlags, ManifestInput, ManifestUse, SizeMode, SizeRequest}; +use crate::util::{self, Failure, GivenSize, ImageFlags, ManifestInput, ManifestUse, NewVolume, SizeMode, SizeRequest}; const USAGE: &str = "\ Usage: ufat COMMAND [OPTIONS...] ARGS... @@ -99,7 +99,9 @@ Options for assemble: --mkfs-fat-compat Reproduce mkfs.fat's layout quirks exactly --zero Zero the whole data area --create Create IMAGE if it does not exist (it then needs --size, - --minimize, --fit, or --manifest without a SOURCE) + --minimize, --fit, or --manifest without a SOURCE). + IMAGE gets its name only once assemble succeeded (the + README says when a failure leaves it nonetheless) --force, -f Format IMAGE whatever it holds --fit DIR Size IMAGE for DIR and leave it empty (no SOURCE): --size, which DIR has to fit, or else the smallest @@ -762,17 +764,19 @@ fn manifest_to_stdout(args: &Args) -> bool { /// Writes the UAPI.16 manifest of everything `v` holds to the file `path`, /// or to standard output for "-", for `--write-manifest`. fn write_manifest(v: &Volume, path: &Path) -> Result<()> { - let features = Features::DEFAULT; - let (report, shown) = if path == Path::new("-") { - let out = std::io::BufWriter::new(std::io::stdout().lock()); - let report = v.write_manifest(v.root_time()?, features, out)?; - (report, STDOUT_MANIFEST.to_string()) + if path == Path::new("-") { + write_manifest_to(v, std::io::stdout().lock(), STDOUT_MANIFEST) } else { let file = std::fs::File::create(path).with_context(|| format!("cannot create {}", path.display()))?; - let report = v.write_manifest(v.root_time()?, features, std::io::BufWriter::new(file))?; - (report, path.display().to_string()) - }; - warn_about_manifest(&report, &shown); + write_manifest_to(v, file, &path.display().to_string()) + } +} + +/// Writes the UAPI.16 manifest of everything `v` holds to `out`, which the +/// messages call `shown`. +fn write_manifest_to(v: &Volume, out: impl Write, shown: &str) -> Result<()> { + let report = v.write_manifest(v.root_time()?, Features::DEFAULT, std::io::BufWriter::new(out))?; + warn_about_manifest(&report, shown); Ok(()) } @@ -901,7 +905,7 @@ fn plan(args: &Args) -> Result<()> { /// `--size` or of the image, or with `--minimize` the smallest one. The /// `--fit` directory or what `--manifest` describes has to fit a size /// given, and without one the file system is the smallest that holds it. -fn assemble_empty(args: &Args, path: &Path) -> Result { +fn assemble_empty(args: &Args, path: &Path) -> std::result::Result { let mut options = format_options(args)?; let fit = args.paths("fit"); let target = util::Target { @@ -926,23 +930,23 @@ fn assemble_empty(args: &Args, path: &Path) -> Result { Some(source) => source.into_plan(plan, args).map(drop), None => bail!(errno::EINVAL, "the content is planned once"), }; - let (volume, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add)) - .map_err(|e| e.into_error(path))?; + let (new, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add))?; if let Some(estimate) = estimate { report_estimate(args, path, &estimate); } - Ok(volume) + Ok(new) } /// `assemble` with a SOURCE: the file system of the size of `--size` or of /// the image, or with `--minimize` the smallest that holds it, filled with /// it. -fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result { +fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> std::result::Result { if !args.paths("fit").is_empty() { - bail!( + return Err(err!( errno::EINVAL, "--fit sizes an empty file system; with a SOURCE --minimize sizes it for the SOURCE" - ); + ) + .into()); } let mode = if args.flag("minimize") { SizeMode::Minimize @@ -963,24 +967,15 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> Result flags: args.image_flags(), }; let mut add = |plan: &mut Plan| source.add_to(plan, args).map(drop); - let (mut v, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add)) - .map_err(|e| e.into_error(path))?; + let (mut new, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add))?; if let Some(estimate) = estimate { report_estimate(args, path, &estimate); } - match source.fill(&mut v, args) { - Ok(()) => Ok(v), - Err(e) => Err(unfinished(v, e)), + if let Err(e) = source.fill(new.volume_mut(), args) { + let leftovers = new.abandon(); + return Err(Failure::new(e, leftovers)); } -} - -/// Closes the file system `assemble` failed to finish with `e`, marked as -/// not cleanly unmounted as after a crash, so that nobody takes it for a -/// finished one. Returns `e`: an error of the close is not the one the -/// user needs to hear about. -fn unfinished(v: Volume, e: Error) -> Error { - let _ = v.close_unfinished(); - e + Ok(new) } fn report_estimate(args: &Args, path: &Path, estimate: &fat::plan::Estimate) { @@ -1007,7 +1002,7 @@ fn force_hint(e: Error) -> Error { } } -fn cmd_assemble(argv: &[OsString]) -> Result<()> { +fn cmd_assemble(argv: &[OsString]) -> std::result::Result<(), Failure> { let args = Args::parse( argv, &with( @@ -1021,7 +1016,7 @@ fn cmd_assemble(argv: &[OsString]) -> Result<()> { fail_unsupported(&args)?; time_policy(&args)?; if args.flag("plan") { - return plan(&args); + return Ok(plan(&args)?); } let hash = match args.value("hash") { None => None, @@ -1032,50 +1027,90 @@ fn cmd_assemble(argv: &[OsString]) -> Result<()> { }; let hash_path = args.path("write-hash"); if hash_path.is_some() && hash.is_none() { - bail!(errno::EINVAL, "--write-hash needs --hash"); + return Err(err!(errno::EINVAL, "--write-hash needs --hash").into()); } if hash_path == Some(Path::new("-")) && manifest_to_stdout(&args) { - bail!( + return Err(err!( errno::EINVAL, "--write-manifest - and --write-hash - cannot both write to standard output" - ); + ) + .into()); } let (path, paths) = match args.positional_paths().split_first() { Some((&i, s)) => (i, s.to_vec()), - None => bail!(errno::EINVAL, "assemble takes an IMAGE and a SOURCE"), + None => return Err(err!(errno::EINVAL, "assemble takes an IMAGE and a SOURCE").into()), }; - let v = if paths.is_empty() { + let mut new = if paths.is_empty() { assemble_empty(&args, path) } else { assemble_filled(&args, path, &paths) } - .map_err(force_hint)?; - if let Some(m) = args.path("write-manifest") { - if let Err(e) = write_manifest(&v, m) { - return Err(unfinished(v, e)); + .map_err(|failure| Failure::new(force_hint(failure.error), failure.leftovers))?; + // The image and the files written next to it get their names only once + // everything else succeeded, the hash of the file system included, so + // a failure before leaves none of them behind. + let digest = match write_outputs(&args, path, &mut new, hash, hash_path) { + Ok(digest) => digest, + Err(e) => { + let leftovers = new.abandon(); + return Err(Failure::new(e, leftovers)); } + }; + let leftovers = new.link()?; + for line in leftovers.lines() { + eprintln!("ufat: {}", line); } - let layout = *v.layout(); - // The hash is of the file system's own bytes, which with --minimize can - // end before --size does. - let window = v.device().len(); - v.close()?; - report_layout(path, &layout, args.flag("verbose")); - if let Some(hash) = hash { - let offset = args.size("offset")?.unwrap_or(0); - let image = util::open_image(path, offset, Some(window), Access::ReadOnly)?; - let digest = hash.of(&image, &mut |_| {})?; - match hash_path { - Some(p) if p != Path::new("-") => { - std::fs::write(p, format!("{}\n", digest)).with_context(|| format!("cannot write {}", p.display()))? - } - None if manifest_to_stdout(&args) => eprintln!("{}", digest), - _ => println!("{}", digest), - } + // Unlike a manifest, which streams, the hash is complete before the + // image gets its name, and printed only once it has it. + match digest { + Some(digest) if manifest_to_stdout(&args) => eprintln!("{}", digest), + Some(digest) => writeln!(std::io::stdout().lock(), "{}", digest).with_context(|| "cannot write the hash")?, + None => {} } Ok(()) } +/// Writes what `assemble` writes about the file system it made in the +/// image `path`: the manifest of `--write-manifest`, and the hash of +/// `--hash`, which is taken through the descriptor the file system was +/// written through, once it is synced. Returns the hash where it is printed +/// rather than written to `--write-hash`. +fn write_outputs( + args: &Args, + path: &Path, + new: &mut NewVolume, + hash: Option, + hash_path: Option<&Path>, +) -> Result> { + match args.path("write-manifest") { + Some(m) if m != Path::new("-") => { + let out = new + .output(m) + .with_context(|| format!("cannot create {}", m.display()))?; + write_manifest_to(new.volume(), out, &m.display().to_string())?; + } + Some(m) => write_manifest(new.volume(), m)?, + None => {} + } + report_layout(path, new.volume().layout(), args.flag("verbose")); + let Some(hash) = hash else { + return Ok(None); + }; + // The device of the volume covers the file system's own bytes, which + // with --minimize can end before --size does. + new.volume_mut().sync()?; + let digest = hash.of(new.volume().device(), &mut |_| {})?; + match hash_path { + Some(p) if p != Path::new("-") => { + let cannot = || format!("cannot write {}", p.display()); + let mut out = new.output(p).with_context(cannot)?; + writeln!(out, "{}", digest).with_context(cannot)?; + Ok(None) + } + _ => Ok(Some(digest)), + } +} + /// The path of the parent directory of `path`, None for one at the root. fn parent_of(path: &str) -> Option<&str> { path.trim_end_matches('/') @@ -1417,7 +1452,7 @@ fn cmd_manifest(argv: &[OsString]) -> Result<()> { Ok(()) } -fn run(argv: &[OsString]) -> Result { +fn run(argv: &[OsString]) -> std::result::Result { let Some(command) = argv.first() else { eprint!("{}", USAGE); return Ok(ExitCode::FAILURE); @@ -1442,11 +1477,11 @@ fn run(argv: &[OsString]) -> Result { "remove" => cmd_remove(rest)?, "list" => cmd_list(rest)?, "describe" => cmd_describe(rest)?, - "check" => return cmd_check(rest), + "check" => return Ok(cmd_check(rest)?), "capabilities" => cmd_capabilities(rest)?, "cat" => cmd_cat(rest)?, "manifest" => cmd_manifest(rest)?, - other => bail!(errno::EINVAL, "unknown command '{}'", other), + other => return Err(err!(errno::EINVAL, "unknown command '{}'", other).into()), } Ok(ExitCode::SUCCESS) } @@ -1464,8 +1499,12 @@ pub(crate) fn main() -> ExitCode { let argv: Vec = std::env::args_os().skip(1).collect(); match run(&argv) { Ok(code) => code, - Err(e) => { - eprintln!("ufat: {}", e); + Err(failure) => { + // What failed, then what that left behind. + eprintln!("ufat: {}", failure.error); + for line in failure.leftovers.lines() { + eprintln!("ufat: {}", line); + } ExitCode::FAILURE } } diff --git a/src/bin/ufat/util.rs b/src/bin/ufat/util.rs index 3934cdc..7791723 100644 --- a/src/bin/ufat/util.rs +++ b/src/bin/ufat/util.rs @@ -12,6 +12,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use fat::device::{Access, Device}; use fat::errno; use fat::format::FormatOptions; +use fat::host::{LinkError, Linked, Naming, NewFile}; use fat::layout::Layout; use fat::manifest::{Order, Reader, RootObject}; use fat::plan::{Estimate, Plan, PlanOptions}; @@ -452,30 +453,44 @@ pub(crate) struct SizeDecision { /// command line makes a volume, and what the Varlink Assemble method does /// in two steps with [`decide_size`] and [`format_sized`]. The image is /// opened once; a block device is planned for its logical block size, a -/// regular image file is grown, never shrunk, to the size, and created -/// first with [`ImageFlags::CREATE`]. What can be found out before the -/// first write is found out while the image is untouched: a size no file -/// system fits in and, when the content is planned, a source tree that -/// cannot be read, a manifest that cannot be planned, and content that -/// does not fit a size given. A file created for the file system is -/// removed again then, so a failed command leaves nothing behind. Without -/// [`ImageFlags::FORCE`], an image that holds a file system, a partition -/// table or other data is not formatted over ([`Prober::ensure_empty`]). +/// regular image file is grown, never shrunk, to the size, and made first +/// with [`ImageFlags::CREATE`]. What can be found out before the first +/// write is found out while the image is untouched: a size no file system +/// fits in and, when the content is planned, a source tree that cannot be +/// read, a manifest that cannot be planned, and content that does not fit +/// a size given. Without [`ImageFlags::FORCE`], an image that holds a file +/// system, a partition table or other data is not formatted over +/// ([`Prober::ensure_empty`]). An image file made for the file system has +/// no name yet, see [`fat::device::Device::create`]. It goes away again +/// when this fails, and is handed over in the [`NewVolume`] otherwise. +/// Errors are the command line's, see [`FitError::into_error`]. pub(crate) fn fit_and_format( target: &Target<'_>, options: &mut FormatOptions, request: SizeRequest<'_>, -) -> std::result::Result<(Volume, Option), FitError> { +) -> std::result::Result<(NewVolume, Option), Failure> { let mut device = open_target(target)?; - let decision = match decide_size(&mut device, target.offset, target.size, options, false, request) { - Ok(decision) => decision, + let created = device.take_created().map(|file| Pending { file }); + match format_fitted(device, target, options, request) { + Ok((volume, estimate)) => Ok((NewVolume::new(volume, created), estimate)), Err(e) => { - // Nothing has been written. The error of the removal, if any, - // is not the one the user needs to hear about. - let _ = device.remove_if_created(); - return Err(e); + let mut leftovers = Leftovers::default(); + if let Some(created) = created { + created.discard(&mut leftovers); + } + Err(Failure::new(e.into_error(target.path), leftovers)) } - }; + } +} + +/// What [`fit_and_format`] does once the image is open. +fn format_fitted( + mut device: Device, + target: &Target<'_>, + options: &mut FormatOptions, + request: SizeRequest<'_>, +) -> std::result::Result<(Volume, Option), FitError> { + let decision = decide_size(&mut device, target.offset, target.size, options, false, request)?; if !target.flags.contains(ImageFlags::FORCE) { Prober::new().ensure_empty(&device, target.offset, Some(decision.size))?; } @@ -483,6 +498,287 @@ pub(crate) fn fit_and_format( Ok((volume, decision.estimate)) } +/// What of the files a command made stays where it gave them up or named +/// them, one line each, which the command line prints after its error, +/// or as warnings after a command that succeeded. +#[derive(Debug, Default)] +pub(crate) struct Leftovers(Vec); + +impl Leftovers { + /// The lines, in the order the files were given up or named. + pub(crate) fn lines(&self) -> impl Iterator { + self.0.iter().map(String::as_str) + } + + fn note(&mut self, line: String) { + self.0.push(line); + } +} + +/// An error a command of the command line failed with, and what of the +/// files it made stays, which the command line prints after the error: +/// what failed, then what that left behind. +#[derive(Debug)] +pub(crate) struct Failure { + pub error: Error, + pub leftovers: Leftovers, +} + +impl Failure { + pub(crate) fn new(error: Error, leftovers: Leftovers) -> Failure { + Failure { error, leftovers } + } +} + +impl From for Failure { + fn from(error: Error) -> Failure { + Failure::new(error, Leftovers::default()) + } +} + +/// A file the command line tool made, which gets its name once the command +/// succeeded. +struct Pending { + file: NewFile, +} + +impl Pending { + /// Gives the file up, noting in `leftovers` what of it stays. + fn discard(self, leftovers: &mut Leftovers) { + if let Some(line) = self.file.give_up() { + leftovers.note(line); + } + } + + /// Gives the file its name, and puts it into `linked` once it has it, + /// also where checking the name failed then. One that does not get it + /// is given up, with what of it stays noted in `leftovers`, and its + /// error gets `context` and the path in front. A temporary name the + /// file was linked from that stays after it got its name goes into + /// `leftovers` too. + fn link(self, context: &str, linked: &mut Vec, leftovers: &mut Leftovers) -> Result<()> { + match self.file.link() { + Ok(named) => { + if let Some(stray) = named.stray() { + leftovers.note(stray.to_string()); + } + linked.push(named); + Ok(()) + } + Err(failed) => Err(Pending::failed(failed, context, linked, leftovers)), + } + } + + /// The error of the link `failed`. A file that did not get its name is + /// given up, with what of it stays noted in `leftovers`, and `context` + /// and its path go in front of the error. A file that has its name goes + /// into `linked`, and its error, which says so, stays as it is. + fn failed(failed: LinkError, context: &str, linked: &mut Vec, leftovers: &mut Leftovers) -> Error { + match failed { + LinkError::Unnamed { error, file } => { + let path = file.path().display().to_string(); + Pending { file }.discard(leftovers); + error.context(format!("{} {}", context, path)) + } + LinkError::Unchecked { error, linked: named } => { + linked.push(named); + error + } + } + } +} + +/// A file system the command line tool made, the image file it made for it +/// with [`ImageFlags::CREATE`] if it made one, and the files it writes next +/// to the image. None of these files gets its name before the command +/// succeeded ([`NewVolume::link`]), so a command that fails, is killed or +/// crashes before leaves nothing under their names, but where the file +/// system leaves the image no other way than the last resort of +/// [`NewFile`]. +/// +/// A new volume that is dropped before [`NewVolume::link`] or +/// [`NewVolume::abandon`], as by an early return, is given up the way +/// abandon() gives it up, without a word: an image made for it goes away +/// with nothing more written to it, and an image that was there is closed +/// as not cleanly unmounted. While a panic unwinds nothing more is written +/// to that one either: it keeps the mark of a file system that was being +/// written, but a panic before the first write leaves the file system as +/// it was formatted, empty and clean. +pub(crate) struct NewVolume { + /// The image file made for the file system. + created: Option, + /// The file system, until it is closed or given up. + volume: Option, + /// The files written next to the image. + outputs: Vec, +} + +impl NewVolume { + fn new(volume: Volume, created: Option) -> NewVolume { + NewVolume { + created, + volume: Some(volume), + outputs: Vec::new(), + } + } + + /// The file system. A new volume holds it until it is closed or given + /// up, which consumes the new volume. + pub(crate) fn volume(&self) -> &Volume { + self.volume.as_ref().expect("a new volume holds its volume") + } + + /// The file system, to fill it. + pub(crate) fn volume_mut(&mut self) -> &mut Volume { + self.volume.as_mut().expect("a new volume holds its volume") + } + + /// A file to write to `path` next to the image, for `--write-manifest` + /// and `--write-hash`. Where nothing or a regular file is there, it is + /// a new file, which gets the name after the image got its own, in + /// place of what is there ([`Naming::Replacing`]), and is given up with + /// the image. What is there and not a regular file, such as a pipe, a + /// device or a symbolic link, is opened for writing as File::create() + /// opens it and written to as the command goes: as with standard + /// output, nothing written there can be taken back. + pub(crate) fn output(&mut self, path: &Path) -> Result { + let regular = match std::fs::symlink_metadata(path) { + Ok(metadata) => metadata.is_file(), + Err(e) if e.kind() == io::ErrorKind::NotFound => true, + Err(e) => return Err(e.into()), + }; + if !regular { + return Ok(File::create(path)?); + } + let pending = Pending { + file: NewFile::create(path, Naming::Replacing)?, + }; + let writer = pending.file.file().try_clone(); + // Kept before anything can fail, so that giving up gives it up. + self.outputs.push(pending); + Ok(writer?) + } + + /// Gives up the file system after the command failed, and returns what + /// of the image or the files next to it stays, where something does, + /// for the command line to print after its error. An image file made + /// for the file system goes away with nothing more written to it, and + /// so do the files next to it. Any other image keeps what was written, + /// closed as not cleanly unmounted, as after a crash, so that nobody + /// takes it for a finished file system. An error of that close is not + /// the one the user needs to hear about. + pub(crate) fn abandon(mut self) -> Leftovers { + self.give_up_volume(); + let mut leftovers = Leftovers::default(); + let created = self.created.take(); + for pending in created.into_iter().chain(std::mem::take(&mut self.outputs)) { + pending.discard(&mut leftovers); + } + leftovers + } + + /// Closes the finished file system and gives the image file made for it + /// its name, and then the files written next to it theirs, each synced + /// before (the image by the close). The image takes no name that + /// something else took while it was made (EEXIST), and the files next + /// to it replace what has their names. Once all of them have their + /// names, each directory they are in is synced once, so that the names + /// last too. Where closing the file system or naming its image file + /// fails, these files go away as after any other failure. A file next + /// to the image that cannot get its own name goes away with the ones + /// after it, and the image keeps its name. A file that has its name + /// keeps it, also where checking it or syncing its directory fails, + /// and the error says so. Its directory is synced also where something + /// fails after it got its name. Returns what stays besides, such as a + /// temporary name that could not be removed, for the command line to + /// warn about. A failure carries that as well. + pub(crate) fn link(mut self) -> std::result::Result { + let mut leftovers = Leftovers::default(); + match self.link_all(&mut leftovers) { + Ok(()) => Ok(leftovers), + Err(e) => Err(Failure::new(e, leftovers)), + } + } + + /// What [`NewVolume::link`] does, noting in `leftovers` what stays. The + /// directories of the files that got their names are synced also where + /// something failed after, since those files keep their names. A sync + /// that fails then goes into `leftovers`, after what came before. + fn link_all(&mut self, leftovers: &mut Leftovers) -> Result<()> { + let mut linked = Vec::new(); + let named = self.give_names(&mut linked, leftovers); + let synced = Linked::sync_directories(&linked); + match (named, synced) { + (Err(e), Err(unsynced)) => { + leftovers.note(unsynced.to_string()); + Err(e) + } + (named, synced) => named.and(synced), + } + } + + /// Closes the file system and gives the image file made for it and the + /// files next to it their names, as [`NewVolume::link`] says. Each file + /// that got its name goes into `linked`. + fn give_names(&mut self, linked: &mut Vec, leftovers: &mut Leftovers) -> Result<()> { + let mut outputs = std::mem::take(&mut self.outputs).into_iter(); + let closed = self.volume.take().map_or(Ok(()), Volume::close); + let created = self.created.take(); + if let Err(e) = closed { + for pending in created.into_iter().chain(outputs) { + pending.discard(leftovers); + } + return Err(e); + } + if let Some(created) = created { + // The image's file is given up already where this fails, or it + // keeps its name. + if let Err(e) = created.link("failed to create", linked, leftovers) { + outputs.for_each(|pending| pending.discard(leftovers)); + return Err(e); + } + } + while let Some(pending) = outputs.next() { + let named = match pending.file.file().sync_all() { + Ok(()) => pending.link("cannot write", linked, leftovers), + Err(e) => { + let e = Error::from(e).context(format!("cannot write {}", pending.file.path().display())); + pending.discard(leftovers); + Err(e) + } + }; + if let Err(e) = named { + outputs.by_ref().for_each(|pending| pending.discard(leftovers)); + return Err(e); + } + } + Ok(()) + } + + /// Gives up the file system, if it is still held, without a word: with + /// nothing more written to an image made for it or while a panic + /// unwinds, and closed as not cleanly unmounted otherwise. + fn give_up_volume(&mut self) { + let Some(volume) = self.volume.take() else { + return; + }; + if self.created.is_some() || std::thread::panicking() { + volume.abandon(); + } else { + let _ = volume.close_unfinished(); + } + } +} + +impl Drop for NewVolume { + fn drop(&mut self) { + // Only an early return or a panic comes here with the volume. The + // image file and the files next to it give themselves up when they + // are dropped right after. + self.give_up_volume(); + } +} + /// Decides the size of a new file system the way `request` says. Nothing /// is written; the image is only asked for its type, block size and /// length. `device` covers the whole image, a descriptor the service was @@ -587,3 +883,302 @@ pub(crate) fn format_sized(mut device: Device, offset: u64, size: u64, options: let device = device.window(offset, Some(size))?; Volume::create(device, options) } + +#[cfg(test)] +mod tests { + use super::*; + use fat::fsck::{self, ProblemKind}; + use std::ffi::CString; + use std::os::fd::AsRawFd; + use std::os::unix::ffi::OsStrExt; + use std::path::PathBuf; + + /// The size of the test images: room for the 65525 clusters of the + /// smallest FAT32 file system with 512 byte clusters. + const IMAGE_SIZE: u64 = 40 << 20; + + /// A directory below TMPDIR, removed with what is in it when dropped. + struct TempDir(PathBuf); + + impl TempDir { + fn new(name: &str) -> TempDir { + let dir = std::env::temp_dir().join(format!("ufat-{}-{}", name, std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// Whether the file system in the image `path` is marked as not cleanly + /// unmounted. + fn marked_dirty(path: &Path) -> bool { + let report = fsck::check(&Device::open(path, Access::ReadOnly).unwrap()).unwrap(); + report + .problems + .iter() + .any(|problem| problem.kind == ProblemKind::DirtyFlag) + } + + /// A new volume, as fit_and_format() makes it: not being written yet. + fn formatted(target: &Target<'_>) -> NewVolume { + fit_and_format(target, &mut FormatOptions::default(), SizeRequest::Given) + .unwrap() + .0 + } + + /// A new volume with a directory written into it: being written, with + /// the marks of that on the image. + fn written(target: &Target<'_>) -> NewVolume { + let mut new = formatted(target); + new.volume_mut().create_dir("/d", now()).unwrap(); + new + } + + /// Gives the file `file`, whatever its names, the name `to` as well, + /// through its magic link in /proc/self/fd. + fn hard_link(file: &File, to: &Path) { + let from = CString::new(format!("/proc/self/fd/{}", file.as_raw_fd())).unwrap(); + let to = CString::new(to.as_os_str().as_bytes()).unwrap(); + // SAFETY: NUL terminated paths and plain flags. + let linked = unsafe { + libc::linkat( + libc::AT_FDCWD, + from.as_ptr(), + libc::AT_FDCWD, + to.as_ptr(), + libc::AT_SYMLINK_FOLLOW, + ) + }; + assert_eq!(linked, 0, "{}", io::Error::last_os_error()); + } + + /// A new volume over an image that was there, dropped without link() or + /// abandon(), as an early return drops it, leaves the file system marked + /// as not cleanly unmounted. One that is linked leaves it clean. + #[test] + fn a_dropped_new_volume_leaves_its_image_marked() { + let dir = TempDir::new("dropped"); + let path = dir.0.join("a.img"); + File::create(&path).unwrap().set_len(IMAGE_SIZE).unwrap(); + let target = Target { + path: &path, + offset: 0, + size: None, + flags: ImageFlags::FORCE, + }; + let leftovers = written(&target).link().unwrap(); + assert_eq!(leftovers.lines().count(), 0); + assert!(!marked_dirty(&path)); + drop(written(&target)); + assert!(marked_dirty(&path)); + } + + /// Giving up an image made for a new volume writes nothing more to it: + /// not the marks a volume that is not being written would get from a + /// close as unfinished, and not the clean marks a close would put back + /// on one that is. A name the image got meanwhile, through its + /// descriptor, keeps the bytes it had. + #[test] + fn abandon_writes_nothing() { + let dir = TempDir::new("abandoned"); + let path = dir.0.join("a.img"); + let kept = dir.0.join("kept.img"); + let target = Target { + path: &path, + offset: 0, + size: Some(IMAGE_SIZE), + flags: ImageFlags::CREATE, + }; + for new in [formatted(&target), written(&target)] { + hard_link(new.created.as_ref().unwrap().file.file(), &kept); + let before = std::fs::read(&kept).unwrap(); + let leftovers = new.abandon(); + assert_eq!(leftovers.lines().count(), 0); + assert!(!path.exists()); + assert!(std::fs::read(&kept).unwrap() == before, "abandon() wrote to the image"); + std::fs::remove_file(&kept).unwrap(); + } + } + + /// A new volume over an image that was there, dropped while a panic + /// unwinds, writes nothing more to it either, not even the marks of a + /// close as unfinished: what the volume holds in memory is not to be + /// trusted then. + #[test] + fn a_new_volume_dropped_by_a_panic_writes_nothing() { + let dir = TempDir::new("panicked"); + let path = dir.0.join("a.img"); + File::create(&path).unwrap().set_len(IMAGE_SIZE).unwrap(); + let target = Target { + path: &path, + offset: 0, + size: None, + flags: ImageFlags::FORCE, + }; + let mut before = Vec::new(); + let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let new = formatted(&target); + before = std::fs::read(&path).unwrap(); + let _held = new; + panic!("unwinding with a new volume"); + })); + assert!(unwound.is_err()); + assert!(std::fs::read(&path).unwrap() == before, "a panic wrote to the image"); + assert!(!marked_dirty(&path)); + } + + /// A link that fails gives a file that did not get its name up, and its + /// error says what was being made. A file that got its name and only + /// the check after failed goes with the others that have their names, + /// to sync its directory, and its error says that it has its name, with + /// nothing in front of it. + #[test] + fn a_failed_link_says_whether_the_file_has_its_name() { + let dir = TempDir::new("unlinked"); + let path = dir.0.join("a.img"); + let new = || NewFile::create(&path, Naming::Exclusive).unwrap(); + let (mut linked, mut leftovers) = (Vec::new(), Leftovers::default()); + let unnamed = LinkError::Unnamed { + error: err!(errno::EIO, "why"), + file: new(), + }; + let e = Pending::failed(unnamed, "failed to create", &mut linked, &mut leftovers); + assert_eq!(e.to_string(), format!("failed to create {}: why", path.display())); + assert!(linked.is_empty()); + let unchecked = LinkError::Unchecked { + error: err!(errno::EIO, "why"), + linked: new().link().unwrap(), + }; + let e = Pending::failed(unchecked, "failed to create", &mut linked, &mut leftovers); + assert_eq!(e.to_string(), "why"); + assert_eq!(linked.len(), 1); + assert_eq!(leftovers.lines().count(), 0); + } + + /// Makes the system call `call` fail with `errno` in the calling thread + /// from here on, with a seccomp filter of the thread's own: every call, + /// or with `flags` only one whose third argument, the flags of + /// openat(2), has one of those bits set. Returns false where seccomp + /// filters cannot be had: on an architecture this does not know, or + /// under qemu-user, which refuses them. + fn refuse_in_this_thread(call: libc::c_long, errno: i32, flags: Option) -> bool { + // The flags of include/uapi/linux/audit.h that make the AUDIT_ARCH a + // filter compares with of a machine of elf.h. + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + const AUDIT_ARCH_64BIT: u32 = 0x8000_0000; + #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))] + const AUDIT_ARCH_LE: u32 = 0x4000_0000; + #[cfg(target_arch = "x86_64")] + const ARCH: Option = Some(libc::EM_X86_64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); + #[cfg(target_arch = "x86")] + const ARCH: Option = Some(libc::EM_386 as u32 | AUDIT_ARCH_LE); + #[cfg(target_arch = "aarch64")] + const ARCH: Option = Some(libc::EM_AARCH64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); + #[cfg(not(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")))] + const ARCH: Option = None; + let Some(arch) = ARCH else { + return false; + }; + let statement = |code: u32, k: u32, jt: u8, jf: u8| libc::sock_filter { + code: code as u16, + jt, + jf, + k, + }; + let load = libc::BPF_LD | libc::BPF_W | libc::BPF_ABS; + let equal = libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K; + let any_of = libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K; + let onward = libc::BPF_JMP | libc::BPF_JA; + let give = libc::BPF_RET | libc::BPF_K; + // Each of these architectures is little endian, so the low 32 bits + // of the third argument come first. + let third = std::mem::offset_of!(libc::seccomp_data, args) + 2 * size_of::(); + // Without flags the call is refused whatever its third argument is. + let refused = match flags { + Some(bits) => statement(any_of, bits as u32, 0, 1), + None => statement(onward, 0, 0, 0), + }; + // Another architecture, another call or flags without those bits + // jump to the last statement, which allows the call. + let filter = [ + statement(load, std::mem::offset_of!(libc::seccomp_data, arch) as u32, 0, 0), + statement(equal, arch, 0, 5), + statement(load, std::mem::offset_of!(libc::seccomp_data, nr) as u32, 0, 0), + statement(equal, call as u32, 0, 3), + statement(load, third as u32, 0, 0), + refused, + statement(give, libc::SECCOMP_RET_ERRNO | errno as u32, 0, 0), + statement(give, libc::SECCOMP_RET_ALLOW, 0, 0), + ]; + let program = libc::sock_fprog { + len: filter.len() as u16, + filter: filter.as_ptr().cast_mut(), + }; + let (on, unused): (libc::c_ulong, libc::c_ulong) = (1, 0); + let mode = libc::SECCOMP_MODE_FILTER as libc::c_ulong; + // SAFETY: prctl() takes plain values and a filter, which it copies + // before it returns. + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, on, unused, unused, unused) == 0 + && libc::prctl(libc::PR_SET_SECCOMP, mode, std::ptr::from_ref(&program)) == 0 + } + } + + /// Where a file written next to the image cannot get its name after the + /// image got its own, the image keeps its name, and its directory is + /// synced all the same, so that a crash does not take the name of an + /// image that the command said it kept. Filters of the test's own thread + /// refuse the rename that the file next to the image gets its name by, + /// and the opening of a directory, which the sync of the image's + /// directory starts with, so that the sync fails and says so. Nothing + /// else the link does opens a directory. + #[test] + fn a_failure_after_the_image_got_its_name_syncs_its_directory() { + // What a rename that may replace is: renameat() where there is one, + // renameat2() without flags elsewhere. + #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] + const RENAME: libc::c_long = libc::SYS_renameat; + #[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))] + const RENAME: libc::c_long = libc::SYS_renameat2; + let dir = TempDir::new("named"); + let (path, written) = (dir.0.join("a.img"), dir.0.join("a.manifest")); + std::fs::write(&written, b"old\n").unwrap(); + let image = Pending { + file: NewFile::create(&path, Naming::Exclusive).unwrap(), + }; + let output = Pending { + file: NewFile::create(&written, Naming::Replacing).unwrap(), + }; + let new = NewVolume { + created: Some(image), + volume: None, + outputs: vec![output], + }; + let linked = std::thread::spawn(move || { + let refused = refuse_in_this_thread(RENAME, libc::EIO, None) + && refuse_in_this_thread(libc::SYS_openat, libc::EIO, Some(libc::O_DIRECTORY)); + refused.then(|| new.link()) + }) + .join() + .unwrap(); + let Some(linked) = linked else { + return eprintln!("skipping: no seccomp filters here"); + }; + let failure = linked.unwrap_err(); + let failed = format!("cannot write {}: ", written.display()); + assert!(failure.error.message().starts_with(&failed), "{}", failure.error); + let unsynced = format!( + "{} is complete and has its name, but syncing its directory failed: ", + path.display() + ); + let lines: Vec<&str> = failure.leftovers.lines().collect(); + assert!(lines.len() == 1 && lines[0].starts_with(&unsynced), "{:?}", lines); + assert!(path.exists()); + assert_eq!(std::fs::read(&written).unwrap(), b"old\n"); + } +} diff --git a/src/fat/device.rs b/src/fat/device.rs index 93c30c9..5b323df 100644 --- a/src/fat/device.rs +++ b/src/fat/device.rs @@ -13,10 +13,11 @@ use std::fs::File; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; use std::os::unix::ffi::OsStrExt; -use std::os::unix::fs::{FileExt, FileTypeExt, MetadataExt}; +use std::os::unix::fs::{FileExt, FileTypeExt}; use std::path::Path; use crate::errno::*; +use crate::host::{Naming, NewFile}; use crate::sys; use crate::{Context, Error, Result}; @@ -46,10 +47,10 @@ pub struct Device { offset: u64, len: u64, block_device: bool, - /// The directory and the name of a file [`Device::create`] made, kept - /// so that [`Device::remove_if_created`] can take it away again while - /// nothing has been written to it. - created_in: Option<(OwnedFd, Vec)>, + /// The file [`Device::create`] made, until [`Device::take_created`] + /// hands it over to get its name. A device that keeps it gives it up + /// when it is dropped. + created: Option, /// How often the data was synced, for the tests of the write order. #[cfg(test)] pub(crate) syncs: std::sync::Arc, @@ -82,42 +83,57 @@ impl Device { Device::open_pinned(pinned.as_fd(), &path.display(), access) } - /// Creates the regular file `path` for a new image, open for writing, - /// or opens the regular file or block device of that name when one - /// exists already, the way systemd's openat_report_new() does: the - /// parent directory is looked up once, the file is created relative to - /// it with O_CREAT|O_EXCL|O_NOFOLLOW so that nothing is ever created - /// through a symbolic link, and an existing file is opened like - /// [`Device::open`] does (a dangling symbolic link in its place is - /// ELOOP). + /// Makes a new regular file for an image that is to be named `path`, + /// open for writing, or opens the regular file or block device of that + /// name when one exists, the way [`Device::open`] does. The parent + /// directory is looked up once, and the name is looked up in it. A + /// dangling symbolic link in its place is ELOOP, so that nothing is ever + /// created through one. A new file is made as a [`NewFile`] that does + /// not take the place of another file: it has no name, or a temporary + /// one, and gets `path` only from [`NewFile::link`] once the image is + /// complete, after [`Device::take_created`] handed it over. Until then + /// nothing is under that name, so a command that fails, is killed or + /// crashes leaves nothing there, and a file that takes the name + /// meanwhile is never replaced. A file system that can neither rename + /// without replacing nor make hard links gets the file under `path` + /// right away, the last resort of [`NewFile`]. pub fn create(path: &Path) -> Result { let failed = || format!("failed to create {}", path.display()); let (parent, name) = crate::host::open_parent(path).with_context(failed)?; - let name = name.as_bytes(); - let created = sys::create_file_at(parent.as_fd(), name, 0o666); - match created { - Ok(file) => { - let mut device = Device::lock_and_wrap(file, &path.display(), Access::ReadWrite)?; - device.created_in = Some((parent, name.to_vec())); + let pinned = match sys::pin_name(parent.as_fd(), name.as_bytes(), false) { + Ok(pinned) => Some(pinned), + // Nothing of that name, or a dangling symbolic link, which + // following it reports as missing too. + Err(e) if e.raw_os_error() == Some(ENOENT) => match sys::pin_entry(parent.as_fd(), name.as_bytes()) { + Ok(entry) if sys::fstat(entry.as_fd())?.file_type().is_symlink() => { + bail!(ELOOP, "{} is a dangling symbolic link", path.display()) + } + // There since the lookup before. + Ok(entry) => Some(entry), + Err(e) if e.raw_os_error() == Some(ENOENT) => None, + Err(e) => return Err(e).with_context(failed), + }, + Err(e) => return Err(e).with_context(failed), + }; + if let Some(pinned) = pinned { + return Device::open_pinned(pinned.as_fd(), &path.display(), Access::ReadWrite); + } + let new = NewFile::create_in(parent, name, path, Naming::Exclusive).with_context(failed)?; + // A descriptor of its own for the device. It shares the open file + // description with the new file's, and so the lock the new file took + // and the device takes again, which stays as long as the new file is + // held. + let device = new + .file() + .try_clone() + .map_err(Error::from) + .and_then(|file| Device::lock_and_wrap(file, &path.display(), Access::ReadWrite)); + match device { + Ok(mut device) => { + device.created = Some(new); Ok(device) } - Err(e) if e.raw_os_error() == Some(EEXIST) => { - let pinned = match sys::pin_name(parent.as_fd(), name, false) { - Ok(p) => p, - Err(e) if e.raw_os_error() == Some(ENOENT) => { - // Gone again, or a dangling symbolic link, which - // O_NOFOLLOW would have reported as ELOOP. - let entry = sys::pin_entry(parent.as_fd(), name).with_context(failed)?; - if sys::fstat(entry.as_fd())?.file_type().is_symlink() { - bail!(ELOOP, "{} is a dangling symbolic link", path.display()); - } - return Err(e).with_context(failed); - } - Err(e) => return Err(e).with_context(failed), - }; - Device::open_pinned(pinned.as_fd(), &path.display(), Access::ReadWrite) - } - Err(e) => Err(e).with_context(failed), + Err(e) => Err(new.given_up(e.context(failed()))), } } @@ -184,7 +200,7 @@ impl Device { offset: 0, len, block_device, - created_in: None, + created: None, #[cfg(test)] syncs: Default::default(), #[cfg(ufat_trace)] @@ -277,31 +293,11 @@ impl Device { Ok(()) } - /// Removes the file [`Device::create`] made, if this device is one, and - /// closes it. A caller that learns before the first write that it has - /// no use for the image after all, because the content does not fit the - /// size it was given or a source cannot be read, takes back what it - /// created so that a failed command leaves nothing behind. The name is - /// looked up in the directory the file was created in and unlinked only - /// while it still refers to this file; something else of that name is - /// left alone. Returns whether a file was removed. - pub fn remove_if_created(self) -> Result { - let Some((parent, name)) = &self.created_in else { - return Ok(false); - }; - let ours = sys::fstat(self.file.as_fd())?; - let entry = match sys::pin_entry(parent.as_fd(), name) { - Ok(entry) => entry, - Err(e) if e.raw_os_error() == Some(ENOENT) => return Ok(false), - Err(e) => return Err(e.into()), - }; - let there = sys::fstat(entry.as_fd())?; - if (there.dev(), there.ino()) != (ours.dev(), ours.ino()) { - return Ok(false); - } - sys::unlink_at(parent.as_fd(), name) - .with_context(|| "failed to remove the image created for the file system")?; - Ok(true) + /// Hands over the new file [`Device::create`] made, if it made one: to + /// get its name once the image is complete, or to be given up without + /// it. The device goes on working with the file either way. + pub fn take_created(&mut self) -> Option { + self.created.take() } /// Length of the window in bytes. @@ -490,10 +486,23 @@ impl Device { #[cfg(test)] mod tests { use super::*; + use crate::host::{LinkError, Linked, Removal}; use crate::test_util::{TempDir, TempImage}; + use std::os::fd::AsRawFd; use std::os::unix::fs::symlink; + use std::path::PathBuf; use std::time::{Duration, Instant}; + /// The names in the directory `dir`, sorted. + fn names_in(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } + #[test] fn locks_keep_writers_apart() { let img = TempImage::new(4096); @@ -545,26 +554,37 @@ mod tests { ); } - /// Creating an image makes a new file, opens an existing one as it is - /// and never goes through a symbolic link to create something. + /// Creating an image makes a new file, which gets its name when it is + /// linked, opens an existing one as it is and never goes through a + /// symbolic link to create something. #[test] fn create_makes_or_opens_a_file() { let tmp = TempDir::new("create"); let dir = tmp.path(); - let mut dev = Device::create(&dir.join("new.img")).unwrap(); + let path = dir.join("new.img"); + let mut dev = Device::create(&path).unwrap(); assert_eq!(dev.len(), 0); dev.grow(8192).unwrap(); assert_eq!(dev.len(), 8192); dev.write_at(0, b"kept").unwrap(); + assert!(!path.exists()); + Linked::sync_directories(&[dev.take_created().unwrap().link().unwrap()]).unwrap(); + assert!(dev.take_created().is_none()); + // The device goes on with the file it named, and keeps its lock. + dev.write_at(4, b"more").unwrap(); + assert_eq!(Device::open(&path, Access::ReadOnly).unwrap_err().errno(), EBUSY); drop(dev); - // Existing: opened, not truncated, not grown when large enough. - let mut dev = Device::create(&dir.join("new.img")).unwrap(); + assert_eq!(names_in(dir), ["new.img"]); + // Existing: opened, not truncated, not grown when large enough, and + // nothing new to hand over. + let mut dev = Device::create(&path).unwrap(); + assert!(dev.take_created().is_none()); assert_eq!(dev.len(), 8192); dev.grow(4096).unwrap(); assert_eq!(dev.len(), 8192); - let mut back = [0u8; 4]; + let mut back = [0u8; 8]; dev.read_at(0, &mut back).unwrap(); - assert_eq!(&back, b"kept"); + assert_eq!(&back, b"keptmore"); drop(dev); // Through a link to an existing file: fine. A dangling link: ELOOP, // and nothing is created where it points. @@ -586,6 +606,50 @@ mod tests { assert_eq!(dev.grow(1 << 20).unwrap_err().errno(), EINVAL); } + /// A new image that does not get its name leaves nothing behind, + /// whatever was written to it, whether the device keeps the new file or + /// hands it over. The lock of the device stays while the new file is + /// held, after the device is gone as well. + #[test] + fn a_new_image_without_its_name_leaves_nothing() { + let tmp = TempDir::new("unnamed"); + let dir = tmp.path(); + let path = dir.join("a.img"); + let mut dev = Device::create(&path).unwrap(); + dev.grow(4096).unwrap(); + dev.write_at(0, b"half").unwrap(); + drop(dev); + assert!(names_in(dir).is_empty()); + let mut dev = Device::create(&path).unwrap(); + dev.grow(4096).unwrap(); + let created = dev.take_created().unwrap(); + drop(dev); + let file = PathBuf::from(format!("/proc/self/fd/{}", created.file().as_raw_fd())); + assert_eq!(Device::open(&file, Access::ReadOnly).unwrap_err().errno(), EBUSY); + assert_eq!(created.discard().unwrap(), Removal::Removed); + assert!(names_in(dir).is_empty()); + } + + /// A name that something else took while the image was made is left + /// as it is: the image does not get it (EEXIST). + #[test] + fn a_name_taken_meanwhile_stays_as_it_is() { + let tmp = TempDir::new("taken"); + let dir = tmp.path(); + let path = dir.join("a.img"); + let mut dev = Device::create(&path).unwrap(); + dev.grow(4096).unwrap(); + std::fs::write(&path, b"theirs").unwrap(); + let LinkError::Unnamed { error, file } = dev.take_created().unwrap().link().unwrap_err() else { + panic!("the image got the name"); + }; + assert_eq!(error.errno(), EEXIST); + drop(dev); + assert_eq!(file.discard().unwrap(), Removal::Removed); + assert_eq!(std::fs::read(&path).unwrap(), b"theirs"); + assert_eq!(names_in(dir), ["a.img"]); + } + #[test] fn zero_makes_a_range_read_as_zeros() { let img = TempImage::new(0); diff --git a/src/fat/host.rs b/src/fat/host.rs index c495075..accd90a 100644 --- a/src/fat/host.rs +++ b/src/fat/host.rs @@ -22,14 +22,14 @@ use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; -use std::os::unix::ffi::OsStrExt; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::os::unix::fs::{FileTypeExt, MetadataExt}; use std::path::{Path, PathBuf}; use crate::device::{Access, Device}; use crate::errno::*; -use crate::sys; -use crate::{Context, Result}; +use crate::sys::{self, Refusal}; +use crate::{Context, Error, Result}; use crate::{DescriptorProblem, Detail}; /// The detail of a passed descriptor that cannot be used, passed as @@ -412,6 +412,679 @@ fn open_pinned_file(pinned: BorrowedFd<'_>, what: &dyn std::fmt::Display) -> Res Ok(File::from(fd)) } +/// The mode a new file is made with before the umask takes its part: read +/// and write for everyone, as std's File::create() and the shell make one. +const NEW_FILE_MODE: u32 = 0o666; + +/// A regular file made for a name in a directory, which it gets only once +/// it is complete, so that a command that fails, is killed or crashes +/// before leaves nothing under that name. It is made with O_TMPFILE, without +/// any name, and goes away with its last descriptor until +/// [`NewFile::link`] gives it its name. Where O_TMPFILE is refused, by a +/// file system without it or a kernel that does not know it, it is made +/// under a temporary name in the same directory instead, and the link +/// renames it then. A kill or a crash leaves that temporary name behind. +/// +/// A file that must not take the place of another one, [`Naming::Exclusive`], +/// is locked with the exclusive BSD lock an image is written under as soon +/// as it is made. If it has a temporary name, it finds out how it gets its +/// name before anything is written to it: with RENAME_NOREPLACE, or else +/// with a link of its descriptor. Where the file system has neither, as +/// vboxsf and orangefs have neither, the file is made under its name right +/// away with O_CREAT|O_EXCL as the last resort, and a kill or a crash +/// leaves it there. +/// +/// Giving a file up removes a temporary name, or the name of the last +/// resort, after checking by device and inode number that the name still +/// refers to the file. A rename onto the name between that check and the +/// removal gets the other file removed, since no unlink is conditional on +/// the inode. That crosses no privilege boundary: whoever can rename onto a +/// name in that directory can remove it as well. An exclusive file has its +/// names removed only while it is locked, by this process, or where the +/// lock cannot be had at all right after the file was made, as NFS without +/// its lock manager refuses it. A file another process locked first keeps +/// its name. Dropping a file that did not get its name gives it up the way +/// [`NewFile::discard`] does, without saying how that went. +#[derive(Debug)] +pub struct NewFile { + /// The file, open for reading and writing. + file: File, + /// The directory it is made in. + parent: OwnedFd, + /// The name it is made for. + name: OsString, + /// That name as the caller named it, for messages. + path: PathBuf, + /// What it does where something has that name when it gets it. + naming: Naming, + /// How it waits for that name, which it removes when it is given up. + /// None once it has that name, or where removing it is not up to it. + waiting: Option, +} + +/// What a [`NewFile`] does where something has its name by the time the +/// file gets that name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Naming { + /// It does not get the name (EEXIST): a new image, which must not take + /// the place of a file that came meanwhile. + Exclusive, + /// It takes the place of what has the name, as a file a command writes + /// anew does. Other hard links to a file that is replaced keep what it + /// held. + Replacing, +} + +/// How a [`NewFile`] waits for its name. +#[derive(Debug)] +enum Waiting { + /// Without any name: made with O_TMPFILE. + Unnamed, + /// Under a temporary name in the same directory. + Temporary(TemporaryName), + /// Under its own name already, made with O_CREAT|O_EXCL as the last + /// resort, see [`NewFile`]. + Claimed, +} + +/// What has a name in the directory of a [`NewFile`], told apart by device +/// and inode number. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Holder { + /// The file itself. + Itself, + /// Another file. + Another, + /// Nothing: the name does not exist. + Nothing, +} + +/// A temporary name in the directory of a [`NewFile`]: `.#`, the name it +/// stands in for and 16 random hex digits, as systemd's tempfn_random() +/// makes one. The name is cut short where the whole would be longer than a +/// file name can be. +#[derive(Clone, Debug, PartialEq, Eq)] +struct TemporaryName(OsString); + +impl TemporaryName { + /// What a temporary name starts with: the dot hides it from ls, as + /// systemd's do. + const PREFIX: &'static str = ".#"; + /// The random hex digits it ends with: two for each byte of the 64 bits + /// tempfn_random() takes. + const DIGITS: usize = 2 * size_of::(); + + /// A new temporary name for `name`. + fn new(name: &OsStr) -> io::Result { + let mut random = [0u8; size_of::()]; + sys::random_bytes(&mut random)?; + let name = name.as_bytes(); + let room = sys::NAME_MAX - TemporaryName::PREFIX.len() - TemporaryName::DIGITS; + let mut temporary = Vec::with_capacity(sys::NAME_MAX); + temporary.extend_from_slice(TemporaryName::PREFIX.as_bytes()); + temporary.extend_from_slice(&name[..name.len().min(room)]); + let digits = format!("{:0width$x}", u64::from_ne_bytes(random), width = TemporaryName::DIGITS); + temporary.extend_from_slice(digits.as_bytes()); + Ok(TemporaryName(OsString::from_vec(temporary))) + } + + /// The name. + fn as_os_str(&self) -> &OsStr { + &self.0 + } + + fn as_bytes(&self) -> &[u8] { + self.0.as_bytes() + } +} + +/// What [`NewFile::discard`] did with the name of a file it gave up. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Removal { + /// The file waits under no name any more: it had none and goes away + /// with its last descriptor, the name it waited under was removed, or + /// it has its own name already, which stays. + Removed, + /// The name it had was gone already: someone else removed or renamed + /// it. + AlreadyGone, + /// The name it had refers to another file now, which is left alone. + NameTaken, +} + +/// Why [`NewFile::link`] failed, and what became of the file. +#[derive(Debug)] +pub enum LinkError { + /// The file does not have its name: EEXIST where something has the name + /// or took the temporary name meanwhile, ENOENT where the name is gone + /// again. The file comes back to be given up with [`NewFile::discard`] + /// or [`NewFile::give_up`], which removes a temporary name it still + /// waits under. + Unnamed { + /// Why. + error: Error, + /// The file. + file: NewFile, + }, + /// The file got its name, but checking by device and inode number that + /// the name refers to it failed, as for want of descriptors or memory, + /// and the error says so. Nothing undoes the name. A temporary name the + /// file was linked from stays as well, since it can be the one name the + /// file has, and the error names it. + Unchecked { + /// Why. + error: Error, + /// The file with its name, to sync its directory with + /// [`Linked::sync_directories`]. + linked: Linked, + }, +} + +/// A [`NewFile`] that got its name. +#[derive(Debug)] +#[must_use] +pub struct Linked { + /// The directory it got its name in, pinned to sync it. + directory: OwnedFd, + /// The name as the caller named it, for messages. + path: PathBuf, + /// A temporary name the file was linked from that stays. + stray: Option, +} + +/// A temporary name a [`NewFile`] was linked from, not renamed from, that +/// stays after the file got its name, as where the file system refuses +/// RENAME_NOREPLACE. Its display is a line that says so. +#[derive(Debug)] +pub enum Stray { + /// It refers to another file now, which is left alone: the path of the + /// temporary name. + Taken(PathBuf), + /// Removing it failed: the error says that it stays, and why. + Kept(Error), +} + +impl std::fmt::Display for Stray { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Stray::Taken(path) => write!(f, "{} refers to another file now, which is left alone", path.display()), + Stray::Kept(error) => write!(f, "{}", error), + } + } +} + +impl Linked { + /// Makes the names of `linked` last: syncs each directory they got + /// their names in, once. Without it a power cut can lose a name although + /// the data of its file was synced, which is why systemd's + /// link_tmpfile_at() syncs it with LINK_TMPFILE_SYNC. A file system + /// without an fsync for directories, as vboxsf, orangefs, AFS and 9p + /// without 9P2000.L have none, refuses it with EINVAL + /// (vfs_fsync_range()), and a directory that cannot be read, as one of + /// mode 0300, cannot be opened to sync it (EACCES). Both are left as + /// they are. A sync that fails otherwise fails this, and the error says + /// that the first file of `linked` in that directory is complete and + /// has its name. + pub fn sync_directories(linked: &[Linked]) -> Result<()> { + let mut directories = linked + .iter() + .map(|linked| Ok((linked.directory_id()?, linked))) + .collect::>>()?; + // A stable sort keeps the first file of each directory first. + directories.sort_by_key(|(id, _)| *id); + directories.dedup_by_key(|(id, _)| *id); + directories + .into_iter() + .try_for_each(|(_, linked)| linked.sync_directory()) + } + + /// The temporary name the file was linked from where it stays. + pub fn stray(&self) -> Option<&Stray> { + self.stray.as_ref() + } + + /// The device and inode number of the directory. + fn directory_id(&self) -> Result<(u64, u64)> { + let metadata = sys::fstat(self.directory.as_fd()).with_context(|| self.unsynced())?; + Ok((metadata.dev(), metadata.ino())) + } + + /// Syncs the directory, where the file system and the permissions of + /// the directory let it be synced, see [`Linked::sync_directories`]. + fn sync_directory(&self) -> Result<()> { + let synced = match sys::reopen(self.directory.as_fd(), sys::O_RDONLY | sys::O_DIRECTORY) { + Ok(directory) => match File::from(directory).sync_all() { + Err(e) if e.refuses_syncing_directories() => Ok(()), + synced => synced, + }, + Err(e) if e.refuses_reading() => Ok(()), + Err(e) => Err(e), + }; + synced.with_context(|| self.unsynced()) + } + + /// What an error of [`Linked::sync_directories`] says first. + fn unsynced(&self) -> String { + format!( + "{} is complete and has its name, but syncing its directory failed", + self.path.display() + ) + } +} + +impl NewFile { + /// Makes a regular file for `path`, open for reading and writing, to + /// get that name as `naming` says. Only the directory of `path` is + /// looked up, once, as [`open_parent`] does it. What is there under the + /// name is left alone until the file gets that name, but for the last + /// resort of [`Naming::Exclusive`], see [`NewFile`]. + pub fn create(path: &Path, naming: Naming) -> Result { + let (parent, name) = open_parent(path)?; + NewFile::create_in(parent, name, path, naming) + } + + /// Makes a regular file in the directory `parent` for the name `name`, + /// to get it as `naming` says. `path` is that name as the caller named + /// it, for messages. Where something fails after the file was made, the + /// file is given up, and the error says what of it stays. + pub(crate) fn create_in(parent: OwnedFd, name: OsString, path: &Path, naming: Naming) -> Result { + let mut new = match sys::create_unnamed_file(parent.as_fd(), NEW_FILE_MODE) { + Ok(file) => NewFile { + file, + parent, + name, + path: path.to_path_buf(), + naming, + waiting: Some(Waiting::Unnamed), + }, + Err(e) if e.refuses_unnamed_files() => NewFile::create_named_in(parent, name, path, naming)?, + Err(e) => return Err(e.into()), + }; + match naming { + Naming::Exclusive => match new.lock().and_then(|()| new.probe_exclusive_naming()) { + Ok(()) => Ok(new), + Err(e) => Err(new.given_up(e)), + }, + // A plain rename replaces on every file system. + Naming::Replacing => Ok(new), + } + } + + /// Makes a regular file in the directory `parent` for the name `name` + /// under a temporary name, as where O_TMPFILE is refused. + fn create_named_in(parent: OwnedFd, name: OsString, path: &Path, naming: Naming) -> io::Result { + let temporary = TemporaryName::new(&name)?; + let file = sys::create_file_at(parent.as_fd(), temporary.as_bytes(), NEW_FILE_MODE)?; + Ok(NewFile { + file, + parent, + name, + path: path.to_path_buf(), + naming, + waiting: Some(Waiting::Temporary(temporary)), + }) + } + + /// Takes the exclusive BSD lock that a device takes for writing, see + /// [`crate::device::Device::create`], before anything can remove a name + /// of the file. A file another process locked between its creation and + /// this is in its hands: the file keeps its name, and this fails with + /// EBUSY. Where the lock cannot be had at all, as NFS without its lock + /// manager refuses it with ENOLCK, this fails with that, and giving the + /// file up removes its name. + fn lock(&mut self) -> Result<()> { + match sys::try_lock(self.file.as_fd(), true) { + Ok(true) => Ok(()), + Ok(false) => { + let shown = self.shown(); + self.waiting = None; + bail!(EBUSY, "{} is being used by another process", shown) + } + Err(e) => Err(Error::from(e).context(format!("failed to lock {}", self.shown()))), + } + } + + /// The file, for messages: the path of the name it has in its directory + /// now, a temporary name or the one it is made for, or "the new file" + /// where it has no name. + fn shown(&self) -> String { + match &self.waiting { + Some(Waiting::Temporary(temporary)) => { + self.path.with_file_name(temporary.as_os_str()).display().to_string() + } + Some(Waiting::Claimed) => self.path.display().to_string(), + Some(Waiting::Unnamed) | None => "the new file".to_string(), + } + } + + /// Finds out how the file, under a temporary name and with nothing + /// written to it yet, gets its name without taking the place of another + /// file. It is renamed to another temporary name with RENAME_NOREPLACE, + /// or else linked to one by its descriptor, and that name is removed + /// again. NFS, CephFS and 9p refuse the flag with EINVAL (their rename + /// operations take no flags), and a file system without hard links + /// refuses the link, see [`sys::Refusal`]. Right before the rename the + /// temporary name is checked to refer to the file still, as + /// [`NewFile::link`] checks it. Where both are refused the temporary + /// file goes and the file is made under its name, locked before it can + /// be removed again: the last resort of [`NewFile`]. + fn probe_exclusive_naming(&mut self) -> Result<()> { + let Some(Waiting::Temporary(temporary)) = &self.waiting else { + return Ok(()); + }; + // Until the file waits under another name, giving it up removes + // this one. + let temporary = temporary.clone(); + let other = TemporaryName::new(&self.name)?; + self.check_temporary(&temporary)?; + let parent = self.parent.as_fd(); + match sys::rename_noreplace_at(parent, temporary.as_bytes(), other.as_bytes()) { + Ok(()) => { + self.waiting = Some(Waiting::Temporary(other)); + return Ok(()); + } + Err(e) if e.refuses_rename_flags() => {} + Err(e) => return Err(e.into()), + } + match sys::link_fd(self.file.as_fd(), parent, other.as_bytes()) { + Ok(()) => { + self.remove_name(other.as_os_str())?; + return Ok(()); + } + Err(e) if e.refuses_hard_links() => {} + Err(e) => return Err(e.into()), + } + self.remove_name(temporary.as_os_str())?; + self.waiting = None; + self.file = sys::create_file_at(parent, self.name.as_bytes(), NEW_FILE_MODE)?; + // Armed before the lock: a file another process locked first is + // left to it, see NewFile::lock(). + self.waiting = Some(Waiting::Claimed); + self.lock() + } + + /// The file, to write it. + pub fn file(&self) -> &File { + &self.file + } + + /// The name the file is made for, as the caller named it. + pub fn path(&self) -> &Path { + &self.path + } + + /// Gives the file its name as its [`Naming`] says, and checks by device + /// and inode number that the name refers to the file then. A file that + /// did not get its name comes back in the error, to be given up. One + /// that got its name where checking that failed comes back linked, see + /// [`LinkError::Unchecked`]. + /// + /// [`Naming::Exclusive`]: a file without a name is linked by its + /// descriptor as systemd's link_fd() links one, with AT_EMPTY_PATH, else + /// through /proc/self/fd; a file system that makes files without a name + /// but cannot link them fails here. A temporary name is renamed with + /// RENAME_NOREPLACE, or where the file system refuses the flag the file + /// is linked by its descriptor and the temporary name removed after the + /// check, the way the probe of [`NewFile`] found out. Where something + /// has the name by now that is EEXIST. A file made under its name as the + /// last resort has it already. + /// + /// [`Naming::Replacing`]: a file without a name that cannot be linked + /// under it because the name exists is linked under a temporary name + /// and renamed onto it, as systemd's linkat_replace() does it, and a + /// temporary name is renamed onto it right away. + /// + /// A rename moves whatever has the temporary name by then. So right + /// before it the temporary name is checked to refer to the file, and a + /// file that took it meanwhile is left where it is (EEXIST). One that + /// takes it between that check and the rename gets the name: the check + /// after fails then, and leaves that file there. + pub fn link(mut self) -> std::result::Result { + // A descriptor of the directory to sync it, taken before the file + // gets its name, which nothing may undo. Opening the directory for + // the sync can fail: that waits for Linked::sync_directories(). + let directory = match self.parent.try_clone() { + Ok(directory) => directory, + Err(e) => return Err(self.unnamed(e.into())), + }; + if let Err(e) = self.give_name() { + return Err(self.unnamed(e)); + } + let shown = self.path.display().to_string(); + match self.holder(&self.name) { + Ok(Holder::Itself) => {} + Ok(Holder::Another) => { + let e = err!( + EEXIST, + "{} is not the file made for it: another file took its name or its temporary name meanwhile", + shown + ); + return Err(self.unnamed(e)); + } + Ok(Holder::Nothing) => { + let e = err!(ENOENT, "{} is gone: something removed or renamed it meanwhile", shown); + return Err(self.unnamed(e)); + } + Err(e) => { + let stays = match self.waiting.take() { + Some(Waiting::Temporary(temporary)) => { + format!( + ", and {} stays", + self.path.with_file_name(temporary.as_os_str()).display() + ) + } + _ => String::new(), + }; + let error = Error::from(e).context(format!("{} has its name, but checking it failed{}", shown, stays)); + let linked = Linked { + directory, + path: self.path.clone(), + stray: None, + }; + return Err(LinkError::Unchecked { error, linked }); + } + } + let stray = match self.waiting.take() { + Some(Waiting::Temporary(temporary)) => { + let stays = self.path.with_file_name(temporary.as_os_str()); + match self.remove_name(temporary.as_os_str()) { + Ok(Removal::Removed | Removal::AlreadyGone) => None, + Ok(Removal::NameTaken) => Some(Stray::Taken(stays)), + Err(e) => Some(Stray::Kept(e.context(format!( + "{}, which {} was linked from, stays", + stays.display(), + shown + )))), + } + } + _ => None, + }; + Ok(Linked { + directory, + path: self.path.clone(), + stray, + }) + } + + /// The error of a [`NewFile::link`] that failed with `error` before + /// the file got its name, or found it gone after. + fn unnamed(self, error: Error) -> LinkError { + LinkError::Unnamed { error, file: self } + } + + /// The naming of [`NewFile::link`]. A temporary name the file is linked + /// from rather than renamed from stays in `waiting`, to be removed once + /// the name is checked. + fn give_name(&mut self) -> Result<()> { + let (parent, name) = (self.parent.as_fd(), self.name.as_bytes()); + match (&self.waiting, self.naming) { + (Some(Waiting::Unnamed), Naming::Exclusive) => { + self.link_unnamed(name)?; + self.waiting = None; + } + (Some(Waiting::Unnamed), Naming::Replacing) => { + match self.link_unnamed(name) { + Err(e) if e.errno() == EEXIST => {} + linked => { + linked?; + self.waiting = None; + return Ok(()); + } + } + let temporary = TemporaryName::new(&self.name)?; + self.link_unnamed(temporary.as_bytes())?; + // From here on giving the file up removes it. + self.waiting = Some(Waiting::Temporary(temporary.clone())); + self.check_temporary(&temporary)?; + sys::rename_at(parent, temporary.as_bytes(), name)?; + self.waiting = None; + } + (Some(Waiting::Temporary(temporary)), naming) => { + let temporary = temporary.clone(); + self.check_temporary(&temporary)?; + let renamed = match naming { + Naming::Exclusive => sys::rename_noreplace_at(parent, temporary.as_bytes(), name), + Naming::Replacing => sys::rename_at(parent, temporary.as_bytes(), name), + }; + match renamed { + Ok(()) => self.waiting = None, + Err(e) if naming == Naming::Exclusive && e.refuses_rename_flags() => { + sys::link_fd(self.file.as_fd(), parent, name)?; + } + Err(e) => return Err(e.into()), + } + } + // Made under its name by the last resort. + (Some(Waiting::Claimed) | None, _) => {} + } + Ok(()) + } + + /// Links the file, made without a name, under `name` by its descriptor. + /// A file system that refuses hard links has made the file but refuses + /// it a name, which shows only here, at the end. + fn link_unnamed(&self, name: &[u8]) -> Result<()> { + sys::link_fd(self.file.as_fd(), self.parent.as_fd(), name).map_err(|e| { + if e.refuses_hard_links() { + Error::from(e).context("the file system made the file but refuses to give it its name") + } else { + e.into() + } + }) + } + + /// Checks right before a rename of the temporary name `temporary` that + /// it refers to the file still: a rename moves whatever has the name by + /// then. A file that took it meanwhile is left where it is (EEXIST). + fn check_temporary(&self, temporary: &TemporaryName) -> Result<()> { + let shown = self.path.with_file_name(temporary.as_os_str()); + let holder = self + .holder(temporary.as_os_str()) + .with_context(|| format!("failed to check {}", shown.display()))?; + match holder { + Holder::Itself => Ok(()), + Holder::Another => bail!( + EEXIST, + "{} refers to another file now: something took that name meanwhile", + shown.display() + ), + Holder::Nothing => bail!( + ENOENT, + "{} is gone: something removed or renamed it meanwhile", + shown.display() + ), + } + } + + /// What has the name `name` of the directory: the file, another file or + /// nothing. + fn holder(&self, name: &OsStr) -> io::Result { + let ours = self.file.metadata()?; + let entry = match sys::pin_entry(self.parent.as_fd(), name.as_bytes()) { + Ok(entry) => entry, + Err(e) if e.raw_os_error() == Some(ENOENT) => return Ok(Holder::Nothing), + Err(e) => return Err(e), + }; + let there = sys::fstat(entry.as_fd())?; + if (there.dev(), there.ino()) == (ours.dev(), ours.ino()) { + Ok(Holder::Itself) + } else { + Ok(Holder::Another) + } + } + + /// Gives the file up. One without a name goes away with its last + /// descriptor. A temporary name, or the name the last resort made the + /// file under, is removed after checking that it refers to the file, + /// see [`NewFile`]. A file that has its name already keeps it. + pub fn discard(mut self) -> Result { + match self.waiting.take() { + Some(Waiting::Temporary(temporary)) => self.remove_name(temporary.as_os_str()), + Some(Waiting::Claimed) => { + let name = self.name.clone(); + self.remove_name(&name) + } + Some(Waiting::Unnamed) | None => Ok(Removal::Removed), + } + } + + /// Gives the file up the way [`NewFile::discard`] does, and says what of + /// it stays where something does, for a message: a name that refers to + /// another file now, which is left alone, or one that removing failed + /// for. + pub fn give_up(self) -> Option { + let (shown, path) = (self.shown(), self.path.clone()); + match self.discard() { + Ok(Removal::Removed | Removal::AlreadyGone) => None, + Ok(Removal::NameTaken) => Some(format!("{} refers to another file now, which is left alone", shown)), + Err(e) => Some(format!("the unfinished {} stays: {}", path.display(), e)), + } + } + + /// `cause`, after which the file is given up, followed by what of it + /// stays where something does. + pub(crate) fn given_up(self, cause: Error) -> Error { + let Some(stays) = self.give_up() else { + return cause; + }; + let detail = cause.detail().cloned(); + let error = Error::new(cause.errno(), format!("{}, and {}", cause.message(), stays)); + match detail { + Some(detail) => error.with(detail), + None => error, + } + } + + /// Removes the name `name` of the directory after checking by device + /// and inode number that it refers to this file. + fn remove_name(&self, name: &OsStr) -> Result { + let failed = || format!("failed to remove {}", self.path.with_file_name(name).display()); + match self.holder(name).with_context(failed)? { + Holder::Itself => {} + Holder::Another => return Ok(Removal::NameTaken), + Holder::Nothing => return Ok(Removal::AlreadyGone), + } + match sys::unlink_at(self.parent.as_fd(), name.as_bytes()) { + Ok(()) => Ok(Removal::Removed), + Err(e) if e.raw_os_error() == Some(ENOENT) => Ok(Removal::AlreadyGone), + Err(e) => Err(e).with_context(failed), + } + } +} + +impl Drop for NewFile { + fn drop(&mut self) { + // The file is still open here, so its inode is not reused while the + // name is compared, and a lock it took is still held. + let name = match self.waiting.take() { + Some(Waiting::Temporary(temporary)) => temporary.0, + Some(Waiting::Claimed) => self.name.clone(), + Some(Waiting::Unnamed) | None => return, + }; + let _ = self.remove_name(&name); + } +} + /// Opens the directory `dir`, pinned or open, for listing: a descriptor of /// our own with its own position, so a caller's descriptor keeps its state. pub(crate) fn listing_of(dir: BorrowedFd<'_>) -> Result { @@ -658,8 +1331,391 @@ impl Read for FromStart<'_> { mod tests { use super::*; use crate::test_util::TempDir; + use std::io::Write; use std::os::unix::fs::symlink; + /// The names in the directory `dir`, sorted. + fn names_in(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + names.sort(); + names + } + + /// The temporary name `new` waits under in its directory, where + /// O_TMPFILE was refused. + fn temporary_name(new: &NewFile) -> Option<&TemporaryName> { + match &new.waiting { + Some(Waiting::Temporary(temporary)) => Some(temporary), + _ => None, + } + } + + /// Whether `temporary` is a temporary name for `name`: `.#`, the name + /// and 16 hex digits. + fn is_temporary_name_of(temporary: &OsStr, name: &str) -> bool { + let temporary = temporary.to_str().unwrap(); + let digits = temporary.strip_prefix(".#").and_then(|rest| rest.strip_prefix(name)); + digits.is_some_and(|digits| { + digits.len() == TemporaryName::DIGITS && digits.bytes().all(|b| b.is_ascii_hexdigit()) + }) + } + + /// A new file is written without a name and gets it when it is linked. + /// An exclusive one does not take the name where something has it, one + /// that replaces does, by a rename, so another hard link to the file + /// it replaces keeps what that held. One that is given up leaves + /// nothing. + #[test] + fn new_files_get_their_names_at_the_end() { + let tmp = TempDir::new("new"); + let dir = tmp.path(); + let path = dir.join("m.json"); + let new = NewFile::create(&path, Naming::Exclusive).unwrap(); + new.file().write_all(b"first").unwrap(); + assert!(!path.exists()); + if temporary_name(&new).is_none() { + assert!(names_in(dir).is_empty()); + } + Linked::sync_directories(&[new.link().unwrap()]).unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"first"); + let new = NewFile::create(&path, Naming::Exclusive).unwrap(); + new.file().write_all(b"second").unwrap(); + let (error, file) = unnamed(new.link().unwrap_err()); + assert_eq!(error.errno(), EEXIST); + assert_eq!(file.discard().unwrap(), Removal::Removed); + assert_eq!(fs::read(&path).unwrap(), b"first"); + fs::hard_link(&path, dir.join("other")).unwrap(); + let new = NewFile::create(&path, Naming::Replacing).unwrap(); + new.file().write_all(b"third").unwrap(); + Linked::sync_directories(&[new.link().unwrap()]).unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"third"); + assert_eq!(fs::read(dir.join("other")).unwrap(), b"first"); + drop(NewFile::create(&dir.join("dropped"), Naming::Exclusive).unwrap()); + assert_eq!(names_in(dir), ["m.json", "other"]); + assert_eq!( + NewFile::create(&dir.join("missing/m.json"), Naming::Exclusive) + .unwrap_err() + .errno(), + ENOENT + ); + } + + /// The error and the file of a link that left the file without its + /// name. + fn unnamed(failed: LinkError) -> (Error, NewFile) { + match failed { + LinkError::Unnamed { error, file } => (error, file), + LinkError::Unchecked { error, .. } => panic!("the file got its name: {}", error), + } + } + + /// A new file made in the directory `dir` for the name `name` under a + /// temporary name, as where O_TMPFILE is refused. + fn named_in(dir: &Path, name: &str, naming: Naming) -> NewFile { + NewFile::create_named_in(open_dir(dir).unwrap(), name.into(), &dir.join(name), naming).unwrap() + } + + /// Where O_TMPFILE is refused a new file waits under a temporary name + /// in its directory. An exclusive one finds out how it gets its name + /// first, where RENAME_NOREPLACE works by a rename to another temporary + /// name. Linking renames it, never onto a name that is taken unless it + /// replaces, and giving it up removes the temporary name while it names + /// the file, which tells apart a name that is gone and one that another + /// file took. + #[test] + fn new_files_under_a_temporary_name() { + let tmp = TempDir::new("temporary"); + let dir = tmp.path(); + let mut new = named_in(dir, "a.img", Naming::Exclusive); + let first = temporary_name(&new).unwrap().as_os_str().to_os_string(); + new.probe_exclusive_naming().unwrap(); + let temporary = temporary_name(&new).unwrap().as_os_str().to_os_string(); + assert_ne!(temporary, first); + assert!(is_temporary_name_of(&temporary, "a.img"), "{:?}", temporary); + assert_eq!(names_in(dir), [temporary.to_str().unwrap()]); + new.file().write_all(b"first").unwrap(); + Linked::sync_directories(&[new.link().unwrap()]).unwrap(); + assert_eq!(names_in(dir), ["a.img"]); + assert_eq!(fs::read(dir.join("a.img")).unwrap(), b"first"); + let (error, file) = unnamed(named_in(dir, "a.img", Naming::Exclusive).link().unwrap_err()); + assert_eq!(error.errno(), EEXIST); + assert_eq!(file.discard().unwrap(), Removal::Removed); + assert_eq!(names_in(dir), ["a.img"]); + let new = named_in(dir, "a.img", Naming::Replacing); + new.file().write_all(b"second").unwrap(); + Linked::sync_directories(&[new.link().unwrap()]).unwrap(); + assert_eq!(fs::read(dir.join("a.img")).unwrap(), b"second"); + drop(named_in(dir, "b.img", Naming::Exclusive)); + assert_eq!(names_in(dir), ["a.img"]); + let new = named_in(dir, "c.img", Naming::Exclusive); + fs::remove_file(dir.join(temporary_name(&new).unwrap().as_os_str())).unwrap(); + assert_eq!(new.discard().unwrap(), Removal::AlreadyGone); + let new = named_in(dir, "c.img", Naming::Exclusive); + let temporary = dir.join(temporary_name(&new).unwrap().as_os_str()); + fs::remove_file(&temporary).unwrap(); + fs::write(&temporary, b"theirs").unwrap(); + assert_eq!(new.discard().unwrap(), Removal::NameTaken); + assert_eq!(fs::read(&temporary).unwrap(), b"theirs"); + } + + /// A rename moves whatever has the temporary name by then, so right + /// before each rename the temporary name is checked to refer to the + /// file still. A file that took it meanwhile stays where it is: the + /// probe does not move it to another temporary name, an exclusive file + /// does not get its name, and one that replaces does not replace what + /// has its name. Giving the file up says that the temporary name refers + /// to another file now. + #[test] + fn a_temporary_name_taken_meanwhile_is_left_alone() { + let tmp = TempDir::new("taken"); + let dir = tmp.path(); + let take = |new: &NewFile| { + let temporary = dir.join(temporary_name(new).unwrap().as_os_str()); + fs::write(dir.join("theirs"), b"theirs").unwrap(); + fs::rename(dir.join("theirs"), &temporary).unwrap(); + temporary + }; + let mut new = named_in(dir, "a.img", Naming::Exclusive); + let taken = take(&new); + assert_eq!(new.probe_exclusive_naming().unwrap_err().errno(), EEXIST); + assert_eq!(names_in(dir), [taken.file_name().unwrap().to_str().unwrap()]); + let left_alone = format!("{} refers to another file now, which is left alone", taken.display()); + assert_eq!(new.give_up().unwrap(), left_alone); + fs::remove_file(&taken).unwrap(); + let mut new = named_in(dir, "a.img", Naming::Exclusive); + new.probe_exclusive_naming().unwrap(); + let taken = take(&new); + let (error, file) = unnamed(new.link().unwrap_err()); + assert_eq!(error.errno(), EEXIST); + assert_eq!(file.discard().unwrap(), Removal::NameTaken); + assert!(!dir.join("a.img").exists()); + assert_eq!(fs::read(&taken).unwrap(), b"theirs"); + fs::remove_file(&taken).unwrap(); + fs::write(dir.join("m.json"), b"old").unwrap(); + let new = named_in(dir, "m.json", Naming::Replacing); + let taken = take(&new); + let (error, _) = unnamed(new.link().unwrap_err()); + assert_eq!(error.errno(), EEXIST); + assert_eq!(fs::read(dir.join("m.json")).unwrap(), b"old"); + assert_eq!(fs::read(&taken).unwrap(), b"theirs"); + } + + /// Where the file system refuses RENAME_NOREPLACE, an exclusive file + /// under a temporary name is linked by its descriptor and the temporary + /// name is removed after: one that cannot be removed stays, and the + /// link says so. Filters of the test's own thread refuse the flag, as + /// NFS refuses it, and the removal. + /// A kernel without renameat2() says ENOSYS, and so does a seccomp + /// filter that does not know the call, as systemd's do. That is refused + /// like the flag: the probe of an exclusive file under a temporary name + /// leaves it under that name, and the link gives it its name by its + /// descriptor and removes the temporary name. A filter of the test's own + /// thread says ENOSYS for renameat2(). + #[test] + fn a_kernel_without_renameat2_links_the_file() { + let tmp = TempDir::new("norenameat2"); + let dir = tmp.path().to_path_buf(); + let mut new = named_in(&dir, "a.img", Naming::Exclusive); + new.file().write_all(b"image").unwrap(); + let first = temporary_name(&new).unwrap().clone(); + let linked = std::thread::spawn(move || { + sys::refuse_in_this_thread(libc::SYS_renameat2, ENOSYS).then(|| { + new.probe_exclusive_naming().unwrap(); + let waits = temporary_name(&new) == Some(&first); + (waits, new.link().unwrap().stray().is_none()) + }) + }) + .join() + .unwrap(); + let Some((waits, unstrayed)) = linked else { + return eprintln!("skipping: no seccomp filters here"); + }; + assert!(waits, "the probe renamed the file"); + assert!(unstrayed, "the temporary name stays"); + assert_eq!(names_in(&dir), ["a.img"]); + assert_eq!(fs::read(dir.join("a.img")).unwrap(), b"image"); + } + + #[test] + fn a_temporary_name_that_cannot_be_removed_stays() { + let tmp = TempDir::new("stray"); + let dir = tmp.path(); + let mut new = named_in(dir, "a.img", Naming::Exclusive); + new.probe_exclusive_naming().unwrap(); + let temporary = dir.join(temporary_name(&new).unwrap().as_os_str()); + let stray = std::thread::spawn(move || { + let refused = sys::refuse_in_this_thread(libc::SYS_renameat2, EINVAL) + && sys::refuse_in_this_thread(libc::SYS_unlinkat, EIO); + refused.then(|| new.link().unwrap().stray().map(ToString::to_string)) + }) + .join() + .unwrap(); + let Some(stray) = stray else { + return eprintln!("skipping: no seccomp filters here"); + }; + let stray = stray.unwrap(); + let stays = format!( + "{}, which {} was linked from, stays: failed to remove {}: ", + temporary.display(), + dir.join("a.img").display(), + temporary.display() + ); + assert!(stray.starts_with(&stays), "{}", stray); + assert!(dir.join("a.img").exists()); + assert!(temporary.exists()); + } + + /// The directories new files got their names in are synced, each once. + /// A file system without an fsync for its directories refuses it with + /// EINVAL (vfs_fsync_range()), and a directory that cannot be read + /// cannot be opened to sync it: those are left as they are. Any other + /// failure fails, and says that the first of the files in that + /// directory is complete and has its name. Filters of the test's own + /// threads refuse the fsync. + #[test] + fn directories_that_cannot_be_synced() { + use std::os::unix::fs::PermissionsExt; + let tmp = TempDir::new("unsynced"); + let dir = tmp.path(); + let linked = |name: &str| { + NewFile::create(&dir.join(name), Naming::Exclusive) + .unwrap() + .link() + .unwrap() + }; + let synced = |linked: &[Linked], errno| { + std::thread::scope(|scope| { + scope + .spawn(move || { + sys::refuse_in_this_thread(libc::SYS_fsync, errno) + .then(|| Linked::sync_directories(linked).map_err(|e| e.to_string())) + }) + .join() + .unwrap() + }) + }; + let unsynced = |name| { + format!( + "{} is complete and has its name, but syncing its directory failed: ", + dir.join(name).display() + ) + }; + let files = [linked("a.img"), linked("b.img")]; + let Some(skipped) = synced(&files, EINVAL) else { + return eprintln!("skipping: no seccomp filters here"); + }; + assert_eq!(skipped, Ok(())); + let failed = synced(&files, EIO).unwrap().unwrap_err(); + assert!(failed.starts_with(&unsynced("a.img")), "{}", failed); + let [a, b] = files; + let failed = synced(&[b, a], EIO).unwrap().unwrap_err(); + assert!(failed.starts_with(&unsynced("b.img")), "{}", failed); + let c = linked("c.img"); + fs::set_permissions(dir, fs::Permissions::from_mode(0o300)).unwrap(); + let unreadable = fs::read_dir(dir).is_err(); + let synced = Linked::sync_directories(&[c]); + fs::set_permissions(dir, fs::Permissions::from_mode(0o755)).unwrap(); + if unreadable { + synced.unwrap(); + } + } + + /// A new file whose name cannot be checked once it got it, as for want + /// of descriptors, keeps the name, and the error says so. A filter of + /// the test's own thread refuses the open the check needs. + #[test] + fn a_name_that_cannot_be_checked_stays() { + let tmp = TempDir::new("unchecked"); + let path = tmp.path().join("a.img"); + let new = NewFile::create(&path, Naming::Exclusive).unwrap(); + if temporary_name(&new).is_some() { + return eprintln!("skipping: no O_TMPFILE here"); + } + let failed = std::thread::spawn(move || { + sys::refuse_in_this_thread(libc::SYS_openat, libc::EMFILE).then(|| new.link().map(drop)) + }) + .join() + .unwrap(); + let Some(failed) = failed else { + return eprintln!("skipping: no seccomp filters here"); + }; + let LinkError::Unchecked { error, linked } = failed.unwrap_err() else { + panic!("the name was checked or not given"); + }; + assert_eq!(error.errno(), libc::EMFILE); + let checked = format!("{} has its name, but checking it failed: ", path.display()); + assert!(error.message().starts_with(&checked), "{}", error); + Linked::sync_directories(&[linked]).unwrap(); + assert!(path.exists()); + } + + /// Where the last resort cannot lock the file it made under its name, + /// it removes the name again, with the check by device and inode + /// number. Where another process holds the lock, the file is in its + /// hands and keeps the name (EBUSY). Filters of the test's own thread + /// refuse RENAME_NOREPLACE and hard links, as vboxsf does, and the + /// lock: with ENOLCK, as NFS without its lock manager, or with + /// EWOULDBLOCK, as where another process holds it. + #[test] + fn the_last_resort_without_its_lock() { + let tmp = TempDir::new("unlocked"); + let path = tmp.path().join("a.img"); + let failures = [ + (libc::ENOLCK, format!("failed to lock {}: ", path.display()), false), + ( + libc::EWOULDBLOCK, + format!("{} is being used by another process", path.display()), + true, + ), + ]; + for (refused, failed, kept) in failures { + let given_up = std::thread::scope(|scope| { + scope + .spawn(|| { + let mut new = named_in(tmp.path(), "a.img", Naming::Exclusive); + new.lock().unwrap(); + let filtered = sys::refuse_in_this_thread(libc::SYS_renameat2, EINVAL) + && sys::refuse_in_this_thread(libc::SYS_linkat, EPERM) + && sys::refuse_in_this_thread(libc::SYS_flock, refused); + filtered.then(|| { + let e = new.probe_exclusive_naming().unwrap_err(); + assert!(path.exists(), "{}", e); + new.given_up(e) + }) + }) + .join() + .unwrap() + }); + let Some(e) = given_up else { + return eprintln!("skipping: no seccomp filters here"); + }; + assert!(e.message().starts_with(&failed), "{}", e); + assert_eq!(e.errno(), if kept { EBUSY } else { refused }); + assert_eq!(path.exists(), kept, "{}", e); + assert_eq!(names_in(tmp.path()).len(), usize::from(kept)); + if kept { + fs::remove_file(&path).unwrap(); + } + } + } + + /// A temporary name is a file name: one for the longest name is that + /// long, the name cut short. Two are never the same. + #[test] + fn temporary_names_are_file_names() { + let longest = "x".repeat(sys::NAME_MAX); + let temporary = TemporaryName::new(OsStr::new(&longest)).unwrap().0; + assert_eq!(temporary.len(), sys::NAME_MAX); + let kept = sys::NAME_MAX - TemporaryName::PREFIX.len() - TemporaryName::DIGITS; + assert!(is_temporary_name_of(&temporary, &longest[..kept])); + let short = TemporaryName::new(OsStr::new("a.img")).unwrap().0; + assert!(is_temporary_name_of(&short, "a.img")); + assert_ne!(short, TemporaryName::new(OsStr::new("a.img")).unwrap().0); + } + /// The listing of a walk, as (path in the volume, kind) pairs. fn walk(root: &Path, follow: bool) -> Result> { let fd = open_dir(root)?; @@ -1156,7 +2212,7 @@ mod tests { sys::set_status_flags(client.as_fd(), flags | sys::O_NONBLOCK).unwrap(); } let refused = |e: io::Error, parameter: &'static str| { - let e = crate::Error::from(e); + let e = Error::from(e); assert_eq!(e.errno(), EBADFD); assert_eq!( e.detail(), diff --git a/src/fat/sys.rs b/src/fat/sys.rs index a158a44..5c0af18 100644 --- a/src/fat/sys.rs +++ b/src/fat/sys.rs @@ -25,7 +25,7 @@ use std::path::Path; use std::sync::atomic::{AtomicU8, Ordering}; use crate::errno::{ - EAGAIN, EBADF, EINVAL, EIO, ELOOP, ENODEV, ENOENT, ENOSYS, ENOTDIR, ENOTTY, ENXIO, EOPNOTSUPP, EPERM, + EAGAIN, EBADF, EINVAL, EIO, EISDIR, ELOOP, ENODEV, ENOENT, ENOSYS, ENOTDIR, ENOTTY, ENXIO, EOPNOTSUPP, EPERM, }; // The open(2) flags. libc has the values of each architecture: alpha, @@ -57,7 +57,7 @@ pub(crate) const O_PATH: c_int = libc::O_PATH; pub(crate) use uapi::{O_EMPTYPATH, O_LARGEFILE}; /// NAME_MAX, include/uapi/linux/limits.h: the longest file name. -const NAME_MAX: usize = libc::NAME_MAX as usize; +pub(crate) const NAME_MAX: usize = libc::NAME_MAX as usize; /// Steps a resolution by hand may take before we assume a loop, the /// CHASE_MAX of src/basic/chase.h: if people change the tree behind our @@ -160,6 +160,141 @@ pub(crate) fn unlink_at(dir: BorrowedFd<'_>, name: &[u8]) -> io::Result<()> { Ok(()) } +/// Makes a regular file without a name in the directory `dir`, open for +/// reading and writing like [`create_file_at`] opens one: open(2) with +/// O_TMPFILE. It goes away with its last descriptor unless [`link_fd`] +/// gives it a name. A file system without O_TMPFILE refuses it with +/// EOPNOTSUPP (vfs_tmpfile() in fs/namei.c), and a kernel that does not +/// know the flag opens the directory for writing, which is EISDIR. +pub(crate) fn create_unnamed_file(dir: BorrowedFd<'_>, mode: u32) -> io::Result { + let flags = libc::O_TMPFILE | O_RDWR | O_NONBLOCK | O_NOCTTY; + Ok(File::from(open_at(dir.as_raw_fd(), c".", flags, mode)?)) +} + +/// `linkat(2)`, with the directories as descriptors or AT_FDCWD. +fn linkat(old_dir: c_int, old: &CStr, new_dir: c_int, new: &CStr, flags: c_int) -> io::Result<()> { + // SAFETY: NUL terminated names and plain integers; linkat reads the + // names for the duration of the call and nothing else. + if unsafe { libc::linkat(old_dir, old.as_ptr(), new_dir, new.as_ptr(), flags) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// Gives the file `fd` refers to the name `name` in the directory `dir`, +/// as systemd's link_fd() does. The file can be one [`create_unnamed_file`] +/// made, and a name that exists is EEXIST. linkat() with an empty path and +/// AT_EMPTY_PATH links the descriptor itself. Since 42bd2af59504 ("vfs: +/// relax linkat() AT_EMPTY_PATH - aka flink() - requirements") the process +/// that opened the file may do that as long as its credentials did not +/// change. Otherwise it needs CAP_DAC_READ_SEARCH, and without it the +/// kernel says ENOENT. Then the file is linked through its magic link +/// /proc/self/fd/N, followed with AT_SYMLINK_FOLLOW, which needs procfs. +/// Both are tried every time: a command links a file or two. +pub(crate) fn link_fd(fd: BorrowedFd<'_>, dir: BorrowedFd<'_>, name: &[u8]) -> io::Result<()> { + let name = filename(name)?; + match linkat(fd.as_raw_fd(), c"", dir.as_raw_fd(), &name, libc::AT_EMPTY_PATH) { + Err(e) if e.raw_os_error() == Some(ENOENT) => {} + linked => return linked, + } + let link = cstring(format!("/proc/self/fd/{}", fd.as_raw_fd()).as_bytes())?; + match linkat(libc::AT_FDCWD, &link, dir.as_raw_fd(), &name, libc::AT_SYMLINK_FOLLOW) { + // The ENOENT can be about the directory as well, so it is replaced + // only where /proc is not procfs, as link_fd() does it. + Err(e) if e.raw_os_error() == Some(ENOENT) => match proc_kind() { + Ok(FsKind::Proc) => Err(e), + Ok(_) => Err(procfs_missing("link")), + Err(missing) if missing.raw_os_error() == Some(ENOENT) => Err(procfs_missing("link")), + Err(_) => Err(e), + }, + linked => linked, + } +} + +/// Renames the entry `old` of the directory `dir` to `new` in the same +/// directory, in place of what has that name: renameat(2). +pub(crate) fn rename_at(dir: BorrowedFd<'_>, old: &[u8], new: &[u8]) -> io::Result<()> { + let (old, new) = (filename(old)?, filename(new)?); + // SAFETY: NUL terminated names and plain integers; renameat reads the + // names for the duration of the call and nothing else. + if unsafe { libc::renameat(dir.as_raw_fd(), old.as_ptr(), dir.as_raw_fd(), new.as_ptr()) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// Renames the entry `old` of the directory `dir` to `new` in the same +/// directory unless something has that name, which is EEXIST: +/// renameat2(2) with RENAME_NOREPLACE, through syscall(2), since the musl +/// that Rust links its musl targets with has no renameat2(). NFS, CephFS +/// and 9p, among others, refuse the flag with EINVAL (their rename +/// operations take no flags), and a kernel without renameat2() says +/// ENOSYS. +pub(crate) fn rename_noreplace_at(dir: BorrowedFd<'_>, old: &[u8], new: &[u8]) -> io::Result<()> { + let (old, new) = (filename(old)?, filename(new)?); + // SAFETY: NUL terminated names and plain integers; renameat2 reads the + // names for the duration of the call and nothing else. + let renamed = unsafe { + libc::syscall( + libc::SYS_renameat2, + dir.as_raw_fd(), + old.as_ptr(), + dir.as_raw_fd(), + new.as_ptr(), + libc::RENAME_NOREPLACE, + ) + }; + if renamed < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// What an error says about a request that not every file system or kernel +/// takes: whether it was refused for that reason, rather than failed. +pub(crate) trait Refusal { + /// O_TMPFILE refused, see [`create_unnamed_file`]. + fn refuses_unnamed_files(&self) -> bool; + /// The flags of renameat2() refused, see [`rename_noreplace_at`]. + fn refuses_rename_flags(&self) -> bool; + /// Hard links refused: EPERM from a file system without a link + /// operation (vfs_link() in fs/namei.c, also for a FUSE server without + /// FUSE_LINK), EOPNOTSUPP from one whose link operation does not take + /// the file. + fn refuses_hard_links(&self) -> bool; + /// An fsync of a directory refused: EINVAL from a file system without + /// an fsync operation for its directories (vfs_fsync_range() in + /// fs/sync.c), as vboxsf, orangefs, AFS and 9p without 9P2000.L have + /// none. + fn refuses_syncing_directories(&self) -> bool; + /// Opening for reading refused: EACCES from a directory we may not + /// read, as one of mode 0300, which can be searched and written to but + /// not opened to sync it. + fn refuses_reading(&self) -> bool; +} + +impl Refusal for io::Error { + fn refuses_unnamed_files(&self) -> bool { + matches!(self.raw_os_error(), Some(EOPNOTSUPP | EISDIR)) + } + + fn refuses_rename_flags(&self) -> bool { + matches!(self.raw_os_error(), Some(EINVAL | ENOSYS | EOPNOTSUPP)) + } + + fn refuses_hard_links(&self) -> bool { + matches!(self.raw_os_error(), Some(EPERM | EOPNOTSUPP)) + } + + fn refuses_syncing_directories(&self) -> bool { + self.raw_os_error() == Some(EINVAL) + } + + fn refuses_reading(&self) -> bool { + self.raw_os_error() == Some(libc::EACCES) + } +} + /// What a probe of the running kernel found out so far: nothing yet, that /// it offers the feature, or that it does not. const PROBE_UNKNOWN: u8 = 0; @@ -224,16 +359,27 @@ pub(crate) fn reopen(fd: BorrowedFd<'_>, flags: c_int) -> io::Result { /// EBADF when it is and the descriptor is not, and the ENOENT itself when /// it cannot tell. fn proc_fd_enoent_errno() -> io::Error { - match open_path(None, Path::new("/proc"), true).and_then(|proc| fs_kind(proc.as_fd())) { + match proc_kind() { Ok(FsKind::Proc) => errno(EBADF), - Ok(_) => procfs_missing(), - Err(e) if e.raw_os_error() == Some(ENOENT) => procfs_missing(), + Ok(_) => procfs_missing("reopen"), + Err(e) if e.raw_os_error() == Some(ENOENT) => procfs_missing("reopen"), Err(_) => errno(ENOENT), } } -fn procfs_missing() -> io::Error { - crate::Error::new(ENOSYS, "procfs is not mounted on /proc, cannot reopen a descriptor").into() +/// The kind of file system on /proc; ENOENT where there is no /proc. +fn proc_kind() -> io::Result { + open_path(None, Path::new("/proc"), true).and_then(|proc| fs_kind(proc.as_fd())) +} + +/// The error for a descriptor that cannot be reopened or linked, as +/// `action` says, through /proc/self/fd/N for want of procfs. +fn procfs_missing(action: &str) -> io::Error { + crate::Error::new( + ENOSYS, + format!("procfs is not mounted on /proc, cannot {} a descriptor", action), + ) + .into() } /// Whether openat2 is available: unknown, yes, or no (an old kernel, or a @@ -815,6 +961,63 @@ pub(crate) fn set_status_flags(fd: BorrowedFd<'_>, flags: c_int) -> io::Result<( Ok(()) } +/// Makes the system call `call` fail with `errno` in the calling thread +/// from here on, for the tests of what a file system or kernel refuses: a +/// seccomp filter without TSYNC, which no other thread gets. Returns false +/// where seccomp filters cannot be had: on an architecture this does not +/// know, or under qemu-user, which refuses them. +#[cfg(test)] +pub(crate) fn refuse_in_this_thread(call: c_long, errno: c_int) -> bool { + // The flags of include/uapi/linux/audit.h that make the AUDIT_ARCH a + // filter compares with of a machine of elf.h. + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + const AUDIT_ARCH_64BIT: u32 = 0x8000_0000; + #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))] + const AUDIT_ARCH_LE: u32 = 0x4000_0000; + #[cfg(target_arch = "x86_64")] + const ARCH: Option = Some(libc::EM_X86_64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); + #[cfg(target_arch = "x86")] + const ARCH: Option = Some(libc::EM_386 as u32 | AUDIT_ARCH_LE); + #[cfg(target_arch = "aarch64")] + const ARCH: Option = Some(libc::EM_AARCH64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); + #[cfg(not(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")))] + const ARCH: Option = None; + let Some(arch) = ARCH else { + return false; + }; + let statement = |code: u32, k: u32, jf: u8| libc::sock_filter { + code: code as u16, + jt: 0, + jf, + k, + }; + let load = libc::BPF_LD | libc::BPF_W | libc::BPF_ABS; + let equal = libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K; + let give = libc::BPF_RET | libc::BPF_K; + // Another architecture or another call jumps to the last statement, + // which allows it. + let filter = [ + statement(load, std::mem::offset_of!(libc::seccomp_data, arch) as u32, 0), + statement(equal, arch, 3), + statement(load, std::mem::offset_of!(libc::seccomp_data, nr) as u32, 0), + statement(equal, call as u32, 1), + statement(give, libc::SECCOMP_RET_ERRNO | errno as u32, 0), + statement(give, libc::SECCOMP_RET_ALLOW, 0), + ]; + let program = libc::sock_fprog { + len: filter.len() as u16, + filter: filter.as_ptr().cast_mut(), + }; + let (on, unused): (libc::c_ulong, libc::c_ulong) = (1, 0); + let mode = libc::SECCOMP_MODE_FILTER as libc::c_ulong; + // SAFETY: prctl() takes plain values and a filter, which it copies + // before it returns. + unsafe { + libc::prctl(libc::PR_SET_NO_NEW_PRIVS, on, unused, unused, unused) == 0 + && libc::prctl(libc::PR_SET_SECCOMP, mode, std::ptr::from_ref(&program)) == 0 + } +} + #[cfg(test)] mod tests { use super::*; @@ -827,6 +1030,64 @@ mod tests { e.raw_os_error().unwrap_or(0) } + /// _LINUX_CAPABILITY_VERSION_3 of include/uapi/linux/capability.h, which + /// takes two of the data structs below. + const CAPABILITY_VERSION_3: u32 = 0x2008_0522; + /// CAP_DAC_READ_SEARCH, the capability that links any descriptor. + const CAP_DAC_READ_SEARCH: u32 = 2; + + #[repr(C)] + struct CapabilityHeader { + version: u32, + pid: c_int, + } + + #[repr(C)] + #[derive(Clone, Copy, Default)] + struct CapabilityData { + effective: u32, + permitted: u32, + inheritable: u32, + } + + /// Gives the calling thread new credentials with the same capabilities, + /// as capset(2) always does, and says whether CAP_DAC_READ_SEARCH is + /// among them. + fn renew_credentials() -> bool { + let mut header = CapabilityHeader { + version: CAPABILITY_VERSION_3, + pid: 0, + }; + let mut data = [CapabilityData::default(); 2]; + // SAFETY: a header and two data structs of the kernel's layout for + // version 3; capget fills them in, capset reads them. + unsafe { + let header = std::ptr::from_mut(&mut header); + assert_eq!(libc::syscall(libc::SYS_capget, header, data.as_mut_ptr()), 0); + assert_eq!(libc::syscall(libc::SYS_capset, header, data.as_ptr()), 0); + } + data[0].effective & (1 << CAP_DAC_READ_SEARCH) != 0 + } + + /// Once the credentials that opened a file changed, linkat() with + /// AT_EMPTY_PATH is ENOENT without CAP_DAC_READ_SEARCH, and link_fd() + /// links the file through /proc/self/fd. The new credentials live and + /// die with the thread of the test. + #[test] + fn link_fd_goes_through_proc_where_it_has_to() { + let tmp = TempDir::new("link"); + let dir = open_path(None, tmp.path(), true).unwrap(); + let file = create_unnamed_file(dir.as_fd(), 0o600).unwrap(); + let capable = renew_credentials(); + let direct = linkat(file.as_raw_fd(), c"", dir.as_raw_fd(), c"direct", libc::AT_EMPTY_PATH); + if !capable { + assert_eq!(code(direct.unwrap_err()), ENOENT); + } + link_fd(file.as_fd(), dir.as_fd(), b"linked").unwrap(); + assert!(tmp.path().join("linked").exists()); + assert_eq!(code(link_fd(file.as_fd(), dir.as_fd(), b"linked").unwrap_err()), EEXIST); + } + fn sorted(mut names: Vec>) -> Vec> { names.sort(); names diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index 63a0133..7a5eda0 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -233,7 +233,8 @@ pub struct Volume { /// Something has been written since open() or the last sync(): the /// volume carries its dirty marks, see [`Volume::begin_write`]. writing: bool, - /// Closed with [`Volume::close_unfinished`]: the marks stay. + /// Closed with [`Volume::close_unfinished`] or given up with + /// [`Volume::abandon`]: dropping it writes nothing, so the marks stay. unfinished: bool, layout: Layout, fat: Fat, @@ -1318,6 +1319,15 @@ impl Volume { self.flush()?; self.device.sync() } + + /// Gives up a volume whose contents are not complete without writing + /// anything more: what was written stays as it is, the marks it carries + /// while it is written included, and nothing is synced. This is for a + /// caller that throws the image away, such as a new file that never + /// gets its name, see [`crate::host::NewFile`]. + pub fn abandon(mut self) { + self.unfinished = true; + } } impl Drop for Volume { diff --git a/tests/cli.rs b/tests/cli.rs index ffc8350..dae31fc 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -8,7 +8,7 @@ mod common; use std::ffi::OsString; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use common::{ufat, Temp}; @@ -753,10 +753,11 @@ fn assemble_and_populate_take_trees_and_manifests() { // The files a manifest names are found below the SOURCE when they are // copied, and the messages about them name the SOURCE. A SOURCE that is // not there leaves nothing behind. A file that is missing, or changed - // since the manifest was written, fails the copy, and the file system - // holds what was complete before it, marked as not cleanly unmounted, - // the way a crash would leave it. A file that grew still has the data - // the manifest describes at its start, and that is what is copied. + // since the manifest was written, fails the copy. An image made for the + // file system is not kept then. One that was there holds what was + // complete before the failure, marked as not cleanly unmounted, the way + // a crash would leave it. A file that grew still has the data the + // manifest describes at its start, and that is what is copied. let d = image("d.img"); let d = d.as_str(); fails( @@ -768,14 +769,18 @@ fn assemble_and_populate_take_trees_and_manifests() { let empty = root.join("empty"); let empty = empty.to_str().unwrap(); fs::create_dir(empty).unwrap(); + let missing = format!( + "ufat: {}: EFI/Linux/linux.efi: failed to open EFI/Linux/linux.efi", + empty + ); fails( &bin, &["assemble", "--create", "--minimize", "--manifest", m, d, empty], - &format!( - "ufat: {}: EFI/Linux/linux.efi: failed to open EFI/Linux/linux.efi", - empty - ), + &missing, ); + assert!(!Path::new(d).exists()); + fs::write(d, b"").unwrap(); + fails(&bin, &["assemble", "--minimize", "--manifest", m, d, empty], &missing); assert_eq!(ok(&bin, &["list", d, "/EFI/Linux"]), ""); fs::write(root.join("tree/EFI/Linux/linux.efi"), b"kernel and more").unwrap(); ok(&bin, &["assemble", "--force", "--manifest", m, d, tree_arg]); @@ -1001,7 +1006,8 @@ fn names_fat_does_not_tell_apart() { &["assemble", "--create", "--size", "40M", &a, &both], "'/readme.txt' and '/README.TXT' are names FAT cannot tell apart", ); - ok(&bin, &["assemble", "--force", "--replace", &a, &both]); + assert!(!Path::new(&a).exists(), "a failed assemble left its image behind"); + ok(&bin, &["assemble", "--create", "--size", "40M", "--replace", &a, &both]); assert_eq!(ok(&bin, &["list", &a]), "readme.txt\n"); assert_eq!(ok(&bin, &["cat", &a, "/README.TXT"]), "lower\n"); fails( @@ -1030,7 +1036,7 @@ fn names_fat_does_not_tell_apart() { &["assemble", "--create", "--size", "40M", &d, &dirs], "'/efi' and '/EFI' are names FAT cannot tell apart", ); - ok(&bin, &["assemble", "--force", "--replace", &d, &dirs]); + ok(&bin, &["assemble", "--create", "--size", "40M", "--replace", &d, &dirs]); assert_eq!(ok(&bin, &["list", &d, "/EFI"]), "a\nb\n"); // A trailing slash means nothing, also to the message, which spells the // path that is there the way the file system does. @@ -1058,19 +1064,23 @@ fn names_fat_does_not_tell_apart() { ); fails( &bin, - &["assemble", "--force", "--replace", &e, &mixed], + &["assemble", "--create", "--size", "40M", "--replace", &e, &mixed], "'/efi' is a directory", ); + assert!(!Path::new(&e).exists(), "a failed assemble left its image behind"); } /// A volume too small for what goes into it. A copy that runs out of /// clusters says which file did not fit and leaves what came before it in /// a consistent file system. `assemble --minimize` with a `--size` the -/// content does not fit says so before it sizes or formats anything: a -/// file `--create` made is gone again and an existing file is as it was. -/// So do `--fit` and `--manifest` without a SOURCE, and a size of 0, which -/// no file system fits in. With `--minimize` and without a size an -/// existing file is grown to the fit and never shrunk. Without +/// content does not fit says so before it sizes or formats anything: +/// nothing is left of a file `--create` made, and an existing file is as +/// it was. So do `--fit` and `--manifest` without a SOURCE, and a size of +/// 0, which no file system fits in. Without `--minimize` content that does +/// not fit is found while it is written: nothing is left of a file +/// `--create` made then either, and an existing file keeps what was +/// written, marked as not cleanly unmounted. With `--minimize` and without +/// a size an existing file is grown to the fit and never shrunk. Without /// `--minimize` the file system takes the size given or the whole file. #[test] fn too_small_volumes_fail_cleanly() { @@ -1134,6 +1144,56 @@ fn too_small_volumes_fail_cleanly() { ); assert!(!new.exists(), "a failed assemble left its image behind"); } + // Without --minimize content that does not fit is found while it is + // written. The image made for it is not kept then either, and neither + // is it when the manifest of what was written or its hash cannot be + // written. + fails( + &bin, + &["assemble", "--create", "--size", "34M", n, t], + "copying big.bin: no free clusters left", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + fails( + &bin, + &["assemble", "--create", "--size", "34M", "--manifest", m, n, t], + "copying big.bin: no free clusters left", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + let nowhere = root.join("missing/m.json"); + let nowhere = nowhere.to_str().unwrap(); + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "64M", + "--write-manifest", + nowhere, + n, + t, + ], + "cannot create", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "64M", + "--hash", + "sha256", + "--write-hash", + nowhere, + n, + t, + ], + "cannot write", + ); + assert!(!new.exists(), "a failed assemble left its image behind"); let existing = root.join("existing.img"); let e = existing.to_str().unwrap(); fs::write(&existing, b"").unwrap(); @@ -1143,6 +1203,15 @@ fn too_small_volumes_fail_cleanly() { "holds 1048576 bytes but the content needs", ); assert_eq!(fs::metadata(&existing).unwrap().len(), 0); + // An image that was there keeps what was written, marked as not + // cleanly unmounted. + fails( + &bin, + &["assemble", "--size", "34M", e, t], + "copying big.bin: no free clusters left", + ); + assert_eq!(fs::metadata(&existing).unwrap().len(), 34 << 20); + assert!(ok(&bin, &["check", e]).contains("marked dirty")); let size: u64 = ok(&bin, &["assemble", "--plan", t]).trim().parse().unwrap(); // A plan against a size says whether the tree fits it, the way @@ -1339,7 +1408,7 @@ fn a_plan_against_a_size_answers_for_assemble() { let stderr = String::from_utf8_lossy(&out.stderr); assert_eq!(out.status.code(), Some(1), "{}", stderr); assert!(stderr.contains("no free clusters left"), "{}", stderr); - fs::remove_file(&image).unwrap(); + assert!(!image.exists(), "a failed assemble left its image behind"); // 400 MiB holds them, and the plan says so. ok(&bin, &["assemble", "--plan", "--size", "400M", "--manifest", m]); let out = run_in( @@ -1400,6 +1469,7 @@ fn directories_under_two_names_fill_up_when_written() { ], "directory is full", ); + assert!(!image.exists(), "a failed assemble left its image behind"); let image = root.join("b.img"); let b = image.to_str().unwrap(); fails( @@ -1407,6 +1477,7 @@ fn directories_under_two_names_fill_up_when_written() { &["assemble", "--create", "--minimize", "--manifest", s, b, "-"], "'/efi' and '/EFI' are names FAT cannot tell apart", ); + assert!(!image.exists(), "a failed assemble left its image behind"); let whole = root.join("whole.manifest"); fs::write(&whole, manifest(&[("EFI", 0..3200)])).unwrap(); fails( @@ -1416,6 +1487,902 @@ fn directories_under_two_names_fill_up_when_written() { ); } +/// The names in `dir` that a new file waits under where O_TMPFILE is +/// refused: `.#`, its name and 16 hex digits. +fn temporary_names(dir: &Path) -> Vec { + let mut names: Vec = fs::read_dir(dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.starts_with(".#")) + .collect(); + names.sort(); + names +} + +/// Whether the file system of `dir` makes a file without a name +/// (O_TMPFILE), as ufat tries first. +fn makes_unnamed_files(dir: &Path) -> bool { + use std::os::fd::{FromRawFd, OwnedFd}; + use std::os::unix::ffi::OsStrExt; + let dir = std::ffi::CString::new(dir.as_os_str().as_bytes()).unwrap(); + // SAFETY: a NUL terminated path and plain flags. + let fd = unsafe { libc::open(dir.as_ptr(), libc::O_TMPFILE | libc::O_RDWR | libc::O_CLOEXEC, 0o600) }; + if fd < 0 { + return false; + } + // SAFETY: a descriptor the kernel just handed out, owned by nothing + // else. + drop(unsafe { OwnedFd::from_raw_fd(fd) }); + true +} + +/// Runs `command` with its standard output a pipe whose reader is gone, so +/// that its first write there fails, and returns how it ended. +fn with_a_closed_pipe(mut command: Command) -> Output { + use std::os::fd::{FromRawFd, OwnedFd}; + use std::process::Stdio; + let mut fds = [0; 2]; + // SAFETY: pipe2() stores two new descriptors in the array. + assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + // SAFETY: both descriptors were just created and nothing else owns + // them. + let (read, write) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + drop(read); + command + .env("SOURCE_DATE_EPOCH", "1700000000") + .stdout(Stdio::from(write)) + .stderr(Stdio::piped()) + .output() + .expect("ufat runs") +} + +/// assemble gives the image it makes its name only once everything else +/// succeeded, the hash included, and the files it writes next to the +/// image, the manifest and the hash, theirs after the image. A failure +/// before leaves none of them behind: what was at their paths stays as it +/// was, also where the manifest was written before the hash failed. On +/// success they replace what is there, and what is not a regular file, +/// such as /dev/stdout, is written to as the command goes. +#[test] +fn assemble_names_what_it_made_at_the_end() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let t = tree.to_str().unwrap(); + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + let manifest = root.join("a.manifest"); + let m = manifest.to_str().unwrap(); + let hash = root.join("a.sha256"); + let h = hash.to_str().unwrap(); + fs::write(&manifest, b"old manifest\n").unwrap(); + fs::write(&hash, b"old hash\n").unwrap(); + let nowhere = root.join("missing/a.sha256"); + let nowhere = nowhere.to_str().unwrap(); + let assemble = |hash| { + let args = ["assemble", "--create", "--size", "40M", "--write-manifest", m]; + [&args[..], &["--hash", "sha256", "--write-hash", hash, a, t]].concat() + }; + fails(&bin, &assemble(nowhere), &format!("cannot write {}", nowhere)); + assert!(!image.exists(), "a failed assemble left its image behind"); + assert_eq!(fs::read(&manifest).unwrap(), b"old manifest\n"); + assert_eq!(fs::read(&hash).unwrap(), b"old hash\n"); + assert_eq!(temporary_names(root), Vec::::new()); + ok(&bin, &assemble(h)); + let digest = fat::manifest::Sha256::digest(&fs::read(&image).unwrap()); + assert_eq!(fs::read_to_string(&hash).unwrap(), format!("{}\n", digest)); + let described = ok(&bin, &["describe", "--write-manifest", "-", a]); + assert_eq!(fs::read_to_string(&manifest).unwrap(), described); + assert!(ok(&bin, &["check", a]).ends_with("; 0 errors, 0 warnings\n")); + assert_eq!(temporary_names(root), Vec::::new()); + // The name is taken now, and what is there is formatted anew. + fails(&bin, &assemble(h), "use --force to format it anyway"); + let written = ok(&bin, &["assemble", "--force", "--write-manifest", "/dev/stdout", a, t]); + assert_eq!(written, ok(&bin, &["describe", "--write-manifest", "-", a])); + assert_eq!(temporary_names(root), Vec::::new()); +} + +/// A manifest on standard output is written before the image gets its +/// name. SIGPIPE ends assemble when the reader of the pipe is gone, and no +/// image is left. A hash is printed once the image has its name, so there +/// SIGPIPE leaves the image complete. +#[test] +fn a_killed_assemble_leaves_no_image() { + use std::os::unix::process::ExitStatusExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let image = root.join("a.img"); + let mut command = Command::new(&bin); + command + .args(["assemble", "--create", "--size", "40M", "--write-manifest", "-"]) + .args([&image, &tree]); + let out = with_a_closed_pipe(command); + assert_eq!(out.status.signal(), Some(libc::SIGPIPE), "{:?}", out); + assert!(!image.exists(), "a killed assemble left its image behind"); + if makes_unnamed_files(root) { + assert_eq!(temporary_names(root), Vec::::new()); + } + let mut command = Command::new(&bin); + command + .args(["assemble", "--create", "--size", "40M", "--hash", "sha256"]) + .args([&image, &tree]); + let out = with_a_closed_pipe(command); + assert_eq!(out.status.signal(), Some(libc::SIGPIPE), "{:?}", out); + assert!(ok(&bin, &["check", image.to_str().unwrap()]).ends_with("; 0 errors, 0 warnings\n")); +} + +/// Where ufat, running as `pid`, makes an image in `dir`: its descriptor of +/// the file without a name, /proc/PID/fd/N, or where O_TMPFILE is refused +/// the temporary name of the file. Only once the image has its size, which +/// comes after the probe that can rename the file, so that its name holds. +fn image_in_the_making(pid: u32, dir: &Path) -> Option { + let unnamed = format!("{}/#", fs::canonicalize(dir).unwrap().display()); + let open = fs::read_dir(format!("/proc/{}/fd", pid)).ok().and_then(|fds| { + fds.flatten() + .map(|fd| fd.path()) + .find(|fd| fs::read_link(fd).is_ok_and(|target| target.to_string_lossy().starts_with(&unnamed))) + }); + open.or_else(|| temporary_names(dir).first().map(|name| dir.join(name))) + .filter(|image| fs::metadata(image).is_ok_and(|metadata| metadata.len() > 0)) +} + +/// Runs `command`, ufat assembling with `--manifest -` an image in `dir`, +/// with the manifest `text` on its standard input. The root object goes +/// first: assemble reads it before it makes the image, and the record +/// separator of the next object ends it. Once the image is in the making, +/// `meanwhile` gets where it is, and the rest of the manifest goes in. +fn assemble_meanwhile(mut command: Command, dir: &Path, text: &str, meanwhile: impl FnOnce(&Path)) -> Output { + use std::io::Write; + use std::process::Stdio; + use std::time::{Duration, Instant}; + let (first, rest) = text.split_at(text[1..].find('\x1e').unwrap() + 2); + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("ufat runs"); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(first.as_bytes()).unwrap(); + let started = Instant::now(); + let image = loop { + if let Some(image) = image_in_the_making(child.id(), dir) { + break image; + } + if let Some(status) = child.try_wait().unwrap() { + panic!("ufat ended before it made the image: {}", status); + } + assert!(started.elapsed() < Duration::from_secs(60), "ufat made no image"); + std::thread::sleep(Duration::from_millis(10)); + }; + meanwhile(&image); + // ufat may fail before it read all of it. + let _ = stdin.write_all(rest.as_bytes()); + drop(stdin); + child.wait_with_output().unwrap() +} + +/// Gives the file at `from` the name `to` as well. `from` can be one of +/// the /proc/PID/fd/N of ufat, which is followed to the file, also to one +/// without a name. +fn hard_link(from: &Path, to: &Path) { + use std::os::unix::ffi::OsStrExt; + let (from, to) = ( + std::ffi::CString::new(from.as_os_str().as_bytes()).unwrap(), + std::ffi::CString::new(to.as_os_str().as_bytes()).unwrap(), + ); + // SAFETY: NUL terminated paths and plain flags. + let linked = unsafe { + libc::linkat( + libc::AT_FDCWD, + from.as_ptr(), + libc::AT_FDCWD, + to.as_ptr(), + libc::AT_SYMLINK_FOLLOW, + ) + }; + assert_eq!(linked, 0, "{}", std::io::Error::last_os_error()); +} + +/// A name that something else takes while assemble makes the image stays +/// as it is: the image does not get it, and nothing is left of the image +/// or of the manifest written next to it. +#[test] +fn a_name_taken_meanwhile_stays_as_it_is() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let text = ok(&bin, &["manifest", tree.to_str().unwrap()]); + let image = root.join("a.img"); + let manifest = root.join("a.manifest"); + fs::write(&manifest, b"old\n").unwrap(); + let mut command = Command::new(&bin); + command + .env("SOURCE_DATE_EPOCH", "1700000000") + .args([ + "assemble", + "--create", + "--size", + "40M", + "--manifest", + "-", + "--write-manifest", + ]) + .args([&manifest, &image, &tree]); + let out = assemble_meanwhile(command, root, &text, |_| fs::write(&image, b"theirs").unwrap()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + let taken = format!( + "failed to create {}: {}", + image.display(), + std::io::Error::from_raw_os_error(libc::EEXIST) + ); + assert!(stderr.contains(&taken), "{}", stderr); + assert_eq!(fs::read(&image).unwrap(), b"theirs"); + assert_eq!(fs::read(&manifest).unwrap(), b"old\n"); + assert_eq!(temporary_names(root), Vec::::new()); +} + +/// An image assemble gives up after it wrote part of the content is not +/// written to anymore. So a file system that got another name while it was +/// made, a hard link through ufat's descriptor or through the temporary +/// name where O_TMPFILE is refused, keeps the marks of one that is being +/// written and is never taken for a finished one. +#[test] +fn a_given_up_image_keeps_its_marks() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let text = ok(&bin, &["manifest", tree.to_str().unwrap()]); + let empty = root.join("empty"); + fs::create_dir(&empty).unwrap(); + let image = root.join("a.img"); + let kept = root.join("kept.img"); + let unnamed = Command::new(&bin); + for command in [Some(unnamed), refusing(&bin, &[Refused::TMPFILE])] + .into_iter() + .flatten() + { + let mut command = command; + command + .env("SOURCE_DATE_EPOCH", "1700000000") + .args(["assemble", "--create", "--size", "40M", "--manifest", "-"]) + .args([&image, &empty]); + let out = assemble_meanwhile(command, root, &text, |made| hard_link(made, &kept)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(stderr.contains("failed to open EFI/Linux/linux.efi"), "{}", stderr); + assert!(!image.exists(), "a failed assemble left its image behind"); + assert_eq!(temporary_names(root), Vec::::new()); + let report = ok(&bin, &["check", kept.to_str().unwrap()]); + assert!(report.contains("marked dirty"), "{}", report); + fs::remove_file(&kept).unwrap(); + } +} + +/// A system call that fails with `errno` under a seccomp filter on ufat, +/// where its argument at the index of `flag` has that flag set, or always +/// without a `flag`. ufat runs then the way it runs where the kernel or the +/// file system refuses what the call asks for. +#[derive(Clone, Copy, Debug)] +struct Refused { + call: libc::c_long, + flag: Option<(usize, u32)>, + errno: i32, +} + +/// The flags of include/uapi/linux/audit.h that make an AUDIT_ARCH of a +/// machine of elf.h, the architecture a seccomp filter compares with. +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +const AUDIT_ARCH_64BIT: u32 = 0x8000_0000; +#[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))] +const AUDIT_ARCH_LE: u32 = 0x4000_0000; + +/// The AUDIT_ARCH of the system calls of ufat, where the filters know it. +/// Each of these is little endian, so the low 32 bits of an argument come +/// first. +#[cfg(target_arch = "x86_64")] +const AUDIT_ARCH: Option = Some(libc::EM_X86_64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); +#[cfg(target_arch = "x86")] +const AUDIT_ARCH: Option = Some(libc::EM_386 as u32 | AUDIT_ARCH_LE); +#[cfg(target_arch = "aarch64")] +const AUDIT_ARCH: Option = Some(libc::EM_AARCH64 as u32 | AUDIT_ARCH_64BIT | AUDIT_ARCH_LE); +#[cfg(not(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64")))] +const AUDIT_ARCH: Option = None; + +impl Refused { + /// O_TMPFILE, refused as a file system without it refuses it. + const TMPFILE: Refused = Refused { + call: libc::SYS_openat, + flag: Some((2, (libc::O_TMPFILE & !libc::O_DIRECTORY) as u32)), + errno: libc::EOPNOTSUPP, + }; + /// linkat() with AT_EMPTY_PATH, refused as without CAP_DAC_READ_SEARCH + /// before Linux 6.10. + const EMPTY_PATH_LINK: Refused = Refused { + call: libc::SYS_linkat, + flag: Some((4, libc::AT_EMPTY_PATH as u32)), + errno: libc::ENOENT, + }; + /// renameat2() with RENAME_NOREPLACE, refused as NFS refuses it. + const NOREPLACE: Refused = Refused { + call: libc::SYS_renameat2, + flag: Some((4, libc::RENAME_NOREPLACE)), + errno: libc::EINVAL, + }; + /// Every linkat(), refused as a file system without hard links refuses + /// it (vfs_link()). + const LINK: Refused = Refused { + call: libc::SYS_linkat, + flag: None, + errno: libc::EPERM, + }; + /// Every flock(), refused as where another process holds the lock. + const FLOCK: Refused = Refused { + call: libc::SYS_flock, + flag: None, + errno: libc::EWOULDBLOCK, + }; + /// Every flock(), refused as NFS without its lock manager refuses it. + const NO_LOCKS: Refused = Refused { + call: libc::SYS_flock, + flag: None, + errno: libc::ENOLCK, + }; + /// Every linkat(), failing for another reason than hard links being + /// refused. + const LINK_FAILS: Refused = Refused { + call: libc::SYS_linkat, + flag: None, + errno: libc::EIO, + }; + /// Every renameat(), a rename that may replace, failing. glibc renames + /// with it on x86_64 and x86, where it is a system call of its own. + #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] + const RENAME: Refused = Refused { + call: libc::SYS_renameat, + flag: None, + errno: libc::EIO, + }; + + /// The seccomp filter: another architecture, another system call or + /// the call without the flag is allowed. + fn filter(self, arch: u32) -> Vec { + use std::mem::offset_of; + let load = |offset: usize| libc::sock_filter { + code: (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, + jt: 0, + jf: 0, + k: offset as u32, + }; + let jump = |code: u32, k: u32| libc::sock_filter { + code: (libc::BPF_JMP | code | libc::BPF_K) as u16, + jt: 0, + jf: 0, + k, + }; + let give = |action: u32| libc::sock_filter { + code: (libc::BPF_RET | libc::BPF_K) as u16, + jt: 0, + jf: 0, + k: action, + }; + let mut filter = vec![ + load(offset_of!(libc::seccomp_data, arch)), + jump(libc::BPF_JEQ, arch), + load(offset_of!(libc::seccomp_data, nr)), + jump(libc::BPF_JEQ, self.call as u32), + ]; + if let Some((arg, flag)) = self.flag { + filter.push(load(offset_of!(libc::seccomp_data, args) + arg * size_of::())); + filter.push(jump(libc::BPF_JSET, flag)); + } + filter.push(give(libc::SECCOMP_RET_ERRNO | self.errno as u32)); + filter.push(give(libc::SECCOMP_RET_ALLOW)); + // Every test that fails jumps to the last instruction, which allows + // the call. + let last = filter.len() - 1; + for (at, instruction) in filter.iter_mut().enumerate() { + if instruction.code == (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16 + || instruction.code == (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16 + { + instruction.jf = (last - at - 1) as u8; + } + } + filter + } +} + +/// ufat with the system calls of `refused` refused, or None where seccomp +/// filters cannot be had: on an architecture the filters do not know, or +/// under qemu-user, which does not pass them on. +fn refusing(bin: &Path, refused: &[Refused]) -> Option { + static USABLE: std::sync::OnceLock = std::sync::OnceLock::new(); + let arch = AUDIT_ARCH?; + let usable = *USABLE.get_or_init(|| { + let mut probe = filtered(bin, arch, &[Refused::TMPFILE]); + probe.arg("--version").output().is_ok_and(|out| out.status.success()) + }); + usable.then(|| filtered(bin, arch, refused)) +} + +/// ufat with the system calls of `refused` refused on the architecture +/// `arch`. +fn filtered(bin: &Path, arch: u32, refused: &[Refused]) -> Command { + use std::os::unix::process::CommandExt; + let filters: Vec> = refused.iter().map(|r| r.filter(arch)).collect(); + let mut command = Command::new(bin); + command.env("SOURCE_DATE_EPOCH", "1700000000"); + // SAFETY: between fork and exec the closure makes prctl() calls only, + // with filters made before the fork. + unsafe { + command.pre_exec(move || { + let (on, unused): (libc::c_ulong, libc::c_ulong) = (1, 0); + if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, on, unused, unused, unused) != 0 { + return Err(std::io::Error::last_os_error()); + } + for filter in &filters { + let program = libc::sock_fprog { + len: filter.len() as u16, + filter: filter.as_ptr().cast_mut(), + }; + let mode = libc::SECCOMP_MODE_FILTER as libc::c_ulong; + if libc::prctl(libc::PR_SET_SECCOMP, mode, std::ptr::from_ref(&program)) != 0 { + return Err(std::io::Error::last_os_error()); + } + } + Ok(()) + }); + } + command +} + +/// Where O_TMPFILE is refused, the image waits under a temporary name in +/// its directory, `.#`, its name and 16 hex digits, and so do the files +/// written next to it. Success renames them, with RENAME_NOREPLACE for the +/// image, and where that is refused too with a link and the removal of the +/// temporary name. A failure, also one after part of the content was +/// written, removes them. A kill leaves the temporary name of the image. +/// Where a link with AT_EMPTY_PATH is refused, the files are linked through +/// /proc/self/fd. seccomp filters on ufat do the refusing; qemu-user does +/// not pass them on, and an architecture the filters do not know skips +/// the test. +#[test] +fn assemble_where_o_tmpfile_or_more_is_refused() { + use std::os::unix::process::ExitStatusExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let refused = |refused: &[Refused], args: &[&str]| { + let mut command = refusing(&bin, refused)?; + command.args(args); + command.output().ok() + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let t = tree.to_str().unwrap(); + let empty = root.join("empty"); + fs::create_dir(&empty).unwrap(); + let image = root.join("a.img"); + let a = image.to_str().unwrap(); + let manifest = root.join("a.manifest"); + let m = manifest.to_str().unwrap(); + fs::write(&manifest, ok(&bin, &["manifest", t])).unwrap(); + let written = root.join("written.manifest"); + let w = written.to_str().unwrap(); + fs::write(&written, b"old\n").unwrap(); + let creates = ["assemble", "--create", "--size", "40M", "--write-manifest", w]; + let tmpfile = &[Refused::TMPFILE][..]; + // A file missing below the SOURCE, after the directories were written. + let out = refused( + tmpfile, + &[&creates[..], &["--manifest", m, a, empty.to_str().unwrap()]].concat(), + ) + .unwrap(); + assert_eq!(out.status.code(), Some(1), "{:?}", out); + assert!(String::from_utf8_lossy(&out.stderr).contains("failed to open EFI/Linux/linux.efi")); + assert!(!image.exists(), "a failed assemble left its image behind"); + assert_eq!(fs::read(&written).unwrap(), b"old\n"); + assert_eq!(temporary_names(root), Vec::::new()); + // A hash that cannot be written, after the manifest was. + let nowhere = root.join("missing/a.sha256"); + let hashed = ["--hash", "sha256", "--write-hash", nowhere.to_str().unwrap(), a, t]; + let out = refused(tmpfile, &[&creates[..], &hashed].concat()).unwrap(); + assert_eq!(out.status.code(), Some(1), "{:?}", out); + assert!(!image.exists(), "a failed assemble left its image behind"); + assert_eq!(fs::read(&written).unwrap(), b"old\n"); + assert_eq!(temporary_names(root), Vec::::new()); + for refusals in [ + tmpfile, + &[Refused::TMPFILE, Refused::NOREPLACE], + &[Refused::EMPTY_PATH_LINK], + ] { + let out = refused(refusals, &[&creates[..], &[a, t]].concat()).unwrap(); + assert!(out.status.success(), "{:?}: {:?}", refusals, out); + assert!(ok(&bin, &["check", a]).ends_with("; 0 errors, 0 warnings\n")); + assert_eq!( + fs::read_to_string(&written).unwrap(), + ok(&bin, &["describe", "--write-manifest", "-", a]) + ); + assert_eq!(temporary_names(root), Vec::::new()); + fs::remove_file(&image).unwrap(); + fs::write(&written, b"old\n").unwrap(); + } + let mut command = refusing(&bin, tmpfile).unwrap(); + command.args(["assemble", "--create", "--size", "40M", "--write-manifest", "-", a, t]); + let out = with_a_closed_pipe(command); + assert_eq!(out.status.signal(), Some(libc::SIGPIPE), "{:?}", out); + assert!(!image.exists(), "a killed assemble left its image behind"); + let left = temporary_names(root); + assert_eq!(left.len(), 1, "{:?}", left); + let digits = left[0].strip_prefix(".#a.img").unwrap(); + assert!( + digits.len() == 16 && digits.bytes().all(|b| b.is_ascii_hexdigit()), + "{:?}", + left + ); +} + +/// Where a file system has neither O_TMPFILE nor RENAME_NOREPLACE nor hard +/// links, as vboxsf and orangefs have none of them, assemble finds that out +/// when it makes the image and takes the image's name right away, as it +/// always did. A failure removes the image by that name again. The files +/// next to the image get their names by a plain rename, which replaces. +#[test] +fn assemble_where_only_a_plain_rename_works() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let empty = root.join("empty"); + fs::create_dir(&empty).unwrap(); + let image = root.join("a.img"); + let manifest = root.join("a.manifest"); + fs::write(&manifest, ok(&bin, &["manifest", tree.to_str().unwrap()])).unwrap(); + let written = root.join("written.manifest"); + fs::write(&written, b"old\n").unwrap(); + let assemble = || { + let mut command = refusing(&bin, &[Refused::TMPFILE, Refused::NOREPLACE, Refused::LINK]).unwrap(); + command.args(["assemble", "--create", "--size", "40M", "--write-manifest"]); + command.args([&written, &image]); + command + }; + let out = assemble() + .arg("--manifest") + .arg(&manifest) + .arg(&empty) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(stderr.contains("failed to open EFI/Linux/linux.efi"), "{}", stderr); + assert!(!image.exists(), "a failed assemble left its image behind"); + assert_eq!(fs::read(&written).unwrap(), b"old\n"); + assert_eq!(temporary_names(root), Vec::::new()); + let out = assemble().arg(&tree).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let a = image.to_str().unwrap(); + assert!(ok(&bin, &["check", a]).ends_with("; 0 errors, 0 warnings\n")); + assert_eq!( + fs::read_to_string(&written).unwrap(), + ok(&bin, &["describe", "--write-manifest", "-", a]) + ); + assert_eq!(temporary_names(root), Vec::::new()); +} + +/// A file that takes the temporary name of the image while assemble makes +/// it is left where it is. Before the image gets its name, by a rename of +/// the temporary name with RENAME_NOREPLACE or, where the flag is refused, +/// by a link of its descriptor, assemble checks that the temporary name +/// still refers to the image. It fails then, and says that the other file +/// is left alone. +#[test] +fn a_temporary_name_taken_meanwhile_is_left_alone() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let text = ok(&bin, &["manifest", tree.to_str().unwrap()]); + let image = root.join("a.img"); + let theirs = root.join("theirs"); + for refusals in [&[Refused::TMPFILE][..], &[Refused::TMPFILE, Refused::NOREPLACE]] { + let mut command = refusing(&bin, refusals).unwrap(); + command + .args(["assemble", "--create", "--size", "40M", "--manifest", "-"]) + .args([&image, &tree]); + let mut taken = PathBuf::new(); + let out = assemble_meanwhile(command, root, &text, |made| { + fs::write(&theirs, b"theirs").unwrap(); + fs::rename(&theirs, made).unwrap(); + taken = made.to_path_buf(); + }); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{:?}: {}", refusals, stderr); + let failed = format!( + "failed to create {}: {} refers to another file now", + image.display(), + taken.display() + ); + assert!(stderr.contains(&failed), "{:?}: {}", refusals, stderr); + let left_alone = format!("{} refers to another file now, which is left alone", taken.display()); + assert!(stderr.contains(&left_alone), "{:?}: {}", refusals, stderr); + assert!(!image.exists(), "{:?}: {}", refusals, stderr); + assert_eq!(fs::read(&taken).unwrap(), b"theirs"); + fs::remove_file(&taken).unwrap(); + assert_eq!(temporary_names(root), Vec::::new()); + } +} + +/// Where the lock of a new image is refused, another process holds the +/// file: assemble fails and leaves it its name, which it says. Where the +/// lock cannot be had at all, as NFS without its lock manager refuses it +/// with ENOLCK, assemble fails with that and leaves nothing. +#[test] +fn a_new_image_locked_by_another_process_keeps_its_name() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let image = root.join("a.img"); + let assemble = |refusals: &[Refused]| { + let mut command = refusing(&bin, refusals).unwrap(); + command + .args(["assemble", "--create", "--size", "40M"]) + .args([&image, &root.join("tree")]); + command.output().unwrap() + }; + let out = assemble(&[Refused::TMPFILE, Refused::FLOCK]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(!image.exists()); + let left = temporary_names(root); + assert_eq!(left.len(), 1, "{:?}", left); + let used = format!("{} is being used by another process", root.join(&left[0]).display()); + assert!(stderr.contains(&used), "{}", stderr); + fs::remove_file(root.join(&left[0])).unwrap(); + for refusals in [&[Refused::TMPFILE, Refused::NO_LOCKS][..], &[Refused::NO_LOCKS]] { + let out = assemble(refusals); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{:?}: {}", refusals, stderr); + let failed = format!("failed to create {}: failed to lock ", image.display()); + assert!(stderr.contains(&failed), "{:?}: {}", refusals, stderr); + let unlocked = std::io::Error::from_raw_os_error(libc::ENOLCK).to_string(); + assert!(stderr.contains(&unlocked), "{:?}: {}", refusals, stderr); + assert!(!image.exists()); + assert_eq!(temporary_names(root), Vec::::new()); + } +} + +/// Where the file system makes files without a name but refuses to link +/// them, assemble says so at its end, and nothing is left. A link that +/// fails for another reason says only that. +#[test] +fn a_file_system_that_cannot_name_the_image() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + if !makes_unnamed_files(root) { + return eprintln!("skipping: no O_TMPFILE here"); + } + let image = root.join("a.img"); + let refused = format!( + "failed to create {}: the file system made the file but refuses to give it its name", + image.display() + ); + // In the words of the C library, which musl and glibc put differently. + let failed = format!( + "failed to create {}: {}", + image.display(), + std::io::Error::from_raw_os_error(libc::EIO) + ); + for (refusal, says) in [(Refused::LINK, &refused), (Refused::LINK_FAILS, &failed)] { + let mut command = refusing(&bin, &[refusal]).unwrap(); + command + .args(["assemble", "--create", "--size", "40M"]) + .args([&image, &root.join("tree")]); + let out = command.output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!(stderr.contains(says.as_str()), "{}", stderr); + assert!(!image.exists()); + assert_eq!(temporary_names(root), Vec::::new()); + } +} + +/// assemble makes an image in a directory it may search and write to but +/// not read, as one of mode 0300. The image and the manifest written next +/// to it get their names, and the directory, which cannot be opened to +/// sync it, is left as it is. +#[test] +fn assemble_in_a_directory_it_cannot_read() { + use std::os::unix::fs::PermissionsExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let images = root.join("images"); + fs::create_dir(&images).unwrap(); + let (image, written) = (images.join("a.img"), images.join("a.manifest")); + let (a, w) = (image.to_str().unwrap(), written.to_str().unwrap()); + let assemble = ["assemble", "--create", "--size", "40M", "--write-manifest", w, a]; + fs::set_permissions(&images, fs::Permissions::from_mode(0o300)).unwrap(); + let unreadable = fs::read_dir(&images).is_err(); + let out = run(&bin, &[&assemble[..], &[root.join("tree").to_str().unwrap()]].concat()); + fs::set_permissions(&images, fs::Permissions::from_mode(0o755)).unwrap(); + if !unreadable { + eprintln!("the directory can be read here, so it was synced"); + } + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(ok(&bin, &["check", a]).ends_with("; 0 errors, 0 warnings\n")); + assert_eq!( + fs::read_to_string(&written).unwrap(), + ok(&bin, &["describe", "--write-manifest", "-", a]) + ); +} + +/// A file written next to the image that cannot get its name, where the +/// name exists and the rename onto it fails, takes its temporary name with +/// it, also with O_TMPFILE. The image keeps its name. +#[cfg(any(target_arch = "x86_64", target_arch = "x86"))] +#[test] +fn an_output_that_cannot_replace_leaves_no_temporary_name() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + if !makes_unnamed_files(root) { + return eprintln!("skipping: no O_TMPFILE here"); + } + let image = root.join("a.img"); + let written = root.join("written.manifest"); + fs::write(&written, b"old\n").unwrap(); + let mut command = refusing(&bin, &[Refused::RENAME]).unwrap(); + command + .args(["assemble", "--create", "--size", "40M", "--write-manifest"]) + .args([&written, &image, &root.join("tree")]); + let out = command.output().unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + assert!( + stderr.contains(&format!("cannot write {}", written.display())), + "{}", + stderr + ); + assert_eq!(fs::read(&written).unwrap(), b"old\n"); + assert!(ok(&bin, &["check", image.to_str().unwrap()]).ends_with("; 0 errors, 0 warnings\n")); + assert_eq!(temporary_names(root), Vec::::new()); +} + +/// Where O_TMPFILE is refused and the temporary name of an image assemble +/// gives up cannot be removed, a line of its own names the image that +/// stays. Where another file took the temporary name meanwhile, that file +/// stays, and a line says so. +#[test] +fn what_stays_of_a_given_up_image_is_reported() { + use std::os::unix::fs::PermissionsExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + if refusing(&bin, &[]).is_none() { + return eprintln!("skipping: no seccomp filters here"); + } + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let tree = root.join("tree"); + let text = ok(&bin, &["manifest", tree.to_str().unwrap()]); + let empty = root.join("empty"); + fs::create_dir(&empty).unwrap(); + let image = root.join("a.img"); + let assemble = || { + let mut command = refusing(&bin, &[Refused::TMPFILE]).unwrap(); + command + .args(["assemble", "--create", "--size", "40M", "--manifest", "-"]) + .args([&image, &empty]); + command + }; + let chmod = |mode| fs::set_permissions(root, fs::Permissions::from_mode(mode)).unwrap(); + // SAFETY: geteuid() reads the effective user id and nothing else. + if unsafe { libc::geteuid() } != 0 { + let out = assemble_meanwhile(assemble(), root, &text, |_| chmod(0o555)); + chmod(0o755); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + let stays = format!( + "ufat: the unfinished {} stays: failed to remove {}", + image.display(), + root.join(".#a.img").display() + ); + // What failed comes first, then what that left behind. + let failed = stderr.find("failed to open EFI/Linux/linux.efi"); + assert!( + failed.is_some_and(|failed| stderr.find(&stays).is_some_and(|stays| failed < stays)), + "{}", + stderr + ); + let left = temporary_names(root); + assert_eq!(left.len(), 1, "{:?}", left); + fs::remove_file(root.join(&left[0])).unwrap(); + } + let theirs = root.join("theirs"); + let mut taken = PathBuf::new(); + let out = assemble_meanwhile(assemble(), root, &text, |made| { + fs::write(&theirs, b"theirs").unwrap(); + fs::rename(&theirs, made).unwrap(); + taken = made.to_path_buf(); + }); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{}", stderr); + let left_alone = format!("{} refers to another file now, which is left alone", taken.display()); + assert!(stderr.contains(&left_alone), "{}", stderr); + assert_eq!(fs::read(&taken).unwrap(), b"theirs"); + assert!(!image.exists(), "a failed assemble left its image behind"); +} + /// Paths on the host are taken as the bytes they are, UTF-8 or not. Paths /// inside the volume are Unicode, and one that is not UTF-8 is refused. #[test] diff --git a/tests/reference.rs b/tests/reference.rs index f3371f8..289a41b 100644 --- a/tests/reference.rs +++ b/tests/reference.rs @@ -732,12 +732,14 @@ fn fsck_fat_sees_a_failed_assemble() { std::fs::write(manifest.path(), run(&ufat, &["manifest", src], &[])).unwrap(); // b.txt changes after the manifest was written and keeps its size. std::fs::write(tree.path().join("b.txt"), b"SECOND").unwrap(); + // An image that is there already: nothing would be left of one made for + // the assembly. let image = Temp::new(".img"); + std::fs::write(&image.0, b"").unwrap(); let img = image.0.to_str().unwrap(); let out = std::process::Command::new(&ufat) .args([ "assemble", - "--create", "--minimize", "--manifest", manifest.0.to_str().unwrap(), From eda51962de994eb51b409516cfe9f877518f09d4 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 18/19] manifest: record and apply the DOS attributes UAPI.16 has flags for the hidden, system and archive attributes of DOS, flagHidden, flagSystem and flagArchive, recorded by the features flag-hidden, flag-system and flag-archive. FAT has exactly these attributes. It has none of the Linux inode flags the spec has flags for: flagAppendOnly, flagImmutable, flagNoAtime, flagNoCow and flagNoDump. The manifest of a volume records the hidden, system and archive attributes now when it is asked for their features. A flag is written where an entry has the attribute and is cleared where it isn't written. Asked for the inode flags, the manifest lists them and so says that they are cleared everywhere, the way it says that FAT has no symbolic links. An assembly applies the flags. A flag that is set sets the attribute, and a flag the manifest lists in features but an object leaves out clears it, also the archive attribute a new file gets otherwise. Without the feature the attribute stays as it is. A directory gets its attributes too, also one that is there already. The inode flags are ignored. A file gets the read-only attribute as before: from readOnly, or from a mode that gives nobody write permission where the manifest doesn't list read-only. A directory gets it the same way now, a new one and one that is there. Otherwise an object isn't read-only, which is the default the spec gives readOnly when an object is placed. So a directory that is there loses the attribute when its object doesn't say that it's read-only. DosAttributes translates between the attribute byte of an entry and what a file object says about it. with_object() is the one place that applies readOnly and the flags of an object to an entry, for files and directories alike. record_in() is its counterpart and puts readOnly and the flags of an entry into the object the manifest of a volume writes for it. A FileWriter tells which attributes the file it writes gets. Nothing calls set_read_only() of FileWriter and OpenFile anymore, so it goes. find_or_create_dir() takes the attributes of a directory it makes. So a new directory is written once, with its attributes, and nothing copies what make_directory() puts into the entry. An assembly calls set_attributes() for a directory that is there. So set_attributes() now looks at the entry and its directory before it begins writing, as set_times() does, and a call that is refused leaves the volume unmarked. The manifest of --write-manifest has the default features, so it has none of the flags. The README says so. Letting the command line ask for them is for later. While at it, say in the README and in the Varlink documentation that the files a manifest lists as hard links of one file become copies. Signed-off-by: Christian Brauner (Amutable) --- README.md | 17 +- docs/org.uapi-group.FileSystem.varlink | 4 +- docs/varlink.md | 36 ++- src/fat/manifest/assemble.rs | 34 ++- src/fat/manifest/mod.rs | 101 ++++++++- src/fat/manifest/tests.rs | 302 ++++++++++++++++++++++++- src/fat/manifest/volume.rs | 143 ++++++++++-- src/fat/populate.rs | 4 +- src/fat/volume/file.rs | 28 +-- src/fat/volume/mod.rs | 62 +++-- src/fat/volume/tests.rs | 77 +++++-- tests/varlink.rs | 70 +++++- 12 files changed, 761 insertions(+), 117 deletions(-) diff --git a/README.md b/README.md index 57512c5..2ed3038 100644 --- a/README.md +++ b/README.md @@ -137,9 +137,10 @@ The most common ones: - `--write-manifest PATH` writes a UAPI.16 manifest of what the file system holds after `assemble` or `populate`, or of what `describe` finds. It has the size and the SHA-256 hash of every file, says which - files and directories are read-only, and has no times. With `-` as - PATH the manifest goes to standard output, and what the command prints - there otherwise goes to standard error. + files and directories are read-only, and has no times. It records no + hidden, system or archive attributes either. With `-` as PATH the + manifest goes to standard output, and what the command prints there + otherwise goes to standard error. - `--hash sha256` or `--hash sha512` prints the hash of the file system `assemble` wrote. - `--write-hash PATH` writes that hash to PATH instead, or with `-` to @@ -217,6 +218,16 @@ too short for the data, or does not match fails the command. If system is left marked as not cleanly unmounted, with the files that were complete. +FAT has no hard links. Files that a manifest lists as hard links of one +file become copies. `readOnly`, `flagHidden`, `flagSystem` and +`flagArchive` set or clear the read-only, hidden, system and archive +attributes of files and directories, also of directories that are there +already. A flag that the manifest lists in `features` and an object +leaves out clears its attribute. An object without `readOnly` is not +read-only, unless the manifest does not list `read-only` and the object +has a `mode` that gives nobody write permission. The inode flags such as +`flagImmutable` are ignored, since FAT has none. + Signatures in a manifest are recognized but not verified. Verify a signed manifest before you hand it to ufat. diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index 9984491..a4e5647 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -323,8 +323,8 @@ type ManifestSink( # filesystem has no notion of is not recorded and not counted as omitted. # Where the filesystem has none of what a feature describes, the manifest # records that there is none, as for symbolic links, device nodes, hard - # links and extended attributes on vfat. The manifest of vfat records the - # read-only attribute whether read_only is asked for or not. + # links, extended attributes and inode flags on vfat. The manifest of vfat + # records the read-only attribute whether read_only is asked for or not. features: ?[]ManifestFeature ) diff --git a/docs/varlink.md b/docs/varlink.md index fa5e68c..56bd3f6 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -450,6 +450,21 @@ fails with `ContentMismatch` and reason `size`. `sizeBytes` is the size of the file and `expectedSizeBytes` the size it needs. A file that changes while it is read fails with `ContentMismatch` and reason `sourceChanged`. +Files of a manifest that share an `inodeToken` are hard links of one +file. FAT has no hard links, so each of them becomes a copy. + +The flags `flagHidden`, `flagSystem` and `flagArchive` set or clear the +hidden, system and archive attributes of a file or a directory, also of +a directory that is there already. A flag that the manifest lists in +`features` and an object leaves out clears the attribute: with +`flag-archive` listed, a file without `flagArchive` has no archive +attribute, which a new file has otherwise. `readOnly` sets or clears the +read-only attribute the same way. An object without `readOnly` is not +read-only, unless the manifest does not list `read-only` and the object +has a `mode` that gives nobody write permission. FAT has no inode flags, +so `flagAppendOnly`, `flagImmutable`, `flagNoAtime`, `flagNoCow` and +`flagNoDump` are ignored. + Symbolic links below a source directory are followed. They are resolved below that directory and never lead out of it. @@ -502,16 +517,17 @@ A `ManifestSink` has a `fileDescriptor` open for writing and optional `features`, the default set of UAPI.16 is used: `device`, `gid`, `hardlink`, `mode`, `sha256`, `size`, `symlink` and `uid`. -FAT records `size`, `sha256` and `mtime`. FAT has no symbolic links, -device nodes, hard links or extended attributes. When asked for them, -the manifest lists them in `features` and so says that there are none. -The manifest records the read-only attribute whether it is asked for or -not, and lists `read-only` in `features`. An entry with the attribute -carries `readOnly`, and an entry without `readOnly` does not have the -attribute. FAT has no notion of modes, owners and their names, and the -manifest does not record them, nor any of the other features. The root -object declares `"order": "codepoint"`, so the manifest can be given as -content again. +FAT records `size`, `sha256`, `mtime` and the hidden, system and archive +attributes as `flag_hidden`, `flag_system` and `flag_archive`. FAT has +no symbolic links, device nodes, hard links, extended attributes or inode +flags. When asked for them, the manifest lists them in `features` and so +says that there are none. The manifest records the read-only attribute +whether it is asked for or not, and lists `read-only` in `features`. An +entry with the attribute carries `readOnly`, and an entry without +`readOnly` does not have the attribute. FAT has no notion of modes, +owners and their names, and the manifest does not record them, nor any +of the other features. The root object declares `"order": "codepoint"`, +so the manifest can be given as content again. The manifest describes the whole volume, including files that were there before the call. Entries whose names a manifest cannot carry are left out diff --git a/src/fat/manifest/assemble.rs b/src/fat/manifest/assemble.rs index 7f7f830..c55649d 100644 --- a/src/fat/manifest/assemble.rs +++ b/src/fat/manifest/assemble.rs @@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use uapi16::{ContentSource, Directory, ErrorKind, FileObject, Name, Object, OpenError, Order, Reader}; -use super::{path_in_volume, EntryKind, ObjectAction, ObjectTriage}; +use super::{path_in_volume, DosAttributes, EntryKind, ObjectAction, ObjectTriage}; use crate::errno::*; use crate::progress::Progress; use crate::sys; @@ -290,14 +290,18 @@ impl PendingFile<'_> { } /// Creates the file unless it is created: with the object's time, or - /// the assembly's where it gives none, read-only as the object is, and - /// replacing a file of the same name where the assembly says so. + /// the assembly's where it gives none, with the read-only, hidden, + /// system and archive attributes the object gives it, see + /// [`DosAttributes::with_object`], and replacing a file of the same + /// name where the assembly says so. The archive attribute a new file + /// has stays where the manifest says nothing about it. fn create(&mut self) -> Result<()> { if let Some(volume) = self.volume.take() { let time = self.object.inode.mtime().unwrap_or(self.options.default_time); let collision = self.options.flags.name_collision(); let mut writer = volume.create_file(self.path, time, collision)?; - writer.set_read_only(self.object.inode.is_read_only()); + let attributes = DosAttributes::new(writer.attributes()).with_object(self.object); + writer.set_attributes(attributes.settable())?; self.writer = Some(writer); } Ok(()) @@ -375,16 +379,30 @@ impl Assembly<'_> { } /// Creates the directory `object` describes, or gives the one that is - /// there its time. + /// there its time. Either gets the read-only, hidden, system and + /// archive attributes the object gives it, see + /// [`DosAttributes::with_object`]. A new directory has no others, and + /// one that is there keeps the hidden, system and archive attributes + /// whose flags the manifest does not list. fn store_directory(&mut self, object: &FileObject) -> Result<()> { let path = path_in_volume(&object.name); let time = object.inode.mtime().unwrap_or(self.options.default_time); + let made = DosAttributes::NONE.with_object(object); + let collision = self.options.flags.name_collision(); match self .volume - .find_or_create_dir(&path, time, self.options.flags.name_collision())? + .find_or_create_dir(&path, time, made.settable(), collision)? { DirectoryOrigin::Created => {} - DirectoryOrigin::Existing { .. } => self.volume.set_times(&path, time)?, + DirectoryOrigin::Existing { attributes } => { + self.volume.set_times(&path, time)?; + // Only what changes is written. + let existing = DosAttributes::new(attributes); + let attributes = existing.with_object(object); + if attributes != existing { + self.volume.set_attributes(&path, attributes.settable())?; + } + } } self.report.directories += 1; self.observer.progress(&self.report.progress()); @@ -459,7 +477,7 @@ impl Volume { /// `source` finds before the data, such as a missing file, and before /// those in the data, such as a hash that does not match. A directory /// the volume holds under the same name gets the directory object's - /// time. + /// time and attributes. pub fn assemble( &mut self, reader: &mut Reader, diff --git a/src/fat/manifest/mod.rs b/src/fat/manifest/mod.rs index 1d9f45f..c0b266a 100644 --- a/src/fat/manifest/mod.rs +++ b/src/fat/manifest/mod.rs @@ -24,11 +24,13 @@ //! the files next to the manifest, or one stream carrying the contents of //! every file in manifest order. Everything FAT cannot store (symlinks, //! device nodes, FIFOs, sockets) is refused unless the caller asks for it to -//! be skipped. +//! be skipped. `readOnly` and the flags of the hidden, system and archive +//! attributes set and clear those attributes of files and directories. +use crate::dirent::{ATTR_ARCHIVE, ATTR_HIDDEN, ATTR_READ_ONLY, ATTR_SYSTEM}; use crate::errno::*; use crate::path::SEPARATOR; -use crate::volume::MAX_FILE_SIZE; +use crate::volume::{MAX_FILE_SIZE, NO_ATTRIBUTES, SETTABLE_ATTRIBUTES}; use crate::{Detail, Result, UnsupportedKind}; mod assemble; @@ -41,8 +43,8 @@ mod volume; pub use assemble::{AssembleFlags, AssembleObserver, AssembleOptions, AssembleReport, PinnedDirectory, SkipReason}; pub use generate::HostTree; pub use uapi16::{ - ContentSource, Contents, DirectorySource, Features, FileObject, Finalize, InodeType, Location, Name, Object, Order, - Problem, Reader, RootObject, Sha256, Sha256Context, StreamSource, + ContentSource, Contents, DirectorySource, DosFlags, Features, FileObject, Finalize, FlagStates, InodeFlags, + InodeType, Location, Name, Object, Order, Problem, Reader, RootObject, Sha256, Sha256Context, StreamSource, }; pub use volume::WriteReport; @@ -64,6 +66,97 @@ pub(crate) fn path_in_volume_into(name: &str, path: &mut String) { path.push_str(name); } +/// The attribute byte of a FAT directory entry, as far as a manifest has +/// fields for it: `readOnly` is its read-only attribute, see +/// [`uapi16::InodeAttributes::is_read_only`], and `flagHidden`, +/// `flagSystem` and `flagArchive` are its hidden, system and archive +/// attributes. The root directory has no entry and so none of them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct DosAttributes(u8); + +impl DosAttributes { + /// The attributes a manifest has a flag for, each with its flag and + /// the feature that records it. + const FLAGS: [(u8, DosFlags, Features); 3] = [ + (ATTR_HIDDEN, DosFlags::HIDDEN, Features::FLAG_HIDDEN), + (ATTR_SYSTEM, DosFlags::SYSTEM, Features::FLAG_SYSTEM), + (ATTR_ARCHIVE, DosFlags::ARCHIVE, Features::FLAG_ARCHIVE), + ]; + + /// No attribute. + pub(crate) const NONE: DosAttributes = DosAttributes(NO_ATTRIBUTES); + + /// The attributes of the attribute byte `attributes`. + pub(crate) const fn new(attributes: u8) -> DosAttributes { + DosAttributes(attributes) + } + + /// The read-only, hidden, system and archive attributes, the ones a + /// caller sets on an entry. + pub(crate) const fn settable(self) -> u8 { + self.0 & SETTABLE_ATTRIBUTES + } + + /// These attributes as `object` gives them to the entry it describes, + /// a file or a directory: the read-only one as + /// [`uapi16::InodeAttributes::is_read_only`] says, and the hidden, + /// system and archive ones set or cleared where the flags of the + /// object say. Those the flags say nothing about stay as they are. + #[must_use] + pub(crate) fn with_object(self, object: &FileObject) -> DosAttributes { + self.with_read_only(object.inode.is_read_only()) + .with_flags(object.dos_flags) + } + + /// Records these attributes of an entry in `object`, the file object + /// of the entry in a manifest that records `features`: `readOnly` and + /// the flags, each where `features` records it. + pub(crate) fn record_in(self, object: &mut FileObject, features: Features) { + if features.contains(Features::READ_ONLY) { + object.inode.read_only = Some(self.0 & ATTR_READ_ONLY != 0); + } + object.dos_flags = self.flag_states(features); + } + + /// These attributes with the read-only one set or cleared as + /// `read_only` says. + #[must_use] + fn with_read_only(self, read_only: bool) -> DosAttributes { + if read_only { + DosAttributes(self.0 | ATTR_READ_ONLY) + } else { + DosAttributes(self.0 & !ATTR_READ_ONLY) + } + } + + /// These attributes with those set or cleared that the flags `states` + /// say are set or cleared. The others stay as they are. + #[must_use] + fn with_flags(self, states: FlagStates) -> DosAttributes { + let bits = DosAttributes::FLAGS + .into_iter() + .fold(self.0, |bits, (attribute, flag, _)| match states.get(flag) { + Some(true) => bits | attribute, + Some(false) => bits & !attribute, + None => bits, + }); + DosAttributes(bits) + } + + /// The flags of an entry with these attributes, in a manifest that + /// records `features`: set or cleared for every flag whose feature it + /// records, not known for the others. + fn flag_states(self, features: Features) -> FlagStates { + let mut states = FlagStates::default(); + for (attribute, flag, feature) in DosAttributes::FLAGS { + if features.contains(feature) { + states.put(flag, Some(self.0 & attribute != 0)); + } + } + states + } +} + /// What a file object becomes in a FAT volume. /// /// FAT stores regular files and directories. Symbolic links, device diff --git a/src/fat/manifest/tests.rs b/src/fat/manifest/tests.rs index a753ba7..f03b311 100644 --- a/src/fat/manifest/tests.rs +++ b/src/fat/manifest/tests.rs @@ -343,10 +343,7 @@ fn assembles_from_a_stream() { ); let b = v.metadata("/EFI/Linux/b.efi").unwrap(); assert_eq!(b.size, 5000); - assert_eq!( - b.attributes & crate::dirent::ATTR_READ_ONLY, - crate::dirent::ATTR_READ_ONLY - ); + assert_eq!(b.attributes & ATTR_READ_ONLY, ATTR_READ_ONLY); // A directory without a time gets the default time, clamped to the FAT // epoch. assert_eq!( @@ -864,9 +861,10 @@ fn case_collisions_are_refused_unless_replaced() { assert_eq!(names(&v, "/EFI"), ["x", "y"]); } -/// Directories that the volume holds with the times the manifest gives -/// are not written again. So a manifest refused at a file after them, or -/// one of nothing but such directories, leaves the volume as it was. +/// Directories that the volume holds with the times and the attributes +/// the manifest gives are not written again. So a manifest refused at a +/// file after them, or one of nothing but such directories, leaves the +/// volume as it was. #[test] fn directories_that_are_there_with_their_times_write_nothing() { let dirs = [ @@ -893,6 +891,17 @@ fn directories_that_are_there_with_their_times_write_nothing() { let r = assemble_stream(&mut v, &seq(&[ROOT_MTIME, dirs[0], dirs[1], TRAILER]), b"", &keep).unwrap(); assert_eq!(r.directories, 2); assert!(!v.is_writing()); + // Other attributes are written, here the read-only attribute that a + // mode without write permission gives. + let read_only = seq(&[ + ROOT_MTIME, + r#"{"mTimeNSec":1700000000000000000,"mode":365,"name":"EFI","type":"dir"}"#, + TRAILER, + ]); + assemble_stream(&mut v, &read_only, b"", &keep).unwrap(); + assert!(v.is_writing()); + assert_eq!(dos_attributes(&v, "/EFI"), ATTR_READ_ONLY); + v.sync().unwrap(); // Another time is written. let later = seq(&[ ROOT_MTIME, @@ -907,6 +916,45 @@ fn directories_that_are_there_with_their_times_write_nothing() { ); } +/// A directory that is there in a damaged directory, with the time the +/// manifest gives and other attributes, fails before anything is written, +/// so a manifest refused there leaves the volume as it was. +#[test] +fn attributes_in_a_damaged_directory_write_nothing() { + use crate::dirent::DIR_ENTRY_SIZE; + let (img, mut v) = volume(8 << 20, 512, 512); + v.create_dir_all("/d/sub", UNIX_EPOCH + Duration::from_secs(1_700_000_000)) + .unwrap(); + let d = v.metadata("/d").unwrap(); + let layout = *v.layout(); + v.close().unwrap(); + // Garbage behind the end marker of /d, in its slot 5 after ".", ".." + // and "sub": such a directory is read, but not written. + img.device() + .write_at( + layout.cluster_offset(d.first_cluster).unwrap() + 5 * DIR_ENTRY_SIZE as u64, + b"X", + ) + .unwrap(); + let mut v = Volume::open(img.device()).unwrap(); + let bytes = std::fs::read(img.path()).unwrap(); + let m = seq(&[ + concat!( + r#"{"features":["flag-hidden","mtime"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ), + r#"{"mTimeNSec":1700000000000000000,"name":"d","type":"dir"}"#, + r#"{"flagHidden":true,"mTimeNSec":1700000000000000000,"name":"d/sub","type":"dir"}"#, + TRAILER, + ]); + let e = assemble_stream(&mut v, &m, b"", &AssembleOptions::default()).unwrap_err(); + assert_eq!(e.errno(), EUCLEAN); + // The image is read while the volume is open: closing it would put + // back marks a refusal set. + assert!(!v.is_writing()); + assert_eq!(std::fs::read(img.path()).unwrap(), bytes); +} + /// What a volume holds under the same name as an object was there before /// the assembly: a directory takes the entries, a file is replaced only /// with REPLACE. @@ -1395,3 +1443,243 @@ fn assemble_flags() { assert_eq!(format!("{:?}", both), "AssembleFlags(REPLACE | SKIP_UNSUPPORTED)"); assert_eq!(format!("{:?}", AssembleFlags::NONE), "AssembleFlags()"); } + +/// The read-only, hidden, system and archive attributes of the entry at +/// `path`. +fn dos_attributes(v: &Volume, path: &str) -> u8 { + DosAttributes::new(v.metadata(path).unwrap().attributes).settable() +} + +/// The error of reading the manifest `bytes` is an UnlistedFeature at +/// record 1, the object `name`, field `field`. +fn assert_unlisted(bytes: &[u8], name: &str, field: &str) { + let e = read(bytes).unwrap_err(); + assert_eq!( + e.detail(), + Some(&Detail::Manifest { + problem: ManifestProblem::Malformed(Problem::UnlistedFeature), + record: Some(1), + name: Some(name.to_string()), + field: Some(field.to_string()), + }) + ); +} + +#[test] +fn applies_the_dos_attributes() { + // A manifest that records the read-only attribute and the flags of the + // archive, hidden and system attributes: an object without one of them + // has the attribute cleared, also the archive attribute a new file has + // otherwise. + let root = concat!( + r#"{"features":["flag-archive","flag-hidden","flag-system","read-only","sha256","size"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ); + let flagged = seq(&[ + root, + r#"{"flagHidden":true,"flagSystem":true,"name":"d","type":"dir"}"#, + r#"{"flagArchive":true,"name":"d/a","size":0}"#, + r#"{"name":"d/b","size":0}"#, + r#"{"flagHidden":true,"name":"h","readOnly":true,"size":0}"#, + r#"{"name":"plain","type":"dir"}"#, + r#"{"name":"ro","readOnly":true,"type":"dir"}"#, + r#"{"name":"unlocked","readOnly":true,"type":"dir"}"#, + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + assemble_stream(&mut v, &flagged, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/d"), ATTR_HIDDEN | ATTR_SYSTEM); + assert_eq!(dos_attributes(&v, "/d/a"), ATTR_ARCHIVE); + assert_eq!(dos_attributes(&v, "/d/b"), NO_ATTRIBUTES); + assert_eq!(dos_attributes(&v, "/h"), ATTR_HIDDEN | ATTR_READ_ONLY); + assert_eq!(dos_attributes(&v, "/plain"), NO_ATTRIBUTES); + assert_eq!(dos_attributes(&v, "/ro"), ATTR_READ_ONLY); + assert_eq!(dos_attributes(&v, "/unlocked"), ATTR_READ_ONLY); + // Without the features nothing is known about the flags: a new file + // keeps its archive attribute, and a flag that is not listed cannot be + // given at all, nor can readOnly. + let unflagged = seq(&[ROOT, r#"{"name":"f","size":0}"#, TRAILER]); + assemble_stream(&mut v, &unflagged, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/f"), ATTR_ARCHIVE); + let hidden = seq(&[ROOT, r#"{"flagHidden":true,"name":"g","size":0}"#, TRAILER]); + assert_unlisted(&hidden, "g", "flagHidden"); + let read_only = seq(&[ROOT, r#"{"name":"g","readOnly":true,"size":0}"#, TRAILER]); + assert_unlisted(&read_only, "g", "readOnly"); + // A directory that is there takes the attributes of its object as + // well: the flags the manifest lists, and the read-only attribute, + // which is cleared where the object does not say it is read-only. The + // system attribute, which this manifest does not list, stays, and so + // does everything of a directory the manifest does not name. + let cleared = seq(&[ + concat!( + r#"{"features":["flag-hidden"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ), + r#"{"name":"d","type":"dir"}"#, + r#"{"name":"unlocked","type":"dir"}"#, + TRAILER, + ]); + assemble_stream(&mut v, &cleared, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/d"), ATTR_SYSTEM); + assert_eq!(dos_attributes(&v, "/unlocked"), NO_ATTRIBUTES); + assert_eq!(dos_attributes(&v, "/ro"), ATTR_READ_ONLY); + // The manifest of the volume says what the volume holds, for files and + // directories, a read-only one among them. The assembly of it gives the + // same attributes again, and the manifest of that volume is the same. + let features = Features::from_names(["flag-archive", "flag-hidden", "flag-system", "size", "sha256"]).unwrap(); + let mut written = Vec::new(); + v.write_manifest(None, features, &mut written).unwrap(); + let (root, objects) = read(&written).unwrap(); + assert!(root.recorded_features().contains(Features::READ_ONLY)); + let object = |name: &str| objects.iter().find(|o| o.name == name).unwrap(); + let d = object("d").dos_flags; + assert_eq!( + ( + d.get(DosFlags::HIDDEN), + d.get(DosFlags::SYSTEM), + d.get(DosFlags::ARCHIVE) + ), + (Some(false), Some(true), Some(false)) + ); + assert_eq!(object("d/a").dos_flags.get(DosFlags::ARCHIVE), Some(true)); + assert_eq!(object("d/b").dos_flags.get(DosFlags::ARCHIVE), Some(false)); + assert_eq!(object("f").dos_flags.get(DosFlags::ARCHIVE), Some(true)); + assert_eq!(object("h").dos_flags.get(DosFlags::HIDDEN), Some(true)); + assert!(object("h").inode.is_read_only()); + assert!(object("ro").inode.is_read_only()); + assert!(!object("unlocked").inode.is_read_only()); + let (_img, mut again) = volume(8 << 20, 512, 512); + assemble_stream(&mut again, &written, b"", &AssembleOptions::default()).unwrap(); + for path in ["/d", "/d/a", "/d/b", "/f", "/h", "/plain", "/ro", "/unlocked"] { + assert_eq!(dos_attributes(&again, path), dos_attributes(&v, path), "{}", path); + } + let mut rewritten = Vec::new(); + again.write_manifest(None, features, &mut rewritten).unwrap(); + assert_eq!(rewritten, written); + // Without the features no flag is written. + let mut written = Vec::new(); + v.write_manifest(None, Features::DEFAULT, &mut written).unwrap(); + assert!(read(&written) + .unwrap() + .1 + .iter() + .all(|o| o.dos_flags == FlagStates::default())); +} + +/// A mode that gives nobody write permission stands in for readOnly only +/// where the manifest does not list read-only, for files and directories, +/// new ones and those that are there. +#[test] +fn a_mode_stands_in_for_read_only_where_it_is_not_listed() { + // The default features have mode and not read-only. + let unlisted = seq(&[ + ROOT, + r#"{"mode":365,"name":"locked","type":"dir"}"#, + r#"{"mode":292,"name":"locked/f","size":0}"#, + r#"{"mode":420,"name":"locked/g","size":0}"#, + r#"{"mode":493,"name":"open","type":"dir"}"#, + TRAILER, + ]); + let (_img, mut v) = volume(8 << 20, 512, 512); + assemble_stream(&mut v, &unlisted, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/locked"), ATTR_READ_ONLY); + assert_eq!(dos_attributes(&v, "/locked/f"), ATTR_ARCHIVE | ATTR_READ_ONLY); + assert_eq!(dos_attributes(&v, "/locked/g"), ATTR_ARCHIVE); + assert_eq!(dos_attributes(&v, "/open"), NO_ATTRIBUTES); + // Where the manifest lists read-only, an object without readOnly is not + // read-only, whatever its mode says. + let listed = seq(&[ + concat!( + r#"{"features":["mode","read-only","size"],"#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ), + r#"{"mode":365,"name":"locked","type":"dir"}"#, + r#"{"mode":292,"name":"locked/h","size":0}"#, + r#"{"mode":365,"name":"open","type":"dir"}"#, + TRAILER, + ]); + assemble_stream(&mut v, &listed, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/locked"), NO_ATTRIBUTES); + assert_eq!(dos_attributes(&v, "/locked/h"), ATTR_ARCHIVE); + assert_eq!(dos_attributes(&v, "/open"), NO_ATTRIBUTES); + // Without it, the mode decides for a directory that is there too. + let again = seq(&[ROOT, r#"{"mode":365,"name":"open","type":"dir"}"#, TRAILER]); + assemble_stream(&mut v, &again, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(dos_attributes(&v, "/open"), ATTR_READ_ONLY); +} + +#[test] +fn dos_attributes_and_flags() { + use crate::dirent::ATTR_DIRECTORY; + let all = Features::FLAG_HIDDEN | Features::FLAG_SYSTEM | Features::FLAG_ARCHIVE; + let attributes = DosAttributes::new(ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_READ_ONLY); + let states = attributes.flag_states(all); + assert_eq!(states.get(DosFlags::HIDDEN), Some(true)); + assert_eq!(states.get(DosFlags::SYSTEM), Some(false)); + assert_eq!(states.get(DosFlags::ARCHIVE), Some(false)); + // A flag the manifest does not record is not known. + assert_eq!( + attributes.flag_states(Features::FLAG_SYSTEM).get(DosFlags::HIDDEN), + None + ); + assert_eq!(attributes.settable(), ATTR_HIDDEN | ATTR_READ_ONLY); + // Setting flags touches what they state and nothing else. + let mut states = FlagStates::default(); + states.put(DosFlags::HIDDEN, Some(false)); + states.put(DosFlags::ARCHIVE, Some(true)); + let changed = attributes.with_flags(states); + assert_eq!( + changed, + DosAttributes::new(ATTR_DIRECTORY | ATTR_READ_ONLY | ATTR_ARCHIVE) + ); + assert_eq!(changed.with_flags(FlagStates::default()), changed); + assert_eq!( + changed.with_read_only(false), + DosAttributes::new(ATTR_DIRECTORY | ATTR_ARCHIVE) + ); + assert_eq!(changed.with_read_only(true), changed); + // An object gives the read-only attribute as it is read-only or not, + // and the flags it states: one with neither readOnly nor a mode is not + // read-only, and a mode without write permission stands in for + // readOnly. + let mut object = FileObject::new(Name::new("x").unwrap()); + object.dos_flags = states; + assert_eq!( + DosAttributes::NONE.with_object(&object), + DosAttributes::new(ATTR_ARCHIVE) + ); + assert_eq!(attributes.with_object(&object), changed.with_read_only(false)); + object.inode.mode = Mode::new(0o444); + assert_eq!(attributes.with_object(&object), changed); + object.inode.mode = Mode::new(0o644); + assert_eq!(attributes.with_object(&object), changed.with_read_only(false)); + object.inode.mode = None; + object.inode.read_only = Some(true); + assert_eq!(attributes.with_object(&object), changed); + // What the attributes of an entry record in its object, an object + // gives back, for every combination of the four. + let recorded = all | Features::READ_ONLY; + for bits in NO_ATTRIBUTES..=SETTABLE_ATTRIBUTES { + if bits & !SETTABLE_ATTRIBUTES != 0 { + continue; + } + let mut object = FileObject::new(Name::new("x").unwrap()); + DosAttributes::new(ATTR_DIRECTORY | bits).record_in(&mut object, recorded); + assert_eq!( + object.inode.read_only, + Some(bits & ATTR_READ_ONLY != 0), + "{:#04x}", + bits + ); + assert_eq!( + DosAttributes::NONE.with_object(&object), + DosAttributes::new(bits), + "{:#04x}", + bits + ); + } + // Without read-only it records no readOnly. + let mut object = FileObject::new(Name::new("x").unwrap()); + DosAttributes::new(ATTR_READ_ONLY).record_in(&mut object, all); + assert_eq!(object.inode.read_only, None); +} diff --git a/src/fat/manifest/volume.rs b/src/fat/manifest/volume.rs index a6df4ab..5329701 100644 --- a/src/fat/manifest/volume.rs +++ b/src/fat/manifest/volume.rs @@ -6,10 +6,12 @@ //! from Assemble, Populate and Describe, see //! docs/org.uapi-group.FileSystem.varlink. It says what the volume stores //! as the volume stores it: times at FAT's 2 s, the read-only attribute as -//! `readOnly`, and no mode, owner, device numbers, hardlinks or extended -//! attributes, since FAT has no notion of them. A feature the file system -//! has no notion of is not recorded and not counted; what FAT keeps and -//! the manifest could not record is counted in the report's `omitted`. +//! `readOnly`, the hidden, system and archive attributes as flags when +//! asked for, and no mode, owner, device numbers, hardlinks, extended +//! attributes or inode flags, since FAT has no notion of them. A feature +//! the file system has no notion of is not recorded and not counted; what +//! FAT keeps and the manifest could not record is counted in the report's +//! `omitted`. //! //! The order is the specification's code point order: the root object //! first, every directory's entries right after it, sorted by the bytes of @@ -27,8 +29,8 @@ use std::time::SystemTime; use uapi16::{Features, FileObject, Finalize, InodeType, Name, Order, RootObject, Sha256, Sha256Context, Writer}; +use super::DosAttributes; use crate::dir::NameDecoding; -use crate::dirent::ATTR_READ_ONLY; use crate::errno::*; use crate::fat::BitSet; use crate::progress::Progress; @@ -74,9 +76,10 @@ impl Volume { /// the read-only attribute, which every entry has set or cleared. const ALWAYS_RECORDED_FEATURES: Features = Features::READ_ONLY; - /// What the manifest of a FAT volume can record: sizes, hashes, times - /// and the read-only attribute, and that there are no symbolic links, - /// device nodes, hardlinks or extended attributes. + /// What the manifest of a FAT volume can record: sizes, hashes, times, + /// the read-only attribute and the hidden, system and archive + /// attributes, and that there are no symbolic links, device nodes, + /// hardlinks, extended attributes or inode flags. const MANIFEST_FEATURES: Features = Features::SIZE .union(Features::SHA256) .union(Features::MTIME) @@ -84,7 +87,15 @@ impl Volume { .union(Features::SYMLINK) .union(Features::DEVICE) .union(Features::HARDLINK) - .union(Features::USER_XATTR); + .union(Features::USER_XATTR) + .union(Features::FLAG_HIDDEN) + .union(Features::FLAG_SYSTEM) + .union(Features::FLAG_ARCHIVE) + .union(Features::FLAG_APPEND_ONLY) + .union(Features::FLAG_IMMUTABLE) + .union(Features::FLAG_NO_ATIME) + .union(Features::FLAG_NO_COW) + .union(Features::FLAG_NO_DUMP); /// Writes the UAPI.16 manifest of everything the volume holds to `out`: /// the root object, one object per entry, the trailer. `root_time` is @@ -96,15 +107,18 @@ impl Volume { /// `BufWriter` around it. /// /// The manifest records what `features` asks for and FAT has a notion - /// of. Of the features only [`Features::SIZE`], [`Features::SHA256`] - /// and [`Features::MTIME`] add fields. FAT has no symbolic links, - /// device nodes, hardlinks and extended attributes, so the manifest - /// records that it has none of them where `features` asks for them. FAT - /// has no mode, owner or user and group names, so the manifest does not - /// record them. It always records the read-only attribute, which every - /// entry has set or cleared: `readOnly` is written where it is set, and - /// an entry without it is not read-only. The manifest lists its - /// features, and declares the code point ordering its objects are in. + /// of. Of the features only [`Features::SIZE`], [`Features::SHA256`], + /// [`Features::MTIME`] and the flags of the hidden, system and archive + /// attributes add fields: a flag is written on a file or a directory + /// that has the attribute, and cleared where it is not written. FAT has + /// no symbolic links, device nodes, hardlinks, extended attributes and + /// inode flags, so the manifest records that it has none of them where + /// `features` asks for them. FAT has no mode, owner or user and group + /// names, so the manifest does not record them. It always records the + /// read-only attribute, which every entry has set or cleared: + /// `readOnly` is written where it is set, and an entry without it is + /// not read-only. The manifest lists its features, and declares the + /// code point ordering its objects are in. /// /// Names the manifest cannot carry are left out, with everything below /// them. The names the specification reserves in the top level for the @@ -298,9 +312,7 @@ impl Listing<'_, W> { }; // A regular file is what an object without a type is. let mut object = FileObject::new(name); - if md.attributes & ATTR_READ_ONLY != 0 { - object.inode.read_only = Some(true); - } + DosAttributes::new(md.attributes).record_in(&mut object, self.features); if self.features.contains(Features::MTIME) { object.inode.set_mtime(md.modified); } @@ -358,6 +370,7 @@ impl Listing<'_, W> { #[cfg(test)] mod tests { use super::*; + use crate::dirent::ATTR_READ_ONLY; use crate::manifest::HostTree; use crate::populate::CopyOptions; use crate::test_util::{volume, TempDir, TempImage}; @@ -365,17 +378,19 @@ mod tests { use json::Object; use std::os::fd::AsFd; use std::time::{Duration, UNIX_EPOCH}; - use uapi16::{Digest, Object as ManifestObject, Reader, RECORD_SEPARATOR}; + use uapi16::{Digest, DosFlags, InodeFlags, Object as ManifestObject, Reader, RECORD_SEPARATOR}; fn t(secs: u64) -> SystemTime { UNIX_EPOCH + Duration::from_secs(secs) } - /// Creates a file with `data`. + /// Creates a file with `data`, read-only as `read_only` says. fn put(v: &mut Volume, path: &str, data: &[u8], time: SystemTime, read_only: bool) { let mut w = v.create_file(path, time, NameCollision::Fail).unwrap(); w.write_all(data).unwrap(); - w.set_read_only(read_only); + if read_only { + w.set_attributes(w.attributes() | ATTR_READ_ONLY).unwrap(); + } w.finish().unwrap(); } @@ -689,6 +704,86 @@ mod tests { assert_eq!(WrittenManifest::read(&bytes).root.inode.mtime_nsec, None); } + #[test] + fn records_the_flags_and_what_fat_has_none_of() { + let (_img, v) = populated(); + // Asked for everything, the manifest lists what FAT records: + // sizes, hashes, times, the read-only attribute and the other DOS + // attributes, and that it has no symbolic links, device nodes, + // hardlinks, extended attributes and inode flags. Modes, owners and + // their names are not listed. + let (bytes, _) = written(&v, None, Features::ALL); + let m = WrittenManifest::read(&bytes); + assert_eq!( + m.root.features.unwrap().names().collect::>(), + [ + "device", + "flag-append-only", + "flag-archive", + "flag-hidden", + "flag-immutable", + "flag-no-atime", + "flag-no-cow", + "flag-no-dump", + "flag-system", + "hardlink", + "mtime", + "read-only", + "sha256", + "size", + "symlink", + "user-xattr" + ] + ); + // The inode flags are cleared everywhere, the root's too, and the + // DOS attributes are what the entries have: every file the volume + // made has the archive attribute, a directory has not. + let inode_flags = [ + InodeFlags::APPEND_ONLY, + InodeFlags::IMMUTABLE, + InodeFlags::NO_ATIME, + InodeFlags::NO_COW, + InodeFlags::NO_DUMP, + ]; + for flag in inode_flags { + assert_eq!(m.root.inode.flags.get(flag), Some(false), "{:?}", flag); + assert!( + m.entries.iter().all(|e| e.inode.flags.get(flag) == Some(false)), + "{:?}", + flag + ); + } + for e in &m.entries { + let archive = e.inode_type == InodeType::Regular; + assert_eq!(e.dos_flags.get(DosFlags::ARCHIVE), Some(archive), "{}", e.name); + assert_eq!(e.dos_flags.get(DosFlags::HIDDEN), Some(false), "{}", e.name); + assert_eq!(e.dos_flags.get(DosFlags::SYSTEM), Some(false), "{}", e.name); + } + let records = records(&bytes); + assert_eq!( + records[1].0, + format!( + r#"{{"flagArchive":true,"mTimeNSec":1700000000000000000,"name":"B.txt","sha256":"{}","size":7}}"#, + Sha256::digest(b"upper B") + ) + ); + assert_eq!( + records[2].0, + r#"{"mTimeNSec":1700000000000000000,"name":"EFI","type":"dir"}"# + ); + // A read-only file has its other attributes as well. + assert_eq!( + records[4].0, + format!( + concat!( + r#"{{"flagArchive":true,"mTimeNSec":1700000002000000000,"#, + r#""name":"EFI/BOOT/BOOTX64.EFI","readOnly":true,"sha256":"{}","size":5000}}"# + ), + Sha256::digest(&boot_data()) + ) + ); + } + #[test] fn agrees_with_the_host_tree_generator() { let tree = host_tree(); diff --git a/src/fat/populate.rs b/src/fat/populate.rs index 228218b..c814c21 100644 --- a/src/fat/populate.rs +++ b/src/fat/populate.rs @@ -16,7 +16,7 @@ use crate::errno::*; use crate::host::{walk_tree, FromStart, HostEntry, UnnamableEntry}; use crate::progress::Progress; use crate::sys; -use crate::volume::{NameCollision, Volume, MAX_FILE_SIZE}; +use crate::volume::{NameCollision, Volume, MAX_FILE_SIZE, NO_ATTRIBUTES}; use crate::Detail; use crate::{Context, Error, Result}; @@ -255,7 +255,7 @@ impl Volume { let mut visit = |target: &str, entry: &HostEntry| -> Result { if entry.is_dir() { let time = options.times.resolve(source_mtime(&entry.metadata)); - self.find_or_create_dir(target, time, options.name_collision)?; + self.find_or_create_dir(target, time, NO_ATTRIBUTES, options.name_collision)?; report.directories += 1; progress(&report.progress()); Ok(true) diff --git a/src/fat/volume/file.rs b/src/fat/volume/file.rs index ef60dbe..b3136c5 100644 --- a/src/fat/volume/file.rs +++ b/src/fat/volume/file.rs @@ -8,10 +8,11 @@ use std::io::{self, Read, Write}; use std::time::SystemTime; use super::{ - check_attributes, writable, Located, NameCollision, NewEntry, Placement, Volume, MAX_FILE_SIZE, SETTABLE_ATTRIBUTES, + check_attributes, writable, Located, NameCollision, NewEntry, Placement, Volume, MAX_FILE_SIZE, NO_ATTRIBUTES, + SETTABLE_ATTRIBUTES, }; use crate::dir::{DirEntry, Directory}; -use crate::dirent::{RawDirEntry, ATTR_ARCHIVE, ATTR_READ_ONLY}; +use crate::dirent::{RawDirEntry, ATTR_ARCHIVE}; use crate::errno::*; use crate::fat::{Entry, Extent}; use crate::time::FatTimestamp; @@ -474,14 +475,11 @@ impl OpenFile { self.size } - /// Sets or clears the read-only attribute the entry gets when the file - /// is finished. - pub fn set_read_only(&mut self, read_only: bool) { - if read_only { - self.entry.attr |= ATTR_READ_ONLY; - } else { - self.entry.attr &= !ATTR_READ_ONLY; - } + /// The read-only, hidden, system and archive attributes the entry gets + /// when the file is finished: the archive attribute alone for a new + /// file, unless they were set. + pub fn attributes(&self) -> u8 { + self.entry.attr & SETTABLE_ATTRIBUTES } /// Sets the read-only, hidden, system and archive attributes the entry @@ -511,12 +509,10 @@ impl FileWriter<'_> { self.file.as_ref().map_or(0, OpenFile::size) } - /// Sets or clears the read-only attribute the entry gets when the writer - /// is finished. - pub fn set_read_only(&mut self, read_only: bool) { - if let Some(file) = self.file.as_mut() { - file.set_read_only(read_only); - } + /// The attributes the entry gets when the writer is finished, see + /// [`OpenFile::attributes`]. + pub fn attributes(&self) -> u8 { + self.file.as_ref().map_or(NO_ATTRIBUTES, OpenFile::attributes) } /// Sets the attributes the entry gets when the writer is finished, see diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index 7a5eda0..eb9b7f7 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -97,7 +97,8 @@ pub enum NameCollision { /// The directory [`Volume::find_or_create_dir`] makes sure is there. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DirectoryOrigin { - /// The volume had none, and it was made. + /// The volume had none, and it was made with the attributes it was + /// given. Created, /// It was there already. Existing { @@ -265,7 +266,10 @@ fn writable(dir: &Directory) -> Result<()> { /// The attributes a caller may set on an entry: the four DOS bits a file or /// a directory carries. The others say what the entry is and are not for /// setting. -const SETTABLE_ATTRIBUTES: u8 = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE; +pub(crate) const SETTABLE_ATTRIBUTES: u8 = ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE; + +/// None of the [`SETTABLE_ATTRIBUTES`]. +pub(crate) const NO_ATTRIBUTES: u8 = 0; /// Refuses attribute bits outside [`SETTABLE_ATTRIBUTES`]. fn check_attributes(attributes: u8) -> Result<()> { @@ -987,10 +991,18 @@ impl Volume { Ok(()) } - /// Creates the directory `name` in `parent`, writes both and returns the - /// new directory, which matches the disk. On failure `parent` may hold - /// an entry that was never written, which keeps it out of the cache. - fn make_directory(&mut self, parent: &mut Directory, name: &LongName, time: SystemTime) -> Result { + /// Creates the directory `name` in `parent` with the read-only, hidden, + /// system and archive attributes `attributes`, writes both and returns + /// the new directory, which matches the disk. On failure `parent` may + /// hold an entry that was never written, which keeps it out of the + /// cache. + fn make_directory( + &mut self, + parent: &mut Directory, + name: &LongName, + time: SystemTime, + attributes: u8, + ) -> Result { let t = FatTimestamp::from_system_time(time); // place_entry() checks the parent first, also that a cluster is // free for the new directory, so a refusal writes nothing. The @@ -1020,7 +1032,7 @@ impl Volume { data[DIR_ENTRY_SIZE..2 * DIR_ENTRY_SIZE].copy_from_slice(&dotdot.to_bytes()); self.device.write_at(self.layout.cluster_offset(cluster)?, &data)?; let mut entry = RawDirEntry { - attr: ATTR_DIRECTORY, + attr: ATTR_DIRECTORY | attributes, first_cluster: cluster, ..RawDirEntry::default() }; @@ -1051,31 +1063,39 @@ impl Volume { if Self::find(parent, name.as_str()).is_some() { bail!(EEXIST, Detail::Path(path.to_string()), "'{}' exists", path); } - vol.make_directory(parent, &name, time).map_err(|e| e.at_path(path)) + vol.make_directory(parent, &name, time, NO_ATTRIBUTES) + .map_err(|e| e.at_path(path)) })?; self.keep_directory(child); Ok(()) } /// Makes sure there is a directory at `path` for content to go into, as - /// a copy or an assembly finds one or makes one with `time`, and says - /// which. A directory of the same name is that one. One under a name FAT - /// does not tell apart from the last name of `path` is that one with - /// [`NameCollision::Replace`], and a case collision with - /// [`NameCollision::Fail`], which comes before anything else about the - /// entry. A file of that name fails with ENOTDIR. The parent has to - /// exist. Only making a directory writes to the volume, and nothing - /// is written for one that is refused, as with [`Volume::create_dir`]. + /// a copy or an assembly finds one or makes one with `time` and the + /// read-only, hidden, system and archive attributes `attributes`, and + /// says which. A directory of the same name is that one, and it keeps + /// its attributes. One under a name FAT does not tell apart from the + /// last name of `path` is that one with [`NameCollision::Replace`], and + /// a case collision with [`NameCollision::Fail`], which comes before + /// anything else about the entry. A file of that name fails with + /// ENOTDIR. The parent has to exist. Other attribute bits fail with + /// EINVAL, as for [`Volume::set_attributes`]. Only making a directory + /// writes to the volume, and nothing is written for one that is + /// refused, as with [`Volume::create_dir`]. pub fn find_or_create_dir( &mut self, path: &str, time: SystemTime, + attributes: u8, collision: NameCollision, ) -> Result { + check_attributes(attributes)?; let (parent, name) = self.locate_parent(path)?; self.with_directory_mut(parent, |vol, parent| { let Some(existing) = Self::find(parent, name.as_str()) else { - let child = vol.make_directory(parent, &name, time).map_err(|e| e.at_path(path))?; + let child = vol + .make_directory(parent, &name, time, attributes) + .map_err(|e| e.at_path(path))?; vol.keep_directory(child); return Ok(DirectoryOrigin::Created); }; @@ -1131,7 +1151,7 @@ impl Volume { for (i, name) in (there..).zip(&names) { cluster = self.with_directory_mut(cluster, |vol, dir| { let child = vol - .make_directory(dir, name, time) + .make_directory(dir, name, time, NO_ATTRIBUTES) .map_err(|e| e.at_path(&format!("/{}", comps[..=i].join("/"))))?; let first = child.first_cluster(); vol.keep_directory(child); @@ -1204,9 +1224,10 @@ impl Volume { /// again. Any other bit is refused with EINVAL. Works for files and /// directories; the root has no entry and is refused. The entry is /// rewritten in place, so a crash leaves the old attributes or the new. + /// Nothing is written for a call that is refused, also not for an entry + /// in a damaged directory. pub fn set_attributes(&mut self, path: &str, attributes: u8) -> Result<()> { check_attributes(attributes)?; - self.begin_write()?; let Located::Entry { parent, entry } = self.locate(path)? else { bail!( EINVAL, @@ -1214,10 +1235,11 @@ impl Volume { "the root directory has no attributes" ); }; + self.with_directory(parent, |parent| writable(parent))?; let mut raw = entry.short; raw.attr = (raw.attr & !SETTABLE_ATTRIBUTES) | attributes; + self.begin_write()?; self.with_directory(parent, |parent| { - writable(parent)?; parent.set_slot(entry.slot, &raw.to_bytes()); self.save_directory(parent) }) diff --git a/src/fat/volume/tests.rs b/src/fat/volume/tests.rs index 5e707b7..b12dcab 100644 --- a/src/fat/volume/tests.rs +++ b/src/fat/volume/tests.rs @@ -163,19 +163,28 @@ fn replace_and_abort() { ); } -/// find_or_create_dir() makes a directory, or takes the one of the same -/// name, and with NameCollision::Replace one under a name FAT does not -/// tell apart. With NameCollision::Fail that is a case collision, which -/// comes first and names the entry that is there the way the volume spells -/// its path. A file of such a name is ENOTDIR. +/// find_or_create_dir() makes a directory with the attributes it is given, +/// or takes the one of the same name with the attributes it has, and with +/// NameCollision::Replace one under a name FAT does not tell apart. With +/// NameCollision::Fail that is a case collision, which comes first and +/// names the entry that is there the way the volume spells its path. A +/// file of such a name is ENOTDIR, and attribute bits that say what an +/// entry is are EINVAL. #[test] fn directories_are_found_or_made() { let (_img, mut v) = volume(8 << 20, 512, 512); assert_eq!( - v.find_or_create_dir("/EFI", t(0), NameCollision::Fail).unwrap(), + v.find_or_create_dir("/EFI", t(0), ATTR_HIDDEN, NameCollision::Fail) + .unwrap(), DirectoryOrigin::Created ); - v.set_attributes("/EFI", ATTR_HIDDEN).unwrap(); + let efi = v.metadata("/EFI").unwrap(); + assert_eq!(efi.attributes, ATTR_DIRECTORY | ATTR_HIDDEN); + // The dot entries are plain directories. + let dir = v.load_directory(efi.first_cluster).unwrap(); + for e in dir.iter().filter(|e| e.is_dot()) { + assert_eq!(e.short.attr, ATTR_DIRECTORY); + } v.create_file("/EFI/x", t(0), NameCollision::Fail) .unwrap() .finish() @@ -184,14 +193,31 @@ fn directories_are_found_or_made() { attributes: ATTR_DIRECTORY | ATTR_HIDDEN, }; assert_eq!( - v.find_or_create_dir("/EFI", t(0), NameCollision::Fail).unwrap(), + v.find_or_create_dir("/EFI", t(0), ATTR_SYSTEM, NameCollision::Fail) + .unwrap(), existing ); assert_eq!( - v.find_or_create_dir("/efi/", t(0), NameCollision::Replace).unwrap(), + v.find_or_create_dir("/efi/", t(0), NO_ATTRIBUTES, NameCollision::Replace) + .unwrap(), existing ); - let e = v.find_or_create_dir("/efi", t(0), NameCollision::Fail).unwrap_err(); + assert_eq!(v.metadata("/EFI").unwrap().attributes, ATTR_DIRECTORY | ATTR_HIDDEN); + let e = v + .find_or_create_dir("/new", t(0), ATTR_DIRECTORY, NameCollision::Fail) + .unwrap_err(); + assert_eq!( + (e.errno(), e.detail()), + (EINVAL, Some(&Detail::InvalidOption("attributes"))) + ); + // The bits come before the path is looked up. + let e = v + .find_or_create_dir("/missing/d", t(0), ATTR_DIRECTORY, NameCollision::Fail) + .unwrap_err(); + assert_eq!(e.errno(), EINVAL); + let e = v + .find_or_create_dir("/efi", t(0), NO_ATTRIBUTES, NameCollision::Fail) + .unwrap_err(); assert_eq!(e.errno(), EEXIST); assert_eq!( e.detail(), @@ -201,7 +227,9 @@ fn directories_are_found_or_made() { }) ); assert_eq!(e.message(), "'/efi' and '/EFI' are names FAT cannot tell apart"); - let e = v.find_or_create_dir("/efi/X", t(0), NameCollision::Fail).unwrap_err(); + let e = v + .find_or_create_dir("/efi/X", t(0), NO_ATTRIBUTES, NameCollision::Fail) + .unwrap_err(); assert_eq!(e.message(), "'/efi/X' and '/EFI/x' are names FAT cannot tell apart"); for (path, collision, errno) in [ ("/EFI/x", NameCollision::Fail, ENOTDIR), @@ -210,7 +238,7 @@ fn directories_are_found_or_made() { ("/EFI/X", NameCollision::Replace, ENOTDIR), ("/missing/d", NameCollision::Fail, ENOENT), ] { - let e = v.find_or_create_dir(path, t(0), collision).unwrap_err(); + let e = v.find_or_create_dir(path, t(0), NO_ATTRIBUTES, collision).unwrap_err(); assert_eq!(e.errno(), errno, "{} {:?}", path, collision); } assert_eq!(names(&v, "/"), vec!["EFI"]); @@ -712,6 +740,7 @@ fn a_damaged_directory_is_read_but_not_written() { assert_eq!(v.create_dir_all("/d/sub/deeper", t(0)).unwrap_err().errno(), EUCLEAN); assert_eq!(v.set_times("/d/x", t(1_700_000_000)).unwrap_err().errno(), EUCLEAN); assert_eq!(v.set_times("/d", t(1_700_000_000)).unwrap_err().errno(), EUCLEAN); + assert_eq!(v.set_attributes("/d/x", ATTR_HIDDEN).unwrap_err().errno(), EUCLEAN); assert_eq!(std::fs::read(img.path()).unwrap(), bytes); assert!(!v.is_writing()); assert_eq!(v.remove_file("/d/x").unwrap_err().errno(), EUCLEAN); @@ -1216,8 +1245,9 @@ fn the_volume_is_marked_dirty_while_written() { /// What the volume refuses before it would write leaves it as it was: a /// name FAT cannot store, one that is too long, one that is taken or is a /// directory, one FAT does not tell apart from a name that is there, a -/// parent that is missing. Nothing is marked, and the image does not -/// change. A directory that is there is no write either. +/// parent that is missing, attributes that cannot be set. Nothing is +/// marked, and the image does not change. A directory that is there is no +/// write either. #[test] fn refusals_leave_the_volume_unmarked() { let (img, mut v) = volume(1 << 20, 512, 512); @@ -1248,11 +1278,24 @@ fn refusals_leave_the_volume_unmarked() { ), (v.create_file("/F", t(0), NameCollision::Fail).map(drop), EEXIST), (v.create_file("/D", t(0), NameCollision::Fail).map(drop), EEXIST), - (v.find_or_create_dir("/D", t(0), NameCollision::Fail).map(drop), EEXIST), ( - v.find_or_create_dir("/f", t(0), NameCollision::Replace).map(drop), + v.find_or_create_dir("/D", t(0), NO_ATTRIBUTES, NameCollision::Fail) + .map(drop), + EEXIST, + ), + ( + v.find_or_create_dir("/f", t(0), NO_ATTRIBUTES, NameCollision::Replace) + .map(drop), ENOTDIR, ), + ( + v.find_or_create_dir("/new", t(0), ATTR_VOLUME_ID, NameCollision::Fail) + .map(drop), + EINVAL, + ), + (v.set_attributes("/", ATTR_HIDDEN), EINVAL), + (v.set_attributes("/missing", ATTR_HIDDEN), ENOENT), + (v.set_attributes("/f", ATTR_DIRECTORY), EINVAL), ] { assert_eq!(e.unwrap_err().errno(), errno); } @@ -1260,7 +1303,7 @@ fn refusals_leave_the_volume_unmarked() { v.create_dir_all("/d", t(0)).unwrap(); v.create_dir_all("/", t(0)).unwrap(); for (path, collision) in [("/d", NameCollision::Fail), ("/D", NameCollision::Replace)] { - let origin = v.find_or_create_dir(path, t(0), collision).unwrap(); + let origin = v.find_or_create_dir(path, t(0), NO_ATTRIBUTES, collision).unwrap(); assert!( matches!(origin, DirectoryOrigin::Existing { .. }), "{} {:?}", diff --git a/tests/varlink.rs b/tests/varlink.rs index ecb35c7..402960c 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -2036,11 +2036,14 @@ fn manifest_problems_are_those_of_uapi16() { assert_eq!(declared, spelled); } -/// The manifest sink takes the features of UAPI.16, with "_" for "-". A -/// refused manifest names the field of a feature it does not list, and a -/// key it has twice is a reason of its own. +/// The manifest sink takes the features of UAPI.16, with "_" for "-", and +/// records the hidden, system and archive attributes when asked. A +/// manifest given as content sets and clears them. A refused manifest +/// names the field of a feature it does not list, and a key it has twice +/// is a reason of its own. #[test] fn manifests_record_and_apply_features() { + use fat::manifest::{DosFlags, InodeFlags, InodeType}; let _serial = common::serial(); let Some(ufat) = ufat() else { return eprintln!("skipping: no ufat binary"); @@ -2094,6 +2097,14 @@ fn manifests_record_and_apply_features() { listed(&out), [ "device", + "flag-append-only", + "flag-archive", + "flag-hidden", + "flag-immutable", + "flag-no-atime", + "flag-no-cow", + "flag-no-dump", + "flag-system", "hardlink", "mtime", "read-only", @@ -2103,6 +2114,13 @@ fn manifests_record_and_apply_features() { "user-xattr" ] ); + // Every file the volume made has the archive attribute, no directory + // has, and FAT has no inode flags. + for e in &read_manifest(&std::fs::read(&out).unwrap()).entries { + let regular = e.inode_type == InodeType::Regular; + assert_eq!(e.dos_flags.get(DosFlags::ARCHIVE), Some(regular), "{}", e.name); + assert_eq!(e.inode.flags.get(InodeFlags::IMMUTABLE), Some(false), "{}", e.name); + } let out_file = sink(&out); reply(call( &mut c, @@ -2125,10 +2143,54 @@ fn manifests_record_and_apply_features() { ); assert_eq!(e.name, "org.varlink.service.InvalidParameter"); assert_eq!(str_of(&e.parameters, "parameter"), "manifestSink"); + // A manifest that records the flags of the hidden and the archive + // attribute: what an object leaves out is cleared, the archive + // attribute of a new file too. + let root = concat!( + "\x1e{\"features\":[\"flag-archive\",\"flag-hidden\",\"sha256\",\"size\"],", + "\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n" + ); + let trailer = "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"; + let flags = format!( + "{}{}{}{}{}", + root, + "\x1e{\"flagHidden\":true,\"name\":\"hidden\",\"size\":0}\n", + "\x1e{\"flagArchive\":true,\"name\":\"kept\",\"size\":0}\n", + "\x1e{\"name\":\"plain\",\"size\":0}\n", + trailer + ); + let manifest_file = file_with(scratch.path(), "flags", flags.as_bytes()); + let empty = file_with(scratch.path(), "empty", b""); + let (flagged, flagged_img) = fresh_image(); + reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0,"size":41943040},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[flagged_img.as_fd(), manifest_file.as_fd(), empty.as_fd()], + )); + let flagged_ro = ro(flagged.path()); + for (name, attributes) in [ + ("/hidden", vec!["hidden"]), + ("/kept", vec!["archive"]), + ("/plain", vec![]), + ] { + let r = reply(call( + &mut c, + "List", + &format!(r#"{{"image":{{"fileDescriptor":0}},"path":"{}"}}"#, name), + &[flagged_ro.as_fd()], + )); + let entry = object_of(&r, "entry"); + let has = if entry.get("dosAttributes").is_some() { + strings_of(entry, "dosAttributes") + } else { + Vec::new() + }; + assert_eq!(has, attributes, "{}", name); + } // A field of a feature the manifest does not list is named, and a key // twice in an object is duplicateKey. let declared = "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n"; - let trailer = "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"; for (record, reason, field) in [ ( "\x1e{\"mTimeNSec\":1,\"name\":\"a\",\"size\":0}\n", From 0acc72b988467bdac7aa03889fdd313fe859cc62 Mon Sep 17 00:00:00 2001 From: Christian Brauner Date: Wed, 18 Nov 2026 10:38:08 +0100 Subject: [PATCH 19/19] manifest: give the volume the identity its manifest names The root object of a manifest can name the file system it is for. fatSerial is the serial number of a FAT volume, fsUUID the UUID of a file system and fsLabel its label. The spec has a file system made from the manifest take them, and a file system the file objects are put into have them. We ignored all three so far. Now a volume assemble makes from a manifest takes the serial number in fatSerial, or else the one the first eight hex digits of fsUUID give, and the label in fsLabel. A manifest that lists fs-label and has no fsLabel names a volume without a label, and so does an empty fsLabel. An --identifier or a --label that differs from what the manifest names fails with EINVAL and the new FileSystemMismatch, and so do identifier and label over Varlink. The error's FileSystemField names the field of the manifest the value comes from. Volume::assemble() checks that the volume has the serial number and the label the manifest names before it writes anything. So populate, and a caller of the library, can't put a manifest into another volume either. The spec defines the label as what the file system reports, and on FAT that's what blkid shows: the name of the root directory's label entry, where Windows, EDK2 and GRUB read it too. Volume::label() fell back to the copy in the boot sector where there is no such entry, which blkid stopped doing in util-linux 2.33. Now it reads the root directory's entry only. FAT pads a label with spaces, which blkid trims, and stores the blank label and NO NAME for no label. So a label with a space at its end, a blank one and NO NAME can't be represented, and we refuse them in a manifest as the spec asks, with InvalidLabel in assemble and in populate alike: a trailing space with reason invalidCharacter, the blank label and NO NAME with the new reason reserved. Taking "TEST " would make a volume labeled TEST, and the manifest ufat writes of that volume would say TEST, so the label wouldn't survive the round trip. --label still takes such a label, as mkfs.fat -n does. A manifest that names no serial number gives the volume one derived from its bytes, as the spec recommends, instead of one drawn at random or derived from the time stamp: the first four bytes of the SHA-256 hash of the manifest, read big-endian. So its eight hex digits are the first ones sha256sum prints for the manifest. Whoever opens a manifest says what it does with it, and only where that may derive a serial number is the manifest hashed while it is read. populate never derives one, and neither does assemble with --identifier, so neither pays for the hash. assemble stops hashing once the manifest turns out to name a serial number. For a manifest of 1M files, 112 MB, the hash costs assemble 1.2% more instructions, populate none. The hash is there once the reader read the end of the manifest, and not before. So assemble knows the serial number once the content is written, whether the manifest came in a regular file or through a pipe. Volume::set_volume_id() sets it then, first in the backup boot sector and then in the boot sector, while the volume is marked as being written. The crash harness sets a serial number at the start and at the end of its scenario. A plan reads the whole manifest up front and keeps its hash, so with --minimize the manifest is hashed once, and the reply of a plan has the serial number right away. reproducible doesn't need an identifier anymore when the content is a manifest, which names the serial number or has it derived. The manifests ufat writes name the volume as well. The root object always has fatSerial, and fsLabel when the volume has a label, and the manifest lists fat-serial and fs-label, since an object can't carry a field whose feature the manifest doesn't list. So a manifest without fsLabel says that the volume has no label. A volume made from the manifest gets the same serial number and label, and its content goes into that volume and no other. A label that a volume made from the manifest wouldn't get, one with a control character or a Latin-1 character that only other tools write, is left out, and the manifest doesn't list fs-label then. WriteReport names it in omitted_label, apart from the entries in omitted, so the command line says which label it left out instead of counting it as an entry. Varlink's omitted counts it with the entries, since it is metadata the manifest couldn't record. Signed-off-by: Christian Brauner (Amutable) --- README.md | 34 +- docs/org.uapi-group.FileSystem.varlink | 48 ++- docs/varlink.md | 55 ++- src/bin/ufat/cli.rs | 196 +++++++-- src/bin/ufat/service.rs | 221 +++++++--- src/bin/ufat/util.rs | 324 ++++++++++++-- src/fat/boot.rs | 3 + src/fat/error.rs | 62 +++ src/fat/format.rs | 70 ++- src/fat/lib.rs | 4 +- src/fat/manifest/assemble.rs | 10 +- src/fat/manifest/identity.rs | 570 +++++++++++++++++++++++++ src/fat/manifest/mod.rs | 10 + src/fat/manifest/tests.rs | 33 ++ src/fat/manifest/volume.rs | 221 ++++++++-- src/fat/volume/mod.rs | 75 +++- src/fat/volume/tests.rs | 108 +++++ tests/cli.rs | 454 ++++++++++++++++++++ tests/common/mod.rs | 33 ++ tests/crash/crash.rs | 45 +- tests/fixtures.rs | 10 +- tests/varlink.rs | 285 ++++++++++++- 22 files changed, 2660 insertions(+), 211 deletions(-) create mode 100644 src/fat/manifest/identity.rs diff --git a/README.md b/README.md index 2ed3038..d25de49 100644 --- a/README.md +++ b/README.md @@ -138,9 +138,12 @@ The most common ones: system holds after `assemble` or `populate`, or of what `describe` finds. It has the size and the SHA-256 hash of every file, says which files and directories are read-only, and has no times. It records no - hidden, system or archive attributes either. With `-` as PATH the - manifest goes to standard output, and what the command prints there - otherwise goes to standard error. + hidden, system or archive attributes either. Its root object names the + serial number of the file system and its label, or says that it has no + label. A label that a file system made from the manifest would not get, + which only other tools write, is left out, and ufat says so. With `-` + as PATH the manifest goes to standard output, and what the command + prints there otherwise goes to standard error. - `--hash sha256` or `--hash sha512` prints the hash of the file system `assemble` wrote. - `--write-hash PATH` writes that hash to PATH instead, or with `-` to @@ -165,7 +168,9 @@ files: This is the default when `SOURCE_DATE_EPOCH` is set. With `--timestamp` or `SOURCE_DATE_EPOCH`, the volume serial number is -derived from the time stamp and the label instead of drawn at random. +derived from the time stamp and the label instead of drawn at random. A +file system made from a manifest gets its serial number from the +manifest, see "Manifests". ### Manifests @@ -228,6 +233,27 @@ read-only, unless the manifest does not list `read-only` and the object has a `mode` that gives nobody write permission. The inode flags such as `flagImmutable` are ignored, since FAT has none. +The root object of a manifest can name the file system it is for, with +`fatSerial`, or `fsUUID` whose first eight hex digits give a serial +number, and `fsLabel`. A manifest that lists `fs-label` in `features` +and has no `fsLabel` names a file system without a label, and so does +an empty `fsLabel`. `assemble` gives the file system that serial number +and label. `--identifier` and `--label` have to agree with them. Without +a serial number from the manifest or from `--identifier`, the serial +number is the first eight hex digits that `sha256sum` prints for the +manifest. So a manifest gives the file system the same serial number +whether it comes from a file or from standard input, with or without +`--minimize`. +`populate` checks that the file system has the serial number and the +label the manifest names, and fails if it has not. + +The label is the one the file system reports, as `blkid` shows it. FAT +pads a label with spaces, and stores the blank label and `NO NAME` for +no label. So `assemble` and `populate` refuse a manifest whose label +ends with a space, is blank or is `NO NAME`, as they refuse one whose +label FAT cannot store. `--label` takes such a label as `mkfs.fat -n` +does: it pads it with spaces, and a blank one or `NO NAME` is no label. + Signatures in a manifest are recognized but not verified. Verify a signed manifest before you hand it to ufat. diff --git a/docs/org.uapi-group.FileSystem.varlink b/docs/org.uapi-group.FileSystem.varlink index a4e5647..2a9c0e8 100644 --- a/docs/org.uapi-group.FileSystem.varlink +++ b/docs/org.uapi-group.FileSystem.varlink @@ -303,6 +303,16 @@ type ManifestFeature( # plans the content first: it reads the whole manifest before it writes and # needs it in a regular file; a pipe is BadFileDescriptor with reason wrongType # then. In mode plan the manifest is read once, and a pipe will do. +# +# The root file object's fsUUID, fsLabel and fatSerial name the filesystem +# the manifest is for. One that lists fs-label in its features without +# fsLabel names a filesystem without a label. Assemble gives the filesystem +# that UUID or serial number and that label, which FormatOptions.identifier +# and label have to agree with; a manifest that names no UUID or serial number +# gives the filesystem one derived from the manifest's bytes. Populate checks +# them against the filesystem, and a difference is FileSystemMismatch. The +# label is the one the filesystem reports: a label the filesystem cannot store, +# or would report as another one or as none, is InvalidLabel for both. type Manifest( # Index of the descriptor, open read-only fileDescriptor: int, @@ -324,7 +334,8 @@ type ManifestSink( # Where the filesystem has none of what a feature describes, the manifest # records that there is none, as for symbolic links, device nodes, hard # links, extended attributes and inode flags on vfat. The manifest of vfat - # records the read-only attribute whether read_only is asked for or not. + # records the read-only attribute, the serial number and the label whether + # read_only, fat_serial and fs_label are asked for or not. features: ?[]ManifestFeature ) @@ -385,9 +396,14 @@ type VfatOptions( # structs are honoured by their own implementation and refused by every # other. type FormatOptions( - # The volume label, within Capabilities.label + # The volume label, within Capabilities.label. With a manifest as content + # that names one, or names none, it has to agree, and it is the manifest's + # by default label: ?string, - # The UUID or serial, as Capabilities.identifier says; random by default + # The UUID or serial, as Capabilities.identifier says; random by default. + # With a manifest as content that names one, it has to be that one, which + # it is by default. With a manifest that names none, it is derived from + # the manifest by default identifier: ?string, # The filesystem's time: stamped where the filesystem has one creation # time or root time, and the fixed or clamping time for content; the @@ -407,9 +423,10 @@ type FormatOptions( # Make the filesystem the smallest that holds the content, false by # default; Image.size is then the most it may take minimize: ?bool, - # Make the bytes a function of the inputs alone: requires identifier and - # timestampUSec and pins everything else the implementation knows to - # vary (seeds, worker counts, walk order) + # Make the bytes a function of the inputs alone: requires timestampUSec, + # and identifier unless the content is a UAPI.16 manifest, which names + # the identifier or has one derived from it, and pins everything else + # the implementation knows to vary (seeds, worker counts, walk order) reproducible: ?bool, # Features to turn on or off, by the names Capabilities.features lists enableFeatures: ?[]string, @@ -726,8 +743,12 @@ error DirectoryNotEmpty(path: string) type NameProblem(empty, dotComponent, invalidCharacter, leadingSpace, trailingSpaceOrDot, tooLong, caseCollision) error InvalidName(name: string, reason: NameProblem) -# The label does not fit the filesystem's rules. -type LabelProblem(tooLong, invalidCharacter, notSupported) +# The label does not fit the filesystem's rules. The label a manifest names is +# the one the filesystem reports, so one the filesystem would report another +# way is refused as well: on FAT one with a space at its end is +# invalidCharacter, and the blank one and NO NAME, which FAT stores for no +# label, are reserved. +type LabelProblem(tooLong, invalidCharacter, notSupported, reserved) error InvalidLabel(label: string, reason: LabelProblem) # The identifier is not of the kind the filesystem carries or not well formed. @@ -765,6 +786,17 @@ error ContentNotSupported(name: ?string, what: UnsupportedKind, value: ?string) type ValidityProblem(revoked, notYetValid, expired) error EntryNotValid(name: string, reason: ValidityProblem) +# What the root file object of a manifest says about the filesystem does not +# match: the filesystem Populate puts the manifest's content into, or the +# identifier or label given to Assemble. field is the manifest's field the +# expected value comes from: fatSerial, fsUUID or fsLabel. expected is what the +# manifest names, absent where it names no label, and found is the +# filesystem's value or the one given, absent where the filesystem has no +# label. A serial number is written XXXX-XXXX, also the one derived from +# fsUUID. +type FileSystemField(fatSerial, fsUUID, fsLabel) +error FileSystemMismatch(field: FileSystemField, expected: ?string, found: ?string) + # The image is in use: mounted, or claimed by another process. error ImageBusy() diff --git a/docs/varlink.md b/docs/varlink.md index 56bd3f6..e3ea410 100644 --- a/docs/varlink.md +++ b/docs/varlink.md @@ -246,15 +246,15 @@ see "Passing file descriptors". | Option | Meaning | |---|---| -| `label` | The volume label. Fails with `InvalidLabel` when it breaks the label rules. | -| `identifier` | The volume serial number, as `XXXX-XXXX` or eight hex digits. Fails with `InvalidIdentifier` otherwise. Random by default. With `timestampUSec` it is derived from the time stamp and the label. | +| `label` | The volume label. Fails with `InvalidLabel` when it breaks the label rules. With a manifest that names a label, or names none, it is the manifest's by default, and a different one fails with `FileSystemMismatch`. | +| `identifier` | The volume serial number, as `XXXX-XXXX` or eight hex digits. Fails with `InvalidIdentifier` otherwise. Random by default. With `timestampUSec` it is derived from the time stamp and the label. With a manifest, it is the serial number the manifest names, and a different one fails with `FileSystemMismatch`. A manifest that names none gives one derived from its bytes. | | `timestampUSec` | The time stamp. It is the time of the root directory, the time `fixed` and `clamp` use, and the time of manifest entries without one. The current time by default. | | `sectorSize` | 512, 1024, 2048 or 4096. The logical block size of a block device by default, 512 for an image file. It must not be smaller than the device's logical block size. | | `blockSize` | The cluster size: a power of two from the sector size up to 32768, at most 128 sectors. Chosen from the volume size by default, like mkfs.fat does. | | `zero` | Overwrites the whole data area with zeros. Off by default. | | `force` | Formats the image whatever it holds. Off by default. | | `minimize` | Makes the file system as small as the content allows. Off by default. | -| `reproducible` | Makes the image depend on the inputs only. Requires `identifier` and `timestampUSec`, and fails with `NotReproducible` without them. Set `times` to `fixed` or `clamp` to make the file times reproducible too. | +| `reproducible` | Makes the image depend on the inputs only. Requires `timestampUSec`, and `identifier` unless the content is a manifest, and fails with `NotReproducible` without them. A manifest names the serial number or has it derived from its bytes. Set `times` to `fixed` or `clamp` to make the file times of a tree reproducible too. | | `discard` | `false` is accepted. `true` fails with `OperationNotSupported`. | | `enableFeatures`, `disableFeatures` | FAT has none. Setting them fails with `OperationNotSupported`. | | `vfat` | FAT32 options, see below. | @@ -465,6 +465,37 @@ has a `mode` that gives nobody write permission. FAT has no inode flags, so `flagAppendOnly`, `flagImmutable`, `flagNoAtime`, `flagNoCow` and `flagNoDump` are ignored. +The root object of a manifest can name the file system it is for: +`fatSerial` its serial number, `fsUUID` a UUID whose first eight hex +digits give the serial number when there is no `fatSerial`, and +`fsLabel` its label. A manifest that lists `fs-label` in `features` and +has no `fsLabel` names a file system without a label, and so does an +empty `fsLabel`. `Assemble` gives the file system that serial number and +that label. An `identifier` or a `label` in the options that differs +from the manifest's fails with `FileSystemMismatch`, where `found` is the +option's value, and `expected` is absent where the manifest names no +label. When neither the manifest nor the options name a serial number, +it is derived from the manifest: the first four bytes of the SHA-256 hash +of the manifest's bytes. So its digits are the first eight that +`sha256sum` prints for the manifest, and a manifest gives the same serial +number from a regular file and from a pipe, with `minimize` and without. +Mode `plan` reports that serial number too. +`Populate` checks the file system's serial number and label against what +the manifest names and fails with `FileSystemMismatch` when they differ, +where `found` is the file system's value, absent when it has no label. +What the manifest does not name is not checked. Serial numbers are +written `XXXX-XXXX`, the one derived from `fsUUID` as well. + +The label is the one the file system reports, as `blkid` shows it. FAT +pads a label with spaces, and stores the blank label and `NO NAME` for +no label. So for `Assemble` and `Populate` alike a manifest whose label +ends with a space fails with `InvalidLabel` and reason +`invalidCharacter`, and one whose label is blank or `NO NAME` with +reason `reserved`, as one whose label FAT cannot store fails with +`InvalidLabel`. The `label` option takes such a label as `mkfs.fat -n` +does: it is padded with spaces, and a blank one or `NO NAME` is no +label. + Symbolic links below a source directory are followed. They are resolved below that directory and never lead out of it. @@ -527,12 +558,19 @@ entry with the attribute carries `readOnly`, and an entry without `readOnly` does not have the attribute. FAT has no notion of modes, owners and their names, and the manifest does not record them, nor any of the other features. The root object declares `"order": "codepoint"`, -so the manifest can be given as content again. +so the manifest can be given as content again. The manifest names the +volume as well, whether it is asked for or not, and lists `fat-serial` +and `fs-label` in `features`: the root object has its serial number as +`fatSerial`, and its label as `fsLabel` when it has one. So the manifest +given to `Assemble` makes a file system with the same serial number and +label, and given to `Populate` it goes into this volume only. The manifest describes the whole volume, including files that were there before the call. Entries whose names a manifest cannot carry are left out -and counted in `omitted`. Two entries whose names FAT takes for one, such -as `README.TXT` and `readme.txt`, are both listed, each with what it +and counted in `omitted`. So is a label that a file system made from the +manifest would not get, which only other tools write, and the manifest +does not list `fs-label` then. Two entries whose names FAT takes for one, +such as `README.TXT` and `readme.txt`, are both listed, each with what it holds. A damaged volume fails with `Corrupt`. `where` is `directory` when a @@ -639,14 +677,15 @@ The service returns no text. Every error is a name with typed fields. | `IsADirectory` | A file where the file system has a directory: under the same name, as for `Populate` of a single file at a path that is a directory, or with `replace` under a name FAT does not tell apart from the directory's. | `path` | | `DirectoryNotEmpty` | `Remove` of a directory with entries, without `recursive`. | `path` | | `InvalidName` | A name FAT cannot store, or with `replace` false a name FAT does not tell apart from one that exists. | `name`, `reason` (`empty`, `dotComponent`, `invalidCharacter`, `leadingSpace`, `trailingSpaceOrDot`, `tooLong`, `caseCollision`) | -| `InvalidLabel` | A label that breaks the label rules. | `label`, `reason` (`tooLong`, `invalidCharacter`) | +| `InvalidLabel` | A label that breaks the label rules, or the label of a manifest that FAT would report another way. | `label`, `reason` (`tooLong`, `invalidCharacter`, `reserved`) | | `InvalidIdentifier` | A serial number that is not `XXXX-XXXX` or eight hex digits. | `identifier`, `reason` (`malformed`) | | `InvalidManifest` | The manifest cannot be parsed or is inconsistent. A key twice in an object is reason `duplicateKey`. With reason `unlistedFeature`, `field` names the field of a feature the manifest does not list, such as `mTimeNSec`. | `reason`, `record`, `name`, `field` | | `SourceMismatch` | A file the manifest names is missing from the source directory, or not a regular file. | `name`, `reason` (`missing`, `notRegular`) | | `ContentMismatch` | Copied contents do not match the manifest, or a file of the source directory is too short for them or changed while it was read. | `name`, `reason` (`size`, `hash`, `streamEnded`, `sourceChanged`), `sizeBytes`, `expectedSizeBytes` | | `ContentNotSupported` | Content FAT cannot store, with `unsupported` set to `fail`. Contents at an `offset` that come from a stream. | `what` (`offset`, `subManifest`, `inodeType`, or `transport` for contents only at a URL or in an encoding, which `value` names), `name`, `value` | | `EntryNotValid` | A manifest entry is revoked or outside its validity window. | `name`, `reason` (`revoked`, `notYetValid`, `expired`) | -| `NotReproducible` | `reproducible` without `identifier` or `timestampUSec`. | `reason` (`identifierRequired`, `timestampRequired`) | +| `FileSystemMismatch` | The serial number or the label a manifest names is not the one of the file system `Populate` writes to, or not the `identifier` or `label` given to `Assemble`. | `field` (`fatSerial`, `fsUUID`, `fsLabel`), `expected`, `found` | +| `NotReproducible` | `reproducible` without `timestampUSec`, or without `identifier` for content that is not a manifest. | `reason` (`identifierRequired`, `timestampRequired`) | | `ImageBusy` | The block device is mounted or claimed by another process. | none | | `io.systemd.System` | Any other failure, such as an I/O error. | `errno`, `errnoName` | diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index ad85066..a2b4bbb 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -16,7 +16,7 @@ use fat::host; use fat::layout::MIN_SECTOR_SIZE; use fat::manifest::{ AssembleFlags, AssembleObserver, AssembleOptions, DirectorySource, Features, HostTree, Name, PinnedDirectory, - Problem, SkipReason, StreamSource, WriteReport, + Problem, SerialSource, SkipReason, StreamSource, WriteReport, }; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, TimePolicy}; @@ -25,7 +25,10 @@ use fat::volume::{NameCollision, Volume}; use fat::{bail, err, Context, DescriptorProblem, Detail, Error, ManifestProblem, Result}; use crate::service; -use crate::util::{self, Failure, GivenSize, ImageFlags, ManifestInput, ManifestUse, NewVolume, SizeMode, SizeRequest}; +use crate::util::{ + self, Failure, GivenSize, ImageFlags, ManifestInput, ManifestOperation, ManifestUse, NewVolume, PlanOutcome, + SerialDerivation, SizeMode, SizeRequest, +}; const USAGE: &str = "\ Usage: ufat COMMAND [OPTIONS...] ARGS... @@ -65,7 +68,12 @@ Without a SOURCE it creates the directory --path. A SOURCE is a directory tree, or for populate one file. With --manifest the one SOURCE is the tree the manifest describes, where its file contents are read, or - for the contents on standard input, back to back in manifest order. -The manifest has to declare \"order\": \"codepoint\" and be in that order. +The manifest has to declare \"order\": \"codepoint\" and be in that order. Its +fatSerial or fsUUID and its fsLabel, or no fsLabel where it lists fs-label, +give the file system assemble makes its serial number and label, which +--identifier and --label have to agree with and populate checks. Without +fatSerial, fsUUID and --identifier the serial number is the start of the +manifest's SHA-256 hash. assemble --minimize with a SOURCE reads the manifest twice, to plan the file system and to fill it, and needs it in a regular file. Everything else reads it once and takes a pipe: @@ -383,14 +391,19 @@ fn time_policy(args: &Args) -> Result { }) } +/// The serial number `--identifier` gives. +fn identifier(args: &Args) -> Result> { + args.value("identifier").map(str::parse::).transpose() +} + fn format_options(args: &Args) -> Result { let (time, reproducible) = stamp_time(args)?; let mut o = FormatOptions::default(); o.sector_size = args.u32("sector-size")?; o.cluster_size = args.u32("cluster-size")?; o.label = args.value("label").map(str::to_string); - o.volume_id = match args.value("identifier") { - Some(v) => v.parse::()?.0, + o.volume_id = match identifier(args)? { + Some(identifier) => identifier.0, None => util::pick_volume_id(time, o.label.as_deref(), reproducible), }; o.timestamp = Some(time); @@ -480,9 +493,14 @@ impl Sourcing { } /// Opens the manifest `path` names, or the one on standard input for "-", -/// for `manifest_use`, and reads its first record. Returns it with the name -/// messages give it. -fn read_manifest(path: &Path, manifest_use: ManifestUse) -> Result<(ManifestInput, String)> { +/// for `manifest_use`, and reads its first record. Its bytes are hashed +/// where `derivation` says that a serial number may be derived from them. +/// Returns it with the name messages give it. +fn read_manifest( + path: &Path, + manifest_use: ManifestUse, + derivation: SerialDerivation, +) -> Result<(ManifestInput, String)> { let (file, name) = if path == Path::new("-") { // A descriptor of our own, since the reader closes it. let fd = std::io::stdin().as_fd().try_clone_to_owned()?; @@ -490,7 +508,7 @@ fn read_manifest(path: &Path, manifest_use: ManifestUse) -> Result<(ManifestInpu } else { (host::open_file(path)?, path.display().to_string()) }; - let input = ManifestInput::open(file, manifest_use).map_err(|e| match e.detail() { + let input = ManifestInput::open(file, manifest_use, derivation).map_err(|e| match e.detail() { // A manifest, but not one ufat takes. Some(Detail::Manifest { problem: ManifestProblem::Malformed(Problem::NoOrder), @@ -519,8 +537,9 @@ impl Source { /// manifest carries the sizes. `--path` is for trees only. The SOURCE /// arguments and `--path` are checked before anything is opened. The /// manifest is opened last, for what `sourcing` does with it, and its - /// root file object is read. - fn open(args: &Args, paths: &[&Path], sourcing: Sourcing) -> Result { + /// root file object is read. It is hashed where `operation`, the one of + /// the command, may derive a serial number from it. + fn open(args: &Args, paths: &[&Path], sourcing: Sourcing, operation: ManifestOperation) -> Result { let Some(m) = args.path("manifest") else { return match paths { [] => Ok(Source::None), @@ -571,7 +590,8 @@ impl Source { "--manifest takes exactly one SOURCE: the directory the manifest describes, or - for the file contents on standard input" ), }; - let (manifest, name) = read_manifest(m, sourcing.manifest_use())?; + let derivation = operation.serial_derivation(identifier(args)?); + let (manifest, name) = read_manifest(m, sourcing.manifest_use(), derivation)?; Ok(Source::Manifest { name, manifest: Box::new(manifest), @@ -582,7 +602,7 @@ impl Source { /// What can be checked before an image is created, formatted or /// written: under `--unsupported fail`, that the tree can be stored. A /// manifest is checked as it is written. - fn check(&self, args: &Args) -> Result<()> { + fn check(&mut self, args: &Args) -> Result<()> { match self { Source::Tree { .. } if fail_unsupported(args)? => { self.add_to(&mut Plan::new(PlanOptions::new(MIN_SECTOR_SIZE)), args)?; @@ -596,8 +616,8 @@ impl Source { /// returns how many objects of a manifest are left out. Under /// `--unsupported fail` what FAT cannot store of a tree fails the plan. /// The plan reads the manifest once more from its start, so its content - /// can be written after. - fn add_to(&self, plan: &mut Plan, args: &Args) -> Result { + /// can be written after, and keeps its hash where it is wanted. + fn add_to(&mut self, plan: &mut Plan, args: &Args) -> Result { match self { Source::None => Ok(0), Source::Tree { path, dir } => { @@ -611,21 +631,53 @@ impl Source { } Ok(0) } - Source::Manifest { name, manifest, .. } => plan - .add_records(&mut manifest.plan_reader()?, assemble_flags(args)?) - .map_err(about_manifest(name)), + Source::Manifest { name, manifest, .. } => { + manifest.plan(plan, assemble_flags(args)?).map_err(about_manifest(name)) + } } } /// Adds the source to a plan when nothing is written after it, and - /// returns how many objects of a manifest are left out. The manifest is - /// read on from its root file object, so it is read once. - fn into_plan(self, plan: &mut Plan, args: &Args) -> Result { + /// returns what the plan found in a manifest. The manifest is read on + /// from its root file object, so it is read once. + fn into_plan(self, plan: &mut Plan, args: &Args) -> Result { match self { - Source::Manifest { name, mut manifest, .. } => plan - .add_records(manifest.reader(), assemble_flags(args)?) + Source::Manifest { name, manifest, .. } => manifest + .plan_once(plan, assemble_flags(args)?) .map_err(about_manifest(&name)), - source => source.add_to(plan, args), + mut source => source + .add_to(plan, args) + .map(|skipped| PlanOutcome { skipped, digest: None }), + } + } + + /// Reconciles the serial number and the label of a file system made + /// from a manifest with `options` and with `--identifier`, see + /// [`fat::manifest::VolumeIdentity::reconcile`], and returns where the + /// serial number comes from. A manifest is not hashed any further where + /// the serial number is not derived from it. Any other source gives the + /// file system nothing. + fn reconcile(&mut self, options: &mut FormatOptions, args: &Args) -> Result { + let Source::Manifest { name, manifest, .. } = self else { + return Ok(SerialSource::Given); + }; + let serial = manifest + .identity() + .reconcile(options, identifier(args)?) + .map_err(|e| e.context(name.as_str()))?; + if serial == SerialSource::Given { + manifest.stop_hashing(); + } + Ok(serial) + } + + /// Gives `volume`, made from a manifest and filled with its content, + /// the serial number derived from the manifest where `serial` says that + /// it takes that one. + fn stamp_serial(&self, volume: &mut Volume, serial: SerialSource) -> Result<()> { + match self { + Source::Manifest { manifest, .. } => manifest.stamp_serial(volume, serial), + Source::None | Source::Tree { .. } => Ok(()), } } @@ -740,9 +792,22 @@ fn assemble_options(args: &Args) -> Result { }) } -/// Names the manifest `name` in an error that is about it. +/// Names the manifest `name` in an error that is about it: one about the +/// manifest itself, or about the label it names. fn about_manifest(name: &str) -> impl Fn(Error) -> Error + '_ { - move |e| if e.is_manifest() { e.context(name) } else { e } + move |e| match e.detail() { + Some(Detail::Manifest { .. } | Detail::Label { .. }) => e.context(name), + _ => e, + } +} + +/// Names the image `image` in an error about the file system in it: that +/// it is not the one a manifest names. +fn about_file_system(image: &Path) -> impl Fn(Error) -> Error + '_ { + move |e| match e.detail() { + Some(Detail::FileSystemMismatch { .. }) => e.context(image.display()), + _ => e, + } } /// Names the directory `path`, where the contents of a manifest's files @@ -784,8 +849,8 @@ fn write_manifest_to(v: &Volume, out: impl Write, shown: &str) -> Result<()> { const STDOUT_MANIFEST: &str = "the manifest on standard output"; /// Says how many entries the manifest `shown`, of which `report` is what -/// it covers, leaves out, and how many files changed while they were read -/// for it. +/// it covers, leaves out, which label it leaves out, and how many files +/// changed while they were read for it. fn warn_about_manifest(report: &WriteReport, shown: &str) { match report.omitted { 0 => {} @@ -798,6 +863,12 @@ fn warn_about_manifest(report: &WriteReport, shown: &str) { n, shown ), } + if let Some(label) = &report.omitted_label { + eprintln!( + "ufat: the label '{}' is not in {}: a file system made from it would not get that label", + label, shown + ); + } match report.changed { 0 => {} 1 => eprintln!( @@ -854,7 +925,18 @@ fn plan(args: &Args) -> Result<()> { if args.positional.is_empty() && args.path("manifest").is_none() { bail!(errno::EINVAL, "assemble --plan needs a SOURCE or --manifest"); } - let options = format_options(args)?; + // Nothing is written after a plan, so it reads the manifest on from its + // root file object, and the manifest is read once. A pipe will do. The + // plan prints no serial number, so the manifest is not hashed. + let mut source = Source::open( + args, + &args.positional_paths(), + Sourcing::Size, + ManifestOperation::PlanSize, + )?; + let mut options = format_options(args)?; + // The label a manifest gives takes an entry in the root directory. + source.reconcile(&mut options, args)?; let mut plan_options = PlanOptions::from_format_options(&options, None)?; let size = args.size("size")?; let given = match size { @@ -865,10 +947,7 @@ fn plan(args: &Args) -> Result<()> { plan_options.cluster_size = Some(given.layout.cluster_size()); } let mut plan = Plan::new(plan_options); - // Nothing is written after a plan, so it reads the manifest on from its - // root file object, and the manifest is read once. A pipe will do. - let source = Source::open(args, &args.positional_paths(), Sourcing::Size)?; - let skipped = source.into_plan(&mut plan, args)?; + let skipped = source.into_plan(&mut plan, args)?.skipped; if skipped > 0 { eprintln!( "ufat: not counted: {}", @@ -906,7 +985,6 @@ fn plan(args: &Args) -> Result<()> { /// `--fit` directory or what `--manifest` describes has to fit a size /// given, and without one the file system is the smallest that holds it. fn assemble_empty(args: &Args, path: &Path) -> std::result::Result { - let mut options = format_options(args)?; let fit = args.paths("fit"); let target = util::Target { path, @@ -917,7 +995,9 @@ fn assemble_empty(args: &Args, path: &Path) -> std::result::Result std::result::Result source.into_plan(plan, args).map(drop), + Some(source) => { + digest = source.into_plan(plan, args)?.digest; + Ok(()) + } None => bail!(errno::EINVAL, "the content is planned once"), }; - let (new, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add))?; + let (mut new, estimate) = util::fit_and_format(&target, &mut options, SizeRequest::new(mode, &mut add))?; if let Some(estimate) = estimate { report_estimate(args, path, &estimate); } + // The plan read all of a manifest, so a serial number derived from it + // is known now. + let stamped = serial + .derived_serial(digest) + .and_then(|id| id.map_or(Ok(()), |id| new.volume_mut().set_volume_id(id))); + if let Err(e) = stamped { + let leftovers = new.abandon(); + return Err(Failure::new(e, leftovers)); + } Ok(new) } @@ -953,13 +1046,19 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> std::result::Re } else { SizeMode::Given }; - let mut source = Source::open(args, paths, Sourcing::Write(mode.manifest_use()))?; + let mut source = Source::open( + args, + paths, + Sourcing::Write(mode.manifest_use()), + ManifestOperation::Assemble, + )?; // Better to learn about a tree FAT cannot hold before an image is sized // and formatted. With --minimize the plan finds it. if mode == SizeMode::Given { source.check(args)?; } let mut options = format_options(args)?; + let serial = source.reconcile(&mut options, args)?; let target = util::Target { path, offset: args.size("offset")?.unwrap_or(0), @@ -971,7 +1070,13 @@ fn assemble_filled(args: &Args, path: &Path, paths: &[&Path]) -> std::result::Re if let Some(estimate) = estimate { report_estimate(args, path, &estimate); } - if let Err(e) = source.fill(new.volume_mut(), args) { + // A serial number derived from a manifest is known once its content is + // written, whichever way the manifest came: in a regular file, read + // once more for --minimize or not, or through a pipe. + let filled = source + .fill(new.volume_mut(), args) + .and_then(|()| source.stamp_serial(new.volume_mut(), serial)); + if let Err(e) = filled { let leftovers = new.abandon(); return Err(Failure::new(e, leftovers)); } @@ -1196,7 +1301,16 @@ fn cmd_populate(argv: &[OsString]) -> Result<()> { } return v.close(); } - let mut source = Source::open(&args, &paths, Sourcing::Write(ManifestUse::Write))?; + // A manifest goes to the root, so it is the one of the whole file + // system, which has to have the serial number and the label it names. + // The assembly checks that before it writes anything, and no serial + // number is derived, so the manifest is not hashed. + let mut source = Source::open( + &args, + &paths, + Sourcing::Write(ManifestUse::Write), + ManifestOperation::Populate, + )?; source.check(&args)?; let mut v = open_volume(&args, image, Access::ReadWrite)?; if matches!(source, Source::Tree { .. }) { @@ -1211,7 +1325,7 @@ fn cmd_populate(argv: &[OsString]) -> Result<()> { if v.is_writing() { let _ = v.close_unfinished(); } - return Err(e); + return Err(about_file_system(image)(e)); } if let Some(m) = args.path("write-manifest") { write_manifest(&v, m)?; diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index f5bc58a..b0ba7d4 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -29,7 +29,7 @@ use fat::host; use fat::layout::{self, LayoutParams, MAX_CLUSTER_SIZE, MAX_SECTOR_SIZE, MIN_CLUSTERS, MIN_SECTOR_SIZE}; use fat::manifest::{ AssembleFlags, AssembleOptions, AssembleReport, DirectorySource, Features, Finalize, Order, PinnedDirectory, - Sha256Context, StreamSource, WriteReport, + SerialSource, Sha256Context, StreamSource, WriteReport, }; use fat::plan::{Plan, PlanOptions}; use fat::populate::{CopyOptions, CopyReport, TimePolicy}; @@ -41,7 +41,10 @@ use fat::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason, UnsupportedKind}; use json::{Object, Value}; use varlink::{Activation, Call, Connection, Info, Reply, Server, Service}; -use crate::util::{self, ImageFlags, ManifestInput, ManifestUse, SizeMode, SizeRequest}; +use crate::util::{ + self, ImageFlags, ManifestInput, ManifestOperation, ManifestUse, PlanOutcome, SerialDerivation, SizeMode, + SizeRequest, +}; /// The interface description, served verbatim. pub(crate) const INTERFACE: &str = include_str!("../../../docs/org.uapi-group.FileSystem.varlink"); @@ -300,6 +303,12 @@ fn map_error(e: &fat::Error) -> varlink::Error { "EntryNotValid", json::object! { "name" => name.as_str(), "reason" => problem.as_str() }, ), + Detail::FileSystemMismatch { field, expected, found } => { + let mut o = json::object! { "field" => field.as_str() }; + optional(&mut o, "expected", expected.as_deref()); + optional(&mut o, "found", found.as_deref()); + interface_error("FileSystemMismatch", o) + } Detail::InvalidOption(name) => varlink::Error::invalid_parameter(option_name(name)), } } @@ -602,6 +611,27 @@ struct Options { image: ImageFlags, /// `minimize`: how large the file system is made. size_mode: SizeMode, + /// `identifier` as given. + identifier: Option, + /// `reproducible` as given: the image depends on the inputs only. + reproducible: bool, + /// Where the serial number comes from: the options, or a manifest that + /// names none, see [`Options::reconcile`]. + serial: SerialSource, +} + +impl Options { + /// Reconciles the serial number and the label of a file system made + /// from the manifest `manifest`, see + /// [`fat::manifest::VolumeIdentity::reconcile`]. The manifest is not + /// hashed any further where the serial number is not derived from it. + fn reconcile(&mut self, manifest: &mut ManifestInput) -> Outcome<()> { + self.serial = manifest.identity().reconcile(&mut self.format, self.identifier)?; + if self.serial == SerialSource::Given { + manifest.stop_hashing(); + } + Ok(()) + } } fn format_options(p: Option>) -> Outcome { @@ -619,6 +649,9 @@ fn format_options(p: Option>) -> Outcome { time: None, image: ImageFlags::default(), size_mode: SizeMode::Given, + identifier: None, + reproducible: false, + serial: SerialSource::Given, }); }; // What FAT has no notion of is refused, not ignored. @@ -640,17 +673,15 @@ fn format_options(p: Option>) -> Outcome { o.label = p.str("label").map(str::to_string); let time = p.time("timestampUSec")?; o.timestamp = Some(time.unwrap_or_else(util::now)); - let identifier = p.str("identifier"); - if p.bool("reproducible", false) { - if identifier.is_none() { - return Err(Failure::NotReproducible("identifierRequired")); - } - if time.is_none() { - return Err(Failure::NotReproducible("timestampRequired")); - } + // The identifier a reproducible file system needs can also come from a + // manifest, which only the content shows: Assemble checks it then. + let reproducible = p.bool("reproducible", false); + if reproducible && time.is_none() { + return Err(Failure::NotReproducible("timestampRequired")); } + let identifier = p.str("identifier").map(str::parse::).transpose()?; o.volume_id = match identifier { - Some(id) => id.parse::()?.0, + Some(identifier) => identifier.0, None => util::pick_volume_id(time.unwrap_or_else(util::now), o.label.as_deref(), time.is_some()), }; o.zero_data_area = p.bool("zero", false); @@ -679,6 +710,9 @@ fn format_options(p: Option>) -> Outcome { time, image, size_mode, + identifier, + reproducible, + serial: SerialSource::Given, }) } @@ -1015,15 +1049,17 @@ struct Content { impl Content { /// Takes the content's descriptors and reads the root file object of - /// its manifest, which is used as `manifest_use` says. `time` is the - /// content's time, Assemble's `timestampUSec` or Populate's, the - /// current time when neither was given. + /// its manifest, which is used as `manifest_use` says and hashed where + /// `derivation` says that a serial number may be derived from it. + /// `time` is the content's time, Assemble's `timestampUSec` or + /// Populate's, the current time when neither was given. fn take( p: &Params<'_>, c: &mut Connection, time: SystemTime, taker: Taker, manifest_use: ManifestUse, + derivation: SerialDerivation, ) -> Outcome { let source = match fd_param(c, p, "sourceFileDescriptor")? { None => None, @@ -1036,7 +1072,7 @@ impl Content { let fd = required_fd(c, &m, "fileDescriptor").map_err(|_| invalid("manifest"))?; let file = host::passed_stream(fd, "manifest")?; check_validity = m.bool("checkValidity", true); - Some(ManifestInput::open(file, manifest_use).map_err(bad("manifest"))?) + Some(ManifestInput::open(file, manifest_use, derivation).map_err(bad("manifest"))?) } }; let sink = match p.object("manifestSink") { @@ -1111,40 +1147,57 @@ impl Content { self.manifest_mtime.or(self.source_mtime) } + /// The manifest of the content, if it has one. + fn manifest(&self) -> Option<&ManifestInput> { + match &self.fill { + Some(Fill::FromDirectory(m, _) | Fill::FromStream(m, _) | Fill::ManifestOnly(m)) => Some(m), + _ => None, + } + } + + /// The manifest of the content, if it has one, to be read. + fn manifest_mut(&mut self) -> Option<&mut ManifestInput> { + match &mut self.fill { + Some(Fill::FromDirectory(m, _) | Fill::FromStream(m, _) | Fill::ManifestOnly(m)) => Some(m), + _ => None, + } + } + /// Puts the content into `plan`, at the root. Under UnsupportedPolicy /// fail a tree with entries FAT cannot hold is refused here, before - /// anything is written. - fn plan(&self, plan: &mut Plan) -> fat::Result<()> { - match &self.fill { + /// anything is written. A manifest is read once more from its start, + /// and its hash is kept where it is wanted. + fn plan(&mut self, plan: &mut Plan) -> fat::Result<()> { + let (copy, flags) = (self.copy_options(), self.assemble_flags()); + match &mut self.fill { Some(Fill::Tree(dir)) => { - let skipped = plan.add_tree(dir.as_fd(), "/", &self.copy_options())?; + let skipped = plan.add_tree(dir.as_fd(), "/", ©)?; if self.fail_unsupported { refuse_skipped(&skipped)?; } + Ok(()) } Some(Fill::FromDirectory(m, _) | Fill::FromStream(m, _) | Fill::ManifestOnly(m)) => { - plan.add_records(&mut m.plan_reader()?, self.assemble_flags())?; - } - Some(Fill::File(_)) | None => { - return Err( - fat::Error::new(errno::EINVAL, "the content is not a tree or a manifest") - .with(Detail::InvalidOption("content")), - ) + m.plan(plan, flags).map(drop) } + Some(Fill::File(_)) | None => Err(fat::Error::new( + errno::EINVAL, + "the content is not a tree or a manifest", + ) + .with(Detail::InvalidOption("content"))), } - Ok(()) } /// Puts the content into `plan`, for a plan and nothing else. A /// manifest is read on from its root file object, so it is read once. - fn plan_once(self, plan: &mut Plan) -> fat::Result<()> { + /// Returns what the plan found in a manifest. + fn plan_once(mut self, plan: &mut Plan) -> fat::Result> { let flags = self.assemble_flags(); match self.fill { - Some(Fill::FromDirectory(mut m, _) | Fill::FromStream(mut m, _) | Fill::ManifestOnly(mut m)) => { - plan.add_records(m.reader(), flags)?; - Ok(()) + Some(Fill::FromDirectory(m, _) | Fill::FromStream(m, _) | Fill::ManifestOnly(m)) => { + m.plan_once(plan, flags).map(Some) } - _ => self.plan(plan), + _ => self.plan(plan).map(|()| None), } } @@ -1184,6 +1237,7 @@ impl Content { /// Puts the content into the volume at `dest`: the directory a tree goes /// below, the path of one file. A manifest's tree goes below the root. + /// The manifest stays, read to its end. fn write_into(&mut self, v: &mut Volume, dest: &str, progress: &mut dyn FnMut(&Progress)) -> Outcome { let copy = self.copy_options(); let assembly = AssembleOptions { @@ -1195,7 +1249,7 @@ impl Content { None }, }; - Ok(match self.fill.take() { + Ok(match self.fill.as_mut() { None => Counts::default(), Some(Fill::Tree(dir)) => Counts::of_copy(&v.copy_tree_with_progress(dir.as_fd(), dest, ©, progress)?), Some(Fill::File(file)) => Counts { @@ -1203,15 +1257,14 @@ impl Content { bytes: v.copy_file_with_progress(file.as_fd(), dest, ©, progress)?, ..Counts::default() }, - Some(Fill::FromDirectory(mut m, mut source)) => Counts::of_assembly(&v.assemble_with_observer( - m.reader(), - &mut source, - &assembly, - &mut |p: &Progress| progress(p), - )?), - Some(Fill::FromStream(mut m, mut file)) => Counts::of_assembly(&v.assemble_with_observer( + Some(Fill::FromDirectory(m, source)) => { + Counts::of_assembly( + &v.assemble_with_observer(m.reader(), source, &assembly, &mut |p: &Progress| progress(p))?, + ) + } + Some(Fill::FromStream(m, file)) => Counts::of_assembly(&v.assemble_with_observer( m.reader(), - &mut StreamSource::new(&mut file), + &mut StreamSource::new(file), &assembly, &mut |p: &Progress| progress(p), )?), @@ -1262,26 +1315,42 @@ impl FileSystemService { None => None, Some(a) => Some(Hash::new(a).ok_or_else(|| invalid("imageHash"))?), }; - let options = format_options(p.object("options"))?; + let mut options = format_options(p.object("options"))?; let content_time = options.format.timestamp.unwrap_or_else(util::now); // A plan alone reads a manifest once, on from its root file object. // An assembly that sizes the file system to fit reads it for the // plan from its start, and once more while its content is written. - let (taker, manifest_use) = if plan_only { - (Taker::Plan, ManifestUse::PlanOnly) + let (taker, manifest_use, operation) = if plan_only { + (Taker::Plan, ManifestUse::PlanOnly, ManifestOperation::Plan) } else { - (Taker::Assemble, options.size_mode.manifest_use()) + ( + Taker::Assemble, + options.size_mode.manifest_use(), + ManifestOperation::Assemble, + ) }; - let content = match p.object("content") { + let mut content = match p.object("content") { None => None, Some(cp) => { - let content = Content::take(&cp, c, content_time, taker, manifest_use)?; + let derivation = operation.serial_derivation(options.identifier); + let content = Content::take(&cp, c, content_time, taker, manifest_use, derivation)?; if matches!(content.shape(), Shape::Nothing) { return Err(invalid("content")); } Some(content) } }; + // A manifest gives the file system its serial number and its label, + // before it is planned or formatted: the serial number it names, or + // the one derived from it. Without a manifest a reproducible file + // system needs the identifier given. + match content.as_mut().and_then(Content::manifest_mut) { + Some(manifest) => options.reconcile(manifest)?, + None if options.reproducible && options.identifier.is_none() => { + return Err(Failure::NotReproducible("identifierRequired")); + } + None => {} + } match image { None => plan(options, content, c, more), Some(image) => assemble_image(image, options, content, hash, c, more), @@ -1303,7 +1372,7 @@ impl FileSystemService { o.insert("files", w.files); o.insert("directories", w.directories); o.insert("bytes", w.bytes); - o.insert("omitted", w.omitted); + o.insert("omitted", w.omissions()); } Ok(o) } @@ -1316,7 +1385,18 @@ impl FileSystemService { let time = p.time("timestampUSec")?.unwrap_or_else(util::now); let mut content = match p.object("content") { None => None, - Some(cp) => Some(Content::take(&cp, c, time, Taker::Populate, ManifestUse::Write)?), + // A manifest goes into the file system only if that has the + // serial number and the label it names, which the assembly + // checks before it writes anything. No serial number is derived, + // so the manifest is not hashed. + Some(cp) => Some(Content::take( + &cp, + c, + time, + Taker::Populate, + ManifestUse::Write, + ManifestOperation::Populate.serial_derivation(None), + )?), }; // A manifest names its paths from the root. if matches!(content.as_ref().map(Content::shape), Some(Shape::Manifest)) && path != "/" { @@ -1375,7 +1455,7 @@ impl FileSystemService { None => None, Some(sink) => { let mut r = Reporter::start(c, more, "reading", Shown::PhaseOnly)?; - Some(sink.write(&v, &mut |p| r.tick(p))?.omitted) + Some(sink.write(&v, &mut |p| r.tick(p))?.omissions()) } }; v.close()?; @@ -1480,8 +1560,17 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more // for the label, or to carry the root's time (see format_image). plan_options.label = true; let mut plan = Plan::new(plan_options); - if let Some(ct) = content { - ct.plan_once(&mut plan)?; + let planned = match content { + Some(ct) => ct.plan_once(&mut plan)?, + None => None, + }; + // The plan read the whole manifest, so the serial number derived from + // it is the one Assemble would give the file system. + if let Some(id) = options + .serial + .derived_serial(planned.and_then(|planned| planned.digest))? + { + options.format.volume_id = id.0; } let e = plan.estimate()?; e.apply(&mut options.format); @@ -1502,14 +1591,15 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more }) } -/// Fills the file system Assemble formatted: the content copied, the root -/// stamped with its time, the manifest of the result written. Returns the -/// counts when there was content, the entries the manifest left out when -/// one was written, and the description of the volume. +/// Fills the file system Assemble formatted: the content copied, the +/// serial number derived from a manifest given, the root stamped with its +/// time, the manifest of the result written. Returns the counts when there +/// was content, the entries the manifest left out when one was written, and +/// the description of the volume. fn fill_image( volume: &mut Volume, content: Option, - time: Option, + options: &Options, c: &mut Connection, more: bool, ) -> Outcome<(Option, Option, Object)> { @@ -1519,9 +1609,16 @@ fn fill_image( if let Some(mut ct) = content { let mut r = Reporter::start(c, more, "populating", Shown::EntriesAndBytes)?; counts = Some(ct.write_into(volume, "/", &mut |p| r.tick(p))?); + // The hash of a manifest is known once it is read to its end, + // whether it came through a pipe or in a regular file, read once + // more for minimize or not. + if let Some(manifest) = ct.manifest() { + manifest.stamp_serial(volume, options.serial)?; + } content_time = Some(ct.root_time()); sink = ct.sink.take(); } + let time = options.time; // The root directory's time, on the volume label entry: the timestamp // given, else what the content says about its root, else now. Without // content and without a timestamp the format left the entry, if any, @@ -1538,7 +1635,7 @@ fn fill_image( None => None, Some(sink) => { let mut r = Reporter::start(c, more, "reading", Shown::PhaseOnly)?; - Some(sink.write(volume, &mut |p| r.tick(p))?.omitted) + Some(sink.write(volume, &mut |p| r.tick(p))?.omissions()) } }; Ok((counts, omitted, description(volume)?)) @@ -1557,7 +1654,7 @@ fn fill_image( fn assemble_image( image: Image, mut options: Options, - content: Option, + mut content: Option, hash: Option, c: &mut Connection, more: bool, @@ -1576,7 +1673,9 @@ fn assemble_image( (SizeMode::Given, None) => {} (SizeMode::Fit | SizeMode::Minimize, _) => phase(c, more, "planning")?, } - let mut add = |plan: &mut Plan| match &content { + // A serial number derived from a manifest is given when its content is + // written, see fill_image. + let mut add = |plan: &mut Plan| match &mut content { Some(ct) => ct.plan(plan), None => Ok(()), }; @@ -1594,7 +1693,7 @@ fn assemble_image( } phase(c, more, "formatting")?; let mut volume = util::format_sized(device, offset, decision.size, &options.format)?; - let (counts, omitted, description) = match fill_image(&mut volume, content, options.time, c, more) { + let (counts, omitted, description) = match fill_image(&mut volume, content, &options, c, more) { Ok(filled) => filled, Err(e) => { // The file system is left marked as not cleanly unmounted, as diff --git a/src/bin/ufat/util.rs b/src/bin/ufat/util.rs index 7791723..38b6c09 100644 --- a/src/bin/ufat/util.rs +++ b/src/bin/ufat/util.rs @@ -11,10 +11,12 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use fat::device::{Access, Device}; use fat::errno; -use fat::format::FormatOptions; +use fat::format::{FormatOptions, VolumeId}; use fat::host::{LinkError, Linked, Naming, NewFile}; use fat::layout::Layout; -use fat::manifest::{Order, Reader, RootObject}; +use fat::manifest::{ + AssembleFlags, Finalize, Order, Reader, RootObject, SerialSource, Sha256, Sha256Context, VolumeIdentity, +}; use fat::plan::{Estimate, Plan, PlanOptions}; use fat::probe::Prober; use fat::volume::Volume; @@ -25,8 +27,8 @@ pub(crate) fn now() -> SystemTime { SystemTime::now() } -/// The bytes of a manifest, as its reader takes them. -pub(crate) enum ManifestBytes { +/// Where the bytes of a manifest come from. +enum Origin { /// A regular file, read with positional reads from `offset` on. The /// manifest starts at `start` in it. Positional reads leave the /// position of the descriptor alone, so the file can be read once more @@ -36,31 +38,130 @@ pub(crate) enum ManifestBytes { Stream(Box), } +/// The SHA-256 hash of the bytes of a manifest, taken while they are read. +enum ManifestHash { + /// Not wanted, and not taken. + Unwanted, + /// The hash of the bytes read so far. + Partial(Sha256Context), + /// The hash of all of them, once their end was read. + Complete(Sha256), +} + +/// Whether the serial number of a file system may be derived from the +/// bytes of a manifest, see [`SerialSource::Derived`]. The bytes are hashed +/// for it, so a manifest is hashed only where that is possible. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SerialDerivation { + /// A file system is made from the manifest and no serial number was + /// given for it: unless the manifest names one, it is derived. + Possible, + /// None is derived: the manifest goes into a file system that is there, + /// the serial number was given, or nobody asks for it. + Never, +} + +/// What a command or a method of the Varlink service does with the +/// manifest it reads, as far as the serial number of a file system goes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ManifestOperation { + /// It makes a file system from the manifest: `assemble`, Assemble. + Assemble, + /// It plans the file system the manifest makes and reports it with its + /// serial number: Assemble in mode plan. + Plan, + /// It plans the size the content needs and reports nothing else: + /// `assemble --plan`. + PlanSize, + /// It puts the content into a file system that is there: `populate`, + /// Populate. + Populate, +} + +impl ManifestOperation { + /// Whether a serial number may be derived from the manifest where the + /// caller gave the serial number `identifier`, if any: only for a file + /// system the operation makes or reports, and only where none is given. + pub(crate) fn serial_derivation(self, identifier: Option) -> SerialDerivation { + match (self, identifier) { + (ManifestOperation::Assemble | ManifestOperation::Plan, None) => SerialDerivation::Possible, + (ManifestOperation::Assemble | ManifestOperation::Plan, Some(_)) => SerialDerivation::Never, + (ManifestOperation::PlanSize | ManifestOperation::Populate, _) => SerialDerivation::Never, + } + } +} + +/// The bytes of a manifest, as its reader takes them, and their SHA-256 +/// hash while it is wanted. +pub(crate) struct ManifestBytes { + origin: Origin, + hash: ManifestHash, +} + impl ManifestBytes { - /// The bytes of the same manifest once more from its start. None for a - /// pipe, which can be read once only. + /// The bytes from `origin`, hashed where `derivation` says that a + /// serial number may be derived from them. + fn new(origin: Origin, derivation: SerialDerivation) -> ManifestBytes { + let hash = match derivation { + SerialDerivation::Possible => ManifestHash::Partial(Sha256Context::default()), + SerialDerivation::Never => ManifestHash::Unwanted, + }; + ManifestBytes { origin, hash } + } + + /// The bytes of the same manifest once more from its start, hashed if + /// these are. None for a pipe, which can be read once only. fn again(&self) -> io::Result> { - let ManifestBytes::At { file, start, .. } = self else { + let Origin::At { file, start, .. } = &self.origin else { return Ok(None); }; - Ok(Some(ManifestBytes::At { + let derivation = match self.hash { + ManifestHash::Unwanted => SerialDerivation::Never, + ManifestHash::Partial(_) | ManifestHash::Complete(_) => SerialDerivation::Possible, + }; + let origin = Origin::At { file: file.try_clone()?, start: *start, offset: *start, - })) + }; + Ok(Some(ManifestBytes::new(origin, derivation))) + } + + /// Stops hashing the bytes, and drops what was hashed. + fn stop_hashing(&mut self) { + self.hash = ManifestHash::Unwanted; + } + + /// The hash of the whole manifest, once its end was read, where it is + /// wanted. The reader reads the end when it is asked for a record after + /// the last one. + fn digest(&self) -> Option { + match self.hash { + ManifestHash::Complete(digest) => Some(digest), + ManifestHash::Unwanted | ManifestHash::Partial(_) => None, + } } } impl Read for ManifestBytes { fn read(&mut self, buf: &mut [u8]) -> io::Result { - match self { - ManifestBytes::At { file, offset, .. } => { + let read = match &mut self.origin { + Origin::At { file, offset, .. } => { let read = file.read_at(buf, *offset)?; *offset += read as u64; - Ok(read) + read + } + Origin::Stream(stream) => stream.read(buf)?, + }; + if let ManifestHash::Partial(context) = &mut self.hash { + if read > 0 { + context.update(&buf[..read]); + } else if !buf.is_empty() { + let context = std::mem::take(context); + self.hash = ManifestHash::Complete(context.finalize()); } - ManifestBytes::Stream(stream) => stream.read(buf), } + Ok(read) } } @@ -80,6 +181,14 @@ pub(crate) enum ManifestUse { Plan, } +/// What a plan found when it read a manifest. +pub(crate) struct PlanOutcome { + /// The file objects the plan leaves out, see [`Plan::add_records`]. + pub skipped: u64, + /// The hash of the manifest's bytes, where it is wanted. + pub digest: Option, +} + /// A manifest the tool was handed, open for reading. /// /// Its first record, the root file object, is read when it is opened, so a @@ -89,9 +198,16 @@ pub(crate) enum ManifestUse { /// from there. A manifest in a regular file can be read once more before /// the content is written, from its start, for a plan. Standard input and /// pipes can be read once only. +/// +/// Where the serial number of a file system made from the manifest may be +/// derived from its bytes, see [`SerialDerivation`], they are hashed as +/// they are read, until [`ManifestInput::stop_hashing`] says that the hash +/// is not wanted. The first pass that reads all of them gives it. pub(crate) struct ManifestInput { /// The reader the content is taken from. reader: Reader, + /// The hash of the manifest a plan found, which reads it all once more. + digest: Option, } impl ManifestInput { @@ -102,17 +218,18 @@ impl ManifestInput { /// is read through `stream`, such as a [`fat::host::PassedStream`], /// which fails a read when the pipe was made non-blocking during the /// call. The manifest has to declare the code point order, see - /// [`RootObject::require_order`]. - pub(crate) fn open(stream: S, manifest_use: ManifestUse) -> Result + /// [`RootObject::require_order`]. Its bytes are hashed where + /// `derivation` says that a serial number may be derived from them. + pub(crate) fn open(stream: S, manifest_use: ManifestUse, derivation: SerialDerivation) -> Result where S: Read + AsFd + Send + 'static, { // A regular file is read with positional reads, through a // descriptor of its own. let mut file = File::from(stream.as_fd().try_clone_to_owned()?); - let bytes = if file.metadata()?.is_file() { + let origin = if file.metadata()?.is_file() { let start = file.stream_position()?; - ManifestBytes::At { + Origin::At { file, start, offset: start, @@ -120,11 +237,17 @@ impl ManifestInput { } else if manifest_use == ManifestUse::Plan { return Err(ManifestInput::not_plannable()); } else { - ManifestBytes::Stream(Box::new(stream)) + Origin::Stream(Box::new(stream)) }; - let reader = Reader::open(bytes)?; + let reader = Reader::open(ManifestBytes::new(origin, derivation))?; reader.root().require_order(Order::CodePoint)?; - Ok(ManifestInput { reader }) + Ok(ManifestInput { reader, digest: None }) + } + + /// Stops hashing the manifest: no serial number is derived from it. + /// Hashing never starts again. + pub(crate) fn stop_hashing(&mut self) { + self.reader.get_mut().stop_hashing(); } /// The root file object of the manifest. @@ -132,6 +255,11 @@ impl ManifestInput { self.reader.root() } + /// The volume the manifest is for, as its root file object says. + pub(crate) fn identity(&self) -> VolumeIdentity { + VolumeIdentity::from_root(self.root()) + } + /// The error for a manifest that cannot be read once more for a plan: /// its descriptor is not of the type a plan needs. pub(crate) fn not_plannable() -> Error { @@ -146,14 +274,33 @@ impl ManifestInput { ) } - /// A reader of the whole manifest once more, for a plan before the - /// content is written. The reader the content is taken from is left as - /// it is. - pub(crate) fn plan_reader(&self) -> Result> { + /// Reads the whole manifest once more, from its start, into `plan`, + /// for content written with `flags` after it. The reader the content + /// is taken from is left as it is. The hash of the manifest the plan + /// finds is the one of the content, which is not hashed again when it + /// is written. Returns how many file objects the plan leaves out. + pub(crate) fn plan(&mut self, plan: &mut Plan, flags: AssembleFlags) -> Result { let Some(bytes) = self.reader.get_ref().again()? else { return Err(ManifestInput::not_plannable()); }; - Ok(Reader::open(bytes)?) + let mut reader = Reader::open(bytes)?; + let skipped = plan.add_records(&mut reader, flags)?; + self.digest = reader.get_ref().digest(); + if self.digest.is_some() { + self.stop_hashing(); + } + Ok(skipped) + } + + /// Reads the rest of the manifest into `plan` with the reader the + /// content would be taken from, for a plan alone of content written + /// with `flags`. So the manifest is read once. + pub(crate) fn plan_once(mut self, plan: &mut Plan, flags: AssembleFlags) -> Result { + let skipped = plan.add_records(&mut self.reader, flags)?; + Ok(PlanOutcome { + skipped, + digest: self.reader.get_ref().digest(), + }) } /// The reader the content is taken from, which goes on after the root @@ -161,6 +308,18 @@ impl ManifestInput { pub(crate) fn reader(&mut self) -> &mut Reader { &mut self.reader } + + /// Gives `volume`, made from the manifest, the serial number derived + /// from the manifest's bytes where `serial` says that it takes that one. + /// A plan or the reader the content was taken from has read them all by + /// then. + pub(crate) fn stamp_serial(&self, volume: &mut Volume, serial: SerialSource) -> Result<()> { + let digest = self.digest.or_else(|| self.reader.get_ref().digest()); + match serial.derived_serial(digest)? { + Some(id) => volume.set_volume_id(id), + None => Ok(()), + } + } } /// Parses seconds since the epoch, as `--timestamp` and `SOURCE_DATE_EPOCH` @@ -1181,4 +1340,119 @@ mod tests { assert!(path.exists()); assert_eq!(std::fs::read(&written).unwrap(), b"old\n"); } + + /// A manifest of a directory with a file in it. + const MANIFEST: &str = concat!( + "\x1e{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n", + "\x1e{\"name\":\"d\",\"type\":\"dir\"}\n", + "\x1e{\"name\":\"d/f\",\"size\":0}\n", + "\x1e{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n", + ); + + /// A manifest is hashed only where a serial number may be derived from + /// it. populate opens its manifest so that none is, and reads it to its + /// end without hashing it. assemble without a serial number given gets + /// the hash of the whole manifest from the pass that reads all of it: + /// the content, or a plan that reads the manifest once more, after + /// which the content is not hashed again. A serial number that turns + /// out to be given stops the hashing. + #[test] + fn manifests_are_hashed_only_where_a_serial_number_may_be_derived() { + let dir = TempDir::new("hashed"); + let path = dir.0.join("manifest"); + std::fs::write(&path, MANIFEST).unwrap(); + let open = |derivation| ManifestInput::open(File::open(&path).unwrap(), ManifestUse::Plan, derivation).unwrap(); + let unwanted = |input: &ManifestInput| matches!(input.reader.get_ref().hash, ManifestHash::Unwanted); + let read_to_end = |input: &mut ManifestInput| { + for object in input.reader() { + object.unwrap(); + } + }; + let plan = || Plan::new(PlanOptions::new(fat::layout::MIN_SECTOR_SIZE)); + let digest = Sha256::digest(MANIFEST.as_bytes()); + // As populate opens it: never hashed. + let mut input = open(SerialDerivation::Never); + read_to_end(&mut input); + assert!(unwanted(&input)); + assert_eq!(input.reader.get_ref().digest(), None); + // As assemble opens it: hashed, and the hash is there once the end + // of the manifest was read. + let mut input = open(SerialDerivation::Possible); + assert_eq!(input.reader.get_ref().digest(), None); + read_to_end(&mut input); + assert_eq!(input.reader.get_ref().digest(), Some(digest)); + // A serial number given stops it. + let mut input = open(SerialDerivation::Possible); + input.stop_hashing(); + read_to_end(&mut input); + assert!(unwanted(&input)); + // A plan that reads the manifest once more takes the hash, and the + // content is not hashed again. + let mut input = open(SerialDerivation::Possible); + input.plan(&mut plan(), AssembleFlags::NONE).unwrap(); + assert_eq!(input.digest, Some(digest)); + assert!(unwanted(&input)); + read_to_end(&mut input); + assert!(unwanted(&input)); + let mut input = open(SerialDerivation::Never); + input.plan(&mut plan(), AssembleFlags::NONE).unwrap(); + assert_eq!(input.digest, None); + // A plan alone reads the manifest once, hashed where it may be. + let planned = open(SerialDerivation::Possible).plan_once(&mut plan(), AssembleFlags::NONE); + assert_eq!(planned.unwrap().digest, Some(digest)); + let planned = open(SerialDerivation::Never).plan_once(&mut plan(), AssembleFlags::NONE); + assert_eq!(planned.unwrap().digest, None); + // The serial number derived from the hash goes into a volume made + // from the manifest, and none does where it is given. + let image = dir.0.join("a.img"); + File::create(&image).unwrap().set_len(IMAGE_SIZE).unwrap(); + let target = Target { + path: &image, + offset: 0, + size: None, + flags: ImageFlags::FORCE, + }; + let mut new = formatted(&target); + let formatted_id = new.volume().boot_sector().volume_id; + let mut input = open(SerialDerivation::Possible); + read_to_end(&mut input); + input.stamp_serial(new.volume_mut(), SerialSource::Given).unwrap(); + assert_eq!(new.volume().boot_sector().volume_id, formatted_id); + input.stamp_serial(new.volume_mut(), SerialSource::Derived).unwrap(); + let derived = VolumeId::from_manifest_digest(&digest); + assert_eq!(new.volume().boot_sector().volume_id, derived.0); + } + + /// A serial number may be derived only by what makes a file system or + /// reports the one it would make, and only where none is given. So + /// populate and assemble --plan never hash their manifests. + #[test] + fn what_derives_a_serial_number() { + let given = Some(VolumeId(0x1234_abcd)); + for (operation, without, with) in [ + ( + ManifestOperation::Assemble, + SerialDerivation::Possible, + SerialDerivation::Never, + ), + ( + ManifestOperation::Plan, + SerialDerivation::Possible, + SerialDerivation::Never, + ), + ( + ManifestOperation::PlanSize, + SerialDerivation::Never, + SerialDerivation::Never, + ), + ( + ManifestOperation::Populate, + SerialDerivation::Never, + SerialDerivation::Never, + ), + ] { + assert_eq!(operation.serial_derivation(None), without, "{:?}", operation); + assert_eq!(operation.serial_derivation(given), with, "{:?}", operation); + } + } } diff --git a/src/fat/boot.rs b/src/fat/boot.rs index 0c6d8d2..21951bd 100644 --- a/src/fat/boot.rs +++ b/src/fat/boot.rs @@ -38,6 +38,9 @@ pub const OEM_NAME_SIZE: usize = size(field::OEM_NAME); pub const FS_TYPE_FAT32: [u8; size(field::FS_TYPE)] = *b"FAT32 "; /// The label stored when the volume has none. pub const NO_NAME: [u8; LABEL_SIZE] = *b"NO NAME "; +/// What a label is padded with to [`LABEL_SIZE`]. A label is read without +/// the padding at its end. +pub const LABEL_PADDING: u8 = b' '; /// The OEM name the FAT specification recommends for maximum compatibility. pub const OEM_NAME_DEFAULT: [u8; OEM_NAME_SIZE] = *b"MSWIN4.1"; /// The media descriptor for fixed media. diff --git a/src/fat/error.rs b/src/fat/error.rs index bc49d63..50b29d7 100644 --- a/src/fat/error.rs +++ b/src/fat/error.rs @@ -56,9 +56,16 @@ pub enum LabelProblem { TooLong, /// A character a FAT label cannot hold: a non-printable or non-ASCII /// one, one of `* ? . , ; : / \ | + = < > [ ] "`, or a leading space. + /// A label that a volume has to report as it is, such as the one a + /// manifest names, cannot end with a space either, since FAT pads a + /// label with spaces. InvalidCharacter, /// The file system has no label at all; unused on FAT. NotSupported, + /// A label the file system stores for no label: on FAT the blank one + /// and `NO NAME`. Refused where a volume has to report the label as it + /// is, such as the one a manifest names. + Reserved, } impl LabelProblem { @@ -68,6 +75,7 @@ impl LabelProblem { LabelProblem::TooLong => "tooLong", LabelProblem::InvalidCharacter => "invalidCharacter", LabelProblem::NotSupported => "notSupported", + LabelProblem::Reserved => "reserved", } } } @@ -336,6 +344,30 @@ impl ValidityProblem { } } +/// The field of the root file object of a manifest that names the volume +/// the manifest is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileSystemField { + /// `fatSerial`: the volume serial number. + FatSerial, + /// `fsUUID`, whose first eight hex digits give the serial number of a + /// volume whose manifest has no `fatSerial`. + FsUuid, + /// `fsLabel`: the label. + FsLabel, +} + +impl FileSystemField { + /// The field as a manifest and the Varlink interface spell it. + pub fn as_str(self) -> &'static str { + match self { + FileSystemField::FatSerial => "fatSerial", + FileSystemField::FsUuid => "fsUUID", + FileSystemField::FsLabel => "fsLabel", + } + } +} + /// What an error is about, for a program. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Detail { @@ -469,11 +501,41 @@ pub enum Detail { /// Why it is not valid. problem: ValidityProblem, }, + /// What the root file object of a manifest says about the volume does + /// not match the volume the manifest's content goes into, or the serial + /// number or label given for a volume made from the manifest. + FileSystemMismatch { + /// The field of the root file object the expected value comes from. + field: FileSystemField, + /// What the manifest says, None for no label. A serial number is + /// written `XXXX-XXXX`, the one derived from `fsUUID` as well. + expected: Option, + /// What the volume has or what was given, None for no label. + found: Option, + }, /// An option the caller gave is not valid, named as the Varlink /// interface spells it. InvalidOption(&'static str), } +impl Detail { + /// The detail of a volume that is not the one a manifest names in + /// `field`: the manifest says `expected`, and the volume has `found`, + /// or `found` was given for a volume made from the manifest. None is + /// no label. + pub(crate) fn file_system_mismatch( + field: FileSystemField, + expected: Option, + found: Option, + ) -> Detail { + Detail::FileSystemMismatch { + field, + expected: expected.map(|value| value.to_string()), + found: found.map(|value| value.to_string()), + } + } +} + /// An error with an errno value, a description of what went wrong and the /// detail a program acts on. /// diff --git a/src/fat/format.rs b/src/fat/format.rs index d2e6910..4f87fce 100644 --- a/src/fat/format.rs +++ b/src/fat/format.rs @@ -13,7 +13,8 @@ use std::time::SystemTime; use crate::boot::{ default_boot_code, field, valid_media, BootSector, FsInfo, BOOT_JUMP, BOOT_SIGNATURE, DRIVE_NUMBER_FIXED, - EXT_BOOT_SIGNATURE, FS_TYPE_FAT32, LABEL_SIZE, MEDIA_FIXED, NO_NAME, OEM_NAME_DEFAULT, OEM_NAME_SIZE, + EXT_BOOT_SIGNATURE, FS_TYPE_FAT32, LABEL_PADDING, LABEL_SIZE, MEDIA_FIXED, NO_NAME, OEM_NAME_DEFAULT, + OEM_NAME_SIZE, }; use crate::bytes::size; use crate::device::Device; @@ -117,7 +118,7 @@ pub fn encode_label(label: &str) -> Result<[u8; LABEL_SIZE]> { LABEL_SIZE ); } - if bytes.iter().all(|&c| c == b' ') { + if bytes.iter().all(|&c| c == LABEL_PADDING) { return Ok(NO_NAME); } if bytes.first() == Some(&b' ') { @@ -146,11 +147,41 @@ pub fn encode_label(label: &str) -> Result<[u8; LABEL_SIZE]> { ); } } - let mut out = [b' '; LABEL_SIZE]; + let mut out = [LABEL_PADDING; LABEL_SIZE]; out[..bytes.len()].copy_from_slice(bytes); Ok(out) } +/// Validates a label that a volume has to report as it is, such as the one +/// a manifest names, and returns its space padded on-disk form. On top of +/// what [`encode_label`] refuses, that is a label that ends with a space, +/// which FAT reads as padding, and the blank label and `NO NAME`, which FAT +/// stores for no label: they fail with EINVAL and [`Detail::Label`]. +pub fn encode_exact_label(label: &str) -> Result<[u8; LABEL_SIZE]> { + let raw = encode_label(label)?; + let invalid = |problem: LabelProblem| Detail::Label { + label: label.to_string(), + problem, + }; + if raw == NO_NAME { + bail!( + EINVAL, + invalid(LabelProblem::Reserved), + "label '{}' is what FAT stores for no label", + label + ); + } + if label.ends_with(char::from(LABEL_PADDING)) { + bail!( + EINVAL, + invalid(LabelProblem::InvalidCharacter), + "label '{}' ends with a space, which FAT does not keep", + label + ); + } + Ok(raw) +} + /// The label `raw` as text, without its padding. The code page is /// unknown, so bytes outside ASCII are taken as Latin-1. pub fn decode_label(raw: &[u8; LABEL_SIZE]) -> String { @@ -516,6 +547,39 @@ mod tests { } } + /// A label a volume has to report as it is: what FAT reads back as + /// another label or as none is refused as well. + #[test] + fn exact_labels() { + for label in ["ESP", "A B", "no name"] { + let raw = encode_exact_label(label).unwrap(); + assert_eq!(raw, encode_label(label).unwrap()); + assert_eq!(decode_label(&raw), label); + } + for (label, problem) in [ + ("ESP ", LabelProblem::InvalidCharacter), + ("A B ", LabelProblem::InvalidCharacter), + (" ", LabelProblem::Reserved), + (" ", LabelProblem::Reserved), + ("NO NAME", LabelProblem::Reserved), + ("NO NAME ", LabelProblem::Reserved), + ("TOOLONGLABEL", LabelProblem::TooLong), + (" X", LabelProblem::InvalidCharacter), + ] { + let e = encode_exact_label(label).unwrap_err(); + assert_eq!(e.errno(), EINVAL, "{:?}", label); + assert_eq!( + e.detail(), + Some(&Detail::Label { + label: label.into(), + problem, + }), + "{:?}", + label + ); + } + } + #[test] fn oem_names() { assert_eq!(encode_oem_name("mkfs.fat").unwrap(), *b"mkfs.fat"); diff --git a/src/fat/lib.rs b/src/fat/lib.rs index 17eeca6..44355f7 100644 --- a/src/fat/lib.rs +++ b/src/fat/lib.rs @@ -19,8 +19,8 @@ compile_error!("ufat supports Linux only"); #[macro_use] mod error; pub use error::{ - ContentProblem, Context, CorruptPlace, DescriptorProblem, Detail, Error, IdentifierProblem, LabelProblem, - ManifestProblem, NameProblem, NoSpaceReason, NotFat32Reason, Result, SourceProblem, UnsupportedKind, + ContentProblem, Context, CorruptPlace, DescriptorProblem, Detail, Error, FileSystemField, IdentifierProblem, + LabelProblem, ManifestProblem, NameProblem, NoSpaceReason, NotFat32Reason, Result, SourceProblem, UnsupportedKind, ValidityProblem, }; diff --git a/src/fat/manifest/assemble.rs b/src/fat/manifest/assemble.rs index c55649d..484cceb 100644 --- a/src/fat/manifest/assemble.rs +++ b/src/fat/manifest/assemble.rs @@ -12,7 +12,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use uapi16::{ContentSource, Directory, ErrorKind, FileObject, Name, Object, OpenError, Order, Reader}; -use super::{path_in_volume, DosAttributes, EntryKind, ObjectAction, ObjectTriage}; +use super::{path_in_volume, DosAttributes, EntryKind, ObjectAction, ObjectTriage, VolumeIdentity}; use crate::errno::*; use crate::progress::Progress; use crate::sys; @@ -478,6 +478,13 @@ impl Volume { /// those in the data, such as a hash that does not match. A directory /// the volume holds under the same name gets the directory object's /// time and attributes. + /// + /// A manifest whose root file object names the file system it is for + /// goes into that one only, see [`VolumeIdentity::check`]: any other + /// volume fails with EINVAL and [`Detail::FileSystemMismatch`] before + /// anything is written. + /// + /// [`Detail::FileSystemMismatch`]: crate::Detail::FileSystemMismatch pub fn assemble( &mut self, reader: &mut Reader, @@ -501,6 +508,7 @@ impl Volume { if let Some(now) = options.now_usec { reader.root().check_validity(now)?; } + VolumeIdentity::from_root(reader.root()).check(self)?; let mut assembly = Assembly { volume: self, source, diff --git a/src/fat/manifest/identity.rs b/src/fat/manifest/identity.rs new file mode 100644 index 0000000..b164414 --- /dev/null +++ b/src/fat/manifest/identity.rs @@ -0,0 +1,570 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! What the root file object of a manifest says about the volume its file +//! objects go into: the volume serial number and the label. A volume made +//! from the manifest takes them, and a volume the manifest's content is put +//! into has to have them. + +use uapi16::{FatSerial, Features, RootObject, Sha256}; + +use crate::boot::{LABEL_SIZE, NO_NAME}; +use crate::errno::*; +use crate::format::{encode_exact_label, encode_label, FormatOptions, VolumeId}; +use crate::volume::Volume; +use crate::{Detail, FileSystemField, Result}; + +/// Where the serial number of a volume made from a manifest comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SerialSource { + /// The manifest names it, or the caller gave it. It is in the format + /// options. + Given, + /// Neither: it is derived from the bytes of the manifest once they are + /// read, see [`VolumeId::from_manifest_digest`]. + Derived, +} + +impl SerialSource { + /// The serial number a volume made from the manifest takes from + /// `digest`, the SHA-256 hash of the manifest's bytes: the one derived + /// from it for [`SerialSource::Derived`], and None where the serial + /// number is given. A derived one needs the hash of the whole manifest, + /// and without it fails with EIO. + pub fn derived_serial(self, digest: Option) -> Result> { + match (self, digest) { + (SerialSource::Given, _) => Ok(None), + (SerialSource::Derived, Some(digest)) => Ok(Some(VolumeId::from_manifest_digest(&digest))), + (SerialSource::Derived, None) => bail!( + EIO, + "the manifest was not read to its end, so no serial number is derived from it" + ), + } + } +} + +/// What the root file object of a manifest says about the label of the +/// volume it is for. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum ManifestLabel { + /// Nothing: the manifest has no `fsLabel` and does not list the + /// feature `fs-label`. + #[default] + Unrecorded, + /// The volume has no label: the manifest has an empty `fsLabel`, or + /// none and lists `fs-label`. + Unlabeled, + /// The volume has the label `fsLabel` names. + Labeled(String), +} + +impl ManifestLabel { + /// The label the manifest names, None for no label and where it says + /// nothing. + pub fn text(&self) -> Option<&str> { + match self { + ManifestLabel::Labeled(label) => Some(label), + ManifestLabel::Unrecorded | ManifestLabel::Unlabeled => None, + } + } + + /// The label field of a volume that has the label the manifest names: + /// [`NO_NAME`] for no label, and None where the manifest says nothing. + /// The label is what the volume reports, so one that FAT cannot store + /// or would report another way fails, see [`encode_exact_label`]. + fn stored(&self) -> Result> { + match self { + ManifestLabel::Unrecorded => Ok(None), + ManifestLabel::Unlabeled => Ok(Some(NO_NAME)), + ManifestLabel::Labeled(label) => encode_exact_label(label).map(Some), + } + } +} + +/// The FAT volume a manifest is for, as its root file object says: the +/// serial number from `fatSerial`, or else the one derived from `fsUUID`, +/// and the label from `fsLabel` and the feature `fs-label`. A manifest +/// without them is for any volume. +/// +/// The specification has a file system made from a manifest take them, and +/// a file system the file objects are placed in have them. The label is +/// what the file system reports, as blkid shows it. A manifest that is +/// placed below the root of a file system is a sub-manifest, which says +/// nothing about it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct VolumeIdentity { + /// The serial number and the field it comes from. + serial: Option<(VolumeId, FileSystemField)>, + /// The label. + label: ManifestLabel, +} + +impl VolumeIdentity { + /// What the root file object `root` says. + pub fn from_root(root: &RootObject) -> VolumeIdentity { + let identity = &root.file_system; + // fatSerial before fsUUID, as the specification has it. + let serial = match (identity.fat_serial, &identity.uuid) { + (Some(serial), _) => Some((VolumeId::from(serial), FileSystemField::FatSerial)), + (None, Some(uuid)) => Some((VolumeId::from(FatSerial::from_uuid(uuid)), FileSystemField::FsUuid)), + (None, None) => None, + }; + let label = match identity.label.as_deref() { + Some("") => ManifestLabel::Unlabeled, + Some(label) => ManifestLabel::Labeled(label.to_string()), + None if root.recorded_features().contains(Features::FS_LABEL) => ManifestLabel::Unlabeled, + None => ManifestLabel::Unrecorded, + }; + VolumeIdentity { serial, label } + } + + /// The serial number the manifest names, with the field it comes + /// from. + pub fn serial(&self) -> Option<(VolumeId, FileSystemField)> { + self.serial + } + + /// The label the manifest names. + pub fn label(&self) -> &ManifestLabel { + &self.label + } + + /// Reconciles the serial number and the label of a volume made from the + /// manifest with `options`: the manifest's go into them. A label in + /// `options` that FAT stores another way than the manifest's, also one + /// where the manifest names no label, and a serial number `identifier` + /// the caller gave that is not the manifest's, fail with EINVAL and + /// [`Detail::FileSystemMismatch`]. A label that FAT cannot store, or + /// would report another way, fails with EINVAL and [`Detail::Label`], + /// see [`encode_exact_label`]. Without a serial number from the + /// manifest the volume takes `identifier`, and without that the one + /// derived from the manifest: the returned [`SerialSource`] says which. + pub fn reconcile(&self, options: &mut FormatOptions, identifier: Option) -> Result { + if let Some(stored) = self.label.stored()? { + if let Some(given) = options.label.as_deref() { + if encode_label(given)? != stored { + let detail = Detail::file_system_mismatch(FileSystemField::FsLabel, self.label.text(), Some(given)); + match self.label.text() { + Some(label) => bail!( + EINVAL, + detail, + "the label '{}' differs from the label '{}' the manifest gives in {}", + given, + label, + FileSystemField::FsLabel.as_str() + ), + None => bail!( + EINVAL, + detail, + "the label '{}' differs from the manifest, which gives the file system no label ({})", + given, + FileSystemField::FsLabel.as_str() + ), + } + } + } + options.label = self.label.text().map(str::to_string); + } + match (self.serial, identifier) { + (Some((serial, field)), Some(given)) if given != serial => bail!( + EINVAL, + Detail::file_system_mismatch(field, Some(serial), Some(given)), + "the identifier {} differs from the serial number {} the manifest gives in {}", + given, + serial, + field.as_str() + ), + (Some((serial, _)), _) | (None, Some(serial)) => { + options.volume_id = serial.0; + Ok(SerialSource::Given) + } + (None, None) => Ok(SerialSource::Derived), + } + } + + /// Checks that `volume` is the one the manifest is for: that it has the + /// serial number and the label the manifest names, or no label where + /// the manifest names none. What the manifest does not name is not + /// checked. A label that FAT cannot store, or would report another way, + /// fails with EINVAL and [`Detail::Label`], see [`encode_exact_label`]. + /// A volume that is not the manifest's fails with EINVAL and + /// [`Detail::FileSystemMismatch`]. + pub fn check(&self, volume: &Volume) -> Result<()> { + if let Some((serial, field)) = self.serial { + let held = VolumeId(volume.boot_sector().volume_id); + if held != serial { + bail!( + EINVAL, + Detail::file_system_mismatch(field, Some(serial), Some(held)), + "the file system has the serial number {}, the manifest is for {} ({})", + held, + serial, + field.as_str() + ); + } + } + let Some(stored) = self.label.stored()? else { + return Ok(()); + }; + if volume.label_bytes()?.unwrap_or(NO_NAME) == stored { + return Ok(()); + } + let held = volume.label()?; + let detail = Detail::file_system_mismatch(FileSystemField::FsLabel, self.label.text(), held.as_deref()); + let field = FileSystemField::FsLabel.as_str(); + match (held.as_deref(), self.label.text()) { + (Some(held), Some(label)) => bail!( + EINVAL, + detail, + "the file system has the label '{}', the manifest is for '{}' ({})", + held, + label, + field + ), + (None, Some(label)) => bail!( + EINVAL, + detail, + "the file system has no label, the manifest is for '{}' ({})", + label, + field + ), + (Some(held), None) => bail!( + EINVAL, + detail, + "the file system has the label '{}', the manifest is for one without a label ({})", + held, + field + ), + // Neither has a label, which the comparison above took. + (None, None) => Ok(()), + } + } +} + +impl VolumeId { + /// The serial number of a volume made from a manifest that names none, + /// derived from the SHA-256 hash `digest` of the manifest's bytes: its + /// first four bytes, read big-endian. So its eight hex digits are the + /// first ones of the hash as `sha256sum` prints it, the way the first + /// eight hex digits of `fsUUID` give a serial number. + pub fn from_manifest_digest(digest: &Sha256) -> VolumeId { + let [a, b, c, d, ..] = *digest.as_bytes(); + VolumeId(u32::from_be_bytes([a, b, c, d])) + } +} + +impl From for VolumeId { + fn from(serial: FatSerial) -> VolumeId { + VolumeId(serial.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::format::format; + use crate::test_util::{format_options, volume, TempImage}; + use crate::{Error, LabelProblem}; + use uapi16::{Field, Reader}; + + /// The identity the root file object `root`, a JSON object, gives. + fn identity_from_root(root: &str) -> VolumeIdentity { + let manifest = format!( + "\x1e{}\n\x1e{{\"mediaType\":\"application/vnd.uapi.16.trailer\"}}\n", + root + ); + VolumeIdentity::from_root(Reader::open(manifest.as_bytes()).unwrap().root()) + } + + /// A root file object with the fields `fields`, of a manifest that + /// lists the features `features`. + fn root(features: &str, fields: &str) -> String { + let fields = if fields.is_empty() { + String::new() + } else { + format!(",{}", fields) + }; + format!( + r#"{{"features":[{}],"mediaType":"application/vnd.uapi.16.manifest"{}}}"#, + features, fields + ) + } + + /// The fields of a mismatch. + fn mismatch_fields(e: &Error) -> (FileSystemField, Option<&str>, Option<&str>) { + match e.detail() { + Some(Detail::FileSystemMismatch { field, expected, found }) => { + (*field, expected.as_deref(), found.as_deref()) + } + other => panic!("{:?}", other), + } + } + + /// What is wrong with a label refused. + fn label_problem(e: &Error) -> LabelProblem { + assert_eq!(e.errno(), EINVAL); + match e.detail() { + Some(Detail::Label { problem, .. }) => *problem, + other => panic!("{:?}", other), + } + } + + #[test] + fn what_the_root_says() { + assert_eq!(identity_from_root(&root("", "")), VolumeIdentity::default()); + let named = identity_from_root(&root( + r#""fat-serial","fs-label","fs-uuid""#, + r#""fatSerial":"1234-abcd","fsLabel":"ESP","fsUUID":"5678abcd-0000-4000-8000-000000000000""#, + )); + assert_eq!( + named.serial(), + Some((VolumeId(0x1234_abcd), FileSystemField::FatSerial)) + ); + assert_eq!(named.label(), &ManifestLabel::Labeled("ESP".into())); + // Without fatSerial, the first four bytes of fsUUID. + let uuid = identity_from_root(&root( + r#""fs-uuid""#, + r#""fsUUID":"5678ABCD-0000-4000-8000-000000000000""#, + )); + assert_eq!(uuid.serial(), Some((VolumeId(0x5678_abcd), FileSystemField::FsUuid))); + assert_eq!(uuid.label(), &ManifestLabel::Unrecorded); + // With fs-label listed, a manifest without fsLabel names no label, + // and so does an empty fsLabel. + for root in [root(r#""fs-label""#, ""), root(r#""fs-label""#, r#""fsLabel":"""#)] { + assert_eq!(identity_from_root(&root).label(), &ManifestLabel::Unlabeled, "{}", root); + } + } + + #[test] + fn reconciles_a_new_volume() { + let named = identity_from_root(&root( + r#""fat-serial","fs-label""#, + r#""fatSerial":"1234-ABCD","fsLabel":"esp""#, + )); + // What the manifest names goes into the options. + let mut options = FormatOptions::default(); + assert_eq!(named.reconcile(&mut options, None).unwrap(), SerialSource::Given); + assert_eq!( + (options.volume_id, options.label.as_deref()), + (0x1234_abcd, Some("esp")) + ); + // The same values given are fine, the label as FAT stores it. + let mut options = FormatOptions { + label: Some("esp ".into()), + ..FormatOptions::default() + }; + assert_eq!( + named.reconcile(&mut options, Some(VolumeId(0x1234_abcd))).unwrap(), + SerialSource::Given + ); + // Other ones are not. + let e = named + .reconcile(&mut FormatOptions::default(), Some(VolumeId(0x1111_2222))) + .unwrap_err(); + assert_eq!(e.errno(), EINVAL); + assert_eq!( + mismatch_fields(&e), + (FileSystemField::FatSerial, Some("1234-ABCD"), Some("1111-2222")) + ); + assert_eq!( + e.message(), + "the identifier 1111-2222 differs from the serial number 1234-ABCD the manifest gives in fatSerial" + ); + let mut options = FormatOptions { + label: Some("ESP".into()), + ..FormatOptions::default() + }; + let e = named.reconcile(&mut options, None).unwrap_err(); + assert_eq!( + mismatch_fields(&e), + (FileSystemField::FsLabel, Some("esp"), Some("ESP")) + ); + assert_eq!( + e.message(), + "the label 'ESP' differs from the label 'esp' the manifest gives in fsLabel" + ); + // The serial number derived from fsUUID is named by its field, and + // written as serial numbers are. + let uuid = identity_from_root(&root( + r#""fs-uuid""#, + r#""fsUUID":"5678abcd-0000-4000-8000-000000000000""#, + )); + let e = uuid + .reconcile(&mut FormatOptions::default(), Some(VolumeId(1))) + .unwrap_err(); + assert_eq!( + mismatch_fields(&e), + (FileSystemField::FsUuid, Some("5678-ABCD"), Some("0000-0001")) + ); + // Without a serial number from the manifest, the one given, and + // without that the one derived from the manifest. A label the + // manifest does not record is the one given. + let nothing = VolumeIdentity::default(); + let mut options = FormatOptions { + label: Some("MINE".into()), + ..FormatOptions::default() + }; + assert_eq!( + nothing.reconcile(&mut options, Some(VolumeId(7))).unwrap(), + SerialSource::Given + ); + assert_eq!((options.volume_id, options.label.as_deref()), (7, Some("MINE"))); + assert_eq!(nothing.reconcile(&mut options, None).unwrap(), SerialSource::Derived); + // A manifest that names no label makes a volume without one, and a + // label given is one too many. + for unlabeled in [root(r#""fs-label""#, ""), root(r#""fs-label""#, r#""fsLabel":"""#)] { + let unlabeled = identity_from_root(&unlabeled); + let mut options = FormatOptions { + label: Some("ESP".into()), + ..FormatOptions::default() + }; + let e = unlabeled.reconcile(&mut options, None).unwrap_err(); + assert_eq!(mismatch_fields(&e), (FileSystemField::FsLabel, None, Some("ESP"))); + assert_eq!( + e.message(), + "the label 'ESP' differs from the manifest, which gives the file system no label (fsLabel)" + ); + for given in [None, Some(""), Some("NO NAME")] { + let mut options = FormatOptions { + label: given.map(str::to_string), + ..FormatOptions::default() + }; + unlabeled.reconcile(&mut options, None).unwrap(); + assert_eq!(options.label, None, "{:?}", given); + } + } + // A label FAT cannot store, or would report as another label or as + // none, is refused: blkid shows a FAT label without the spaces at + // its end, and nothing for the blank label and NO NAME. + for (label, problem) in [ + ("much too long", LabelProblem::TooLong), + ("TEST ", LabelProblem::InvalidCharacter), + (" ", LabelProblem::Reserved), + ("NO NAME", LabelProblem::Reserved), + ] { + let identity = identity_from_root(&root(r#""fs-label""#, &format!(r#""fsLabel":"{}""#, label))); + let e = identity.reconcile(&mut FormatOptions::default(), None).unwrap_err(); + assert_eq!(label_problem(&e), problem, "{:?}", label); + } + } + + #[test] + fn checks_a_volume() { + // The test volume has the serial number 1234-ABCD and the label + // TEST. + let (_img, v) = volume(8 << 20, 512, 512); + assert_eq!(format_options(512, 512).volume_id, 0x1234_abcd); + for fits in [ + root("", ""), + root( + r#""fat-serial","fs-label""#, + r#""fatSerial":"1234-abcd","fsLabel":"TEST""#, + ), + root(r#""fs-uuid""#, r#""fsUUID":"1234abcd-0000-4000-8000-000000000000""#), + ] { + identity_from_root(&fits).check(&v).unwrap(); + } + let e = identity_from_root(&root(r#""fat-serial""#, r#""fatSerial":"1234-ABCE""#)) + .check(&v) + .unwrap_err(); + assert_eq!( + mismatch_fields(&e), + (FileSystemField::FatSerial, Some("1234-ABCE"), Some("1234-ABCD")) + ); + assert_eq!( + e.message(), + "the file system has the serial number 1234-ABCD, the manifest is for 1234-ABCE (fatSerial)" + ); + let e = identity_from_root(&root(r#""fs-label""#, r#""fsLabel":"test""#)) + .check(&v) + .unwrap_err(); + assert_eq!( + mismatch_fields(&e), + (FileSystemField::FsLabel, Some("test"), Some("TEST")) + ); + // A manifest that names no label is not for a volume with one. + let e = identity_from_root(&root(r#""fs-label""#, "")).check(&v).unwrap_err(); + assert_eq!(mismatch_fields(&e), (FileSystemField::FsLabel, None, Some("TEST"))); + assert_eq!( + e.message(), + "the file system has the label 'TEST', the manifest is for one without a label (fsLabel)" + ); + // A label no FAT volume reports is refused as such, whatever the + // volume has: one FAT cannot store, one with a space at its end, + // which blkid shows without it, and the blank label and NO NAME, + // which it shows as no label. + for (label, problem) in [ + ("much too long", LabelProblem::TooLong), + ("TEST ", LabelProblem::InvalidCharacter), + (" ", LabelProblem::Reserved), + ("NO NAME", LabelProblem::Reserved), + ] { + let identity = identity_from_root(&root(r#""fs-label""#, &format!(r#""fsLabel":"{}""#, label))); + assert_eq!(label_problem(&identity.check(&v).unwrap_err()), problem, "{:?}", label); + } + // A label the manifest names on a volume without one. + let img = TempImage::new(8 << 20); + let options = FormatOptions { + label: None, + ..format_options(512, 512) + }; + format(&img.device(), &options).unwrap(); + let unlabeled = Volume::open(img.device()).unwrap(); + let e = identity_from_root(&root(r#""fs-label""#, r#""fsLabel":"TEST""#)) + .check(&unlabeled) + .unwrap_err(); + assert_eq!(mismatch_fields(&e), (FileSystemField::FsLabel, Some("TEST"), None)); + assert_eq!( + e.message(), + "the file system has no label, the manifest is for 'TEST' (fsLabel)" + ); + for fits in [root(r#""fs-label""#, ""), root(r#""fs-label""#, r#""fsLabel":"""#)] { + identity_from_root(&fits).check(&unlabeled).unwrap(); + } + // A label in the boot sector only is no label: the volume's label is + // the one of its root directory, where blkid reads it. + drop(unlabeled); + img.device() + .write_at(crate::boot::field::VOLUME_LABEL.start as u64, b"TEST ") + .unwrap(); + let boot_only = Volume::open(img.device()).unwrap(); + identity_from_root(&root(r#""fs-label""#, "")) + .check(&boot_only) + .unwrap(); + let e = identity_from_root(&root(r#""fs-label""#, r#""fsLabel":"TEST""#)) + .check(&boot_only) + .unwrap_err(); + assert_eq!(mismatch_fields(&e), (FileSystemField::FsLabel, Some("TEST"), None)); + } + + #[test] + fn the_serial_number_of_a_manifest() { + // The first eight hex digits of the hash are those of the serial + // number. + let digest = Sha256::digest(b"a manifest"); + let serial = VolumeId::from_manifest_digest(&digest); + let hex = digest.to_string(); + assert_eq!( + serial.to_string(), + format!("{}-{}", &hex[..4], &hex[4..8]).to_uppercase() + ); + assert_eq!(VolumeId::from(FatSerial(0x1234_abcd)), VolumeId(0x1234_abcd)); + assert_eq!(SerialSource::Given.derived_serial(Some(digest)).unwrap(), None); + assert_eq!( + SerialSource::Derived.derived_serial(Some(digest)).unwrap(), + Some(serial) + ); + assert_eq!(SerialSource::Derived.derived_serial(None).unwrap_err().errno(), EIO); + } + + /// The fields that name the volume are spelt as the manifest spells + /// them. + #[test] + fn file_system_fields() { + for (field, named) in [ + (FileSystemField::FatSerial, Field::FatSerial), + (FileSystemField::FsUuid, Field::FsUuid), + (FileSystemField::FsLabel, Field::FsLabel), + ] { + assert_eq!(field.as_str(), named.as_str()); + } + } +} diff --git a/src/fat/manifest/mod.rs b/src/fat/manifest/mod.rs index c0b266a..c11f062 100644 --- a/src/fat/manifest/mod.rs +++ b/src/fat/manifest/mod.rs @@ -26,6 +26,14 @@ //! device nodes, FIFOs, sockets) is refused unless the caller asks for it to //! be skipped. `readOnly` and the flags of the hidden, system and archive //! attributes set and clear those attributes of files and directories. +//! +//! The root file object can name the volume the manifest is for, see +//! [`VolumeIdentity`]: a volume made from the manifest takes the serial +//! number and the label, and a volume the content goes into has to have +//! them. A manifest that names no serial number gives a volume the one +//! derived from its bytes, see [`VolumeId::from_manifest_digest`]. +//! +//! [`VolumeId::from_manifest_digest`]: crate::format::VolumeId::from_manifest_digest use crate::dirent::{ATTR_ARCHIVE, ATTR_HIDDEN, ATTR_READ_ONLY, ATTR_SYSTEM}; use crate::errno::*; @@ -36,12 +44,14 @@ use crate::{Detail, Result, UnsupportedKind}; mod assemble; mod error; mod generate; +mod identity; #[cfg(test)] mod tests; mod volume; pub use assemble::{AssembleFlags, AssembleObserver, AssembleOptions, AssembleReport, PinnedDirectory, SkipReason}; pub use generate::HostTree; +pub use identity::{ManifestLabel, SerialSource, VolumeIdentity}; pub use uapi16::{ ContentSource, Contents, DirectorySource, DosFlags, Features, FileObject, Finalize, FlagStates, InodeFlags, InodeType, Location, Name, Object, Order, Problem, Reader, RootObject, Sha256, Sha256Context, StreamSource, diff --git a/src/fat/manifest/tests.rs b/src/fat/manifest/tests.rs index f03b311..7f35b8f 100644 --- a/src/fat/manifest/tests.rs +++ b/src/fat/manifest/tests.rs @@ -656,6 +656,39 @@ fn files_without_a_size() { } } +/// A manifest that names the file system it is for goes into that one +/// only, also for a caller of the library, and nothing is written into +/// another one. The test volume has the serial number 1234-ABCD and the +/// label TEST. +#[test] +fn manifests_go_into_their_file_system() { + let (_img, mut v) = volume(8 << 20, 512, 512); + let named = |features: &str, fields: &str| { + let root = format!( + r#"{{"features":[{}],{}"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}}"#, + features, fields + ); + seq(&[&root, r#"{"name":"x","size":0}"#, TRAILER]) + }; + for (features, fields) in [ + (r#""fat-serial","size""#, r#""fatSerial":"1234-ABCE","#), + (r#""fs-label","size""#, r#""fsLabel":"OTHER","#), + // fs-label listed without fsLabel: the file system has no label. + (r#""fs-label","size""#, ""), + ] { + let e = assemble_stream(&mut v, &named(features, fields), b"", &AssembleOptions::default()).unwrap_err(); + assert!(matches!(e.detail(), Some(Detail::FileSystemMismatch { .. })), "{:?}", e); + assert!(v.read_dir("/").unwrap().is_empty()); + assert!(!v.is_writing()); + } + let fits = named( + r#""fat-serial","fs-label","size""#, + r#""fatSerial":"1234-abcd","fsLabel":"TEST","#, + ); + assemble_stream(&mut v, &fits, b"", &AssembleOptions::default()).unwrap(); + assert_eq!(v.read_dir("/").unwrap().len(), 1); +} + /// A directory that refers to a sub-manifest is refused at its object, /// before the stream is asked for the sub-manifest, with or without a size. /// Left out instead, it takes its sub-manifest along: the stream has that diff --git a/src/fat/manifest/volume.rs b/src/fat/manifest/volume.rs index 5329701..a422201 100644 --- a/src/fat/manifest/volume.rs +++ b/src/fat/manifest/volume.rs @@ -10,8 +10,8 @@ //! asked for, and no mode, owner, device numbers, hardlinks, extended //! attributes or inode flags, since FAT has no notion of them. A feature //! the file system has no notion of is not recorded and not counted; what -//! FAT keeps and the manifest could not record is counted in the report's -//! `omitted`. +//! FAT keeps and the manifest could not record goes into the report: the +//! entries in `omitted`, the label in `omitted_label`. //! //! The order is the specification's code point order: the root object //! first, every directory's entries right after it, sorted by the bytes of @@ -21,24 +21,28 @@ //! regular files. So with the same features the manifest of a volume is //! the one the host tree generator writes for the tree the volume was //! filled from, apart from what FAT changes on the way: FAT keeps times at -//! 2 s, the manifest always lists `read-only`, and a read-only file gets -//! `readOnly`. +//! 2 s, a read-only file gets `readOnly`, and the root object names the +//! volume with `fatSerial` and `fsLabel`. The manifest always lists +//! `read-only`, `fat-serial` and `fs-label`. use std::io::Write; use std::time::SystemTime; -use uapi16::{Features, FileObject, Finalize, InodeType, Name, Order, RootObject, Sha256, Sha256Context, Writer}; +use uapi16::{ + FatSerial, Features, FileObject, Finalize, InodeType, Name, Order, RootObject, Sha256, Sha256Context, Writer, +}; use super::DosAttributes; use crate::dir::NameDecoding; use crate::errno::*; use crate::fat::BitSet; +use crate::format::{decode_label, encode_exact_label}; use crate::progress::Progress; use crate::volume::{Metadata, Volume}; use crate::{CorruptPlace, Detail, Result}; /// What a written manifest covers. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct WriteReport { /// Regular files listed. pub files: u64, @@ -46,13 +50,17 @@ pub struct WriteReport { pub directories: u64, /// Bytes of the regular files listed. pub bytes: u64, - /// What the tree or the volume holds that the manifest could not + /// The entries of the tree or the volume that the manifest could not /// record: entries whose names a manifest cannot carry, a directory /// with everything below it counting once. A feature the file system /// has no notion of is not an omission. A manifest with omissions does /// not describe all of it, and repart refuses such a manifest of a /// volume. pub omitted: u64, + /// The label of the volume where the manifest leaves it out: one that a + /// volume made from the manifest would not get, which only other tools + /// write. It is an omission as well, but not an entry. + pub omitted_label: Option, /// Regular files of a host tree that changed while they were read for /// their hash. The manifest has the size and the hash of what was /// read, which need not be what the file holds now. A volume does not @@ -61,6 +69,12 @@ pub struct WriteReport { } impl WriteReport { + /// Everything the manifest leaves out, as one count: the entries in + /// `omitted` and a label in `omitted_label`. + pub fn omissions(&self) -> u64 { + self.omitted + u64::from(self.omitted_label.is_some()) + } + /// What the manifest covers so far, as a progress callback hears it. fn progress(&self) -> Progress { Progress { @@ -73,17 +87,23 @@ impl WriteReport { impl Volume { /// What the manifest of a FAT volume records whatever it is asked for: - /// the read-only attribute, which every entry has set or cleared. - const ALWAYS_RECORDED_FEATURES: Features = Features::READ_ONLY; + /// the read-only attribute, which every entry has set or cleared, and + /// the serial number and the label, which name the volume. + const ALWAYS_RECORDED_FEATURES: Features = Features::READ_ONLY + .union(Features::FAT_SERIAL) + .union(Features::FS_LABEL); /// What the manifest of a FAT volume can record: sizes, hashes, times, /// the read-only attribute and the hidden, system and archive - /// attributes, and that there are no symbolic links, device nodes, - /// hardlinks, extended attributes or inode flags. + /// attributes, the serial number and the label, and that there are no + /// symbolic links, device nodes, hardlinks, extended attributes or + /// inode flags. const MANIFEST_FEATURES: Features = Features::SIZE .union(Features::SHA256) .union(Features::MTIME) .union(Features::READ_ONLY) + .union(Features::FAT_SERIAL) + .union(Features::FS_LABEL) .union(Features::SYMLINK) .union(Features::DEVICE) .union(Features::HARDLINK) @@ -120,15 +140,26 @@ impl Volume { /// not read-only. The manifest lists its features, and declares the /// code point ordering its objects are in. /// + /// The root object names the volume, whatever `features` asks for: its + /// serial number as `fatSerial`, and its label as `fsLabel` when it has + /// one. The manifest lists `fat-serial` and `fs-label`, and without + /// `fsLabel` it says that the volume has no label. A volume made from + /// the manifest gets the same serial number and label again, and the + /// content of the manifest goes into this volume and no other. + /// /// Names the manifest cannot carry are left out, with everything below /// them. The names the specification reserves in the top level for the /// manifest itself and its signatures (`Uapi16Manifest`, /// `Uapi16Manifest.*`) are left out silently, as `systemd-manifest` /// leaves them out; any other, one with a noncharacter or an unpaired /// surrogate for instance, which FAT stores but no manifest has, is - /// counted in the report's `omitted`. Names that FAT takes for one, - /// such as `README.TXT` and `readme.txt`, are two names to a manifest, - /// and each is listed with what its entry holds. + /// counted in the report's `omitted`. A label that a volume made from + /// the manifest would not have, see [`encode_exact_label`], which only + /// other tools write, is left out as well and named in the report's + /// `omitted_label`: the manifest does not list `fs-label` then. + /// Names that FAT takes for one, such as `README.TXT` and `readme.txt`, + /// are two names to a manifest, and each is listed with what its entry + /// holds. /// /// What only a damaged volume has fails with EUCLEAN: a cluster that /// belongs to two entries, or twice to one, as in a loop or a @@ -164,7 +195,19 @@ impl Volume { progress: &mut dyn FnMut(&Progress), ) -> Result { let top = self.metadata("/")?; - let features = (features | Volume::ALWAYS_RECORDED_FEATURES) & Volume::MANIFEST_FEATURES; + let mut features = (features | Volume::ALWAYS_RECORDED_FEATURES) & Volume::MANIFEST_FEATURES; + // The label goes in where a volume made from the manifest gets the + // same label field, so that the manifest goes into this volume + // again. Only other tools write one that it does not, and without + // fs-label listed the manifest says nothing about it. + let stored = self.label_bytes()?; + let label = stored.map(|raw| decode_label(&raw)); + let carried = label + .as_deref() + .is_none_or(|label| encode_exact_label(label).ok() == stored); + if !carried { + features = features.without(Features::FS_LABEL); + } // The root object is a directory by definition and carries no type. let mut root = RootObject::default(); root.features = Some(features); @@ -172,11 +215,17 @@ impl Volume { if let Some(time) = root_time.filter(|_| features.contains(Features::MTIME)) { root.inode.set_mtime(time); } + root.file_system.fat_serial = Some(FatSerial(self.boot_sector().volume_id)); + let (label, omitted_label) = if carried { (label, None) } else { (None, label) }; + root.file_system.label = label; let mut listing = Listing { volume: self, features, writer: Writer::begin(out, &root)?, - report: WriteReport::default(), + report: WriteReport { + omitted_label, + ..WriteReport::default() + }, buf: vec![0u8; self.layout().cluster_size() as usize], claimed: BitSet::new(self.layout().max_cluster() as usize + 1), progress, @@ -541,6 +590,7 @@ mod tests { directories: 4, bytes: 7 + 5000 + 10 + 7, omitted: 0, + omitted_label: None, changed: 0, } ); @@ -589,8 +639,9 @@ mod tests { assert_eq!( recs[0].0, concat!( - r#"{"features":["device","hardlink","read-only","sha256","size","symlink"],"#, - r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + r#"{"fatSerial":"1234-ABCD","#, + r#""features":["device","fat-serial","fs-label","hardlink","read-only","sha256","size","symlink"],"#, + r#""fsLabel":"TEST","mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# ) ); assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); @@ -632,14 +683,18 @@ mod tests { #[test] fn features_govern_what_is_written() { let (_img, v) = populated(); - // Nothing but names, the types of directories and the read-only - // attribute, which the manifest always records. + // Nothing but names, the types of directories, the read-only + // attribute and what names the volume, which the manifest always + // records. let (bytes, report) = written(&v, Some(t(1_600_000_000)), Features::NONE); assert_eq!((report.files, report.directories, report.bytes), (5, 4, 5024)); let recs = records(&bytes); assert_eq!( recs[0].0, - r#"{"features":["read-only"],"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + concat!( + r#"{"fatSerial":"1234-ABCD","features":["fat-serial","fs-label","read-only"],"fsLabel":"TEST","#, + r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# + ) ); assert_eq!(recs[1].0, r#"{"name":"B.txt"}"#); assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); @@ -695,7 +750,8 @@ mod tests { assert_eq!( records(&bytes)[0].0, concat!( - r#"{"features":["mtime","read-only"],"mTimeNSec":1600000000000000005,"#, + r#"{"fatSerial":"1234-ABCD","features":["fat-serial","fs-label","mtime","read-only"],"#, + r#""fsLabel":"TEST","mTimeNSec":1600000000000000005,"#, r#""mediaType":"application/vnd.uapi.16.manifest","order":"codepoint"}"# ) ); @@ -709,7 +765,8 @@ mod tests { let (_img, v) = populated(); // Asked for everything, the manifest lists what FAT records: // sizes, hashes, times, the read-only attribute and the other DOS - // attributes, and that it has no symbolic links, device nodes, + // attributes, the serial number and the label of the volume, and + // that it has no symbolic links, device nodes, // hardlinks, extended attributes and inode flags. Modes, owners and // their names are not listed. let (bytes, _) = written(&v, None, Features::ALL); @@ -718,6 +775,7 @@ mod tests { m.root.features.unwrap().names().collect::>(), [ "device", + "fat-serial", "flag-append-only", "flag-archive", "flag-hidden", @@ -726,6 +784,7 @@ mod tests { "flag-no-cow", "flag-no-dump", "flag-system", + "fs-label", "hardlink", "mtime", "read-only", @@ -793,14 +852,22 @@ mod tests { assert_eq!((copied.files, copied.directories), (5, 4)); // The generator records sizes, hashes and times. With the tree's own // time for the root and times FAT keeps as they are, the two - // manifests are the same bytes, but for the read-only attribute, - // which the manifest of a volume always lists in its features. + // manifests are the same bytes, but for what the manifest of a + // volume always records: the read-only attribute, and the serial + // number and the label of the volume, which a tree does not have. let mut host = Vec::new(); let host_report = HostTree::new(dir.as_fd()).write_manifest(&mut host).unwrap(); let host = String::from_utf8(host).unwrap(); - let listed = r#""features":["mtime","sha256","size"]"#; + let listed = r#"{"features":["mtime","sha256","size"],"#; assert!(host.contains(listed), "{}", host); - let host = host.replacen(listed, r#""features":["mtime","read-only","sha256","size"]"#, 1); + let host = host.replacen( + listed, + concat!( + r#"{"fatSerial":"1234-ABCD","#, + r#""features":["fat-serial","fs-label","mtime","read-only","sha256","size"],"fsLabel":"TEST","# + ), + 1, + ); let root_time = std::fs::metadata(tree.path()).unwrap().modified().unwrap(); let features = Features::from_names(["size", "sha256", "mtime"]).unwrap(); let (bytes, report) = written(&v, Some(root_time), features); @@ -810,6 +877,105 @@ mod tests { assert_eq!(report, host_report); } + #[test] + fn names_the_volume() { + use crate::dirent::{self, ATTR_VOLUME_ID, DIR_ENTRY_SIZE}; + use crate::format::{format, FormatOptions}; + use crate::manifest::{ManifestLabel, VolumeIdentity}; + use crate::test_util::format_options; + // The serial number and the label with their features, whatever the + // features asked for say, and no UUID, which FAT does not have. The + // manifest goes into the volume it names. + let (img, v) = populated(); + let (bytes, report) = written(&v, None, Features::NONE); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.root.file_system.fat_serial, Some(FatSerial(0x1234_abcd))); + assert_eq!(m.root.file_system.label.as_deref(), Some("TEST")); + assert_eq!(m.root.file_system.uuid, None); + assert!(m + .root + .features + .unwrap() + .contains(Features::FAT_SERIAL | Features::FS_LABEL)); + assert_eq!(report.omitted, 0); + VolumeIdentity::from_root(&m.root).check(&v).unwrap(); + // A label that a volume made from the manifest would not have, which + // ufat does not write but another tool may, is left out and counted, + // and the manifest does not list fs-label then: one with a control + // character, one beyond ASCII, one with a character mkfs.fat refuses + // or a space in front, and one whose last character the volume + // reads as padding. + let root = v.boot_sector().root_cluster; + let offset = v.layout().cluster_offset(root).unwrap(); + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + v.close().unwrap(); + img.device().read_at(offset, &mut cluster).unwrap(); + let slot = cluster + .chunks(DIR_ENTRY_SIZE) + .position(|e| e[dirent::field::ATTR] == ATTR_VOLUME_ID) + .unwrap(); + let name_at = offset + (slot * DIR_ENTRY_SIZE + dirent::field::NAME.start) as u64; + for (raw, label) in [ + (b"\x01EST ", "\u{1}EST"), + (b"\x85EST ", "\u{85}EST"), + (b"\xe9TE ", "\u{e9}TE"), + (b"A.B ", "A.B"), + (b"A+B ", "A+B"), + (b" X ", " X"), + (b"ESP\xa0 ", "ESP"), + ] { + img.device().write_at(name_at, raw).unwrap(); + let v = Volume::open(img.device()).unwrap(); + assert_eq!(v.label().unwrap().as_deref(), Some(label)); + let (bytes, report) = written(&v, None, Features::NONE); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.root.file_system.fat_serial, Some(FatSerial(0x1234_abcd))); + assert_eq!( + ( + m.root.file_system.label.as_deref(), + report.omitted, + report.omitted_label.as_deref() + ), + (None, 0, Some(label)), + "{:?}", + label + ); + assert_eq!(report.omissions(), 1); + assert!(!m.root.features.unwrap().contains(Features::FS_LABEL), "{:?}", label); + assert_eq!(VolumeIdentity::from_root(&m.root).label(), &ManifestLabel::Unrecorded); + v.close().unwrap(); + } + // A volume without a label names none: the manifest lists fs-label + // and has no fsLabel. + let img = TempImage::new(8 << 20); + let options = FormatOptions { + label: None, + ..format_options(512, 512) + }; + format(&img.device(), &options).unwrap(); + let v = Volume::open(img.device()).unwrap(); + let (bytes, _) = written(&v, None, Features::NONE); + let m = WrittenManifest::read(&bytes); + assert_eq!(m.root.file_system.label, None); + assert_eq!(VolumeIdentity::from_root(&m.root).label(), &ManifestLabel::Unlabeled); + VolumeIdentity::from_root(&m.root).check(&v).unwrap(); + assert!(records(&bytes)[0] + .0 + .starts_with(r#"{"fatSerial":"1234-ABCD","features":["fat-serial","fs-label","read-only"],"mediaType""#)); + // Nor does one with a label in its boot sector only, which is no + // label to blkid, Windows and EDK2, who read the root directory. + drop(v); + img.device() + .write_at(crate::boot::field::VOLUME_LABEL.start as u64, b"ESP ") + .unwrap(); + let v = Volume::open(img.device()).unwrap(); + let (bytes, report) = written(&v, None, Features::NONE); + let m = WrittenManifest::read(&bytes); + assert_eq!((m.root.file_system.label.as_deref(), report.omissions()), (None, 0)); + assert_eq!(VolumeIdentity::from_root(&m.root).label(), &ManifestLabel::Unlabeled); + VolumeIdentity::from_root(&m.root).check(&v).unwrap(); + } + #[test] fn names_the_manifest_cannot_carry() { let (_img, mut v) = volume(8 << 20, 512, 512); @@ -831,6 +997,7 @@ mod tests { directories: 1, bytes: 8, omitted: 0, + omitted_label: None, changed: 0, } ); diff --git a/src/fat/volume/mod.rs b/src/fat/volume/mod.rs index eb9b7f7..91d0799 100644 --- a/src/fat/volume/mod.rs +++ b/src/fat/volume/mod.rs @@ -32,6 +32,7 @@ use crate::dirent::{ }; use crate::errno::*; use crate::fat::{Entry, Extent, Fat, FatStore, CACHE_BYTES, ENTRY1_CLEAN_SHUTDOWN}; +use crate::format::VolumeId; use crate::layout::Layout; use crate::name::{fold_str, long_name_entries, short_name_to_string, Alias, LongName}; use crate::path::{components, SEPARATOR}; @@ -284,8 +285,10 @@ fn check_attributes(attributes: u8) -> Result<()> { Ok(()) } -/// Whether a label field says the volume has no label: `NO NAME`, which -/// mkfs.fat and Windows put there, or blanks. +/// Whether the name of a label entry says that the volume has no label: +/// blanks, or `NO NAME`, which the boot sector holds for no label, and +/// which [`Volume::set_root_time`] copies from there into the entry it +/// makes. fn is_no_name(label: &[u8; LABEL_SIZE]) -> bool { *label == NO_NAME || label.iter().all(|&b| b == b' ') } @@ -496,23 +499,23 @@ impl Volume { u64::from(self.fat.free_count()) * u64::from(self.layout.cluster_size()) } - /// The volume label, from the root directory entry or else from the - /// boot sector. None when the volume has no label: `NO NAME` and a - /// blank label mean none, to us as to blkid and mtools. + /// The volume label: the name of the root directory's label entry, + /// where Windows, EDK2, GRUB and blkid read it. The copy in the boot + /// sector counts for nothing, as it does for them. None when there is + /// no such entry, or when it is blank or says `NO NAME`. blkid shows a + /// blank entry as no label as well, but an entry `NO NAME` as the label + /// `NO NAME`. pub fn label(&self) -> Result> { Ok(self.label_bytes()?.map(|raw| crate::format::decode_label(&raw))) } /// The volume label as stored on disk, eleven space padded bytes in the - /// OEM code page: the root directory's label entry if there is one, else - /// the boot sector's. None when that says `NO NAME` or is blank, which - /// is how a volume without a label is written. + /// OEM code page: the name of the root directory's label entry. None + /// when there is no such entry, or when it is blank or says `NO NAME`, + /// see [`Volume::label`]. pub fn label_bytes(&self) -> Result> { - let label = match self.label_entry()? { - Some(e) => e.short.name, - None => self.boot.volume_label, - }; - Ok(Some(label).filter(|l| !is_no_name(l))) + let label = self.label_entry()?.map(|e| e.short.name); + Ok(label.filter(|l| !is_no_name(l))) } /// The root directory's volume label entry, if there is one. @@ -548,11 +551,13 @@ impl Volume { /// Sets the root directory's time on the volume label entry, creating /// the entry when there is none. A new entry carries the boot sector's - /// label, `NO NAME` when the volume has none, so the label the volume - /// reports stays what it was, see [`Volume::label`]. The time is stored - /// as on any entry: the modification time in two second steps, the - /// creation time in hundredths. The entry is one slot written in place, - /// so a crash leaves the old time or the new one. + /// label, `NO NAME` when that is blank or zeroed. So a volume without a + /// label keeps none, and a volume whose boot sector holds a label that + /// its root directory does not, as another tool can leave it, gets that + /// label, see [`Volume::label`]. The time is stored as on any entry: the + /// modification time in two second steps, the creation time in + /// hundredths. The entry is one slot written in place, so a crash + /// leaves the old time or the new one. pub fn set_root_time(&mut self, time: SystemTime) -> Result<()> { self.begin_write()?; let t = FatTimestamp::from_system_time(time); @@ -583,6 +588,40 @@ impl Volume { }) } + /// Sets the volume serial number to `id`, in the boot sector and in its + /// backup, for a serial number that is known only once the volume is + /// written, such as the one derived from a manifest. + /// + /// The two copies are written while the volume carries the marks of a + /// session, see [`Volume::begin_write`]: the backup first, then the + /// boot sector that readers go by. In durable mode a flush before them + /// makes the marks reach the device first, and one after them makes + /// both copies reach it before [`Volume::close`] takes the marks away. + /// So a crash in between leaves a volume marked as not cleanly + /// unmounted, with the old or the new serial number in each copy, as + /// nothing orders the two writes against each other on the device, and + /// fsck reports a backup that differs along with the marks. Each copy + /// is four bytes within one sector, written in place, so a crash + /// leaves the old serial number in it or the new one. + pub fn set_volume_id(&mut self, id: VolumeId) -> Result<()> { + self.begin_write()?; + self.commit_barrier()?; + let field = boot::field::VOLUME_ID; + let bytes = id.0.to_le_bytes(); + let backup = u64::from(self.boot.backup_boot_sector); + if backup != 0 { + let offset = backup * u64::from(self.layout.sector_size) + field.start as u64; + self.device.write_at(offset, &bytes)?; + } + self.device.write_at(field.start as u64, &bytes)?; + self.commit_barrier()?; + // What close() puts back into the boot sector has the new serial + // number too. + self.boot_raw[field].copy_from_slice(&bytes); + self.boot.volume_id = id.0; + Ok(()) + } + /// Reads a directory from disk, past the cache. Operations go through /// [`Volume::take_directory`]; this is for looking at what is on disk. pub(crate) fn load_directory(&self, first_cluster: u32) -> Result { diff --git a/src/fat/volume/tests.rs b/src/fat/volume/tests.rs index b12dcab..9b9eed2 100644 --- a/src/fat/volume/tests.rs +++ b/src/fat/volume/tests.rs @@ -1506,6 +1506,33 @@ fn root_time() { assert_eq!(v.root_time().unwrap(), Some(t(1_650_000_000))); } +/// The label is the root directory's label entry, as Windows, EDK2, GRUB +/// and blkid read it. A label only in the boot sector, which Windows leaves +/// there when it removes the label, is none. Stamping the root's time makes +/// a label entry with the boot sector's label, which is the label then. +#[test] +fn the_label_is_the_one_of_the_root_directory() { + let img = TempImage::new(1 << 20); + let unlabelled = FormatOptions { + label: None, + ..format_options(512, 512) + }; + format::format(&img.device(), &unlabelled).unwrap(); + img.device() + .write_at(boot::field::VOLUME_LABEL.start as u64, b"ESP ") + .unwrap(); + let mut v = Volume::open(img.device()).unwrap(); + assert_eq!(v.boot_sector().volume_label, *b"ESP "); + assert_eq!(v.label().unwrap(), None); + assert_eq!(v.label_bytes().unwrap(), None); + v.set_root_time(t(1_700_000_000)).unwrap(); + assert_eq!(v.label().unwrap().as_deref(), Some("ESP")); + let entries = v.load_directory(v.boot.root_cluster).unwrap(); + let label = entries.iter().find(|e| e.short.is_volume_label()).unwrap(); + assert_eq!(label.short.name, *b"ESP "); + v.close().unwrap(); +} + /// set_times() writes the dot entries of a directory where only they /// differ: its entry has the time already and its "." and ".." do not. #[test] @@ -1645,3 +1672,84 @@ fn set_attributes() { assert_eq!(v.metadata("/d/f").unwrap().attributes, 0); assert_eq!(v.metadata("/d/g").unwrap().attributes, ATTR_SYSTEM | ATTR_ARCHIVE); } + +/// The serial numbers in the boot sector and in its backup of the volume +/// in `img`, and the NT flags of the boot sector, as they are on disk. The +/// file is read past the volume, which holds the image open. +fn serials_on_disk(img: &TempImage) -> (u32, u32, u8) { + let bytes = std::fs::read(img.path()).unwrap(); + let boot = BootSector::parse(&bytes).unwrap(); + let ss = usize::from(boot.bytes_per_sector); + let backup = BootSector::parse(&bytes[usize::from(boot.backup_boot_sector) * ss..]).unwrap(); + (boot.volume_id, backup.volume_id, boot.nt_flags) +} + +#[test] +fn the_serial_number_is_set_in_both_boot_sectors() { + let (img, mut v) = volume(8 << 20, 512, 512); + assert_eq!(serials_on_disk(&img), (0x1234_abcd, 0x1234_abcd, 0)); + let mut w = v.create_file("/a", t(1_500_000_000), NameCollision::Fail).unwrap(); + w.write_all(b"data").unwrap(); + w.finish().unwrap(); + v.set_volume_id(VolumeId(0x5678_9abc)).unwrap(); + assert_eq!(v.boot_sector().volume_id, 0x5678_9abc); + // Both copies have it while the volume is written, which it says. + assert_eq!(serials_on_disk(&img), (0x5678_9abc, 0x5678_9abc, NT_FLAG_DIRTY)); + v.close().unwrap(); + // Closing marks the volume clean and keeps the new serial number. + assert_eq!(serials_on_disk(&img), (0x5678_9abc, 0x5678_9abc, 0)); + // The test volume is small, which is worth a warning of its own. + let report = fsck::check(&img.device()).unwrap(); + assert!( + report + .problems + .iter() + .all(|p| p.kind == fsck::ProblemKind::BelowMinimumClusters), + "{:?}", + report.problems + ); + let v = Volume::open(img.device()).unwrap(); + assert_eq!(v.boot_sector().volume_id, 0x5678_9abc); + assert_eq!(v.label().unwrap().as_deref(), Some("TEST")); + drop(v); + // On its own it is a session of its own, with the marks of one, and on + // a volume left unfinished they stay. + let mut v = Volume::open(img.device()).unwrap(); + v.set_volume_id(VolumeId(1)).unwrap(); + v.close_unfinished().unwrap(); + assert_eq!(serials_on_disk(&img), (1, 1, NT_FLAG_DIRTY)); + // In durable mode too, which flushes around the two writes. + let mut v = Volume::open(img.device()).unwrap(); + v.set_durable(true); + v.set_volume_id(VolumeId(2)).unwrap(); + v.close().unwrap(); + assert_eq!(serials_on_disk(&img), (2, 2, NT_FLAG_DIRTY)); +} + +#[test] +fn a_volume_without_a_backup_boot_sector_gets_the_serial_number_once() { + let img = TempImage::new(8 << 20); + let options = FormatOptions { + reserved_sectors: 2, + ..format_options(512, 512) + }; + format::format(&img.device(), &options).unwrap(); + let mut v = Volume::open(img.device()).unwrap(); + assert_eq!(v.boot_sector().backup_boot_sector, 0); + let mut before = std::fs::read(img.path()).unwrap(); + v.set_volume_id(VolumeId(0x0bad_cafe)).unwrap(); + v.close().unwrap(); + let after = std::fs::read(img.path()).unwrap(); + // The serial number changed, and nothing else of the boot sector. + before[boot::field::VOLUME_ID].copy_from_slice(&0x0bad_cafe_u32.to_le_bytes()); + assert_eq!(after[..BOOT_SECTOR_SIZE], before[..BOOT_SECTOR_SIZE]); + let report = fsck::check(&img.device()).unwrap(); + assert!( + report.problems.iter().all(|p| matches!( + p.kind, + fsck::ProblemKind::NoBackupBootSector | fsck::ProblemKind::BelowMinimumClusters + )), + "{:?}", + report.problems + ); +} diff --git a/tests/cli.rs b/tests/cli.rs index dae31fc..890bf87 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -979,6 +979,416 @@ fn manifests_have_to_declare_their_order() { assert_eq!(ok(&bin, &["list", a]), "EFI/\nloader/\n"); } +/// The serial number and the label `describe` shows for `image`. +fn described_identity(bin: &Path, image: &str) -> (String, String) { + let described = ok(bin, &["describe", image]); + let field = |name: &str| { + described + .lines() + .find_map(|line| line.strip_prefix(name)) + .unwrap() + .trim() + .to_string() + }; + (field("volume id:"), field("volume label:")) +} + +/// The root object of a manifest names the file system: assemble gives it +/// the serial number and the label, --identifier and --label have to agree, +/// and populate checks them. Without a serial number from the manifest or +/// --identifier, it is the one derived from the manifest's bytes, the same +/// from a file, from standard input and with --minimize. A manifest that +/// lists fs-label without fsLabel is for a file system without a label. A +/// label that FAT cannot store, or would report as another one or as none, +/// is refused. The manifests ufat writes of a file system name it, those of +/// a tree do not. +#[test] +fn manifests_name_the_file_system() { + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let dir = Temp::dir(); + let root = dir.path(); + tree(&root.join("tree")); + let t = root.join("tree"); + let t = t.to_str().unwrap(); + let image = |name: &str| root.join(name).to_str().unwrap().to_string(); + let manifest = ok(&bin, &["manifest", t]); + // A tree describes no file system. + assert!(!manifest.contains("fatSerial") && !manifest.contains("fsLabel")); + let plain = root.join("plain.manifest"); + fs::write(&plain, &manifest).unwrap(); + let p = plain.to_str().unwrap(); + // The serial number derived from the manifest, whichever way it comes: + // the first eight hex digits sha256sum prints for it. + let derived = common::derived_serial(manifest.as_bytes()); + match common::find_program("sha256sum") { + Some(sha256sum) => { + let out = Command::new(sha256sum).arg(&plain).output().unwrap(); + let printed = String::from_utf8(out.stdout).unwrap().to_uppercase(); + assert_eq!(format!("{}-{}", &printed[..4], &printed[4..8]), derived); + } + None => eprintln!("not comparing with sha256sum: not found"), + } + let (a, b, c, d) = (image("a.img"), image("b.img"), image("c.img"), image("d.img")); + ok(&bin, &["assemble", "--create", "--size", "40M", "--manifest", p, &a, t]); + let out = run_in( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", "-", &b, t], + manifest.as_bytes(), + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + ok(&bin, &["assemble", "--create", "--minimize", "--manifest", p, &c, t]); + ok(&bin, &["assemble", "--create", "--manifest", p, &d]); + for img in [&a, &b, &c, &d] { + assert_eq!( + described_identity(&bin, img), + (derived.clone(), String::new()), + "{}", + img + ); + } + // The image is the same whether the manifest came from a file and was + // read twice for --minimize, or from standard input with the size and + // the cluster size that --minimize chose. + let size = fs::metadata(&c).unwrap().len().to_string(); + let cluster = ok(&bin, &["describe", &c]) + .lines() + .find_map(|line| line.strip_prefix("cluster size:").map(|v| v.trim().to_string())) + .unwrap(); + let e = image("e.img"); + let out = run_in( + &bin, + &[ + "assemble", + "--create", + "--size", + &size, + "--cluster-size", + &cluster, + "--manifest", + "-", + &e, + t, + ], + manifest.as_bytes(), + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(fs::read(&c).unwrap() == fs::read(&e).unwrap(), "the images differ"); + // --identifier and --label are used where the manifest names nothing. + let f = image("f.img"); + ok( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + "--identifier", + "1111-2222", + "--label", + "MINE", + "--manifest", + p, + &f, + t, + ], + ); + assert_eq!( + described_identity(&bin, &f), + ("1111-2222".to_string(), "MINE".to_string()) + ); + // A manifest that names the file system gives it its serial number and + // label, from fatSerial, or else from the start of fsUUID. + let named = |name: &str, features: &[&str], fields: &str| { + let path = root.join(format!("{}.manifest", name)); + fs::write(&path, common::with_root_fields(manifest.as_bytes(), features, fields)).unwrap(); + path.to_str().unwrap().to_string() + }; + let esp = named( + "esp", + &["fat-serial", "fs-label", "fs-uuid"], + r#""fatSerial":"1234-abcd","fsLabel":"ESP","fsUUID":"9999aaaa-0000-4000-8000-000000000000""#, + ); + let uuid = named( + "uuid", + &["fs-uuid"], + r#""fsUUID":"5678abcd-0000-4000-8000-000000000000""#, + ); + let g = image("g.img"); + ok(&bin, &["assemble", "--create", "--manifest", &esp, &g]); + assert_eq!( + described_identity(&bin, &g), + ("1234-ABCD".to_string(), "ESP".to_string()) + ); + let h = image("h.img"); + ok( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", &uuid, &h, t], + ); + assert_eq!(described_identity(&bin, &h), ("5678-ABCD".to_string(), String::new())); + // The options have to agree with what the manifest names: the same + // values are fine, others are refused before an image is made. + let i = image("i.img"); + ok( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + "--identifier", + "1234ABCD", + "--label", + "ESP", + "--manifest", + &esp, + &i, + t, + ], + ); + let j = image("j.img"); + for (option, value, message) in [ + ( + "--identifier", + "1234-0000", + "the identifier 1234-0000 differs from the serial number 1234-ABCD the manifest gives in fatSerial", + ), + ( + "--label", + "esp", + "the label 'esp' differs from the label 'ESP' the manifest gives in fsLabel", + ), + ] { + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + option, + value, + "--manifest", + &esp, + &j, + t, + ], + &format!("ufat: {}: {}", esp, message), + ); + assert!(!Path::new(&j).exists()); + } + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + "--identifier", + "00000001", + "--manifest", + &uuid, + &j, + t, + ], + "the identifier 0000-0001 differs from the serial number 5678-ABCD the manifest gives in fsUUID", + ); + // A manifest that lists fs-label without fsLabel is for a file system + // without a label, and a --label is one too many. + let unlabeled = named("unlabeled", &["fs-label"], ""); + let k = image("k.img"); + ok( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", &unlabeled, &k, t], + ); + assert_eq!(described_identity(&bin, &k).1, ""); + fails( + &bin, + &[ + "assemble", + "--create", + "--size", + "40M", + "--label", + "MINE", + "--manifest", + &unlabeled, + &j, + t, + ], + "the label 'MINE' differs from the manifest, which gives the file system no label (fsLabel)", + ); + assert!(!Path::new(&j).exists()); + // A label FAT cannot store is refused, and so is one it would report + // as another label or as none: blkid shows a FAT label without the + // spaces at its end, and nothing for the blank label and NO NAME. + let mut refused = Vec::new(); + for (name, label, message) in [ + ( + "long", + "much too long", + "label 'much too long' is longer than 11 characters", + ), + ( + "trailing", + "ESP ", + "label 'ESP ' ends with a space, which FAT does not keep", + ), + ("blank", " ", "label ' ' is what FAT stores for no label"), + ("no-name", "NO NAME", "label 'NO NAME' is what FAT stores for no label"), + ] { + let m = named(name, &["fs-label"], &format!(r#""fsLabel":"{}""#, label)); + fails( + &bin, + &["assemble", "--create", "--size", "40M", "--manifest", &m, &j, t], + message, + ); + fails(&bin, &["assemble", "--plan", "--manifest", &m], message); + assert!(!Path::new(&j).exists()); + refused.push((m, message)); + } + // populate checks the file system against what the manifest names, and + // writes nothing into another one. Its errors name the image, or the + // manifest for a label it refuses. A manifest that names nothing goes + // anywhere. + ok(&bin, &["populate", "--manifest", &esp, &g, t]); + ok(&bin, &["populate", "--replace", "--manifest", p, &g, t]); + ok(&bin, &["populate", "--replace", "--manifest", &unlabeled, &a, t]); + let other = named("other", &["fs-label"], r#""fsLabel":"OTHER""#); + let (before_a, before_g) = (fs::read(&a).unwrap(), fs::read(&g).unwrap()); + for (img, m, message) in [ + ( + &a, + &esp, + format!( + "the file system has the serial number {}, the manifest is for 1234-ABCD (fatSerial)", + derived + ), + ), + ( + &g, + &other, + "the file system has the label 'ESP', the manifest is for 'OTHER' (fsLabel)".to_string(), + ), + ( + &a, + &other, + "the file system has no label, the manifest is for 'OTHER' (fsLabel)".to_string(), + ), + ( + &g, + &unlabeled, + "the file system has the label 'ESP', the manifest is for one without a label (fsLabel)".to_string(), + ), + ] { + fails( + &bin, + &["populate", "--replace", "--manifest", m, img, t], + &format!("ufat: {}: {}", img, message), + ); + } + for (m, message) in &refused { + fails( + &bin, + &["populate", "--replace", "--manifest", m, &g, t], + &format!("ufat: {}: {}", m, message), + ); + } + assert!(fs::read(&a).unwrap() == before_a, "a.img changed"); + assert!(fs::read(&g).unwrap() == before_g, "g.img changed"); + // What ufat writes of a file system names it, so it makes the same + // serial number and label again and goes into that file system. + let written = root.join("written.manifest"); + ok(&bin, &["describe", "--write-manifest", written.to_str().unwrap(), &g]); + let text = fs::read_to_string(&written).unwrap(); + assert!( + text.starts_with(concat!( + "\u{1e}{\"fatSerial\":\"1234-ABCD\",", + "\"features\":[\"device\",\"fat-serial\",\"fs-label\",\"hardlink\",\"read-only\",\"sha256\",\"size\",\"symlink\"],", + "\"fsLabel\":\"ESP\"," + )), + "{}", + text + ); + let l = image("l.img"); + ok( + &bin, + &[ + "assemble", + "--create", + "--minimize", + "--manifest", + written.to_str().unwrap(), + &l, + t, + ], + ); + assert_eq!( + described_identity(&bin, &l), + ("1234-ABCD".to_string(), "ESP".to_string()) + ); + ok( + &bin, + &["populate", "--replace", "--manifest", written.to_str().unwrap(), &g, t], + ); + // So does what ufat writes of a file system without a label, which + // lists fs-label and has no fsLabel. + ok(&bin, &["describe", "--write-manifest", written.to_str().unwrap(), &a]); + let text = fs::read_to_string(&written).unwrap(); + assert!(!text.contains("fsLabel") && text.contains("\"fs-label\""), "{}", text); + let m = image("m.img"); + ok( + &bin, + &["assemble", "--create", "--manifest", written.to_str().unwrap(), &m], + ); + assert_eq!(described_identity(&bin, &m), (derived.clone(), String::new())); + fails( + &bin, + &["populate", "--replace", "--manifest", written.to_str().unwrap(), &g, t], + &format!("ufat: {}: the file system has the serial number 1234-ABCD", g), + ); + // The label a manifest names takes an entry in the root directory, + // which a plan counts: sixteen files fill a cluster of 512 bytes, the + // label entry is a seventeenth. A manifest that names no label takes + // none. + let mut sixteen = + String::from("\u{1e}{\"mediaType\":\"application/vnd.uapi.16.manifest\",\"order\":\"codepoint\"}\n"); + for i in 0..16 { + sixteen.push_str(&format!("\u{1e}{{\"name\":\"f{:02}\",\"size\":0}}\n", i)); + } + sixteen.push_str("\u{1e}{\"mediaType\":\"application/vnd.uapi.16.trailer\"}\n"); + for (fields, clusters) in [ + ("", "1 cluster"), + (r#""features":["fs-label","size"],"fsLabel":"ESP","#, "2 clusters"), + (r#""features":["fs-label","size"],"#, "1 cluster"), + ] { + let path = root.join("sixteen.manifest"); + fs::write(&path, sixteen.replacen("\u{1e}{", &format!("\u{1e}{{{}", fields), 1)).unwrap(); + let out = run( + &bin, + &[ + "assemble", + "--plan", + "--verbose", + "--cluster-size", + "512", + "--manifest", + path.to_str().unwrap(), + ], + ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains(&format!("16 files, 0 directories, 0 bytes: {} of 512 bytes", clusters)), + "{}: {}", + fields, + stderr + ); + } +} + /// Names FAT does not tell apart are one name: assemble and populate refuse /// a second one, in a manifest as well as in a tree, a directory's as well /// as a file's, unless --replace says to take it as the first. A tree is @@ -2791,6 +3201,50 @@ fn counts_of_one() { assert!(stderr.starts_with("ufat: 1 entry is not in "), "{}", stderr); } +/// A label that a file system made from the manifest would not get, which +/// only other tools write, is not in the manifest of a volume, and describe +/// names it, apart from the entries it leaves out. +#[test] +fn a_label_the_manifest_leaves_out_is_named() { + use std::os::unix::fs::FileExt; + let _serial = common::serial(); + let Some(bin) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let root = Temp::dir(); + let img = root.path().join("l.img"); + let img = img.to_str().unwrap(); + ok(&bin, &["assemble", "--create", "--size", "40M", "--label", "ESP", img]); + // The label entry of the root directory as another tool writes it: A+B, + // which a file system made from the manifest would not get. + let device = fat::device::Device::open(Path::new(img), fat::device::Access::ReadOnly).unwrap(); + let v = fat::volume::Volume::open(device).unwrap(); + let offset = v.layout().cluster_offset(v.boot_sector().root_cluster).unwrap(); + let mut cluster = vec![0u8; v.layout().cluster_size() as usize]; + drop(v); + let file = fs::OpenOptions::new().read(true).write(true).open(img).unwrap(); + file.read_exact_at(&mut cluster, offset).unwrap(); + let slot = cluster + .chunks(fat::dirent::DIR_ENTRY_SIZE) + .position(|e| e[fat::dirent::field::ATTR] == fat::dirent::ATTR_VOLUME_ID) + .unwrap(); + let name = slot * fat::dirent::DIR_ENTRY_SIZE + fat::dirent::field::NAME.start; + file.write_all_at(b"A+B ", offset + name as u64).unwrap(); + let m = root.path().join("l.manifest"); + let out = run(&bin, &["describe", "--write-manifest", m.to_str().unwrap(), img]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{}", stderr); + assert_eq!( + stderr, + format!( + "ufat: the label 'A+B' is not in {}: a file system made from it would not get that label\n", + m.display() + ) + ); + let manifest = fs::read_to_string(&m).unwrap(); + assert!(!manifest.contains("fsLabel"), "{}", manifest); +} + /// `ufat manifest` prints the manifest while it walks the tree. It leaves /// out what a manifest cannot name and says how many entries it left out. /// What it printed of a tree it cannot walk to its end has no trailer. diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 808fbfa..a9426f0 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -398,3 +398,36 @@ pub fn bytes_at(path: &Path, offset: u64, len: usize) -> Vec { buf.truncate(n); buf } + +/// The serial number a manifest of the bytes `manifest` gives a file +/// system that names none: the first eight hex digits of its SHA-256 hash, +/// written as serial numbers are. +pub fn derived_serial(manifest: &[u8]) -> String { + let hex = fat::manifest::Sha256::digest(manifest).to_string().to_uppercase(); + format!("{}-{}", &hex[..4], &hex[4..8]) +} + +/// The manifest `manifest`, whose root object starts with its features, +/// with `fields` added to its root object and the features they belong to, +/// `features`, added to the ones it lists. +pub fn with_root_fields(manifest: &[u8], features: &[&str], fields: &str) -> Vec { + const LISTED: &str = "\u{1e}{\"features\":["; + let text = String::from_utf8(manifest.to_vec()).unwrap(); + let rest = text + .strip_prefix(LISTED) + .expect("the root object starts with its features"); + let (listed, rest) = rest.split_once(']').unwrap(); + let mut names: Vec = listed + .split(',') + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect(); + names.extend(features.iter().map(|feature| format!("\"{}\"", feature))); + names.sort_unstable(); + let fields = if fields.is_empty() { + String::new() + } else { + format!("{},", fields) + }; + format!("\u{1e}{{{}\"features\":[{}]{}", fields, names.join(","), rest).into_bytes() +} diff --git a/tests/crash/crash.rs b/tests/crash/crash.rs index 1d1cce3..9bd4d24 100644 --- a/tests/crash/crash.rs +++ b/tests/crash/crash.rs @@ -34,7 +34,7 @@ use fat::boot::BootSector; use fat::device::{Access, Device}; use fat::dirent::{self, short_name_checksum, RawDirEntry, ATTR_ARCHIVE, DIR_ENTRY_SIZE, ENTRY_DELETED, ENTRY_END}; use fat::fat::{Entry, Fat, BAD_CLUSTER, END_OF_CHAIN_MIN, ENTRY_MASK, ENTRY_SIZE, FREE}; -use fat::format::{self, FormatOptions}; +use fat::format::{self, FormatOptions, VolumeId}; use fat::fsck::{self, ProblemKind, Severity}; use fat::layout::{Layout, FIRST_CLUSTER}; use fat::manifest::Sha256; @@ -55,6 +55,12 @@ const SEED: u64 = 20261107; const TIME: u64 = 1_700_000_000; /// Failures of one kind shown in the summary, at most. const SHOWN_PER_KIND: usize = 3; +/// The serial number the volume is formatted with, the one the scenario +/// sets first, before anything else is written, and the one it sets at its +/// end, as an assembly from a manifest does. +const FORMAT_SERIAL: u32 = 0x4352_5348; +const FIRST_SERIAL: u32 = 0x4649_5253; +const FINAL_SERIAL: u32 = 0x5345_5249; fn fixed_time() -> SystemTime { UNIX_EPOCH + Duration::from_secs(TIME) @@ -152,6 +158,9 @@ enum Op { chunk: usize, }, Remove(String), + /// `set_volume_id`: the serial number in the boot sector and its + /// backup. + Serial(u32), /// `close`: the marks go back, FSInfo gets its counts, fsync. Close, } @@ -181,6 +190,7 @@ impl Op { chunk ), Op::Remove(p) => format!("remove {}", p), + Op::Serial(id) => format!("serial {}", VolumeId(*id)), Op::Close => "close".to_string(), } } @@ -200,9 +210,9 @@ impl Op { /// A tree with long names, files replaced within one directory cluster and /// across two, a directory grown past its first cluster, a removed file /// whose slots are reused, nested directories, directories made with and -/// without their parent growing for them. BOOTX64.EFI is written in -/// small pieces so that its epoch holds many writes; the kernel names take -/// four slots each. +/// without their parent growing for them, and a serial number set first +/// and last. BOOTX64.EFI is written in small pieces so that its epoch +/// holds many writes; the kernel names take four slots each. fn scenario(slots_per_cluster: usize) -> Vec { let mut rng = Rng(SEED); let mut ops: Vec = Vec::new(); @@ -216,6 +226,10 @@ fn scenario(slots_per_cluster: usize) -> Vec { }); }; let kernel = |n: usize| format!("/EFI/Linux/linux-6.12.{}-200.fc41.x86_64+3.efi", n); + // A serial number set before anything else is written. set_volume_id() + // begins the session itself, so the marks of the session go down before + // the serial number does. + ops.push(Op::Serial(FIRST_SERIAL)); ops.push(Op::Mkdir("/EFI/BOOT".into())); file(&mut ops, "/EFI/BOOT/BOOTX64.EFI", 70_000, NameCollision::Fail, 4096); ops.push(Op::Mkdir("/EFI/Linux".into())); @@ -284,6 +298,8 @@ fn scenario(slots_per_cluster: usize) -> Vec { path: "/full/sub".into(), grows: true, }); + // The serial number an assembly from a manifest knows at its end. + ops.push(Op::Serial(FINAL_SERIAL)); ops.push(Op::Close); ops } @@ -360,7 +376,7 @@ fn simulate(ops: &[Op]) -> Tree { Op::Remove(path) => { tree.remove(path); } - Op::Close => {} + Op::Serial(_) | Op::Close => {} } } tree @@ -662,7 +678,7 @@ impl Harness { let options = FormatOptions { sector_size: Some(cfg.sector_size), cluster_size: Some(cfg.cluster_size), - volume_id: 0x4352_5348, + volume_id: FORMAT_SERIAL, label: Some("ESP".into()), timestamp: Some(fixed_time()), allow_small: true, @@ -691,11 +707,17 @@ impl Harness { w.finish().unwrap(); } Op::Remove(path) => v.remove_file(path).unwrap(), + Op::Serial(id) => v.set_volume_id(VolumeId(*id)).unwrap(), Op::Close => {} } } v.close().unwrap(); let final_image = std::fs::read(img.path()).unwrap(); + // Both boot sectors have the serial number the scenario set. + let boot = BootSector::parse(&final_image).unwrap(); + let backup = usize::from(boot.backup_boot_sector) * usize::from(boot.bytes_per_sector); + let backup = BootSector::parse(&final_image[backup..]).unwrap(); + assert_eq!((boot.volume_id, backup.volume_id), (FINAL_SERIAL, FINAL_SERIAL)); let records = read_trace(trace.path()); // The format is the pre-state: its records must turn the stale @@ -925,7 +947,7 @@ impl Harness { format!(" ({} sectors)", sectors) }; let region = if w.offset < l.fat_offset(0) { - if w.offset == 0 { + if w.offset < self.ss { "boot sector".to_string() } else { format!("reserved sector {}", w.offset / self.ss) @@ -1065,6 +1087,7 @@ const ACCEPT_BEHIND_MARKER: &str = "a short entry behind the end marker of a par const ACCEPT_DUPLICATE: &str = "both versions of a replaced file in a partly written directory"; const ACCEPT_ALIAS: &str = "a file listed under its alias in a partly written directory"; const ACCEPT_REPLACED_ABSENT: &str = "a replaced file absent"; +const ACCEPT_BACKUP_SERIAL: &str = "the backup boot sector a serial number behind or ahead"; struct Verdict { failure: Option, @@ -1352,6 +1375,10 @@ impl<'a> Worker<'a> { let partial_dirs = h.partial_directories(pieces); let torn_dir = |dir: &str| partial_dirs.iter().any(|d| d == dir); let replaced: BTreeSet<&str> = in_flight.iter().filter_map(|op| op.replaces()).collect(); + // The serial number goes into the backup boot sector and the boot + // sector one after the other, while the boot sector says that the + // volume is being written. + let serial_in_flight = in_flight.iter().any(|op| matches!(op, Op::Serial(_))); let versions_of = |path: &str| -> BTreeSet> { (lo..=hi).map(|j| h.boundaries[j].tree.get(path).cloned()).collect() }; @@ -1381,6 +1408,7 @@ impl<'a> Worker<'a> { return (bad, accepted); } }; + let marked = report.problems.iter().any(|p| p.kind == ProblemKind::DirtyFlag); for p in &report.problems { let msg = p.to_string(); let path = p.path.as_deref().unwrap_or(""); @@ -1418,6 +1446,9 @@ impl<'a> Worker<'a> { Severity::Warning if p.kind == ProblemKind::FatCopyDiffers => Some(ACCEPT_FAT_COPIES), Severity::Warning if p.kind == ProblemKind::LostClusters => Some(ACCEPT_LOST), Severity::Warning if p.kind == ProblemKind::FsinfoFreeCount => Some(ACCEPT_FSINFO), + Severity::Warning if p.kind == ProblemKind::BackupBootSectorDiffers && serial_in_flight && marked => { + Some(ACCEPT_BACKUP_SERIAL) + } Severity::Warning => None, }; match rule { diff --git a/tests/fixtures.rs b/tests/fixtures.rs index c815ac4..c9343a4 100644 --- a/tests/fixtures.rs +++ b/tests/fixtures.rs @@ -472,8 +472,10 @@ fn generator_agrees_with_systemd_manifest() { /// has a notion of: none at all, and size, sha256 and mtime. The manifests /// of systemd got their features and their order declared, see the README. /// A manifest of a volume records the read-only attribute as well, which -/// systemd-manifest does not record. So it lists read-only next to the -/// features systemd-manifest lists. +/// systemd-manifest does not record, and it names the volume: its serial +/// number, 0000-0000 here, and its label, which it has none of. So it lists +/// read-only, fat-serial and fs-label next to the features systemd-manifest +/// lists, and its root object has fatSerial. #[test] fn volume_manifest_agrees_with_systemd_manifest() { let m = load("esp", "size-hash-mtime.Uapi16Manifest"); @@ -485,13 +487,13 @@ fn volume_manifest_agrees_with_systemd_manifest() { "none.Uapi16Manifest", Features::NONE, r#""features":[]"#, - r#""features":["read-only"]"#, + r#""fatSerial":"0000-0000","features":["fat-serial","fs-label","read-only"]"#, ), ( "size-hash-mtime.Uapi16Manifest", Features::from_names(["size", "sha256", "mtime"]).unwrap(), r#""features":["mtime","sha256","size"]"#, - r#""features":["mtime","read-only","sha256","size"]"#, + r#""fatSerial":"0000-0000","features":["fat-serial","fs-label","mtime","read-only","sha256","size"]"#, ), ] { let mut ours = Vec::new(); diff --git a/tests/varlink.rs b/tests/varlink.rs index 402960c..5ff3d76 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -2078,7 +2078,7 @@ fn manifests_record_and_apply_features() { features.unwrap().names().collect::>() }; // Every value is taken. What FAT has no notion of is not recorded, and - // the read-only attribute always is. + // the read-only attribute and what names the volume always are. let img_ro = ro(image.path()); let out = scratch.path().join("all.manifest"); let out_file = sink(&out); @@ -2097,6 +2097,7 @@ fn manifests_record_and_apply_features() { listed(&out), [ "device", + "fat-serial", "flag-append-only", "flag-archive", "flag-hidden", @@ -2105,6 +2106,7 @@ fn manifests_record_and_apply_features() { "flag-no-cow", "flag-no-dump", "flag-system", + "fs-label", "hardlink", "mtime", "read-only", @@ -2131,7 +2133,16 @@ fn manifests_record_and_apply_features() { drop(out_file); assert_eq!( listed(&out), - ["device", "hardlink", "read-only", "sha256", "size", "symlink"] + [ + "device", + "fat-serial", + "fs-label", + "hardlink", + "read-only", + "sha256", + "size", + "symlink" + ] ); // systemd-manifest's name for sha256 is not one of them. let out_file = sink(&out); @@ -2222,6 +2233,254 @@ fn manifests_record_and_apply_features() { } } +/// The root object of a manifest names the file system: Assemble gives it +/// the serial number and the label, its identifier and label options have +/// to agree, and Populate checks them. A manifest that names no serial +/// number gives the one derived from its bytes, the same from a file, from +/// a pipe, with minimize and in a plan. One that lists fs-label without +/// fsLabel is for a file system without a label. A label that FAT cannot +/// store, or would report as another one or as none, is refused. The sink +/// names the file system. +#[test] +fn manifests_name_the_file_system() { + let _serial = common::serial(); + let Some(ufat) = ufat() else { + return eprintln!("skipping: no ufat binary"); + }; + let tree = esp_tree(); + let (manifest, _) = manifest_and_blob(tree.path()); + let scratch = Temp::dir(); + let mut c = connect_fd3(&ufat); + let source = ro(tree.path()); + let mismatch = |e: varlink::Error, field: &str, expected: Option<&str>, found: Option<&str>| { + assert_eq!( + e.name, + format!("{}.FileSystemMismatch", IFACE), + "{}", + Value::Object(e.parameters.clone()) + ); + assert_eq!(str_of(&e.parameters, "field"), field); + assert_eq!(e.parameters.get("expected").and_then(Value::as_str), expected); + assert_eq!(e.parameters.get("found").and_then(Value::as_str), found); + }; + // The serial number derived from the manifest: in a plan, from a file, + // with minimize, and from a pipe. + let derived = common::derived_serial(&manifest); + let plain = file_with(scratch.path(), "plain", &manifest); + let r = reply(call( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0}}}"#, + &[plain.as_fd()], + )); + assert_eq!(str_of(object_of(&r, "description"), "identifier"), derived); + let sized = r#"{"image":{"fileDescriptor":0,"size":41943040},"options":{"timestampUSec":1700000000000000},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"manifestSink":{"fileDescriptor":3}},"imageHash":"sha256"}"#; + let minimized = r#"{"image":{"fileDescriptor":0},"options":{"minimize":true,"timestampUSec":1700000000000000},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"manifestSink":{"fileDescriptor":3}}}"#; + let mut images = Vec::new(); + for (params, manifest_file) in [ + (sized, ro(&scratch.path().join("plain"))), + (minimized, ro(&scratch.path().join("plain"))), + (sized, pipe_with(&manifest)), + ] { + let (image, img) = fresh_image(); + let written = scratch.path().join("written.manifest"); + let out_file = sink(&written); + let r = reply(call( + &mut c, + "Assemble", + params, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd(), out_file.as_fd()], + )); + drop(out_file); + assert_eq!(str_of(object_of(&r, "description"), "identifier"), derived); + assert_eq!(serial_in(image.path()), derived); + // The hash is the one of the image with the serial number in it. + if let Some(hash) = r.get("imageHash").and_then(Value::as_str) { + assert_eq!(hash, sha256_hex(&std::fs::read(image.path()).unwrap())); + } + // So is the manifest written of it, which says that the file system + // has no label. + let m = read_manifest(&std::fs::read(&written).unwrap()); + let identity = &m.root.file_system; + assert_eq!( + identity.fat_serial.map(|serial| serial.to_string()), + Some(derived.clone()) + ); + assert_eq!(identity.label, None); + assert!(m.root.recorded_features().contains(fat::manifest::Features::FS_LABEL)); + images.push(image); + } + // A manifest that names the file system gives it its serial number and + // label, and the options have to agree with them. + let esp = common::with_root_fields( + &manifest, + &["fat-serial", "fs-label"], + r#""fatSerial":"1234-abcd","fsLabel":"ESP""#, + ); + let esp_file = file_with(scratch.path(), "esp", &esp); + let r = reply(call( + &mut c, + "Assemble", + r#"{"mode":"plan","options":{"identifier":"1234ABCD","label":"ESP"},"content":{"manifest":{"fileDescriptor":0}}}"#, + &[esp_file.as_fd()], + )); + let d = object_of(&r, "description"); + assert_eq!((str_of(d, "identifier"), str_of(d, "label")), ("1234-ABCD", "ESP")); + let (named, named_img) = fresh_image(); + let esp_file = ro(&scratch.path().join("esp")); + let r = reply(call( + &mut c, + "Assemble", + r#"{"image":{"fileDescriptor":0},"options":{"minimize":true},"content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2}}"#, + &[named_img.as_fd(), esp_file.as_fd(), source.as_fd()], + )); + let d = object_of(&r, "description"); + assert_eq!((str_of(d, "identifier"), str_of(d, "label")), ("1234-ABCD", "ESP")); + let unlabeled = common::with_root_fields(&manifest, &["fs-label"], ""); + file_with(scratch.path(), "unlabeled", &unlabeled); + for (file, options, field, expected, found) in [ + ( + "esp", + r#"{"identifier":"1234-0000"}"#, + "fatSerial", + Some("1234-ABCD"), + "1234-0000", + ), + ("esp", r#"{"label":"BOOT"}"#, "fsLabel", Some("ESP"), "BOOT"), + // fs-label listed without fsLabel: no label, and a label given is + // one too many. + ("unlabeled", r#"{"label":"BOOT"}"#, "fsLabel", None, "BOOT"), + ] { + let manifest_file = ro(&scratch.path().join(file)); + let e = error_of( + &mut c, + "Assemble", + &format!( + r#"{{"mode":"plan","options":{},"content":{{"manifest":{{"fileDescriptor":0}}}}}}"#, + options + ), + &[manifest_file.as_fd()], + ); + mismatch(e, field, expected, Some(found)); + } + let uuid = common::with_root_fields( + &manifest, + &["fs-uuid"], + r#""fsUUID":"5678abcd-0000-4000-8000-000000000000""#, + ); + let uuid_file = file_with(scratch.path(), "uuid", &uuid); + let e = error_of( + &mut c, + "Assemble", + r#"{"mode":"plan","options":{"identifier":"00000001"},"content":{"manifest":{"fileDescriptor":0}}}"#, + &[uuid_file.as_fd()], + ); + mismatch(e, "fsUUID", Some("5678-ABCD"), Some("0000-0001")); + // Populate puts the content of a manifest into the file system it + // names. + let populate = r#"{"image":{"fileDescriptor":0},"path":"/","content":{"manifest":{"fileDescriptor":1},"sourceFileDescriptor":2,"replace":true}}"#; + let esp_file = ro(&scratch.path().join("esp")); + let r = reply(call( + &mut c, + "Populate", + populate, + &[named_img.as_fd(), esp_file.as_fd(), source.as_fd()], + )); + assert_eq!(u64_of(&r, "files"), 2); + // From here on Populate refuses every manifest, and writes nothing. + let other = rw(images[0].path()); + let (before_other, before_named) = ( + std::fs::read(images[0].path()).unwrap(), + std::fs::read(named.path()).unwrap(), + ); + // A label FAT cannot store is refused, and so is one it would report as + // another label or as none: blkid shows a FAT label without the spaces + // at its end, and nothing for the blank label and NO NAME. Populate + // refuses them as Assemble does. + for (label, reason) in [ + ("much too long", "tooLong"), + ("ESP ", "invalidCharacter"), + (" ", "reserved"), + ("NO NAME", "reserved"), + ] { + let refused = common::with_root_fields(&manifest, &["fs-label"], &format!(r#""fsLabel":"{}""#, label)); + let refused_file = file_with(scratch.path(), "refused", &refused); + let e = error_of( + &mut c, + "Assemble", + r#"{"mode":"plan","content":{"manifest":{"fileDescriptor":0}}}"#, + &[refused_file.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidLabel", IFACE), "{:?}", label); + assert_eq!(str_of(&e.parameters, "reason"), reason, "{:?}", label); + assert_eq!(str_of(&e.parameters, "label"), label); + let refused_file = ro(&scratch.path().join("refused")); + let e = error_of( + &mut c, + "Populate", + populate, + &[named_img.as_fd(), refused_file.as_fd(), source.as_fd()], + ); + assert_eq!(e.name, format!("{}.InvalidLabel", IFACE), "{:?}", label); + assert_eq!(str_of(&e.parameters, "reason"), reason, "{:?}", label); + } + // Populate checks the file system against what the manifest names. + let label = common::with_root_fields(&manifest, &["fs-label"], r#""fsLabel":"ESP""#); + file_with(scratch.path(), "label", &label); + for (img, file, field, expected, found) in [ + (&other, "esp", "fatSerial", Some("1234-ABCD"), Some(derived.as_str())), + (&other, "label", "fsLabel", Some("ESP"), None), + (&named_img, "unlabeled", "fsLabel", None, Some("ESP")), + ] { + let manifest_file = ro(&scratch.path().join(file)); + let e = error_of( + &mut c, + "Populate", + populate, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + ); + mismatch(e, field, expected, found); + } + assert!(std::fs::read(images[0].path()).unwrap() == before_other); + assert!(std::fs::read(named.path()).unwrap() == before_named); + // A manifest that names no label goes into a file system without one. + let unlabeled_file = ro(&scratch.path().join("unlabeled")); + let r = reply(call( + &mut c, + "Populate", + populate, + &[other.as_fd(), unlabeled_file.as_fd(), source.as_fd()], + )); + assert_eq!(u64_of(&r, "files"), 2); + // The manifest of a file system names it. + let out = scratch.path().join("described.manifest"); + let out_file = sink(&out); + let named_ro = ro(named.path()); + reply(call( + &mut c, + "Describe", + r#"{"image":{"fileDescriptor":0},"manifestSink":{"fileDescriptor":1}}"#, + &[named_ro.as_fd(), out_file.as_fd()], + )); + drop(out_file); + let m = read_manifest(&std::fs::read(&out).unwrap()); + let identity = &m.root.file_system; + assert_eq!( + identity.fat_serial.map(|serial| serial.to_string()).as_deref(), + Some("1234-ABCD") + ); + assert_eq!(identity.label.as_deref(), Some("ESP")); + assert!(m + .root + .recorded_features() + .contains(fat::manifest::Features::FAT_SERIAL | fat::manifest::Features::FS_LABEL)); +} + +/// The serial number of the FAT volume in `image`, written XXXX-XXXX. +fn serial_in(image: &Path) -> String { + fat::format::VolumeId(volume(image, Access::ReadOnly).boot_sector().volume_id).to_string() +} + /// With the more flag Assemble tells which step it is in, in order. #[test] fn assemble_reports_its_phases() { @@ -2354,6 +2613,28 @@ fn reproducible_images_are_identical() { reply(call(&mut c, "Assemble", &options, &[b_img.as_fd(), source.as_fd()])); assert!(std::fs::metadata(a.path()).unwrap().len() > 0); assert_eq!(first_difference(a.path(), b.path()).unwrap(), None); + // A manifest names the serial number or has it derived from its bytes, + // so it needs no identifier. + let (manifest, _) = manifest_and_blob(tree.path()); + let scratch = Temp::dir(); + file_with(scratch.path(), "manifest", &manifest); + let options = format!( + r#"{{"image":{{"fileDescriptor":0}},"options":{{"minimize":true,"reproducible":true,"timestampUSec":{},"label":"ESP"}},"content":{{"manifest":{{"fileDescriptor":1}},"sourceFileDescriptor":2}}}}"#, + T0 + ); + let (a, a_img) = fresh_image(); + let (b, b_img) = fresh_image(); + for img in [&a_img, &b_img] { + let manifest_file = ro(&scratch.path().join("manifest")); + reply(call( + &mut c, + "Assemble", + &options, + &[img.as_fd(), manifest_file.as_fd(), source.as_fd()], + )); + } + assert!(std::fs::metadata(a.path()).unwrap().len() > 0); + assert_eq!(first_difference(a.path(), b.path()).unwrap(), None); } /// Describe: what is there, and the manifest of it when asked for.