diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82a2e11..b8851b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -450,9 +450,16 @@ jobs: - name: Check the crates from outside the tree # Cargo.lock lists every dependency of every package, for all # targets and features, the build and test dependencies included. - # libc, lexopt, and sha2 with the crates it needs. + # libc, lexopt, sha2 and serde_json with the crates they need. + # serde_json and serde_core name serde and serde_derive for + # cfg(any()), which no target has, so that all three keep one + # version. So these two and the crates serde_derive needs are in + # Cargo.lock, and nothing builds them. env: - EXPECTED: block-buffer cfg-if cpufeatures crypto-common digest hybrid-array lexopt libc sha2 typenum + EXPECTED: >- + block-buffer cfg-if cpufeatures crypto-common digest equivalent foldhash hashbrown hybrid-array + indexmap itoa lexopt libc memchr proc-macro2 quote serde serde_core serde_derive serde_json sha2 + syn typenum unicode-ident zmij run: | deps=$(cargo metadata --locked --format-version 1 | jq -r '.workspace_members as $m | .packages[] | select(.id as $i | $m | index($i) | not) | .name' | diff --git a/Cargo.lock b/Cargo.lock index afd3e73..a65282b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6,7 +6,6 @@ version = 4 name = "bench" version = "0.1.0" dependencies = [ - "json", "libc", "varlink", ] @@ -74,13 +73,19 @@ dependencies = [ name = "dlopen-note" version = "0.1.0" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "fat" version = "0.1.0" dependencies = [ "blkid", - "json", "libc", + "serde_json", "sha2", "uapi16", ] @@ -90,8 +95,8 @@ name = "fat-trace" version = "0.1.0" dependencies = [ "blkid", - "json", "libc", + "serde_json", "sha2", "uapi16", ] @@ -100,6 +105,12 @@ dependencies = [ name = "fold-table" version = "0.1.0" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "fuzz-seeds" version = "0.1.0" @@ -107,6 +118,12 @@ dependencies = [ "fat", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -117,8 +134,20 @@ dependencies = [ ] [[package]] -name = "json" -version = "0.1.0" +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "lexopt" @@ -132,6 +161,74 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "sha2" version = "0.11.0" @@ -143,6 +240,17 @@ dependencies = [ "digest", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "typenum" version = "1.20.1" @@ -153,8 +261,9 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" name = "uapi16" version = "0.1.0" dependencies = [ - "json", "libc", + "serde_core", + "serde_json", "sha2", ] @@ -163,17 +272,29 @@ name = "ufat" version = "0.1.0" dependencies = [ "fat", - "json", "lexopt", "libc", "uapi16", "varlink", ] +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + [[package]] name = "varlink" version = "0.1.0" dependencies = [ - "json", "libc", + "serde_core", + "serde_json", ] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 30776d3..01fc585 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,6 @@ members = [ "src/dlopen", "src/dlopen-note", "src/fat", - "src/json", "src/uapi16", "src/varlink", "tools", @@ -23,7 +22,6 @@ default-members = [ "src/dlopen", "src/dlopen-note", "src/fat", - "src/json", "src/uapi16", "src/varlink", "tests/crash", @@ -44,11 +42,16 @@ blkid = { path = "src/blkid" } dlopen = { path = "src/dlopen" } dlopen-note = { path = "src/dlopen-note" } fat = { path = "src/fat" } -json = { path = "src/json" } lexopt = "0.3.2" # The _IO and _IOR helpers came with 0.2.172. Stay on 0.2: 1.0 may drop # the LFS64 functions such as openat64 and fstatfs64. libc = "0.2.191" +# Reads and writes JSON. What a manifest asks for beyond JSON is checked +# by src/uapi16/strict.rs. Never turn on arbitrary_precision: serde_json +# then hands numbers to the visitors of uapi16 and varlink as objects, see +# the crate docs of uapi16. +serde_core = "1.0.229" +serde_json = "1.0.154" # 0.11.1 and later need rustc 1.88. sha2 = { version = "0.11.0", default-features = false } uapi16 = { path = "src/uapi16" } @@ -69,7 +72,6 @@ publish.workspace = true [dependencies] fat.workspace = true -json.workspace = true lexopt.workspace = true libc.workspace = true varlink.workspace = true diff --git a/HACKING.md b/HACKING.md index cdec898..f367f57 100644 --- a/HACKING.md +++ b/HACKING.md @@ -1,7 +1,8 @@ # Hacking on ufat -ufat is built with cargo. It depends on the libc, sha2 and lexopt -crates. lexopt parses the command line of the tool. +ufat is built with cargo. It depends on the libc, sha2, lexopt and +serde_json crates. lexopt parses the command line of the tool, and +serde_json reads and writes JSON. ufat does not link against libblkid. It loads libblkid.so.1 with dlopen() when it needs it. The workspace has a crate for each part of @@ -48,8 +49,8 @@ With rustup, `cargo +1.85.0` selects rustc 1.85: `cargo test` runs: -- the unit tests of the library and of the json, uapi16, varlink, - dlopen, dlopen-note and blkid crates, +- the unit tests of the library and of the uapi16, varlink, dlopen, + dlopen-note and blkid crates, - the integration tests in tests/, - the crash consistency harness. @@ -279,7 +280,7 @@ every push to main and once a week. It runs: - Kani with `--only-codegen`, which checks that every proof builds. The proofs themselves need more time and memory than the CI has, - a check that the crates from outside the tree are libc, lexopt, sha2 - and the crates sha2 needs, + and serde_json, and the crates they need, - bench/compare.sh with the release binary and that of the base: the target branch for a pull request, main before a push, and main of a week earlier for the weekly run. It accepts the regressions that the diff --git a/README.md b/README.md index d25de49..837600d 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ tool and the service are the same binary. - Writes are ordered so that a crash or a power loss leaves every file in its old state, its new state, or absent. A file is never left damaged. -- The code uses the Rust standard library and the crates libc, sha2 and - lexopt. +- The code uses the Rust standard library and the crates libc, sha2, + lexopt and serde_json. - libblkid names what an image holds when it holds no FAT32 file system, and keeps `assemble` from formatting over a file system or a partition table. ufat loads it at run time when it is installed, and diff --git a/bench/Cargo.toml b/bench/Cargo.toml index e1005cb..a0bdb86 100644 --- a/bench/Cargo.toml +++ b/bench/Cargo.toml @@ -18,7 +18,6 @@ name = "measure" path = "measure.rs" [dependencies] -json.workspace = true libc.workspace = true varlink.workspace = true diff --git a/bench/measure.rs b/bench/measure.rs index faf095f..a07bc24 100644 --- a/bench/measure.rs +++ b/bench/measure.rs @@ -4,7 +4,7 @@ //! bytes the child passed to read and write system calls. //! //! Like the rest of ufat, it uses the standard library and the libc crate, -//! and the json and varlink crates of this tree. +//! and the varlink crate of this tree. //! //! Usage: //! measure [OPTIONS] -- COMMAND [ARGS...] @@ -213,11 +213,16 @@ fn spawn_ufat(o: &Options) -> io::Result<(Child, UnixStream)> { } fn varlink_call(o: &Options, socket: UnixStream) -> io::Result<()> { - let Ok(json::Value::Object(params)) = json::parse(&o.params) else { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "--params is not a JSON object", - )); + // A key twice is refused, as the service refuses it. + let params = match varlink::UniqueKeys::parse(&o.params) { + Ok(varlink::Value::Object(params)) => params, + Ok(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "--params is not a JSON object", + )) + } + Err(e) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("--params: {}", e))), }; // The descriptors, in the order given: index n of the call is fds[n]. let mut files = Vec::new(); @@ -240,7 +245,7 @@ fn varlink_call(o: &Options, socket: UnixStream) -> io::Result<()> { "{} failed: {} {}", method, e.name, - json::Value::Object(e.parameters) + varlink::Value::Object(e.parameters) ))), } } diff --git a/src/bin/ufat/cli.rs b/src/bin/ufat/cli.rs index a2b4bbb..8aed0b8 100644 --- a/src/bin/ufat/cli.rs +++ b/src/bin/ufat/cli.rs @@ -1547,7 +1547,7 @@ fn cmd_capabilities(argv: &[OsString]) -> Result<()> { if !args.positional.is_empty() { bail!(errno::EINVAL, "capabilities takes no arguments"); } - println!("{}", json::Value::Object(service::capabilities()?)); + println!("{}", varlink::Value::Object(service::capabilities()?)); Ok(()) } diff --git a/src/bin/ufat/service.rs b/src/bin/ufat/service.rs index b0ba7d4..792f183 100644 --- a/src/bin/ufat/service.rs +++ b/src/bin/ufat/service.rs @@ -38,7 +38,7 @@ use fat::progress::Progress; use fat::sha512::Sha512Context; use fat::volume::{Metadata, NameCollision, Volume}; use fat::{CorruptPlace, Detail, NoSpaceReason, NotFat32Reason, UnsupportedKind}; -use json::{Object, Value}; +use varlink::{object, Object, Value}; use varlink::{Activation, Call, Connection, Info, Reply, Server, Service}; use crate::util::{ @@ -147,7 +147,7 @@ fn interface_error(name: &str, parameters: Object) -> varlink::Error { /// Adds `value` to `o` under `key` when there is one. fn optional>(o: &mut Object, key: &str, value: Option) { if let Some(v) = value { - o.insert(key, v); + o.insert(key.into(), v.into()); } } @@ -211,27 +211,27 @@ fn map_error(e: &fat::Error) -> varlink::Error { errno::ENOTEMPTY => "DirectoryNotEmpty", other => return varlink::Error::system(other), }; - interface_error(name, json::object! { "path" => path.as_str() }) + interface_error(name, object! { "path" => path.as_str() }) } Detail::Name { name, problem } => interface_error( "InvalidName", - json::object! { "name" => name.as_str(), "reason" => problem.as_str() }, + object! { "name" => name.as_str(), "reason" => problem.as_str() }, ), Detail::Label { label, problem } => interface_error( "InvalidLabel", - json::object! { "label" => label.as_str(), "reason" => problem.as_str() }, + object! { "label" => label.as_str(), "reason" => problem.as_str() }, ), Detail::Identifier { identifier, problem } => interface_error( "InvalidIdentifier", - json::object! { "identifier" => identifier.as_str(), "reason" => problem.as_str() }, + object! { "identifier" => identifier.as_str(), "reason" => problem.as_str() }, ), Detail::TooLarge { path, size, maximum } => { - let mut o = json::object! { "sizeBytes" => *size, "sizeMaxBytes" => *maximum }; + let mut o = object! { "sizeBytes" => *size, "sizeMaxBytes" => *maximum }; optional(&mut o, "path", path.as_deref()); interface_error("TooLarge", o) } Detail::NoSpace { reason, path } => { - let mut o = json::object! { "reason" => no_space_reason(*reason) }; + let mut o = object! { "reason" => no_space_reason(*reason) }; optional(&mut o, "path", path.as_deref()); interface_error("NoSpaceLeft", o) } @@ -240,19 +240,19 @@ fn map_error(e: &fat::Error) -> varlink::Error { found, sector_size, } => { - let mut o = json::object! { "reason" => not_file_system_reason(*reason) }; + let mut o = object! { "reason" => not_file_system_reason(*reason) }; optional(&mut o, "found", found.as_deref()); optional(&mut o, "sectorSize", *sector_size); interface_error("NotFileSystem", o) } - Detail::NotEmpty { found } => interface_error("ImageNotEmpty", json::object! { "found" => found.as_str() }), + Detail::NotEmpty { found } => interface_error("ImageNotEmpty", object! { "found" => found.as_str() }), Detail::Corrupt { place, field, path, cluster, } => { - let mut o = json::object! { "where" => corrupt_place(*place) }; + let mut o = object! { "where" => corrupt_place(*place) }; optional(&mut o, "field", *field); optional(&mut o, "path", path.as_deref()); optional(&mut o, "block", *cluster); @@ -272,7 +272,7 @@ fn map_error(e: &fat::Error) -> varlink::Error { name, field, } => { - let mut o = json::object! { "reason" => problem.as_str() }; + let mut o = object! { "reason" => problem.as_str() }; optional(&mut o, "record", *record); optional(&mut o, "name", name.as_deref()); optional(&mut o, "field", field.as_deref()); @@ -280,7 +280,7 @@ fn map_error(e: &fat::Error) -> varlink::Error { } Detail::Source { name, problem } => interface_error( "SourceMismatch", - json::object! { "name" => name.as_str(), "reason" => problem.as_str() }, + object! { "name" => name.as_str(), "reason" => problem.as_str() }, ), Detail::Content { name, @@ -288,23 +288,23 @@ fn map_error(e: &fat::Error) -> varlink::Error { size, expected, } => { - let mut o = json::object! { "name" => name.as_str(), "reason" => problem.as_str() }; + let mut o = object! { "name" => name.as_str(), "reason" => problem.as_str() }; optional(&mut o, "sizeBytes", *size); optional(&mut o, "expectedSizeBytes", *expected); interface_error("ContentMismatch", o) } Detail::Unsupported { name, what, value } => { - let mut o = json::object! { "what" => what.as_str() }; + let mut o = object! { "what" => what.as_str() }; optional(&mut o, "name", name.as_deref()); optional(&mut o, "value", value.as_deref()); interface_error("ContentNotSupported", o) } Detail::Validity { name, problem } => interface_error( "EntryNotValid", - json::object! { "name" => name.as_str(), "reason" => problem.as_str() }, + object! { "name" => name.as_str(), "reason" => problem.as_str() }, ), Detail::FileSystemMismatch { field, expected, found } => { - let mut o = json::object! { "field" => field.as_str() }; + let mut o = object! { "field" => field.as_str() }; optional(&mut o, "expected", expected.as_deref()); optional(&mut o, "found", found.as_deref()); interface_error("FileSystemMismatch", o) @@ -320,7 +320,7 @@ fn bad_file_descriptor(parameter: &str, e: &fat::Error) -> varlink::Error { Some(Detail::Descriptor { problem, flags, .. }) => (problem.as_str(), *flags), _ => ("wrongType", None), }; - let mut o = json::object! { "parameter" => parameter, "reason" => problem }; + let mut o = object! { "parameter" => parameter, "reason" => problem }; optional(&mut o, "flags", flags); interface_error("BadFileDescriptor", o) } @@ -331,18 +331,16 @@ fn fail(f: Failure) -> varlink::Error { Failure::BadDescriptor { parameter, error } => bad_file_descriptor(¶meter, &error), Failure::TooSmall { minimal, actual } => interface_error( "TooSmall", - json::object! { + object! { "minimalSizeBytes" => minimal, "sizeBytes" => actual, }, ), Failure::Unsupported(operation) => { - interface_error("OperationNotSupported", json::object! { "operation" => operation }) + interface_error("OperationNotSupported", object! { "operation" => operation }) } - Failure::FileSystemType(t) => { - interface_error("FileSystemTypeNotSupported", json::object! { "fileSystemType" => t }) - } - Failure::NotReproducible(reason) => interface_error("NotReproducible", json::object! { "reason" => reason }), + Failure::FileSystemType(t) => interface_error("FileSystemTypeNotSupported", object! { "fileSystemType" => t }), + Failure::NotReproducible(reason) => interface_error("NotReproducible", object! { "reason" => reason }), Failure::SizeRequired => interface_error("SizeRequired", Object::new()), Failure::Busy => interface_error("ImageBusy", Object::new()), Failure::ExpectedMore => varlink::Error::expected_more(), @@ -371,7 +369,7 @@ fn fit_error(e: util::FitError) -> Failure { /// A finding of Check as the interface carries it: its class, its kind and /// the facts it has, with the interface's names (a cluster is a block). fn problem(p: &Problem) -> Object { - let mut o = json::object! { + let mut o = object! { "severity" => if p.severity == fsck::Severity::Error { "error" } else { "warning" }, "class" => p.kind.class().as_str(), "kind" => p.kind.as_str(), @@ -410,7 +408,7 @@ impl Params<'_> { fn u64(&self, key: &str) -> Outcome> { match self.0.get(key) { None | Some(Value::Null) => Ok(None), - Some(Value::Int(i)) => u64::try_from(*i).map(Some).map_err(|_| invalid(key)), + Some(Value::Number(n)) => n.as_u64().map(Some).ok_or_else(|| invalid(key)), Some(Value::String(s)) => s.parse::().map(Some).map_err(|_| invalid(key)), Some(_) => Err(invalid(key)), } @@ -474,7 +472,7 @@ fn check_type(p: &Params<'_>) -> Outcome<()> { /// Tells a client that asked for intermediate replies which step begins. fn phase(c: &mut Connection, more: bool, phase: &str) -> Outcome<()> { if more { - c.notify(json::object! { "phase" => phase })?; + c.notify(object! { "phase" => phase })?; } Ok(()) } @@ -511,7 +509,7 @@ impl<'c> Reporter<'c> { /// Enters `phase` and tells the caller, as [`phase`] does. fn start(connection: &'c mut Connection, more: bool, phase: &'static str, shown: Shown) -> Outcome> { if more { - connection.notify(json::object! { "phase" => phase })?; + connection.notify(object! { "phase" => phase })?; } Ok(Reporter { connection, @@ -529,13 +527,13 @@ impl<'c> Reporter<'c> { if !self.more || self.gone || self.last.elapsed() < PROGRESS_INTERVAL { return; } - let mut o = json::object! { "phase" => self.phase }; + let mut o = object! { "phase" => self.phase }; if self.shown != Shown::PhaseOnly { - o.insert("files", progress.files); - o.insert("directories", progress.directories); + o.insert("files".into(), progress.files.into()); + o.insert("directories".into(), progress.directories.into()); } if self.shown == Shown::EntriesAndBytes { - o.insert("bytes", progress.bytes); + o.insert("bytes".into(), progress.bytes.into()); } self.gone = self.connection.notify(o).is_err(); self.last = Instant::now(); @@ -748,7 +746,7 @@ fn stored_label(options: &FormatOptions) -> Outcome> { /// The file system as it is: the interface's `Description`. fn description(v: &Volume) -> Outcome { let l = v.layout(); - let mut o = json::object! { + let mut o = object! { "fileSystemType" => FILE_SYSTEM_TYPE, "identifier" => VolumeId(v.boot_sector().volume_id).to_string(), "sectorSize" => l.sector_size, @@ -763,7 +761,7 @@ fn description(v: &Volume) -> Outcome { /// A directory entry as the interface's `Entry`: FAT has names, an 8.3 /// alias, sizes, two times and the DOS attributes, and nothing else. fn entry(m: &Metadata) -> Object { - let mut o = json::object! { + let mut o = object! { "name" => m.name.as_str(), "type" => if m.is_dir { "dir" } else { "reg" }, "sizeBytes" => m.size, @@ -782,7 +780,7 @@ fn entry(m: &Metadata) -> Object { .map(|(_, name)| *name) .collect(); if !attributes.is_empty() { - o.insert("dosAttributes", attributes); + o.insert("dosAttributes".into(), attributes.into()); } o } @@ -796,7 +794,7 @@ pub(crate) fn capabilities() -> fat::Result { let minimal = layout::minimal(¶ms, MIN_CLUSTERS)?.size(); let powers_of_two = |from: u32, to: u32| -> Vec { (0..).map(|i| from << i).take_while(|&s| s <= to).collect() }; - Ok(json::object! { + Ok(object! { "fileSystemType" => FILE_SYSTEM_TYPE, "implementation" => "ufat", "version" => VERSION, @@ -824,10 +822,10 @@ pub(crate) fn capabilities() -> fat::Result { // as the planner goes; larger clusters work on Linux but not // everywhere. "blockSizes" => powers_of_two(MIN_SECTOR_SIZE, MAX_CLUSTER_SIZE), - "label" => json::object! { "lengthMax" => 11, "unit" => "bytes", "charset" => "fat" }, + "label" => object! { "lengthMax" => 11, "unit" => "bytes", "charset" => "fat" }, "identifier" => "serial", "preserves" => vec!["dosAttributes"], - "times" => json::object! { + "times" => object! { "resolutionNSec" => 2_000_000_000u64, "minUSec" => fat::time::FAT_EPOCH as u64 * 1_000_000, "maxUSec" => fat::time::FAT_MAX as u64 * 1_000_000, @@ -842,7 +840,7 @@ pub(crate) fn capabilities() -> fat::Result { "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() }, + "manifest" => object! { "order" => Order::CodePoint.as_str() }, }) } @@ -1000,10 +998,10 @@ impl Counts { /// relative to a directory the caller knows by descriptor only, and /// a list is as long as the caller's tree lets it be. fn put(&self, o: &mut Object) { - o.insert("files", self.files); - o.insert("directories", self.directories); - o.insert("bytes", self.bytes); - o.insert("skipped", self.skipped); + o.insert("files".into(), self.files.into()); + o.insert("directories".into(), self.directories.into()); + o.insert("bytes".into(), self.bytes.into()); + o.insert("skipped".into(), self.skipped.into()); } } @@ -1303,7 +1301,7 @@ fn parent_of(path: &str) -> Option<&str> { impl FileSystemService { fn get_capabilities(&self, p: &Params<'_>) -> Outcome { check_type(p)?; - Ok(json::object! { "capabilities" => capabilities()? }) + Ok(object! { "capabilities" => capabilities()? }) } fn assemble(&self, p: &Params<'_>, c: &mut Connection, more: bool) -> Outcome { @@ -1365,14 +1363,14 @@ impl FileSystemService { Some(s) => Some(Sink::take(&s, c)?), }; let volume = image.open_volume(Access::ReadOnly)?; - let mut o = json::object! { "description" => description(&volume)? }; + let mut o = object! { "description" => description(&volume)? }; if let Some(sink) = sink { let mut r = Reporter::start(c, more, "reading", Shown::EntriesAndBytes)?; let w = sink.write(&volume, &mut |p| r.tick(p))?; - o.insert("files", w.files); - o.insert("directories", w.directories); - o.insert("bytes", w.bytes); - o.insert("omitted", w.omissions()); + o.insert("files".into(), w.files.into()); + o.insert("directories".into(), w.directories.into()); + o.insert("bytes".into(), w.bytes.into()); + o.insert("omitted".into(), w.omissions().into()); } Ok(o) } @@ -1488,7 +1486,7 @@ impl FileSystemService { (0, 1) }; v.close()?; - Ok(json::object! { "files" => files, "directories" => directories }) + Ok(object! { "files" => files, "directories" => directories }) } fn list(&self, p: &Params<'_>, c: &mut Connection, more: bool) -> Outcome { @@ -1498,7 +1496,7 @@ impl FileSystemService { let v = image.open_volume(Access::ReadOnly)?; let md = v.metadata(path)?; if !md.is_dir { - return Ok(json::object! { "entry" => entry(&md) }); + return Ok(object! { "entry" => entry(&md) }); } if !more { return Err(Failure::ExpectedMore); @@ -1508,7 +1506,7 @@ impl FileSystemService { let entries = v.read_dir(path)?; let mut it = entries.iter().peekable(); while let Some(m) = it.next() { - let o = json::object! { "entry" => entry(m) }; + let o = object! { "entry" => entry(m) }; if it.peek().is_none() { return Ok(o); } @@ -1527,7 +1525,7 @@ impl FileSystemService { let device = image.open(Access::ReadOnly)?; let mut r = Reporter::start(c, more, "checking", Shown::PhaseOnly)?; let report = fsck::check_with_progress(&device, &mut |p| r.tick(p))?; - let mut o = json::object! { + let mut o = object! { "errors" => report.errors(), "warnings" => report.warnings(), "repaired" => 0u64, @@ -1540,11 +1538,11 @@ impl FileSystemService { // The findings in batches, the counts in the final reply. for batch in report.problems.chunks(PROBLEM_BATCH) { let problems: Vec = batch.iter().map(|pr| Value::Object(problem(pr))).collect(); - c.notify(json::object! { "problems" => problems })?; + c.notify(object! { "problems" => problems })?; } } else { let problems: Vec = report.problems.iter().map(|pr| Value::Object(problem(pr))).collect(); - o.insert("problems", problems); + o.insert("problems".into(), problems.into()); } Ok(o) } @@ -1574,7 +1572,7 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more } let e = plan.estimate()?; e.apply(&mut options.format); - let mut d = json::object! { + let mut d = object! { "fileSystemType" => FILE_SYSTEM_TYPE, "identifier" => VolumeId(options.format.volume_id).to_string(), "sectorSize" => e.layout.sector_size, @@ -1583,7 +1581,7 @@ fn plan(mut options: Options, content: Option, c: &mut Connection, more "minimalSizeBytes" => e.size(), }; optional(&mut d, "label", stored_label(&options.format)?); - Ok(json::object! { + Ok(object! { "description" => d, "files" => e.files, "directories" => e.directories, @@ -1706,7 +1704,7 @@ fn assemble_image( }; let window = volume.device().len(); volume.close()?; - let mut o = json::object! { "description" => description }; + let mut o = object! { "description" => description }; if let Some(counts) = counts { counts.put(&mut o); } @@ -1714,7 +1712,7 @@ fn assemble_image( if let (Some(hash), Some(fd)) = (hash, reader) { let mut r = Reporter::start(c, more, "reading", Shown::PhaseOnly)?; let device = Device::from_passed(fd, Access::ReadOnly)?.window(offset, Some(window))?; - o.insert("imageHash", hash.of(&device, &mut |p| r.tick(p))?); + o.insert("imageHash".into(), hash.of(&device, &mut |p| r.tick(p))?.into()); } Ok(o) } diff --git a/src/fat/Cargo.toml b/src/fat/Cargo.toml index ca92cfa..89a0414 100644 --- a/src/fat/Cargo.toml +++ b/src/fat/Cargo.toml @@ -17,8 +17,9 @@ libc.workspace = true sha2.workspace = true uapi16.workspace = true +# The tests look at the order of the keys the manifest writer writes. [dev-dependencies] -json.workspace = true +serde_json = { workspace = true, features = ["preserve_order"] } [lints] workspace = true diff --git a/src/fat/manifest/error.rs b/src/fat/manifest/error.rs index 0d677d9..4eb3ec5 100644 --- a/src/fat/manifest/error.rs +++ b/src/fat/manifest/error.rs @@ -2,7 +2,7 @@ //! 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, Field, Invalid, Problem, UnsupportedContent}; +use uapi16::{ErrorKind, Field, Problem, UnsupportedContent}; use super::path_in_volume; use crate::errno::*; @@ -152,9 +152,12 @@ impl From for Error { } ErrorKind::NotValid(reason) => { let (errno, problem) = match reason { - Invalid::Revoked => (EKEYREVOKED, ValidityProblem::Revoked), - Invalid::NotYetValid => (EKEYEXPIRED, ValidityProblem::NotYetValid), - Invalid::Expired => (EKEYEXPIRED, ValidityProblem::Expired), + uapi16::ValidityProblem::Revoked => (EKEYREVOKED, ValidityProblem::Revoked), + uapi16::ValidityProblem::NotYetValid => (EKEYEXPIRED, ValidityProblem::NotYetValid), + uapi16::ValidityProblem::Expired => (EKEYEXPIRED, ValidityProblem::Expired), + // A reason this crate does not know of. The entry is not + // to be used now all the same. + _ => return Error::new(EKEYEXPIRED, e.to_string()), }; Error::new(errno, e.to_string()).with(Detail::Validity { name: path, problem }) } diff --git a/src/fat/manifest/generate.rs b/src/fat/manifest/generate.rs index 8dc877a..b4b2e97 100644 --- a/src/fat/manifest/generate.rs +++ b/src/fat/manifest/generate.rs @@ -5,7 +5,7 @@ use std::io::{Read, Write}; use std::os::fd::BorrowedFd; -use uapi16::{Features, FileObject, Finalize, InodeType, InvalidName, Name, Order, RootObject, Sha256Context, Writer}; +use uapi16::{Features, FileObject, Finalize, InodeType, Name, Order, RootObject, Sha256Context, Writer}; use super::WriteReport; use crate::host::{read_some, HostEntry, UnnamableEntry}; @@ -102,7 +102,7 @@ impl Listing { 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(uapi16::NameProblem::Reserved) => return Ok(false), Err(_) => { self.report.omitted += 1; return Ok(false); diff --git a/src/fat/manifest/volume.rs b/src/fat/manifest/volume.rs index a422201..f01c5bf 100644 --- a/src/fat/manifest/volume.rs +++ b/src/fat/manifest/volume.rs @@ -424,7 +424,7 @@ mod tests { use crate::populate::CopyOptions; use crate::test_util::{volume, TempDir, TempImage}; use crate::volume::NameCollision; - use json::Object; + use serde_json::{Map, Value}; use std::os::fd::AsFd; use std::time::{Duration, UNIX_EPOCH}; use uapi16::{Digest, DosFlags, InodeFlags, Object as ManifestObject, Reader, RECORD_SEPARATOR}; @@ -524,7 +524,7 @@ mod tests { /// The records as text and as objects, to look at what the parser /// drops. Checks the frame on the way: one separator, one newline per /// record, keys sorted, no whitespace (none of the names here has any). - fn records(bytes: &[u8]) -> Vec<(String, Object)> { + fn records(bytes: &[u8]) -> Vec<(String, Map)> { let text = std::str::from_utf8(bytes).unwrap(); assert!(text.starts_with(RECORD_SEPARATOR as char)); text.split(RECORD_SEPARATOR as char) @@ -532,11 +532,11 @@ mod tests { .map(|r| { let r = r.strip_suffix('\n').unwrap(); assert!(!r.chars().any(char::is_whitespace), "{}", r); - let o = match json::parse(r).unwrap() { - json::Value::Object(o) => o, + let o = match serde_json::from_str(r).unwrap() { + Value::Object(o) => o, other => panic!("{} is not an object", other), }; - let keys: Vec<&str> = o.keys().collect(); + let keys: Vec<&str> = o.keys().map(String::as_str).collect(); let mut sorted = keys.clone(); sorted.sort_unstable(); assert_eq!(keys, sorted, "{}", r); @@ -656,7 +656,7 @@ mod tests { 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!( - o.get("type").and_then(json::Value::as_str), + o.get("type").and_then(Value::as_str), (e.inode_type == D).then_some("dir"), "{}", text @@ -700,8 +700,8 @@ mod tests { assert_eq!(recs[2].0, r#"{"name":"EFI","type":"dir"}"#); assert_eq!(recs[4].0, r#"{"name":"EFI/BOOT/BOOTX64.EFI","readOnly":true}"#); for (text, o) in &recs[1..=NAMES.len()] { - let keys: Vec<&str> = o.keys().filter(|k| *k != "readOnly").collect(); - let name = o.get("name").and_then(json::Value::as_str).unwrap(); + let keys: Vec<&str> = o.keys().map(String::as_str).filter(|k| *k != "readOnly").collect(); + let name = o.get("name").and_then(Value::as_str).unwrap(); let expected: &[&str] = if ["EFI", "EFI/BOOT", "_notes", "zz"].contains(&name) { &["name", "type"] } else { diff --git a/src/json/Cargo.toml b/src/json/Cargo.toml deleted file mode 100644 index 7b45639..0000000 --- a/src/json/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: LGPL-2.1-or-later - -[package] -name = "json" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -publish.workspace = true - -[lib] -path = "lib.rs" - -[lints] -workspace = true diff --git a/src/json/lib.rs b/src/json/lib.rs deleted file mode 100644 index ff97f3f..0000000 --- a/src/json/lib.rs +++ /dev/null @@ -1,2609 +0,0 @@ -// SPDX-License-Identifier: LGPL-2.1-or-later -//! 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, 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 -//! 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::{self, Write as _}; -use std::str::FromStr; - -/// A JSON value. -#[derive(Clone, Debug, PartialEq)] -pub enum Value { - /// `null` - Null, - /// `true` or `false` - Bool(bool), - /// A number without fraction or exponent, other than -0. - Int(i128), - /// Any other number. - Float(f64), - /// A string. - String(String), - /// An array. - Array(Vec), - /// An object. - Object(Object), -} - -/// A JSON object: key/value pairs in insertion order with unique keys. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Object { - entries: Vec<(String, Value)>, -} - -impl Object { - /// An empty object. - pub fn new() -> Object { - Object::default() - } - - /// The value stored under `key`. - pub fn get(&self, key: &str) -> Option<&Value> { - self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v) - } - - /// Whether `key` is present, even with a null value. - pub fn contains_key(&self, key: &str) -> bool { - self.entries.iter().any(|(k, _)| k == key) - } - - /// Stores `value` under `key`, replacing an existing value. - pub fn insert(&mut self, key: impl Into, value: impl Into) -> &mut Object { - let key = key.into(); - let value = value.into(); - match self.entries.iter_mut().find(|(k, _)| *k == key) { - Some(slot) => slot.1 = value, - None => self.entries.push((key, value)), - } - self - } - - /// Removes `key` and returns its value. - pub fn remove(&mut self, key: &str) -> Option { - let i = self.entries.iter().position(|(k, _)| k == key)?; - Some(self.entries.remove(i).1) - } - - /// Number of entries. - pub fn len(&self) -> usize { - self.entries.len() - } - - /// Whether the object has no entries. - pub fn is_empty(&self) -> bool { - self.entries.is_empty() - } - - /// The entries in insertion order. - pub fn iter(&self) -> impl Iterator { - self.into_iter() - } - - /// The keys in insertion order. - pub fn keys(&self) -> impl Iterator { - self.entries.iter().map(|(k, _)| k.as_str()) - } - - /// Sorts the entries by key, recursively. - pub fn sort(&mut self) { - self.entries.sort_by(|a, b| a.0.cmp(&b.0)); - for (_, v) in &mut self.entries { - v.sort_objects(); - } - } -} - -impl Value { - /// Whether the value is `null`. - pub fn is_null(&self) -> bool { - matches!(self, Value::Null) - } - - /// The boolean, if this is one. - pub fn as_bool(&self) -> Option { - match self { - Value::Bool(b) => Some(*b), - _ => None, - } - } - - /// The integer as i64, if this is an integer in range. - pub fn as_i64(&self) -> Option { - match self { - Value::Int(i) => i64::try_from(*i).ok(), - _ => None, - } - } - - /// The integer as u64, if this is a non-negative integer in range. - pub fn as_u64(&self) -> Option { - match self { - Value::Int(i) => u64::try_from(*i).ok(), - _ => None, - } - } - - /// The number as f64, integers included. - pub fn as_f64(&self) -> Option { - match self { - Value::Int(i) => Some(*i as f64), - Value::Float(f) => Some(*f), - _ => None, - } - } - - /// The string, if this is one. - pub fn as_str(&self) -> Option<&str> { - match self { - Value::String(s) => Some(s), - _ => None, - } - } - - /// The array, if this is one. - pub fn as_array(&self) -> Option<&[Value]> { - match self { - Value::Array(a) => Some(a), - _ => None, - } - } - - /// The object, if this is one. - pub fn as_object(&self) -> Option<&Object> { - match self { - Value::Object(o) => Some(o), - _ => None, - } - } - - /// The object, mutably, if this is one. - pub fn as_object_mut(&mut self) -> Option<&mut Object> { - match self { - Value::Object(o) => Some(o), - _ => None, - } - } - - /// Member `key` of an object. - pub fn get(&self, key: &str) -> Option<&Value> { - self.as_object()?.get(key) - } - - /// Sorts all objects inside the value by key. - pub fn sort_objects(&mut self) { - match self { - Value::Object(o) => o.sort(), - Value::Array(a) => a.iter_mut().for_each(Value::sort_objects), - _ => {} - } - } -} - -/// The entries of an object. -type Entries<'a> = - std::iter::Map, fn(&'a (String, Value)) -> (&'a str, &'a Value)>; - -impl<'a> IntoIterator for &'a Object { - type Item = (&'a str, &'a Value); - type IntoIter = Entries<'a>; - - /// The entries in insertion order. - fn into_iter(self) -> Entries<'a> { - self.entries.iter().map(|(k, v)| (k.as_str(), v)) - } -} - -impl FromStr for Value { - type Err = ParseError; - - /// Parses a complete JSON text, see [`parse`]. - fn from_str(text: &str) -> Result { - parse(text) - } -} - -impl From for Value { - fn from(b: bool) -> Value { - Value::Bool(b) - } -} - -impl From for Value { - fn from(i: i64) -> Value { - Value::Int(i128::from(i)) - } -} - -impl From for Value { - fn from(i: u64) -> Value { - Value::Int(i128::from(i)) - } -} - -impl From for Value { - fn from(i: u32) -> Value { - Value::Int(i128::from(i)) - } -} - -impl From for Value { - fn from(i: i32) -> Value { - Value::Int(i128::from(i)) - } -} - -impl From for Value { - fn from(i: usize) -> Value { - // No usize is wider than 64 bits. - Value::Int(i as i128) - } -} - -impl From for Value { - fn from(f: f64) -> Value { - Value::Float(f) - } -} - -impl From<&str> for Value { - fn from(s: &str) -> Value { - Value::String(s.to_string()) - } -} - -impl From for Value { - fn from(s: String) -> Value { - Value::String(s) - } -} - -impl From for Value { - fn from(o: Object) -> Value { - Value::Object(o) - } -} - -impl> From> for Value { - fn from(v: Vec) -> Value { - Value::Array(v.into_iter().map(Into::into).collect()) - } -} - -impl> From> for Value { - fn from(v: Option) -> Value { - match v { - Some(v) => v.into(), - None => Value::Null, - } - } -} - -/// Where and why parsing failed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct ParseError { - /// Byte offset into the text. - pub offset: usize, - /// What went wrong. - pub message: &'static str, - /// Whether the text is not JSON, has a key twice in an object, or - /// breaks a rule of the parser. - 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, - /// A string breaks one of the [`StringRules`] the parser was made with. - StringRule, -} - -impl fmt::Display for ParseError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} at byte {}", self.message, self.offset) - } -} - -impl std::error::Error for ParseError {} - -/// 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; - -/// 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), - } - } -} - -/// 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 { - /// 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>, - /// 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, - levels: [Container::Array; MAX_OPEN], - depth: 0, - empty: false, - keys: Keys::default(), - skipped: SkippedValue::default(), - rules, - } - } - - /// 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 self.byte().is_some_and(is_whitespace) { - self.pos += 1; - } - } - - fn byte(&self) -> Option { - self.bytes().get(self.pos).copied() - } - - fn expect(&mut self, b: u8) -> Result<(), ParseError> { - if self.byte() == Some(b) { - self.pos += 1; - Ok(()) - } else { - Err(self.error("unexpected character")) - } - } - - /// 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.byte() { - None => Err(self.error("unexpected end of input")), - 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) -> Result<(), ParseError> { - if self.bytes()[self.pos..].starts_with(word.as_bytes()) { - self.pos += word.len(); - Ok(()) - } else { - Err(self.error("invalid literal")) - } - } - - /// 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; - } - // 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(); - } - _ => 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")); - } - } - 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; - } - if !self.digits() { - return Err(self.error("invalid number")); - } - } - Ok((&self.text[start..self.pos], is_float)) - } - - /// 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)) - } - - /// 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"))?; - // 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..]); - } - - /// 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; - // 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]); - loop { - match self.byte() { - None => return Err(self.error("unterminated string")), - Some(QUOTE) => { - self.pos += 1; - break; - } - Some(ESCAPE) => { - self.pos += 1; - let esc = self.byte().ok_or_else(|| self.error("unterminated string"))?; - self.pos += 1; - match esc { - 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 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")); - } - 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]); - } - 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> { - if self.peek()? != Kind::String { - return Ok(None); - } - 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(); - } - 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) - } - _ if first => Ok(true), - Some(VALUE_SEPARATOR) => { - self.pos += 1; - Ok(true) - } - _ => Err(self.error("expected ',' or ']'")), - } - } - - /// 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 first => {} - Some(VALUE_SEPARATOR) => { - self.pos += 1; - self.skip_whitespace(); - } - _ => 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; - } - } - } - - /// 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")); - } - if self.pos != self.text.len() { - return Err(self.error("trailing characters")); - } - 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 parser = Parser::new(text); - let value = parser.value()?; - parser.end()?; - Ok(value) -} - -/// 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[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; - } -} - -/// 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('"') -} - -/// 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)?; - } - f.write_char(']') - } - Value::Object(o) => o.fmt(f), - } - } -} - -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)?; - } - f.write_char('}') - } -} - -/// 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 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()) - } -} - -/// Builds an object from key/value pairs. -#[macro_export] -macro_rules! object { - ($($key:expr => $value:expr),* $(,)?) => {{ - let mut o = $crate::Object::new(); - $( o.insert($key, $value); )* - o - }}; -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn serializes_escapes_and_floats() { - let text = Value::String("a\u{1}b\"c\\\n\u{7f}\u{e9}".into()).to_string(); - assert_eq!(text, "\"a\\u0001b\\\"c\\\\\\n\u{7f}\u{e9}\""); - assert_eq!( - text.parse::(), - Ok(Value::String("a\u{1}b\"c\\\n\u{7f}\u{e9}".into())) - ); - for (f, text) in [ - (1.0, "1.0"), - (-0.0, "-0.0"), - (1.5, "1.5"), - (1e15, "1000000000000000.0"), - (1e21, "1e21"), - (-2.5e-8, "-2.5e-8"), - (5e-324, "5e-324"), - (f64::NAN, "null"), - (f64::INFINITY, "null"), - ] { - assert_eq!(Value::Float(f).to_string(), text); - } - let o = object! { "a" => 1u32, "b" => "x" }; - assert_eq!(o.to_string(), r#"{"a":1,"b":"x"}"#); - assert_eq!((&o).into_iter().map(|(k, _)| k).collect::>(), ["a", "b"]); - } - - #[test] - fn round_trips() { - for text in [ - r#"{"a":1,"b":[true,false,null],"c":"x\"y\\z\n","d":{"e":-12,"f":1.5}}"#, - r#"[]"#, - r#"{}"#, - r#""\u00e9\ud83d\ude00""#, - r#"18446744073709551615"#, - r#"-170141183460469231731687303715884105728"#, - r#"1e300"#, - ] { - let v = parse(text).unwrap(); - let again = parse(&v.to_string()).unwrap(); - assert_eq!(v, again, "{}", text); - } - assert_eq!(parse("\"\\u00e9\"").unwrap().as_str(), Some("é")); - assert_eq!(parse("\"\\ud83d\\ude00\"").unwrap().as_str(), Some("\u{1F600}")); - assert_eq!(parse("18446744073709551615").unwrap().as_u64(), Some(u64::MAX)); - assert_eq!(parse("-1").unwrap().as_u64(), None); - 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 [ - "", - " ", - "{", - "[1,]", - "{\"a\":1,}", - "{a:1}", - "01", - "1.", - ".5", - "+1", - "1e", - "tru", - "nul", - "\"abc", - "\"a\u{01}b\"", - "\"\\x\"", - "\"\\ud83d\"", - "\"\\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\"", - "\"\\u+041\"", - "\"\\u-041\"", - ] { - assert!(parse(text).is_err(), "{:?} accepted", text); - } - let deep = "[".repeat(200) + &"]".repeat(200); - assert!(parse(&deep).is_err()); - // Many keys stay cheap to check for duplicates; one duplicate among - // them is still found. - let keys: Vec = (0..20_000).map(|i| format!("\"k{}\":{}", i, i)).collect(); - let wide = format!("{{{}}}", keys.join(",")); - 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 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(","))) - .unwrap() - .as_object() - .unwrap() - .len(), - n - ); - for at in [0, n / 2, n - 1] { - let dup = format!("{{{},\"k{}\":0}}", keys.join(","), at); - assert!(parse(&dup).is_err(), "{} keys, duplicate of {}", n, at); - } - } - } - - #[test] - fn objects() { - let mut o = object! { "b" => 1i64, "a" => "x" }; - assert_eq!(o.keys().collect::>(), vec!["b", "a"]); - o.insert("b", 2i64); - assert_eq!(o.get("b").unwrap().as_i64(), Some(2)); - assert_eq!(o.len(), 2); - o.sort(); - assert_eq!(o.keys().collect::>(), vec!["a", "b"]); - assert_eq!(o.remove("a"), Some(Value::from("x"))); - assert!(!o.contains_key("a")); - let v: Value = object! { "n" => Value::Null, "list" => vec![1u32, 2] }.into(); - assert_eq!(v.to_string(), r#"{"n":null,"list":[1,2]}"#); - assert_eq!(v.get("list").unwrap().as_array().unwrap().len(), 2); - } - - #[test] - fn escapes() { - 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 - /// 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)); - } - } - } - - #[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; - - #[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); - } - } - } - } - - #[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); - } -} diff --git a/src/uapi16/Cargo.toml b/src/uapi16/Cargo.toml index bec37f0..d716245 100644 --- a/src/uapi16/Cargo.toml +++ b/src/uapi16/Cargo.toml @@ -12,9 +12,16 @@ publish.workspace = true path = "lib.rs" [dependencies] -json.workspace = true libc.workspace = true +serde_core.workspace = true +# Without float_roundtrip serde_json refuses some spellings of the largest +# doubles as out of range, such as 1.7976931348623158e308. +serde_json = { workspace = true, features = ["float_roundtrip"] } sha2.workspace = true +# The tests look at the order of the keys the writer writes. +[dev-dependencies] +serde_json = { workspace = true, features = ["preserve_order"] } + [lints] workspace = true diff --git a/src/uapi16/blocking.rs b/src/uapi16/blocking.rs index dd26d74..f5f0869 100644 --- a/src/uapi16/blocking.rs +++ b/src/uapi16/blocking.rs @@ -14,10 +14,6 @@ use crate::writer::Encoder; /// How much is read from the input at a time. pub(crate) const READ_SIZE: usize = 64 * 1024; -/// 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; /// Reads a manifest record by record. /// @@ -274,38 +270,34 @@ impl FusedIterator for Reader {} #[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 }; + let encoder = Encoder::start(root)?; + let mut writer = Writer { out, 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)) + self.send_record(|encoder| encoder.encode_file(file)) } /// 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)) + self.send_record(|encoder| encoder.encode_signature(signature)) } /// 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.send_record(Encoder::encode_trailer)?; self.out.flush().map_err(|e| Error::from(e).in_record(record_number))?; Ok(self.out) } @@ -318,30 +310,18 @@ impl Writer { &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> { + /// Writes out the record that `encode` has the encoder put together. + fn send_record(&mut self, encode: impl FnOnce(&mut Encoder) -> 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) - } - } + encode(&mut self.encoder)?; + self.write_out(record_number) } - /// 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. + /// Writes out the record the encoder put together, the one with the + /// number `record_number`, in one write. 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); + let written = self.out.write_all(&self.encoder.record); + self.encoder.clear_record(); written.map_err(|e| Error::from(e).in_record(record_number)) } } @@ -354,6 +334,7 @@ mod tests { directory, everything, manifest, name, read_whole, read_whole_from, record, recording_all, sequence, write_whole, Whole, EMPTY, PIECES, ROOT, SIGNATURE, TRAILER, }; + use crate::writer::RECORD_CAPACITY; use crate::{InodeType, Name, Sha256, MAX_RECORD_SIZE, RECORD_SEPARATOR}; use std::collections::BTreeMap; @@ -628,7 +609,7 @@ mod tests { format!("manifest record exceeds {} bytes", MAX_RECORD_SIZE) ); assert_eq!(writer.get_ref().len(), before); - assert!(writer.text.capacity() <= TEXT_CAPACITY); + assert!(writer.encoder.record.capacity() <= RECORD_CAPACITY); // A directory that is not written is not the directory of what // comes next. let mut large = padded("d", MAX_RECORD_SIZE); @@ -641,7 +622,7 @@ mod tests { 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); + assert!(writer.encoder.record.capacity() <= RECORD_CAPACITY); let mut signature = Signature::new("pkcs7"); signature.data = Some(vec![0; MAX_RECORD_SIZE]); let e = writer.signature(&signature).unwrap_err(); diff --git a/src/uapi16/content.rs b/src/uapi16/content.rs index 4e84df7..fbb28b6 100644 --- a/src/uapi16/content.rs +++ b/src/uapi16/content.rs @@ -494,6 +494,7 @@ pub trait ContentSource { /// Why a [`Directory`] does not hand out a file. #[derive(Debug)] +#[non_exhaustive] pub enum OpenError { /// What the name names is not a regular file. NotRegular, @@ -1081,7 +1082,7 @@ impl ContentSource for StreamSource { #[cfg(test)] mod tests { use super::*; - use crate::testing::{manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; + use crate::testing::{json, manifest, read_whole, sequence, HELLO, TRAILER, WORLD}; use crate::Digest; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -1226,9 +1227,13 @@ mod tests { /// 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)) + let name = json(record) + .and_then(|value| { + value + .get("name") + .and_then(serde_json::Value::as_str) + .map(str::to_string) + }) .unwrap_or_default(); let mut records: Vec = name .match_indices('/') diff --git a/src/uapi16/decode.rs b/src/uapi16/decode.rs index c8e8626..9756af2 100644 --- a/src/uapi16/decode.rs +++ b/src/uapi16/decode.rs @@ -3,19 +3,21 @@ //! 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. +//! A record is read once, member by member: serde_json reads it, and the +//! visitors here take its values as they come. 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::convert::Infallible; use std::fmt; use std::num::NonZeroU64; -use json::{ParseError, Parser}; +use serde_core::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor}; use crate::base64::Base64; use crate::digest::Digest; @@ -25,9 +27,9 @@ use crate::object::{ Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FlagSet, GptPartition, InodeAttributes, InodeFlags, InodeType, Location, Mode, RootObject, Signature, Uuid, Validity, }; +use crate::strict::{FieldTable, Key, Members, Skip, Strict}; use crate::{ - Features, Name, Order, Sha256, MAX_CONTENTS, MEDIA_TYPE, SIGNATURE_MEDIA_TYPE, STRING_RULES, TRAILER_MEDIA_TYPE, - USER_NAMESPACE, + Features, Name, Order, Sha256, MAX_CONTENTS, MEDIA_TYPE, SIGNATURE_MEDIA_TYPE, TRAILER_MEDIA_TYPE, USER_NAMESPACE, }; /// The user and group ID that is -1 as an unsigned 32-bit integer, @@ -192,7 +194,7 @@ impl SizeHashConflict { impl Field { /// The fields of a file object this crate reads, the most common /// first. - const FILE_OBJECT: [Field; 40] = [ + const FILE_OBJECT: FieldTable = FieldTable::new(&[ Field::Name, Field::Size, Field::Sha256, @@ -233,9 +235,9 @@ impl Field { Field::ValidSinceUSec, Field::ValidUntilUSec, Field::Validity, - ]; + ]); /// The fields of a contents object. - const CONTENTS: [Field; 10] = [ + const CONTENTS: FieldTable = FieldTable::new(&[ Field::File, Field::Url, Field::Literal, @@ -246,40 +248,11 @@ impl Field { Field::OriginalSha256, Field::Offset, Field::HttpHeaders, - ]; + ]); /// The fields of the value of an extended attribute. - const EXTENDED_ATTRIBUTE: [Field; 2] = [Field::Text, Field::Base64]; + const EXTENDED_ATTRIBUTE: FieldTable = FieldTable::new(&[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) - } + const SIGNATURE: FieldTable = FieldTable::new(&[Field::Mechanism, Field::Key, Field::Data]); } /// An object as far as its record was read: what does not go into a @@ -959,7 +932,8 @@ const ROOT_NAME: &str = "root"; /// Reads one record, member by member, into the object it holds. pub(crate) struct RecordDecoder<'a> { - json: Parser<'a>, + /// What holds the JSON of the record to the rules of a manifest. + json: Strict<'a>, /// The number of the record, for what is said about it. record_number: u64, /// The first error found in a field. @@ -1009,27 +983,178 @@ impl Candidate { } } +/// A value of a record as a field takes it: its type, and what it holds +/// where a field can take that. What a [`Part`] made of an array or an +/// object is a `T`. +enum Value<'a, T> { + /// `null`. A field that is null is not there. + Null, + Bool(bool), + /// A number without sign, fraction and exponent that fits into 64 + /// bits. + Unsigned(u64), + String(Cow<'a, str>), + /// What a part made of an array or an object. + Part(T), + /// Any other number, and an array or an object the part read through. + Other, +} + +/// What a [`Part`] parsed: the value it read, or the error that ended the +/// read. +type Parsed<'a, T, E> = Result, E>; + +impl<'a, T> From> for StringMember<'a> { + fn from(value: Value<'a, T>) -> StringMember<'a> { + match value { + Value::Null => StringMember::Absent, + Value::String(text) => StringMember::String(text), + _ => StringMember::NotString, + } + } +} + +impl MediaType { + /// What the `mediaType` `value` says the record is. None is a media + /// type that is not a string. + fn of(value: Value<'_, T>) -> Option { + let Value::String(media_type) = value else { + return None; + }; + Some(match media_type.as_ref() { + MEDIA_TYPE => MediaType::Manifest, + SIGNATURE_MEDIA_TYPE => MediaType::Signature, + TRAILER_MEDIA_TYPE => MediaType::Trailer, + _ => MediaType::Other, + }) + } +} + +/// A part of a record that is an array or an object: the record itself, +/// and the fields that have elements or members. A [`RecordDecoder`] reads +/// a value with a part, and the part reads the array or the object. An +/// array or an object the part does not read is read through, and so is a +/// member or an element the part passes over. Their keys and strings are +/// held to the rules of a manifest all the same. +trait Part<'a>: Sized { + /// What the part makes of what it reads. + type Value; + + /// Reads the array `seq` hands out. + fn array>(self, decoder: &mut RecordDecoder<'a>, seq: A) -> Parsed<'a, Self::Value, A::Error> { + Skip(&mut decoder.json).visit_seq(seq).map(|()| Value::Other) + } + + /// Reads the object `map` hands out. + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + Skip(&mut decoder.json).visit_map(map).map(|()| Value::Other) + } +} + +/// Reads a value of a record, whatever its type is, and an array or an +/// object with `part`. +struct ValueSeed<'r, 'a, P> { + decoder: &'r mut RecordDecoder<'a>, + part: P, +} + +impl<'a, P: Part<'a>> DeserializeSeed<'a> for ValueSeed<'_, 'a, P> { + type Value = Value<'a, P::Value>; + + fn deserialize>(self, deserializer: D) -> Result { + deserializer.deserialize_any(self) + } +} + +impl<'a, P: Part<'a>> Visitor<'a> for ValueSeed<'_, 'a, P> { + type Value = Value<'a, P::Value>; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a JSON value") + } + + fn visit_unit(self) -> Result { + Ok(Value::Null) + } + + fn visit_bool(self, value: bool) -> Result { + Ok(Value::Bool(value)) + } + + // serde_json hands out a number without sign, fraction and exponent + // that fits into 64 bits as a u64, and any other number as an i64 or + // an f64. + fn visit_u64(self, value: u64) -> Result { + Ok(Value::Unsigned(value)) + } + + fn visit_i64(self, _: i64) -> Result { + Ok(Value::Other) + } + + fn visit_f64(self, _: f64) -> Result { + Ok(Value::Other) + } + + fn visit_borrowed_str(self, value: &'a str) -> Result { + self.decoder.json.check_unescaped(value)?; + Ok(Value::String(Cow::Borrowed(value))) + } + + fn visit_str(self, value: &str) -> Result { + self.decoder.json.check_string(value)?; + Ok(Value::String(Cow::Owned(value.to_owned()))) + } + + fn visit_seq>(self, seq: A) -> Result { + self.part.array(self.decoder, seq) + } + + fn visit_map>(self, map: A) -> Result { + self.part.object(self.decoder, map) + } +} + 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), + /// The decoder of the record with the number `record_number`. + fn new(record_number: u64) -> RecordDecoder<'a> { + RecordDecoder { + json: Strict::default(), 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( + } + } + + /// What reads a value of the record with `part`. + fn seed>(&mut self, part: P) -> ValueSeed<'_, 'a, P> { + ValueSeed { decoder: self, part } + } + + /// Reads `text`, the whole record, as an object with `part`. A record + /// that is JSON but no object is an error too. + fn object>(&mut self, text: &'a str, part: P) -> Result { + let mut json = serde_json::Deserializer::from_str(text); + let read = self + .seed(part) + .deserialize(&mut json) + .and_then(|value| json.end().map(|()| value)); + let record_number = self.record_number; + match read { + Ok(Value::Part(object)) => Ok(object), + Ok(_) => Err(Error::manifest( Problem::NotObject, format!("manifest record {} is not a JSON object", record_number), ) - .in_record(record_number)); + .in_record(record_number)), + Err(e) => Err(Error::not_json(record_number, self.json.error(text, &e))), } - let (media_type, draft) = decoder.file_object().map_err(not_json)?; - decoder.json.end().map_err(not_json)?; + } + + /// 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::new(record_number); + let (media_type, draft) = decoder.object(text, FileObjectRecord)?; let Some(media_type) = media_type else { return Err(Error::manifest( Problem::InvalidMediaType, @@ -1101,101 +1226,104 @@ impl<'a> RecordDecoder<'a> { } } - /// 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()?; + /// What the part made of `value`, which is none for null. A value of + /// another type is the error `problem` in `field`, which `message` + /// describes, and is noted. + fn part( + &mut self, + value: Value<'a, T>, + problem: Problem, + field: Field, + message: impl FnOnce() -> String, + ) -> Option { + match value { + Value::Part(part) => Some(part), + Value::Null => None, + _ => { + self.note_error(problem, field, message); + None + } + } + } + + /// The string `value` is. Any other value is an error, which is noted. + fn string(&mut self, field: Field, value: Value<'a, T>) -> Option> { + let Value::String(value) = value else { self.note_error(Problem::WrongFieldType, field, || { format!("manifest field '{}' is not a string", field) }); - } - Ok(value) + return None; + }; + Some(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()?; + /// The boolean `value` is. Any other value is an error, which is noted. + fn bool(&mut self, field: Field, value: Value<'a, T>) -> Option { + let Value::Bool(value) = value else { self.note_error(Problem::WrongFieldType, field, || { format!("manifest field '{}' is not a boolean", field) }); - } - Ok(value) + return None; + }; + Some(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() { + /// The unsigned integer of 64 bits `value` is: 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, value: Value<'a, T>) -> Option { + let Value::Unsigned(value) = value else { self.note_error(Problem::WrongFieldType, field, || { format!("manifest field '{}' is not an unsigned integer", field) }); - } - Ok(value) + return None; + }; + Some(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); - }; + /// The hash `value` is. Anything but the hex digits of one is an error, + /// which is noted. + fn digest(&mut self, field: Field, value: Value<'a, T>) -> Option { + let text = self.string(field, value)?; 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) + 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); - }; + /// The access mode `value` is, an unsigned integer like every other + /// one. + fn mode(&mut self, field: Field, value: Value<'a, T>) -> Option { + let bits = self.unsigned(field, value)?; 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) + 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()))) + /// The user or group ID `value` is. + fn id(&mut self, field: Field, value: Value<'a, T>) -> Option { + let id = self.unsigned(field, value)?; + 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); - }; + /// The name of a user or of a group `value` is. + fn user_or_group_name(&mut self, field: Field, value: Value<'a, T>) -> Option> { + let name = self.string(field, value)?; let checked = FileObject::check_owner_name(field, &name, self.subject()); - Ok(self.note_err(checked).map(|()| name.into())) + 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); - }; + /// The UUID `value` is. + fn uuid(&mut self, field: Field, value: Value<'a, T>) -> Option { + let text = self.string(field, value)?; let uuid = text.parse().ok(); if uuid.is_none() { let subject = self.subject(); @@ -1203,23 +1331,19 @@ impl<'a> RecordDecoder<'a> { format!("{}: {} '{}' is not a UUID", subject, field, text.escape_debug()) }); } - Ok(uuid) + 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); - }; + /// The GPT partition label `value` is. + fn gpt_label(&mut self, field: Field, value: Value<'a, T>) -> Option { + let label = self.string(field, value)?; let checked = GptPartition::check_label(&label, self.subject()); - Ok(self.note_err(checked).map(|()| label.into_owned())) + 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); - }; + /// The FAT volume serial number `value` is, `1234-ABCD`. + fn fat_serial(&mut self, field: Field, value: Value<'a, T>) -> Option { + let text = self.string(field, value)?; let serial = text.parse().ok(); if serial.is_none() { let subject = self.subject(); @@ -1232,368 +1356,365 @@ impl<'a> RecordDecoder<'a> { ) }); } - Ok(serial) + 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); - }; + /// The file system label `value` is. + fn fs_label(&mut self, field: Field, value: Value<'a, T>) -> Option { + let label = self.string(field, value)?; let checked = FileSystemIdentity::check_label(&label, self.subject()); - Ok(self.note_err(checked).map(|()| label.into_owned())) + 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))) + /// The order `value`, the value of `order`, declares. A value the + /// specification does not have declares no order, as it asks. + fn order(&mut self, field: Field, value: Value<'a, T>) -> Option { + self.string(field, value).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; + /// Takes `value`, which is not null, as the value of `field` into + /// `draft`: one of the fields of a file object or of the root file + /// object that hold no array and no object. + fn file_field(&mut self, field: Field, value: Value<'a, Infallible>, draft: &mut Draft) { + let object = &mut *draft.object; + match field { + Field::Name => { + if let Some(name) = self.string(field, value) { + 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()); + } + } + } } - if names.contains(&name) { - self.note_error(Problem::FieldOutOfRange, field, || { - format!("{}: '{}' lists '{}' twice", subject, field, name.escape_debug()) - }); + Field::Type => { + if let Some(name) = self.string(field, value) { + 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()) + }); + } + } } - 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; + Field::Size => object.size = self.unsigned(field, value), + Field::Mode => object.inode.mode = self.mode(field, value), + Field::Uid => object.inode.uid = self.id(field, value), + Field::Gid => object.inode.gid = self.id(field, value), + Field::UserName => object.inode.user_name = self.user_or_group_name(field, value), + Field::GroupName => object.inode.group_name = self.user_or_group_name(field, value), + Field::Major => object.major = self.unsigned(field, value), + Field::Minor => object.minor = self.unsigned(field, value), + Field::MTimeNSec => object.inode.mtime_nsec = self.unsigned(field, value), + // The token 0 is that of a file with one name. + Field::InodeToken => object.inode_token = self.unsigned(field, value).and_then(NonZeroU64::new), + Field::GptLabel => draft.gpt().label = self.gpt_label(field, value), + Field::GptUuid => draft.gpt().uuid = self.uuid(field, value), + Field::GptTypeUuid => draft.gpt().type_uuid = self.uuid(field, value), + Field::GptFlags => draft.gpt().flags = self.unsigned(field, value), + Field::GptFlagNoAuto => draft.gpt().no_auto = self.bool(field, value), + Field::GptFlagGrowFileSystem => draft.gpt().grow_file_system = self.bool(field, value), + Field::ReadOnly => object.inode.read_only = self.bool(field, value), + Field::FlagHidden | Field::FlagSystem | Field::FlagArchive => { + if let (Some(flag), Some(set)) = (DosFlags::from_field(field), self.bool(field, value)) { + object.dos_flags.put(flag, Some(set)); + } } - 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())); + Field::FlagAppendOnly + | Field::FlagImmutable + | Field::FlagNoAtime + | Field::FlagNoCow + | Field::FlagNoDump => { + if let (Some(flag), Some(set)) = (InodeFlags::from_field(field), self.bool(field, value)) { + 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, value); + } + Field::FsUuid => { + draft.root_only.get_or_insert(field); + draft.file_system.uuid = self.uuid(field, value); + } + Field::FsLabel => { + draft.root_only.get_or_insert(field); + draft.file_system.label = self.fs_label(field, value); + } + Field::GptDiskUuid => { + draft.root_only.get_or_insert(field); + draft.gpt_disk_uuid = self.uuid(field, value); + } + Field::Order => { + draft.root_only.get_or_insert(field); + draft.order = self.order(field, value); + } + Field::Sha256 => object.sha256 = self.digest(field, value), + Field::ValidSinceUSec => object.validity.since_usec = self.unsigned(field, value).unwrap_or_default(), + Field::ValidUntilUSec => object.validity.until_usec = self.unsigned(field, value), + // A value the specification does not have yet is good. + Field::Validity => { + let validity = self.string(field, value); + if validity.is_some_and(|validity| validity == Validity::Revoked.as_str()) { + object.validity.state = Validity::Revoked; + } + } + _ => {} } - 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 - } - }) - } +/// The part of a member that is to be a string, a number or a boolean: it +/// reads no array and no object. +struct Scalar; - /// 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 - } - }) - } +impl Part<'_> for Scalar { + type Value = Infallible; +} + +/// The record as a file object or as the root file object: the draft of +/// the object, and the media type the record gives. None is a media type +/// that is not a string. +struct FileObjectRecord; + +impl<'a> Part<'a> for FileObjectRecord { + type Value = (Option, Draft); - /// 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> { + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let subject = decoder.subject(); 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()?; + let mut members = Members::new(map, &Field::FILE_OBJECT, &mut decoder.json); + while let Some(key) = members.next_key(&mut decoder.json)? { + let Key::Field(field) = key else { + members.skip(&mut decoder.json)?; 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; + // A field that is null is a field that is not there. The fields + // that hold an array or an object are read with their parts. 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::ExtendedAttributes => { + let value = members.value(decoder.seed(XattrNamespaces))?; + let user = decoder.part(value, Problem::InvalidExtendedAttributes, field, || { + format!("{}: 'extendedAttributes' is not an object", subject) + }); + draft.object.inode.user_xattrs = user.flatten().map(Box::new); } - Field::Order => { - draft.root_only.get_or_insert(field); - draft.order = self.order(field)?; + Field::Contents => { + let value = members.value(decoder.seed(ContentsArray))?; + let contents = decoder.part(value, Problem::WrongFieldType, field, || { + format!("manifest field '{}' is not an array", field) + }); + draft.object.contents = contents.unwrap_or_default(); } 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; + let value = members.value(decoder.seed(FeatureNames))?; + if !matches!(value, Value::Null) { + draft.root_only.get_or_insert(field); } + draft.features = decoder.part(value, Problem::WrongFieldType, field, || { + format!("{}: '{}' is not an array of strings", subject, field) + }); } - _ => self.json.skip()?, + _ => match members.value(decoder.seed(Scalar))? { + Value::Null => {} + value if field == Field::MediaType => media_type = MediaType::of(value), + value => decoder.file_field(field, value, &mut draft), + }, } } - Ok((media_type, draft)) + Ok(Value::Part((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); +/// `features`: the names of the features the manifest records, strings +/// and none of them twice. Names the specification does not have are +/// passed over, as it asks. +struct FeatureNames; + +impl<'a> Part<'a> for FeatureNames { + type Value = Features; + + fn array>(self, decoder: &mut RecordDecoder<'a>, mut seq: A) -> Parsed<'a, Self::Value, A::Error> { + let field = Field::Features; + let subject = decoder.subject(); + let mut features = Features::NONE; + let mut names = HashSet::new(); + while let Some(value) = seq.next_element_seed(decoder.seed(Scalar))? { + let Value::String(name) = value else { + decoder.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) { + decoder.note_error(Problem::FieldOutOfRange, field, || { + format!("{}: '{}' lists '{}' twice", subject, field, name.escape_debug()) + }); + } + names.insert(name); } + Ok(Value::Part(features)) + } +} + +/// `extendedAttributes`: namespaces that map the names of extended +/// attributes to their values. Only the `user` namespace is defined, and +/// what the part makes of it. Others are passed over, as systemd passes +/// over them. +struct XattrNamespaces; + +impl<'a> Part<'a> for XattrNamespaces { + type Value = Option>>; + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let field = Field::ExtendedAttributes; + let subject = decoder.subject(); let mut user = None; - while let Some(namespace) = self.json.key()? { + let mut members = Members::new(map, &FieldTable::NONE, &mut decoder.json); + while let Some(namespace) = members.next_name(&mut decoder.json)? { if namespace != USER_NAMESPACE { - self.json.skip()?; + members.skip(&mut decoder.json)?; continue; } // A namespace that is null says nothing about its attributes. - if self.json.null()? { + let value = members.value(decoder.seed(UserXattrs))?; + user = decoder.part(value, Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: extended attribute namespace '{}' is not an object", + subject, namespace + ) + }); + } + Ok(Value::Part(user)) + } +} + +/// The extended attributes of the `user` namespace: their names and +/// their values. +struct UserXattrs; + +impl<'a> Part<'a> for UserXattrs { + type Value = BTreeMap>; + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let field = Field::ExtendedAttributes; + let subject = decoder.subject(); + let mut attributes = BTreeMap::new(); + let mut members = Members::new(map, &FieldTable::NONE, &mut decoder.json); + while let Some(name) = members.next_name(&mut decoder.json)? { + let value = members.value(decoder.seed(XattrValue))?; + // An attribute that is null is not there. + if matches!(value, Value::Null) || decoder.note_err(FileObject::check_xattr_name(&name, subject)).is_none() + { continue; } - if !self.json.object()? { - self.json.skip()?; - self.note_error(Problem::InvalidExtendedAttributes, field, || { - format!( - "{}: extended attribute namespace '{}' is not an object", - subject, namespace - ) - }); + let Some((text, base64)) = decoder.part(value, Problem::InvalidExtendedAttributes, field, || { + format!( + "{}: value of extended attribute '{}' is not an object", + subject, + name.escape_debug() + ) + }) else { 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() - ) + }; + let value = match (text, base64) { + (StringMember::String(text), StringMember::Absent) => Some(text.into_owned().into_bytes()), + (StringMember::NotString, StringMember::Absent) => { + decoder.note_error(Problem::WrongFieldType, Field::Text, || { + format!("manifest field '{}' is not a string", Field::Text) }); - 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()?, - } + None } - 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, || { + (StringMember::Absent, StringMember::String(base64)) => { + let value = Base64::decode(&base64); + if value.is_none() { + decoder.note_error(Problem::InvalidExtendedAttributes, field, || { format!( - "{}: extended attribute '{}' needs exactly one of 'text' and 'base64'", + "{}: extended attribute '{}' is not valid Base64", subject, name.escape_debug() ) }); - None } - }; - if let Some(value) = value { - attributes.insert(name.into_owned(), value); + value } + (StringMember::Absent, StringMember::NotString) => { + decoder.note_error(Problem::WrongFieldType, Field::Base64, || { + format!("manifest field '{}' is not a string", Field::Base64) + }); + None + } + _ => { + decoder.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) + Ok(Value::Part(attributes)) } +} - /// 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); +/// The value of an extended attribute, an object that is to have exactly +/// one of `text` and `base64`: the two as they were found. +struct XattrValue; + +impl<'a> Part<'a> for XattrValue { + type Value = (StringMember<'a>, StringMember<'a>); + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let (mut text, mut base64) = (StringMember::Absent, StringMember::Absent); + let mut members = Members::new(map, &Field::EXTENDED_ATTRIBUTE, &mut decoder.json); + while let Some(key) = members.next_key(&mut decoder.json)? { + match key { + Key::Field(Field::Text) => text = members.value(decoder.seed(Scalar))?.into(), + Key::Field(Field::Base64) => base64 = members.value(decoder.seed(Scalar))?.into(), + _ => members.skip(&mut decoder.json)?, + } } - let error_before = self.first_error.is_some(); + Ok(Value::Part((text, base64))) + } +} + +/// `contents`: the contents objects of a file object. +struct ContentsArray; + +impl<'a> Part<'a> for ContentsArray { + type Value = Vec; + + fn array>(self, decoder: &mut RecordDecoder<'a>, mut seq: A) -> Parsed<'a, Self::Value, A::Error> { + let subject = decoder.subject(); + let mut list = Vec::new(); + let error_before = decoder.first_error.is_some(); let mut count = 0usize; - while self.json.element()? { - let contents = self.contents_object()?; + while let Some(value) = seq.next_element_seed(decoder.seed(ContentsObject))? { + let contents = match value { + Value::Part(contents) => contents, + _ => { + decoder.note_error(Problem::InvalidContents, Field::Contents, || { + format!("{}: contents entry is not an object", subject) + }); + Contents::default() + } + }; count += 1; if count <= MAX_CONTENTS { list.push(contents); @@ -1602,41 +1723,51 @@ impl<'a> RecordDecoder<'a> { // 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())); + decoder.first_error = Some(Error::too_many_contents(subject)); } - Ok(list) + Ok(Value::Part(list)) } +} + +/// A contents object. +struct ContentsObject; - /// Reads one contents object. - fn contents_object(&mut self) -> Result { - let subject = self.subject(); +impl<'a> Part<'a> for ContentsObject { + type Value = Contents; + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let subject = decoder.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()?; + let mut members = Members::new(map, &Field::CONTENTS, &mut decoder.json); + while let Some(key) = members.next_key(&mut decoder.json)? { + let Key::Field(field) = key else { + members.skip(&mut decoder.json)?; continue; }; - if self.json.null()? { + // A field that is null is a field that is not there. + if field == Field::HttpHeaders { + let value = members.value(decoder.seed(HeaderFields))?; + let headers = decoder.part(value, Problem::InvalidContents, field, || { + format!("{}: '{}' is not an object", subject, field) + }); + contents.http_headers = headers.unwrap_or_default(); + continue; + } + let value = members.value(decoder.seed(Scalar))?; + if matches!(value, Value::Null) { continue; } match field { Field::File => { - if let Some(file) = self.string(field)? { + if let Some(file) = decoder.string(field, value) { match Name::new(file.as_ref()) { Ok(file) => { contents.location = Location::File(file); places += 1; } - Err(reason) => self.note_error(Problem::InvalidContents, field, || { + Err(reason) => decoder.note_error(Problem::InvalidContents, field, || { format!( "{}: contents file reference: {}: '{}'", subject, @@ -1648,46 +1779,45 @@ impl<'a> RecordDecoder<'a> { } } Field::Url => { - if let Some(url) = self.string(field)? { - if self.note_err(Contents::check_url(&url, subject)).is_some() { + if let Some(url) = decoder.string(field, value) { + if decoder.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)? { + if let Some(literal) = decoder.string(field, value) { match Base64::decode(&literal) { Some(literal) => { contents.location = Location::Literal(literal); places += 1; } - None => self.note_error(Problem::InvalidContents, field, || { + None => decoder.note_error(Problem::InvalidContents, field, || { format!("{}: literal contents are not Base64", subject) }), } } } Field::Encoding => { - if let Some(encoding) = self.string(field)? { + if let Some(encoding) = decoder.string(field, value) { let encoding = encoding.to_ascii_lowercase(); - if self.note_err(Contents::check_encoding(&encoding, subject)).is_some() { + if decoder.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()?, + Field::EncodedSize => contents.encoded_size = decoder.unsigned(field, value), + Field::EncodedSha256 => contents.encoded_sha256 = decoder.digest(field, value), + Field::OriginalSize => contents.original_size = decoder.unsigned(field, value), + Field::OriginalSha256 => contents.original_sha256 = decoder.digest(field, value), + Field::Offset => contents.offset = decoder.unsigned(field, value).unwrap_or_default(), + _ => {} } } // What is wrong with the contents object as a whole counts unless an // error was noted before. - if self.first_error.is_none() { + if decoder.first_error.is_none() { let checked = if places > 1 { Err(Error::manifest( Problem::InvalidContents, @@ -1698,10 +1828,78 @@ impl<'a> RecordDecoder<'a> { }; match checked { Ok(data) => contents.fill_in(data), - Err(e) => self.first_error = Some(e), + Err(e) => decoder.first_error = Some(e), + } + } + Ok(Value::Part(contents)) + } +} + +/// `httpHeaders`: an object that maps the names of HTTP header fields to +/// their values, see [`Contents::check_headers`]. +struct HeaderFields; + +impl<'a> Part<'a> for HeaderFields { + type Value = Vec<(String, String)>; + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let field = Field::HttpHeaders; + let subject = decoder.subject(); + let mut headers = Vec::new(); + let mut members = Members::new(map, &FieldTable::NONE, &mut decoder.json); + while let Some(name) = members.next_name(&mut decoder.json)? { + match members.value(decoder.seed(Scalar))? { + // A header field that is null is not there. + Value::Null => {} + Value::String(value) => headers.push((name.into_owned(), value.into_owned())), + _ => decoder.note_error(Problem::InvalidContents, field, || { + format!( + "{}: the value of HTTP header field '{}' is not a string", + subject, + name.escape_debug() + ) + }), } } - Ok(contents) + decoder.note_err(Contents::check_headers(&headers, subject)); + Ok(Value::Part(headers)) + } +} + +/// The record as a signature object: its `mechanism`, `key` and `data` +/// as they were found. +struct SignatureRecord; + +/// The members of a signature object, as they were found. +struct SignatureMembers<'a> { + mechanism: StringMember<'a>, + key: StringMember<'a>, + data: StringMember<'a>, +} + +impl<'a> Part<'a> for SignatureRecord { + type Value = SignatureMembers<'a>; + + fn object>(self, decoder: &mut RecordDecoder<'a>, map: A) -> Parsed<'a, Self::Value, A::Error> { + let mut signature = SignatureMembers { + mechanism: StringMember::Absent, + key: StringMember::Absent, + data: StringMember::Absent, + }; + let mut members = Members::new(map, &Field::SIGNATURE, &mut decoder.json); + while let Some(key) = members.next_key(&mut decoder.json)? { + let found = match key { + Key::Field(Field::Mechanism) => &mut signature.mechanism, + Key::Field(Field::Key) => &mut signature.key, + Key::Field(Field::Data) => &mut signature.data, + _ => { + members.skip(&mut decoder.json)?; + continue; + } + }; + *found = members.value(decoder.seed(Scalar))?.into(); + } + Ok(Value::Part(signature)) } } @@ -1711,33 +1909,17 @@ impl Signature { /// 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))? + RecordDecoder::new(record_number) + .object(text, SignatureRecord)? + .into_signature(record_number) .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()?; +impl SignatureMembers<'_> { + /// The signature object of the record with the number `record_number` + /// that has these members. + fn into_signature(self, record_number: u64) -> Result { let not_a_string = |field: Field| { Error::manifest( Problem::WrongFieldType, @@ -1745,45 +1927,45 @@ impl RecordDecoder<'_> { ) .at(field) }; - let StringMember::String(mechanism) = mechanism else { - return Ok(Err(Error::manifest( + let StringMember::String(mechanism) = self.mechanism else { + return Err(Error::manifest( Problem::InvalidSignature, format!("manifest signature object {} has no 'mechanism' string", record_number), ) - .at(Field::Mechanism))); + .at(Field::Mechanism)); }; - let key = match key { + let key = match self.key { StringMember::Absent => None, - StringMember::NotString => return Ok(Err(not_a_string(Field::Key))), + StringMember::NotString => return Err(not_a_string(Field::Key)), StringMember::String(key) => match Hex::decode(&key) { Some(key) => Some(key), None => { - return Ok(Err(Error::manifest( + return Err(Error::manifest( Problem::InvalidSignature, format!("manifest signature object {}: 'key' is not hex", record_number), ) - .at(Field::Key))); + .at(Field::Key)); } }, }; - let data = match data { + let data = match self.data { StringMember::Absent => None, - StringMember::NotString => return Ok(Err(not_a_string(Field::Data))), + StringMember::NotString => return Err(not_a_string(Field::Data)), StringMember::String(data) => match Base64::decode(&data) { Some(data) => Some(data), None => { - return Ok(Err(Error::manifest( + return Err(Error::manifest( Problem::InvalidSignature, format!("manifest signature object {}: 'data' is not Base64", record_number), ) - .at(Field::Data))); + .at(Field::Data)); } }, }; let mut signature = Signature::new(mechanism); signature.key = key; signature.data = data; - Ok(Ok(signature)) + Ok(signature) } } @@ -1791,7 +1973,7 @@ impl RecordDecoder<'_> { mod tests { use super::*; use crate::error::ErrorKind; - use crate::testing::{read_whole, sequence, EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, WORLD}; + use crate::testing::{read_whole, sequence, EMPTY, HELLO, MAX_NESTING, ROOT, SIGNATURE, TRAILER, WORLD}; /// The file object of `record`, the record after the root file object. fn object(record: &str) -> FileObject { @@ -2003,11 +2185,34 @@ mod tests { 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] { + // Also large numbers and nesting. What JSON takes nowhere else in + // a record it does not take in such a field either: a number too + // large for a double, and more arrays and objects inside each other + // than serde_json reads, the object of the record among them. + // 1.7976931348623158e308 rounds to the largest double, and only + // float_roundtrip reads it as that. + let largest = "1.7976931348623158e308"; + let deep = |depth: usize| format!("{}1{}", r#"[{"a":"#.repeat(depth), "}]".repeat(depth)); + let nested = |depth: usize| format!("{}1{}", "[".repeat(depth), "]".repeat(depth)); + for value in [ + "1e300", + "-1e300", + &"9".repeat(300), + largest, + &deep(50), + &nested(MAX_NESTING - 1), + ] { assert_eq!(object(&format!(r#"{{"name":"x","xUnknown":{}}}"#, value)), o); } + for value in ["1e400", "-1e400", &"9".repeat(400), &deep(500), &nested(MAX_NESTING)] { + let e = refused(&format!(r#"{{"name":"x","xUnknown":{}}}"#, value)); + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::NotJson), "{}", value); + } + let e = refused(&format!(r#"{{"name":"x","size":{}}}"#, largest)); + assert_eq!( + (e.kind(), e.field()), + (ErrorKind::Manifest(Problem::WrongFieldType), Some(Field::Size)) + ); // Integers are numbers of up to 64 bits. for (text, size) in [("5", 5), ("0", 0), ("18446744073709551615", u64::MAX)] { assert_eq!( @@ -2121,7 +2326,7 @@ mod tests { ] { let e = refused(&format!( r#"{{"name":"x","gptLabel":{}}}"#, - json::Value::from(label.as_str()) + serde_json::Value::from(label.as_str()) )); assert_eq!(e.kind(), ErrorKind::Manifest(Problem::WrongFieldType), "{:?}", label); } @@ -2691,7 +2896,7 @@ mod tests { ("pkcs7", None, Some(&[0u8, 0, 0][..])) ); let s = signature(concat!( - r#"{"data":null,"key":"ABcd01","mechanism":"openpgp","other":[1,2,1e400],"#, + r#"{"data":null,"key":"ABcd01","mechanism":"openpgp","other":[1,2,1e300],"#, r#""mediaType":"application/vnd.uapi.16.signature"}"# )); assert_eq!( @@ -2845,27 +3050,128 @@ mod tests { /// [`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 tables = [ + &Field::FILE_OBJECT, + &Field::CONTENTS, + &Field::EXTENDED_ATTRIBUTE, + &Field::SIGNATURE, ]; 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); + for table in tables { + for (place, &field) in table.iter().enumerate() { + assert_eq!(table.find(field.as_str()), Some((place, field)), "{}", field); + assert_eq!(fields_of(field), &table[..], "{}", field); assert!(names.insert(field.as_str()), "{}", field); } - assert_eq!(of("xUnknown"), None); + assert_eq!(table.find("xUnknown"), None); } // Data is the last of the fields. assert_eq!(names.len(), Field::Data as usize + 1); } + /// A key twice in an object is refused right behind the second one, + /// whether it names a field of the object or not, and however it is + /// written. + #[test] + fn keys_twice() { + let records = [ + // A field of a file object, also one written with an escape. + (r#"{"name":"x","size":1,"size":2}"#, r#""size""#), + (r#"{"name":"x","s\u0069ze":1,"size":2}"#, r#""size""#), + // A key that is no field of the object, between fields. + (r#"{"name":"x","xA":1,"size":1,"xA":2}"#, r#""xA""#), + // The name of a field as a key of a value that is passed over. + (r#"{"name":"x","xB":{"name":1,"name":2}}"#, r#""name""#), + // A field of a contents object, and a key that is none. + (r#"{"name":"x","contents":[{"file":"a","file":"b"}]}"#, r#""file""#), + (r#"{"name":"x","contents":[{"file":"a","xC":1,"xC":2}]}"#, r#""xC""#), + // Names: of a namespace, of an extended attribute and of an HTTP + // header field. + ( + r#"{"name":"x","extendedAttributes":{"user":{},"user":{}}}"#, + r#""user""#, + ), + ( + r#"{"name":"x","extendedAttributes":{"user":{"a":{"text":"1"},"a":{"text":"2"}}}}"#, + r#""a""#, + ), + ( + r#"{"name":"x","contents":[{"url":"https://x","httpHeaders":{"A":"1","A":"2"}}]}"#, + r#""A""#, + ), + // A field of the value of an extended attribute. + ( + r#"{"name":"x","extendedAttributes":{"user":{"a":{"text":"1","text":"2"}}}}"#, + r#""text""#, + ), + // A field of a signature object. + ( + r#"{"mediaType":"application/vnd.uapi.16.signature","mechanism":"a","mechanism":"b"}"#, + r#""mechanism""#, + ), + // What follows the second key is not read: whitespace, the colon + // and the value. + (r#"{"name":"x","size":1,"size" :[}"#, r#""size""#), + ("{\"name\":\"x\",\"xA\":1,\"xA\"\n\t2}", r#""xA""#), + (r#"{"name":"x","xB":{"a":1,"a" :}}"#, r#""a""#), + ]; + let root = r#"{"mediaType":"application/vnd.uapi.16.manifest","order":"codepoint","order":"codepoint"}"#; + let errors = records + .iter() + .map(|&(record, key)| (record, key, refused(record))) + .chain([(root, r#""order""#, RecordDecoder::root(root).unwrap_err())]); + for (record, key, e) in errors { + assert_eq!(e.kind(), ErrorKind::Manifest(Problem::DuplicateKey), "{}", record); + let behind = record.rfind(key).unwrap() + key.len(); + let message = format!("has a key twice in an object: duplicate key at byte {}", behind); + assert!(e.to_string().ends_with(&message), "{}: {}", record, e); + } + } + + /// A key twice in an object, and a key with a noncharacter or NUL in + /// it, is refused right behind the key, whatever follows it: the colon + /// and the value, a comma, or the end of the object, right away or + /// after whitespace. That holds for the fields of an object, for a + /// value the reader passes over, and for the names of extended + /// attributes and of HTTP header fields. + #[test] + fn refuses_a_key_right_behind_it() { + // What comes in front of the key, with a member whose key is the + // one that comes twice, and what closes the objects around the one + // the key is in. + let places = [ + (r#"{"name":"x","#, r#""name""#, ""), + (r#"{"name":"x","xA":{"b":1,"#, r#""b""#, "}"), + ( + r#"{"name":"x","extendedAttributes":{"user":{"b":{"text":"1"},"#, + r#""b""#, + "}}", + ), + ( + r#"{"name":"x","contents":[{"url":"https://x","httpHeaders":{"B":"1","#, + r#""B""#, + "}}]}", + ), + ]; + let followers = [":1}", " :1}", r#","c":1}"#, "}", " \n }"]; + for (front, twice, behind) in places { + let keys = [ + (twice, Problem::DuplicateKey, "duplicate key"), + (r#""\uFDD0""#, Problem::InvalidString, "noncharacter in string"), + (r#""a\u0000""#, Problem::InvalidString, "NUL in string"), + ]; + for (key, problem, message) in keys { + for follower in followers { + let record = format!("{}{}{}{}", front, key, follower, behind); + let e = refused(&record); + assert_eq!(e.kind(), ErrorKind::Manifest(problem), "{}", record); + let at = format!("{} at byte {}", message, front.len() + key.len()); + assert!(e.to_string().ends_with(&at), "{}: {}", record, e); + } + } + } + } + /// 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, @@ -2876,8 +3182,8 @@ mod tests { 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 { + let vector: serde_json::Value = serde_json::from_str(line).unwrap(); + let [records, problem, record_number, name, field, message] = vector.as_array().unwrap().as_slice() else { panic!("{}", line); }; let records: Vec<&str> = records diff --git a/src/uapi16/error.rs b/src/uapi16/error.rs index 5b2fa60..54c4a4a 100644 --- a/src/uapi16/error.rs +++ b/src/uapi16/error.rs @@ -6,6 +6,7 @@ use std::io; use crate::decode::Subject; use crate::object::FileObject; +use crate::strict::{ParseError, ParseErrorKind}; use crate::{MAX_CONTENTS, MAX_RECORD_SIZE}; /// What is wrong with a manifest. @@ -54,7 +55,7 @@ pub enum Problem { /// 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). + /// [`NameProblem`](crate::NameProblem). InvalidName, /// Two objects carry the same name. DuplicateName, @@ -226,7 +227,8 @@ pub enum UnsupportedContent { /// Why a file object must not be used now. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Invalid { +#[non_exhaustive] +pub enum ValidityProblem { /// Its `validity` is `revoked`. Revoked, /// The time is before its `validSinceUSec`. @@ -248,7 +250,7 @@ pub enum ErrorKind { /// 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), + NotValid(ValidityProblem), /// Reading or writing failed. Io, } @@ -442,7 +444,7 @@ impl fmt::Display for Field { #[derive(Debug)] enum Cause { Io(io::Error), - Json(json::ParseError), + Json(ParseError), } /// What went wrong reading a manifest, or using one. @@ -536,20 +538,20 @@ impl Error { /// 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 { + pub(crate) fn not_json(record_number: u64, error: ParseError) -> Error { let (problem, message) = match error.kind { - json::ParseErrorKind::Syntax => ( + ParseErrorKind::Syntax => ( Problem::NotJson, format!("manifest record {} is not valid JSON: {}", record_number, error), ), - json::ParseErrorKind::DuplicateKey => ( + ParseErrorKind::DuplicateKey => ( Problem::DuplicateKey, format!( "manifest record {} has a key twice in an object: {}", record_number, error ), ), - json::ParseErrorKind::StringRule => ( + ParseErrorKind::StringRule => ( Problem::InvalidString, format!("manifest record {} has an invalid string: {}", record_number, error), ), @@ -729,6 +731,7 @@ impl From for io::Error { #[cfg(test)] mod tests { use super::*; + use crate::strict::Strict; #[test] fn an_io_error_passes_through() { @@ -770,12 +773,14 @@ mod tests { (e.found_size(), e.expected_size(), e.value()), (Some(1), Some(2), Some("gzip")) ); - let e = Error::not_json(7, json::parse("{").unwrap_err()); + let text = "{"; + let json = serde_json::from_str::(text).unwrap_err(); + let e = Error::not_json(7, Strict::default().error(text, &json)); 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" + "manifest record 7 is not valid JSON: EOF while parsing an object at byte 1" ); assert!(std::error::Error::source(&e).is_some()); } diff --git a/src/uapi16/lib.rs b/src/uapi16/lib.rs index 0eb7fc6..309bee2 100644 --- a/src/uapi16/lib.rs +++ b/src/uapi16/lib.rs @@ -66,8 +66,20 @@ //! 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 -//! asks. +//! not know is passed over, as the specification asks, unless it holds a +//! number too large for a double, such as 1E400, or more arrays and +//! objects inside each other than serde_json reads. serde_json reads 127, +//! the object of the record included. +//! +//! The reader reads JSON with serde_json. The features of serde_json are +//! the same for every crate of a build, and uapi16 cannot turn one off that +//! another crate turns on. With arbitrary_precision, serde_json hands every +//! number with a fraction or an exponent, -0 and every integer that does +//! not fit into 64 bits to the reader as an object. Then a field the reader +//! does not know may hold a number too large for a double. A field it knows +//! that holds such a number has a value of the wrong type instead of not +//! being JSON. A record that is one of these numbers, such as 1.5 or -0, is +//! read as an object without a name. //! //! [UAPI.16 file manifest]: https://uapi-group.org/specifications/specs/file_manifest/ //! [`Read`]: std::io::Read @@ -88,14 +100,15 @@ mod name; mod object; mod reader; mod sequence; +mod strict; mod writer; pub use blocking::{Reader, Writer}; pub use content::{ContentCheck, ContentSource, Data, Directory, DirectorySource, OpenError, Reference, StreamSource}; pub use digest::{Digest, Finalize, InvalidDigest, Sha256, Sha256Context}; -pub use error::{ContentProblem, Error, ErrorKind, Field, Invalid, Problem, SourceProblem, UnsupportedContent}; +pub use error::{ContentProblem, Error, ErrorKind, Field, Problem, SourceProblem, UnsupportedContent, ValidityProblem}; pub use features::{Features, Order, UnknownFeature}; -pub use name::{InvalidName, Name}; +pub use name::{Name, NameProblem}; pub use object::{ Contents, DosFlags, FatSerial, FileObject, FileSystemIdentity, FilledIn, FlagStates, GptPartition, InodeAttributes, InodeFlags, InodeType, InvalidFatSerial, InvalidUuid, Location, Mode, RootObject, Signature, UnknownInodeType, @@ -132,7 +145,8 @@ 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. -pub(crate) const STRING_RULES: json::StringRules = json::StringRules::NO_NONCHARACTERS.union(json::StringRules::NO_NUL); +pub(crate) const STRING_RULES: strict::StringRules = + strict::StringRules::NO_NONCHARACTERS.union(strict::StringRules::NO_NUL); /// What the tests of this crate build manifests from. #[cfg(test)] @@ -142,6 +156,8 @@ pub(crate) mod testing { Contents, DosFlags, Error, Features, FileObject, GptPartition, InodeFlags, InodeType, Location, Mode, Name, Object, Reader, RootObject, Sha256, Signature, Uuid, Validity, Writer, RECORD_END, RECORD_SEPARATOR, }; + use crate::strict::{ParseError, Skip, Strict}; + use serde_core::de::DeserializeSeed; use std::collections::BTreeMap; use std::num::NonZeroU64; @@ -188,6 +204,26 @@ pub(crate) mod testing { pub(crate) signatures: Vec, } + /// How many arrays and objects serde_json reads inside each other. + pub(crate) const MAX_NESTING: usize = 127; + + /// Reads the JSON text `text` the way a reader reads a value it passes + /// over: every key and every string held to the rules of a manifest. + pub(crate) fn read_json(text: &str) -> Result<(), ParseError> { + let mut strict = Strict::default(); + let mut json = serde_json::Deserializer::from_str(text); + let read = Skip(&mut strict).deserialize(&mut json).and_then(|()| json.end()); + read.map_err(|e| strict.error(text, &e)) + } + + /// The JSON value of `text`, none for a text a reader refuses, see + /// [`read_json`]: one with a key twice in an object too, which + /// serde_json's own Value takes. + pub(crate) fn json(text: &str) -> Option { + read_json(text).ok()?; + serde_json::from_str(text).ok() + } + /// Reads the manifest `bytes` to its end. pub(crate) fn read_whole(bytes: &[u8]) -> Result { read_whole_from(bytes) diff --git a/src/uapi16/name.rs b/src/uapi16/name.rs index b592008..72b8569 100644 --- a/src/uapi16/name.rs +++ b/src/uapi16/name.rs @@ -7,8 +7,7 @@ use std::iter; use std::ops::Deref; use std::str::FromStr; -use json::StringRules; - +use crate::strict::StringRules; use crate::{InodeType, FILENAME, STRING_RULES}; /// What separates the components of a name. @@ -55,14 +54,14 @@ const RULES: StringRules = STRING_RULES.without(StringRules::NO_NUL); /// name. /// /// ``` -/// use uapi16::{InvalidName, Name}; +/// use uapi16::{Name, NameProblem}; /// /// 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_eq!("EFI//BOOT".parse::(), Err(NameProblem::EmptyComponent)); +/// assert_eq!(Name::new("../etc/passwd"), Err(NameProblem::ContainsDotComponent)); /// assert!(Name::new("a/x")? < Name::new("a-b")?); -/// # Ok::<(), InvalidName>(()) +/// # Ok::<(), NameProblem>(()) /// ``` #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub struct Name(String); @@ -70,7 +69,7 @@ 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 { +pub enum NameProblem { /// 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, @@ -93,22 +92,22 @@ pub enum InvalidName { ContainsSeparator, } -impl fmt::Display for InvalidName { +impl fmt::Display for NameProblem { 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), + NameProblem::Empty => f.write_str("name is empty"), + NameProblem::TooLong => write!(f, "name is longer than {} bytes", Name::MAX_LEN), + NameProblem::Reserved => f.write_str("name is reserved for the manifest"), + NameProblem::ContainsControlCharacter => f.write_str("name contains a control character"), + NameProblem::ContainsNoncharacter => f.write_str("name contains a noncharacter"), + NameProblem::EmptyComponent => f.write_str("name has an empty component"), + NameProblem::ContainsDotComponent => write!(f, "name contains a '{}' or '{}' component", CURRENT, PARENT), + NameProblem::ContainsSeparator => write!(f, "name component contains '{}'", SEPARATOR), } } } -impl std::error::Error for InvalidName {} +impl std::error::Error for NameProblem {} impl Name { /// The name of the root file object: the empty one. @@ -119,16 +118,16 @@ impl Name { /// 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 { + pub fn new(name: impl Into) -> Result { let name = name.into(); if name.is_empty() { - return Err(InvalidName::Empty); + return Err(NameProblem::Empty); } if name.len() > Name::MAX_LEN { - return Err(InvalidName::TooLong); + return Err(NameProblem::TooLong); } if Name::is_reserved(&name) { - return Err(InvalidName::Reserved); + return Err(NameProblem::Reserved); } // The separator is neither a control character nor a noncharacter, // so the text of the components is checked all at once. @@ -142,16 +141,16 @@ impl 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 { + pub fn join(&self, component: &str) -> Result { if component.contains(SEPARATOR) { - return Err(InvalidName::ContainsSeparator); + return Err(NameProblem::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); + return Err(NameProblem::TooLong); } // In the order of Name::new(), so that a component is refused for // the reason the whole name would be refused for. @@ -166,7 +165,7 @@ impl 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> { + fn check_text(text: &str) -> Result<(), NameProblem> { // 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 @@ -175,10 +174,10 @@ impl Name { .bytes() .fold(false, |control, b| control | (b < SPACE) | (b == DELETE)); if control { - return Err(InvalidName::ContainsControlCharacter); + return Err(NameProblem::ContainsControlCharacter); } if !RULES.admits(text) { - return Err(InvalidName::ContainsNoncharacter); + return Err(NameProblem::ContainsNoncharacter); } Ok(()) } @@ -186,12 +185,12 @@ impl Name { /// 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> { + fn check_component(component: &[u8]) -> Result<(), NameProblem> { if component.is_empty() { - return Err(InvalidName::EmptyComponent); + return Err(NameProblem::EmptyComponent); } if component == CURRENT.as_bytes() || component == PARENT.as_bytes() { - return Err(InvalidName::ContainsDotComponent); + return Err(NameProblem::ContainsDotComponent); } Ok(()) } @@ -344,25 +343,25 @@ impl fmt::Display for Name { } impl FromStr for Name { - type Err = InvalidName; + type Err = NameProblem; - fn from_str(name: &str) -> Result { + fn from_str(name: &str) -> Result { Name::new(name) } } impl TryFrom for Name { - type Error = InvalidName; + type Error = NameProblem; - fn try_from(name: String) -> Result { + fn try_from(name: String) -> Result { Name::new(name) } } impl TryFrom<&str> for Name { - type Error = InvalidName; + type Error = NameProblem; - fn try_from(name: &str) -> Result { + fn try_from(name: &str) -> Result { Name::new(name) } } @@ -420,31 +419,31 @@ mod tests { 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), + ("", NameProblem::Empty), + ("/", NameProblem::EmptyComponent), + ("/abs", NameProblem::EmptyComponent), + ("a/", NameProblem::EmptyComponent), + ("a//b", NameProblem::EmptyComponent), + (".", NameProblem::ContainsDotComponent), + ("..", NameProblem::ContainsDotComponent), + ("a/.", NameProblem::ContainsDotComponent), + ("a/..", NameProblem::ContainsDotComponent), + ("./a", NameProblem::ContainsDotComponent), + ("../a", NameProblem::ContainsDotComponent), + ("a/./b", NameProblem::ContainsDotComponent), + ("a/../b", NameProblem::ContainsDotComponent), + ("a\nb", NameProblem::ContainsControlCharacter), + ("a\0b", NameProblem::ContainsControlCharacter), + ("a/\u{1}", NameProblem::ContainsControlCharacter), + ("a\u{7f}", NameProblem::ContainsControlCharacter), + ("\u{fdd0}", NameProblem::ContainsNoncharacter), + ("a\u{fffe}", NameProblem::ContainsNoncharacter), + ("a/\u{10ffff}", NameProblem::ContainsNoncharacter), + ("Uapi16Manifest", NameProblem::Reserved), + ("Uapi16Manifest.", NameProblem::Reserved), + ("Uapi16Manifest.sig", NameProblem::Reserved), + ("Uapi16Manifest.gz", NameProblem::Reserved), + ("Uapi16Manifest.d/inside", NameProblem::Reserved), ] { assert_eq!(Name::new(name), Err(reason), "{:?}", name); assert_eq!(name.parse::(), Err(reason), "{:?}", name); @@ -458,20 +457,20 @@ mod tests { #[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"), + (NameProblem::Empty, "name is empty"), + (NameProblem::TooLong, "name is longer than 4095 bytes"), + (NameProblem::Reserved, "name is reserved for the manifest"), ( - InvalidName::ContainsControlCharacter, + NameProblem::ContainsControlCharacter, "name contains a control character", ), - (InvalidName::ContainsNoncharacter, "name contains a noncharacter"), - (InvalidName::EmptyComponent, "name has an empty component"), + (NameProblem::ContainsNoncharacter, "name contains a noncharacter"), + (NameProblem::EmptyComponent, "name has an empty component"), ( - InvalidName::ContainsDotComponent, + NameProblem::ContainsDotComponent, "name contains a '.' or '..' component", ), - (InvalidName::ContainsSeparator, "name component contains '/'"), + (NameProblem::ContainsSeparator, "name component contains '/'"), ] { assert_eq!(reason.to_string(), text); } @@ -482,21 +481,21 @@ mod tests { // 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)); + assert_eq!(Name::new(format!("{}x", longest)), Err(NameProblem::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)); + assert_eq!(Name::new(format!("{}z", fits)), Err(NameProblem::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) + Err(NameProblem::TooLong) ); } @@ -581,32 +580,32 @@ mod tests { /// 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 { + fn reasons(name: &str) -> Vec { let mut reasons = Vec::new(); if name.is_empty() { - reasons.push(InvalidName::Empty); + reasons.push(NameProblem::Empty); } if name.len() > Name::MAX_LEN { - reasons.push(InvalidName::TooLong); + reasons.push(NameProblem::TooLong); } if Name::is_reserved(name) { - reasons.push(InvalidName::Reserved); + reasons.push(NameProblem::Reserved); } if name.chars().any(|c| c.is_ascii_control()) { - reasons.push(InvalidName::ContainsControlCharacter); + reasons.push(NameProblem::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); + reasons.push(NameProblem::ContainsNoncharacter); } for component in name.split(SEPARATOR) { if component.is_empty() { - reasons.push(InvalidName::EmptyComponent); + reasons.push(NameProblem::EmptyComponent); } if component == CURRENT || component == PARENT { - reasons.push(InvalidName::ContainsDotComponent); + reasons.push(NameProblem::ContainsDotComponent); } } reasons @@ -665,11 +664,11 @@ mod tests { 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)), + ('\0', Some(NameProblem::ContainsControlCharacter)), + ('\u{1f}', Some(NameProblem::ContainsControlCharacter)), + ('\u{7f}', Some(NameProblem::ContainsControlCharacter)), + ('\u{fdd0}', Some(NameProblem::ContainsNoncharacter)), + ('\u{10ffff}', Some(NameProblem::ContainsNoncharacter)), (' ', None), ('\u{85}', None), ('\u{e9}', None), @@ -701,7 +700,7 @@ mod tests { assert!(Name::ROOT.is_root()); assert_eq!(Name::ROOT, ""); assert_eq!(Name::default(), Name::ROOT); - assert_eq!(Name::new(""), Err(InvalidName::Empty)); + assert_eq!(Name::new(""), Err(NameProblem::Empty)); } #[test] @@ -762,7 +761,7 @@ mod tests { format!("{}/{}", parent, component) }; let expected = if component.contains(SEPARATOR) { - Err(InvalidName::ContainsSeparator) + Err(NameProblem::ContainsSeparator) } else { Name::new(whole) }; @@ -778,11 +777,11 @@ mod tests { 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)); + assert_eq!(deep.join(&"y".repeat(room + 1)), Err(NameProblem::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)); + assert_eq!(deep.join(&wrong), Err(NameProblem::TooLong)); + assert_eq!(Name::new(format!("{}/{}", deep, wrong)), Err(NameProblem::TooLong)); } } diff --git a/src/uapi16/object.rs b/src/uapi16/object.rs index 26b3a17..fb9cb88 100644 --- a/src/uapi16/object.rs +++ b/src/uapi16/object.rs @@ -9,12 +9,13 @@ use std::str::FromStr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crate::decode::ROOT_RECORD; -use crate::error::{Error, ErrorKind, Field, Invalid, Problem}; +use crate::error::{Error, ErrorKind, Field, Problem, ValidityProblem}; 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)] +#[non_exhaustive] pub enum InodeType { /// `reg`: a regular file. Regular, @@ -151,6 +152,7 @@ impl fmt::Debug for Mode { /// The `validity` field of a file object. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] pub enum Validity { /// `good`, and any value the specification adds later. #[default] @@ -200,11 +202,11 @@ impl ValidityWindow { /// 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") + (ValidityProblem::Revoked, "is revoked") } else if now_usec < self.since_usec { - (Invalid::NotYetValid, "is not valid yet") + (ValidityProblem::NotYetValid, "is not valid yet") } else if self.until_usec.is_some_and(|until| now_usec >= until) { - (Invalid::Expired, "has expired") + (ValidityProblem::Expired, "has expired") } else { return Ok(()); }; @@ -850,6 +852,7 @@ impl FileSystemIdentity { /// Where a contents object says the data is. It names at most one place. #[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] 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. @@ -1542,10 +1545,10 @@ mod tests { 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, 9), Err(ErrorKind::NotValid(ValidityProblem::NotYetValid))); assert_eq!(kind(&object, 10), Ok(())); assert_eq!(kind(&object, 19), Ok(())); - assert_eq!(kind(&object, 20), Err(ErrorKind::NotValid(Invalid::Expired))); + assert_eq!(kind(&object, 20), Err(ErrorKind::NotValid(ValidityProblem::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!( @@ -1555,7 +1558,7 @@ mod tests { // 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!(kind(&object, now), Err(ErrorKind::NotValid(ValidityProblem::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. @@ -1563,7 +1566,7 @@ mod tests { 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.kind(), ErrorKind::NotValid(ValidityProblem::Expired)); assert_eq!((e.name(), e.to_string().as_str()), (None, "the manifest has expired")); root.validity.state = Validity::Revoked; assert_eq!( diff --git a/src/uapi16/reader.rs b/src/uapi16/reader.rs index b1a9d2b..2e985eb 100644 --- a/src/uapi16/reader.rs +++ b/src/uapi16/reader.rs @@ -4,12 +4,11 @@ use std::fmt; use std::io::{self, BufRead}; -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::strict::is_whitespace; use crate::{MAX_RECORD_SIZE, RECORD_END, RECORD_SEPARATOR}; /// The most bytes a record has behind its record separator, which counts diff --git a/src/uapi16/refused.jsonl b/src/uapi16/refused.jsonl index 7ea3329..4786eae 100644 --- a/src/uapi16/refused.jsonl +++ b/src/uapi16/refused.jsonl @@ -4,8 +4,8 @@ [["@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\"","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: EOF while parsing an object at byte 12"] +[["@root","{\"name\":\"x\",}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: trailing comma 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"] @@ -17,7 +17,7 @@ [["@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","{\"name\":5,\"size\":}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: expected value 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"] @@ -42,7 +42,7 @@ [["{\"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","{\"mediaType\":\"application/x-unknown\",\"name\":}","@trailer"],"notJson",1,null,null,"manifest record 1 is not valid JSON: expected value 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"] diff --git a/src/uapi16/strict.rs b/src/uapi16/strict.rs new file mode 100644 index 0000000..286557d --- /dev/null +++ b/src/uapi16/strict.rs @@ -0,0 +1,961 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! What the JSON of a manifest keeps to beyond what serde_json checks, and +//! how a record that breaks it is reported. +//! +//! serde_json refuses what is not JSON. A manifest asks for more: no object +//! has a key twice, and no string has a noncharacter or the NUL character, +//! keys among them, however they are written. Both hold for the values a +//! reader passes over too. serde_json hands every key and every string it +//! reads to the visitor of the value it is in, and the visitors that read +//! a record see to the rules with what this module has: [`StringRules`] +//! for the strings, [`Members`] for the keys of an object, and [`Skip`] +//! for a value the reader does not take. [`Strict`] holds what they need. +//! A key that names a field of its object is told apart from the keys +//! before it by a bit, see [`FieldTable`]. Only other keys are hashed. +//! +//! A visitor that finds a rule broken fails the read. serde_json reports +//! that like any other error, at a line and a column of the record. +//! [`Strict::error`] tells a broken rule from what serde_json found itself, +//! and says which byte of the record the error is at. + +use std::borrow::Cow; +use std::collections::HashSet; +use std::fmt; +use std::ops::Deref; + +use serde_core::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor}; + +use crate::error::Field; +use crate::STRING_RULES; + +/// What the strings of a manifest may not hold beyond what JSON forbids. +/// +/// JSON lets a string hold any Unicode scalar value. A manifest rules out +/// more, see [`STRING_RULES`], however a string is written: as it is or +/// with escapes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) 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(crate) const NO_NONCHARACTERS: StringRules = StringRules(1 << 0); + /// No NUL character, which JSON only lets a string have as `\u0000`. + pub(crate) const NO_NUL: StringRules = StringRules(1 << 1); + /// No rule beyond those of JSON. + const NONE: StringRules = StringRules(0); + + /// Whether every rule of `rules` is among these. + const fn contains(self, rules: StringRules) -> bool { + self.0 & rules.0 == rules.0 + } + + /// These rules and those of `rules`. + pub(crate) const fn union(self, rules: StringRules) -> StringRules { + StringRules(self.0 | rules.0) + } + + /// These rules but those of `rules`. + pub(crate) const fn without(self, rules: StringRules) -> StringRules { + StringRules(self.0 & !rules.0) + } + + /// Whether the string `s` keeps to these rules. + pub(crate) fn admits(self, s: &str) -> bool { + self.broken_in(s).is_none() + } + + /// Which of these rules the string `s` breaks first, if one, as a + /// reader tells it. + 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"; +/// What a string that holds a noncharacter is told. +const NONCHARACTER_IN_STRING: &str = "noncharacter in string"; +/// What an object that has a key twice is told. +const DUPLICATE_KEY: &str = "duplicate key"; + +/// 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 +} + +/// 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(crate) const fn is_whitespace(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\n' | b'\r') +} + +/// Where and why a record is not JSON as a manifest has it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ParseError { + /// The byte of the record the error is at. + pub(crate) offset: usize, + /// What is wrong. + pub(crate) message: Cow<'static, str>, + /// Whether the record is not JSON, has a key twice in an object, or + /// has a string a manifest may not have. + pub(crate) kind: ParseErrorKind, +} + +/// What kind of error a [`ParseError`] is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ParseErrorKind { + /// The record is not JSON. + Syntax, + /// An object has a key twice. RFC 8259 leaves open what such an object + /// means, and a manifest may not have one. + DuplicateKey, + /// A string breaks one of the [`StringRules`] of a manifest. + StringRule, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} at byte {}", self.message, self.offset) + } +} + +impl std::error::Error for ParseError {} + +/// How many keys the set of an object has room for once it takes its first +/// key. A set that grows hashes all its keys again. +const OBJECT_KEYS: usize = 8; + +/// The keys of the objects a reader is inside of that name none of their +/// fields, a set for each of the objects. The set of an object the reader +/// 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 +/// reader 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. A set takes room for keys only +/// once it takes one, so an object that has nothing but fields needs none. +/// +/// 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<'de> { + /// How many objects the reader is inside of. + objects: usize, + /// The keys of the outermost object the reader 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<'de> Keys<'de> { + /// The set of the innermost object the reader 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 reader goes into. + fn open(&mut self) { + if self.objects > self.inner.len() { + self.inner.push(HashSet::new()); + } + self.objects += 1; + } + + /// Empties the set of the innermost object, which the reader 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<'de, str>) -> bool { + self.innermost().is_some_and(|keys| { + if keys.is_empty() { + keys.reserve(OBJECT_KEYS); + } + keys.insert(key) + }) + } +} + +/// A rule of a manifest that a key or a string broke. +#[derive(Clone, Copy)] +struct Broken { + kind: ParseErrorKind, + message: &'static str, +} + +/// What the read of one JSON text keeps to hold it to the rules of a +/// manifest: the keys of the objects the reader is inside of, and the rule +/// a key or a string broke, which ended the read. +#[derive(Default)] +pub(crate) struct Strict<'de> { + keys: Keys<'de>, + broken: Option, +} + +impl Strict<'_> { + /// Checks the string or the key `s` against the [`StringRules`] of a + /// manifest. + pub(crate) fn check_string(&mut self, s: &str) -> Result<(), E> { + self.check(s, STRING_RULES) + } + + /// Checks `s`, a string or a key the text has as it is, without an + /// escape, against the [`StringRules`] of a manifest. serde_json + /// refuses a control character in a string, so only an escape can put + /// a NUL into one. + pub(crate) fn check_unescaped(&mut self, s: &str) -> Result<(), E> { + self.check(s, STRING_RULES.without(StringRules::NO_NUL)) + } + + /// Checks `s` against `rules`. + fn check(&mut self, s: &str, rules: StringRules) -> Result<(), E> { + match rules.broken_in(s) { + Some(message) => Err(self.break_rule(ParseErrorKind::StringRule, message)), + None => Ok(()), + } + } + + /// Notes that a rule of the kind `kind` was broken, which `message` + /// tells, and returns the error that ends the read. + fn break_rule(&mut self, kind: ParseErrorKind, message: &'static str) -> E { + self.broken = Some(Broken { kind, message }); + E::custom(message) + } + + /// What `error`, which serde_json returned for the text `text`, is, and + /// at which byte of the text. + /// + /// serde_json tells where it found an error by line and column, both + /// counted from 1, and a column counts bytes. A syntax error is at the + /// byte the column names, and one where the text ends too early at the + /// end of the text. A rule is found broken once the key or the string + /// that breaks it was read, and the error is right behind its closing + /// quote. For a string, that is the byte the column names. For a key, + /// serde_json may have read on over whitespace and the brace that ends + /// the object before it said where it was. So the error is behind the + /// last quote serde_json read. What serde_json says about an error ends + /// with where it is, which the message leaves out. + pub(crate) fn error(&self, text: &str, error: &serde_json::Error) -> ParseError { + let line: usize = text + .split_inclusive('\n') + .take(error.line().saturating_sub(1)) + .map(str::len) + .sum(); + // The byte behind the one the column names. + let behind = line + error.column(); + if let Some(Broken { kind, message }) = self.broken { + let read = &text.as_bytes()[..behind]; + return ParseError { + offset: read.iter().rposition(|&b| b == b'"').map_or(0, |quote| quote + 1), + message: message.into(), + kind, + }; + } + let said = error.to_string(); + let place = format!(" at line {} column {}", error.line(), error.column()); + let message = said.strip_suffix(&place).unwrap_or(&said).to_owned(); + ParseError { + offset: if error.is_eof() { + text.len() + } else { + behind.saturating_sub(1) + }, + message: message.into(), + kind: ParseErrorKind::Syntax, + } + } +} + +/// The fields of a kind of object of a manifest, those its keys can name. +/// A field has the bit of its place in the table in a [`FieldSet`], so a +/// table has no more fields than a set has bits. A table with more does +/// not build. +pub(crate) struct FieldTable(&'static [Field]); + +impl FieldTable { + /// The table of an object whose keys are names and none of them a + /// field, such as the names of extended attributes and of HTTP header + /// fields. + pub(crate) const NONE: FieldTable = FieldTable::new(&[]); + + /// The table of `fields`. + pub(crate) const fn new(fields: &'static [Field]) -> FieldTable { + assert!( + fields.len() <= FieldSet::CAPACITY, + "a field set has a bit for every field of a table" + ); + FieldTable(fields) + } + + /// The field the key `name` names, with its place in the table. + pub(crate) fn find(&self, name: &str) -> Option<(usize, Field)> { + self.iter() + .copied() + .enumerate() + .find(|(_, field)| field.as_str() == name) + } +} + +impl Deref for FieldTable { + type Target = [Field]; + + fn deref(&self) -> &[Field] { + self.0 + } +} + +/// The fields an object had so far, each the bit of its place in the +/// [`FieldTable`] of the object. +#[derive(Clone, Copy, Default)] +struct FieldSet(u64); + +impl FieldSet { + /// How many fields a set can hold, as many as it has bits. + const CAPACITY: usize = u64::BITS as usize; + + /// Notes the field at `place` in the table. Returns false when the set + /// had it before. + fn insert(&mut self, place: usize) -> bool { + let bit = 1 << place; + let first = self.0 & bit == 0; + self.0 |= bit; + first + } +} + +/// A key of an object as a reader takes it: one of the fields of the +/// object, or any other key, as the text has it. +pub(crate) enum Key<'de> { + Field(Field), + Other(Cow<'de, str>), +} + +impl<'de> Key<'de> { + /// The key as the text has it. + fn into_name(self) -> Cow<'de, str> { + match self { + Key::Field(field) => Cow::Borrowed(field.as_str()), + Key::Other(name) => name, + } + } +} + +/// The members of an object a visitor reads, key by key. Every key is held +/// to the string rules, and a key the object had before is an error, +/// reported right behind the key. A key that names a field of the object +/// is told apart from the keys before it by the bit of the field in a +/// [`FieldSet`]. Any other key goes into the set of keys of the object, see +/// [`Keys`]. +pub(crate) struct Members { + map: A, + /// The fields the keys of the object can name. + table: &'static FieldTable, + /// The fields the object had so far. + fields: FieldSet, +} + +impl<'de, A: MapAccess<'de>> Members { + /// The members `map` hands out, of an object whose keys can name the + /// fields of `table`, in the text `strict` holds to the rules. + pub(crate) fn new(map: A, table: &'static FieldTable, strict: &mut Strict<'de>) -> Members { + strict.keys.open(); + Members { + map, + table, + fields: FieldSet::default(), + } + } + + /// The key of the next member, whose value is read next. None at the + /// end of the object. + pub(crate) fn next_key(&mut self, strict: &mut Strict<'de>) -> Result>, A::Error> { + let Some(name) = self.map.next_key_seed(KeySeed(strict))? else { + strict.keys.close(); + return Ok(None); + }; + // A field of the object goes into its set of fields, any other key + // into its set of keys. + let (key, first) = match self.table.find(&name) { + Some((place, field)) => (Key::Field(field), self.fields.insert(place)), + None => (Key::Other(name.clone()), strict.keys.insert(name)), + }; + if !first { + return Err(strict.break_rule(ParseErrorKind::DuplicateKey, DUPLICATE_KEY)); + } + Ok(Some(key)) + } + + /// The key of the next member as the text has it, of an object whose + /// keys are names. None at the end of the object. + pub(crate) fn next_name(&mut self, strict: &mut Strict<'de>) -> Result>, A::Error> { + Ok(self.next_key(strict)?.map(Key::into_name)) + } + + /// Reads the value of the member with `seed`. + pub(crate) fn value>(&mut self, seed: S) -> Result { + self.map.next_value_seed(seed) + } + + /// Reads through the value of the member, see [`Skip`]. + pub(crate) fn skip(&mut self, strict: &mut Strict<'de>) -> Result<(), A::Error> { + self.map.next_value_seed(Skip(strict)) + } +} + +/// Reads a key, which is borrowed from the text unless it has an escape. +struct KeySeed<'s, 'de>(&'s mut Strict<'de>); + +impl<'de> DeserializeSeed<'de> for KeySeed<'_, 'de> { + type Value = Cow<'de, str>; + + fn deserialize>(self, deserializer: D) -> Result, D::Error> { + deserializer.deserialize_str(self) + } +} + +impl<'de> Visitor<'de> for KeySeed<'_, 'de> { + type Value = Cow<'de, str>; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a key") + } + + fn visit_borrowed_str(self, key: &'de str) -> Result, E> { + self.0.check_unescaped(key)?; + Ok(Cow::Borrowed(key)) + } + + fn visit_str(self, key: &str) -> Result, E> { + self.0.check_string(key)?; + Ok(Cow::Owned(key.to_owned())) + } +} + +/// Reads through a value of any type and keeps nothing of it, but holds +/// its keys and strings to the rules: what serde's `IgnoredAny` does not +/// do. +pub(crate) struct Skip<'s, 'de>(pub(crate) &'s mut Strict<'de>); + +impl<'de> DeserializeSeed<'de> for Skip<'_, 'de> { + type Value = (); + + fn deserialize>(self, deserializer: D) -> Result<(), D::Error> { + deserializer.deserialize_any(self) + } +} + +impl<'de> Visitor<'de> for Skip<'_, 'de> { + type Value = (); + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a JSON value") + } + + fn visit_unit(self) -> Result<(), E> { + Ok(()) + } + + fn visit_bool(self, _: bool) -> Result<(), E> { + Ok(()) + } + + fn visit_u64(self, _: u64) -> Result<(), E> { + Ok(()) + } + + fn visit_i64(self, _: i64) -> Result<(), E> { + Ok(()) + } + + fn visit_f64(self, _: f64) -> Result<(), E> { + Ok(()) + } + + fn visit_borrowed_str(self, s: &'de str) -> Result<(), E> { + self.0.check_unescaped(s) + } + + fn visit_str(self, s: &str) -> Result<(), E> { + self.0.check_string(s) + } + + fn visit_seq>(self, mut seq: A) -> Result<(), A::Error> { + while seq.next_element_seed(Skip(&mut *self.0))?.is_some() {} + Ok(()) + } + + fn visit_map>(self, map: A) -> Result<(), A::Error> { + let mut members = Members::new(map, &FieldTable::NONE, self.0); + while members.next_key(self.0)?.is_some() { + members.skip(self.0)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::fmt::Write as _; + + use super::*; + use crate::testing::{read_json, MAX_NESTING}; + + #[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 rules_hold_for_every_string() { + 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#""\ufdd0""#, NONCHARACTER_IN_STRING), + (r#""\uffff""#, NONCHARACTER_IN_STRING), + (r#""\ud83f\udffe""#, NONCHARACTER_IN_STRING), + (r#""\udbff\udfff""#, NONCHARACTER_IN_STRING), + (r#""a\u0000b""#, NUL_IN_STRING), + (r#"{"a\u0000":1}"#, NUL_IN_STRING), + ("{\"\u{ffff}\":1}", NONCHARACTER_IN_STRING), + (r#"{"x":["\uffff"]}"#, NONCHARACTER_IN_STRING), + ]; + for (text, message) in refused { + let e = read_json(text).unwrap_err(); + assert_eq!( + (e.kind, e.message.as_ref()), + (ParseErrorKind::StringRule, message), + "{}", + text + ); + assert!(serde_json::from_str::(text).is_ok(), "{}", text); + } + // Their neighbours and the replacement character are fine. + for text in [ + "\"\u{fdcf}\u{fdf0}\u{fffd}\u{e000}\u{1fffd}\u{10fffd}\"", + r#""\ufdcf\ufdf0\ufffd\ud83f\udffd\u0001""#, + r#"{"a":"b","c":[1,"d"]}"#, + ] { + assert_eq!(read_json(text), 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: what they find is the same for every kind of string, + /// a value or a key, with an escape or without. + #[test] + fn string_rules_in_every_kind_of_string() { + let strict = StringRules::NO_NONCHARACTERS.union(StringRules::NO_NUL); + assert_eq!(strict, STRING_RULES); + // 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) { + // Reported right behind the string. + let [value, key] = texts(&string); + let e = read_json(&value).unwrap_err(); + assert_eq!( + (e.kind, e.message.as_ref(), e.offset), + (ParseErrorKind::StringRule, NONCHARACTER_IN_STRING, value.len()), + "{:?}", + value + ); + let e = read_json(&key).unwrap_err(); + let behind = string.len() + "{\"\"".len(); + assert_eq!( + (e.message.as_ref(), e.offset), + (NONCHARACTER_IN_STRING, behind), + "{:?}", + key + ); + } + } + 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_eq!(read_json(&text), 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_json(&format!("\"{}\"", string)).unwrap_err(); + assert_eq!(e.kind, ParseErrorKind::Syntax, "{:?}", string); + } + for string in strings(r"\u0000") { + let [value, key] = texts(&string); + let e = read_json(&value).unwrap_err(); + assert_eq!( + (e.kind, e.message.as_ref(), e.offset), + (ParseErrorKind::StringRule, NUL_IN_STRING, value.len()), + "{:?}", + value + ); + let e = read_json(&key).unwrap_err(); + let behind = string.len() + "{\"\"".len(); + assert_eq!((e.message.as_ref(), e.offset), (NUL_IN_STRING, behind), "{:?}", key); + } + 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_json(text).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; + + /// The members `"0":0` to `"":`. + fn members(prefix: &str, n: usize) -> String { + (0..n) + .map(|i| format!("\"{}{}\":{}", prefix, i, i)) + .collect::>() + .join(",") + } + + /// The error of a key twice, right behind the `n`th time `key` is in + /// `text`, counted from 1. + fn duplicate(text: &str, key: &str, n: usize) -> ParseError { + let (at, _) = text.match_indices(key).nth(n - 1).unwrap(); + ParseError { + offset: at + key.len(), + message: DUPLICATE_KEY.into(), + kind: ParseErrorKind::DuplicateKey, + } + } + + #[test] + fn finds_duplicates_in_large_and_nested_objects() { + // Every object has its own keys, also inside another one. + 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) + ); + assert_eq!(read_json(&unique), Ok(()), "{}", unique); + for at in [0, inner / 2, inner - 1] { + let repeated = format!( + "{{{}{}\"in\":{{{},\"i{}\":0}}}}", + members("o", outer), + comma, + members("i", inner), + at + ); + let key = format!("\"i{}\"", at); + assert_eq!(read_json(&repeated), Err(duplicate(&repeated, &key, 2)), "{}", repeated); + } + 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 + ); + let key = format!("\"o{}\"", outer - 1); + assert_eq!(read_json(&repeated), Err(duplicate(&repeated, &key, 2)), "{}", repeated); + } + } + } + } + + /// A key twice in an object is found right behind the key, before + /// what follows it is read: whitespace, the colon and the value, a + /// comma or the end of the object. So is a key that breaks a rule for + /// strings. + #[test] + fn finds_a_key_twice_right_behind_it() { + for text in [ + "{\"a\":1,\"a\":2}", + "{\"a\":1,\"a\":[}", + "{\"a\":1,\"a\" 2}", + "{\"a\":1,\"a\" :2}", + "{\"a\":1,\"a\"\r\n\t:2}", + "{\"a\":1,\"a\",\"b\":2}", + "{\"a\":1,\"a\"}", + "{\"a\":1,\"a\" \n }", + "{\"a\":1,\"a\"", + "{\"a\":1,\"a\" ", + "[{\"a\":1,\"a\"}]", + "[{\"k\":{\"a\":1,\"a\" :2}}]", + "[{\"k\":{\"a\":1,\"a\"} }]", + ] { + assert_eq!(read_json(text), Err(duplicate(text, "\"a\"", 2)), "{:?}", text); + } + // A key with a noncharacter or NUL in it, whatever follows it. + let object = "{"; + for (key, message) in [("\"\\uFFFF\"", NONCHARACTER_IN_STRING), ("\"a\\u0000\"", NUL_IN_STRING)] { + for follower in [":1}", " :1}", ",\"b\":1}", "}", " \n }", "\n"] { + let text = format!("{}{}{}", object, key, follower); + let e = ParseError { + offset: object.len() + key.len(), + message: message.into(), + kind: ParseErrorKind::StringRule, + }; + assert_eq!(read_json(&text), Err(e), "{:?}", text); + } + } + } + + #[test] + fn 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 = members("k", MANY_MEMBERS); + for (text, duplicate_at) in [ + (format!("[{{{0}}},{{{0}}},{{\"k1\":1}},{{}}]", large), None), + (format!("[{{{0}}},{{\"k1\":1,\"k1\":2}}]", large), Some(3)), + ( + format!("{{\"a\":{{\"b\":{{{0}}}}},\"b\":{{{0}}},\"c\":[[{{{0}}}]]}}", large), + None, + ), + ( + format!("{{\"a\":{{\"b\":{{{0}}}}},\"b\":{{\"k1\":1,\"k1\":2}}}}", large), + Some(3), + ), + ] { + let e = duplicate_at.map(|n| duplicate(&text, "\"k1\"", n)); + assert_eq!(read_json(&text), e.map_or(Ok(()), Err), "{}", text); + } + } + + #[test] + fn 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}"#, + ] { + let e = read_json(text).unwrap_err(); + assert_eq!(e.kind, ParseErrorKind::DuplicateKey, "{}", text); + // Right behind the second key, which ends the text but for + // its value and the braces behind it. + let value = text.rfind(':').unwrap(); + assert_eq!(e.offset, value, "{}", text); + } + for text in [r#"{"a":1,"\u0062":2}"#, r#"{"a":{"a":{"a":1}},"\u0062":[{"a":1}]}"#] { + assert_eq!(read_json(text), Ok(()), "{}", text); + } + } + + /// serde_json's errors are at the byte the column names, a text that + /// ends too early at its end, on any line. What serde_json says leaves + /// out where. + #[test] + fn says_where_serde_json_finds_an_error() { + for (text, message, offset) in [ + ("", "EOF while parsing a value", 0), + ("{", "EOF while parsing an object", 1), + ("{\"a\":1\n", "EOF while parsing an object", 7), + ("[1,]", "trailing comma", 3), + ("{\"a\":1,}", "trailing comma", 7), + ("{1:2}", "key must be a string", 1), + ("1 2", "trailing characters", 2), + ("{\"a\":1}\n\nx", "trailing characters", 9), + ("{\n\"a\":1,\n\"b\":}", "expected value", 13), + ( + "\"a\tb\"", + "control character (\\u0000-\\u001F) found while parsing a string", + 2, + ), + ( + "\"a\nb\"", + "control character (\\u0000-\\u001F) found while parsing a string", + 2, + ), + ("[01]", "invalid number", 2), + ("1E400", "number out of range", 4), + ("[\"\\x\"]", "invalid escape", 3), + ] { + let e = read_json(text).unwrap_err(); + assert_eq!( + (e.kind, e.message.as_ref(), e.offset), + (ParseErrorKind::Syntax, message, offset), + "{:?}", + text + ); + } + // A rule broken on a later line, behind the key. + let text = "{\n \"a\": 1,\n \"a\": 2\n}"; + assert_eq!(read_json(text), Err(duplicate(text, "\"a\"", 2))); + } + + /// Nesting is as deep as serde_json reads it, and refused beyond that, + /// without overflowing the stack. + #[test] + fn limits_nesting() { + for (open, close) in [("[", "]"), ("{\"k\":", "}")] { + let nested = |n: usize| format!("{}1{}", open.repeat(n), close.repeat(n)); + assert_eq!(read_json(&nested(MAX_NESTING)), Ok(())); + for depth in [MAX_NESTING + 1, 1_000, 1_000_000] { + let e = read_json(&nested(depth)).unwrap_err(); + assert_eq!( + (e.kind, e.message.as_ref()), + (ParseErrorKind::Syntax, "recursion limit exceeded") + ); + } + } + } +} diff --git a/src/uapi16/writer.rs b/src/uapi16/writer.rs index 2a57518..433591a 100644 --- a/src/uapi16/writer.rs +++ b/src/uapi16/writer.rs @@ -4,10 +4,11 @@ //! //! [`Writer`]: crate::Writer +use std::collections::BTreeMap; use std::fmt; use std::num::NonZeroU64; -use json::{ObjectWriter, ValueWriter}; +use serde_core::ser::{Serialize, SerializeMap, Serializer}; use crate::base64::Base64; use crate::decode::{Subject, ROOT_RECORD}; @@ -24,6 +25,11 @@ use crate::{ SIGNATURE_MEDIA_TYPE, STRING_RULES, TRAILER_MEDIA_TYPE, USER_NAMESPACE, }; +/// The most room for a record that an [`Encoder`] keeps from one record to +/// the next. A larger record takes more, and gives it back once it went +/// out. +pub(crate) const RECORD_CAPACITY: usize = 64 * 1024; + /// How far an encoder has got in the manifest. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Stage { @@ -46,10 +52,11 @@ enum Stage { /// /// 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. +/// that: at most [`Name::MAX_LEN`] bytes. It keeps room for the record it +/// puts together, and gives back what a record larger than 64 KiB took +/// once it was appended. 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}; @@ -82,33 +89,68 @@ pub struct Encoder { /// The check of the file objects so far, which the next one is checked /// against. sequence_check: SequenceCheck, + /// The record put together last, with its record separator and its + /// newline. serde_json writes JSON into an [`io::Write`](std::io::Write), + /// which a string is not. + pub(crate) record: Vec, } 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(); + let mut encoder = Encoder::start(root)?; + encoder.append_to(text); + Ok(encoder) + } + + /// Appends the record of the file object `file` to `text`. + pub fn file(&mut self, file: &FileObject, text: &mut String) -> Result<(), Error> { + self.encode_file(file)?; + self.append_to(text); + 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> { + self.encode_signature(signature)?; + self.append_to(text); + Ok(()) + } + + /// Ends the manifest: appends the record of the trailer object to + /// `text`. + pub fn finish(&mut self, text: &mut String) -> Result<(), Error> { + self.encode_trailer()?; + self.append_to(text); + Ok(()) + } + + /// An encoder that puts together the record of the root file object + /// `root` first. + pub(crate) fn start(root: &RootObject) -> Result { + let mut encoder = Encoder { + next_record: ROOT_RECORD, + stage: Stage::Files, + sequence_check: SequenceCheck::new(root.recorded_features(), root.order), + record: Vec::new(), + }; // In the order a reader finds what is wrong with the record, see - // Encoder::file(). - Encoder::write_record(text, |object| root.write(object)) + // Encoder::encode_file(). + encoder + .write_record(root) .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, - }) + .and_then(|()| encoder.sequence_check.check_root_fields(root)) + .map_err(|e| e.in_record(ROOT_RECORD))?; + encoder.next_record += 1; + Ok(encoder) } - /// Appends the record of the file object `file` to `text`. - pub fn file(&mut self, file: &FileObject, text: &mut String) -> Result<(), Error> { + /// Puts together the record of the file object `file`. + pub(crate) fn encode_file(&mut self, file: &FileObject) -> Result<(), Error> { let record_number = self.next_record; if self.stage == Stage::Done { return Err(Error::data_after_trailer(record_number)); @@ -124,8 +166,8 @@ impl Encoder { // 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)) + let encoded = self + .write_record(file) .and_then(|()| file.check_strings(record_number)) .and_then(|()| match self.stage { Stage::Signatures => Err(Error::file_after_signature(record_number)), @@ -134,8 +176,8 @@ impl Encoder { .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); + if let Err(e) = encoded { + self.clear_record(); let e = e.in_record(record_number); return Err(if file.name.is_root() { e @@ -147,16 +189,13 @@ impl Encoder { 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> { + /// Puts together the record of the signature object `signature`. + pub(crate) fn encode_signature(&mut self, signature: &Signature) -> 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)) + self.write_record(signature) .and_then(|()| { Field::Mechanism.check_string( &signature.mechanism, @@ -164,7 +203,7 @@ impl Encoder { ) }) .map_err(|e| { - text.truncate(start); + self.clear_record(); e.in_record(record_number) })?; self.stage = Stage::Signatures; @@ -172,58 +211,90 @@ impl Encoder { Ok(()) } - /// Ends the manifest: appends the record of the trailer object to - /// `text`. - pub fn finish(&mut self, text: &mut String) -> Result<(), Error> { + /// Puts together the record of the trailer object. + pub(crate) fn encode_trailer(&mut self) -> 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.write_record(&Trailer).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); + /// Puts together the record of `object`, in place of the one before. + /// A record larger than [`MAX_RECORD_SIZE`], its record separator + /// included, is refused. + fn write_record(&mut self, object: &impl Fields) -> Result<(), Error> { + self.record.clear(); + self.record.push(RECORD_SEPARATOR); + serde_json::to_writer(&mut self.record, &Json(object)).expect("a record serializes into a Vec"); + self.record.push(RECORD_END); + if self.record.len() > MAX_RECORD_SIZE { + self.clear_record(); return Err(Error::record_too_large()); } Ok(()) } + + /// Appends the record that was put together to `text`. + fn append_to(&mut self, text: &mut String) { + text.push_str(std::str::from_utf8(&self.record).expect("serde_json writes UTF-8")); + self.clear_record(); + } + + /// Forgets the record that was put together. A record larger than + /// [`RECORD_CAPACITY`] gives back the room it took beyond that. + pub(crate) fn clear_record(&mut self) { + self.record.clear(); + self.record.shrink_to(RECORD_CAPACITY); + } +} + +/// An object of a manifest: what writes its fields. +trait Fields { + /// The fields a reader filled in, of the object and of the parts it + /// has, such as its inode attributes. They are not written. + fn filled_in(&self) -> FilledIn; + + /// Writes the fields into `fields` in the order of their names. + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error>; +} + +/// An object of a manifest as JSON. +struct Json<'a, T>(&'a T); + +impl Serialize for Json<'_, T> { + fn serialize(&self, serializer: S) -> Result { + let mut fields = FieldWriter::new(serializer.serialize_map(None)?, self.0.filled_in()); + self.0.write_fields(&mut fields)?; + fields.end() + } +} + +/// What `T` prints, as a JSON string. +struct Text(T); + +impl Serialize for Text { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_str(&self.0) + } } /// 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. +struct FieldWriter { + map: M, + /// The fields a reader filled in. filled_in: FilledIn, } -impl<'w, 'o> FieldWriter<'w, 'o> { - /// Writes the fields of an object into `object`, but none of those of +impl FieldWriter { + /// Writes the fields of an object into `map`, 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())) + fn new(map: M, filled_in: FilledIn) -> FieldWriter { + FieldWriter { map, filled_in } } /// What is written of `value`, the value of `field`: nothing where a @@ -232,34 +303,38 @@ impl<'w, 'o> FieldWriter<'w, 'o> { 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 `value`, if there is one, as the field `field`. + fn put(&mut self, field: Field, value: Option<&T>) -> Result<(), M::Error> { + match self.written(field, value) { + Some(value) => self.map.serialize_entry(field.as_str(), value), + None => Ok(()), } } /// 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)); + fn unsigned(&mut self, field: Field, value: Option) -> Result<(), M::Error> { + self.put(field, value.as_ref()) } /// 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)); + fn bool(&mut self, field: Field, value: Option) -> Result<(), M::Error> { + self.put(field, value.as_ref()) } /// 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)); + fn string(&mut self, field: Field, value: Option<&str>) -> Result<(), M::Error> { + self.put(field, 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)); + fn display(&mut self, field: Field, value: Option) -> Result<(), M::Error> { + self.put(field, value.map(Text).as_ref()) + } + + /// Ends the object. + fn end(self) -> Result { + self.map.end() } } @@ -324,40 +399,47 @@ impl RootObject { } self.check_consistency() } +} + +/// The root file object has the media type of a manifest, and neither a +/// name nor a type: it is a directory. +impl Fields for RootObject { + fn filled_in(&self) -> FilledIn { + self.inode.filled_in + } - /// 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); + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { 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); - } - } - } + inode.write_xattrs(fields)?; + fields.display(Field::FatSerial, identity.fat_serial)?; + let listed = self.features.filter(|listed| *listed != Features::DEFAULT); + fields.put(Field::Features, listed.map(FeatureNames).as_ref())?; for field in inode.flags.set_fields() { - fields.bool(field, Some(true)); + 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); + 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_fields(fields) + } +} + +/// The names of the features a manifest records, as `features` has them. +struct FeatureNames(Features); + +impl Serialize for FeatureNames { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.0.names()) } } @@ -419,58 +501,10 @@ impl FileObject { 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<'_, '_>) { + fn write_flags(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { 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()); @@ -488,13 +522,68 @@ impl FileObject { next_inode = inode.next(); second } - (None, None) => break, + (None, None) => return Ok(()), }; - fields.bool(field, Some(true)); + fields.bool(field, Some(true))?; } } } +impl Fields for FileObject { + fn filled_in(&self) -> FilledIn { + self.filled_in.union(self.inode.filled_in) + } + + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { + let inode = &self.inode; + let gpt = self.gpt.as_deref(); + let contents = (!self.contents.is_empty()).then_some(ContentsList(&self.contents)); + fields.put(Field::Contents, contents.as_ref())?; + inode.write_xattrs(fields)?; + self.write_flags(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_fields(fields) + } +} + +/// The contents objects of a file object, as `contents` has them. +struct ContentsList<'a>(&'a [Contents]); + +impl Serialize for ContentsList<'_> { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.0.iter().map(Json)) + } +} + impl InodeAttributes { /// The names of the extended attributes, in the order they are /// written. @@ -527,25 +616,48 @@ impl InodeAttributes { .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)), - } + /// Writes `extendedAttributes`, unless there are none. + fn write_xattrs(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { + let attributes = self.user_xattrs.as_deref().filter(|attributes| !attributes.is_empty()); + fields.put(Field::ExtendedAttributes, attributes.map(XattrNamespaces).as_ref()) + } +} + +/// The extended attributes of a file, as `extendedAttributes` has them: +/// all of them in the `user` namespace. +struct XattrNamespaces<'a>(&'a BTreeMap>); + +impl Serialize for XattrNamespaces<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut namespaces = serializer.serialize_map(Some(1))?; + let attributes = self.0.iter().map(|(name, value)| (name, XattrValue(value))); + namespaces.serialize_entry(USER_NAMESPACE, &Entries(attributes))?; + namespaces.end() + } +} + +/// The value of an extended attribute: text if it is a string a manifest +/// can have, and Base64 otherwise. +struct XattrValue<'a>(&'a [u8]); + +impl Serialize for XattrValue<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut value = serializer.serialize_map(Some(1))?; + match std::str::from_utf8(self.0) { + Ok(text) if STRING_RULES.admits(text) => value.serialize_entry(Field::Text.as_str(), text)?, + _ => value.serialize_entry(Field::Base64.as_str(), &Text(Base64(self.0)))?, } + value.end() + } +} + +/// The keys and the values of a JSON object, which an iterator hands out +/// once. +struct Entries(I); + +impl + Clone> Serialize for Entries { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_map(self.0.clone()) } } @@ -564,11 +676,11 @@ impl ValidityWindow { /// 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); + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { + 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)); + fields.string(Field::Validity, state.map(Validity::as_str)) } } @@ -631,15 +743,18 @@ impl Contents { headers.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); headers } +} + +/// Of the sizes and hashes a contents object 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. +impl Fields for Contents { + fn filled_in(&self) -> FilledIn { + self.filled_in + } - /// 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); + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { let original_size = fields.written(Field::OriginalSize, self.original_size); let original_sha256 = fields .written(Field::OriginalSha256, self.original_sha256.as_ref()) @@ -658,24 +773,19 @@ impl Contents { 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)); + 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))?; + let headers = Some(self.sorted_headers()).filter(|headers| !headers.is_empty()); + let headers = headers.map(|headers| Entries(headers.into_iter().map(|(name, value)| (name, value)))); + fields.put(Field::HttpHeaders, headers.as_ref())?; + 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()); + 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()) } } @@ -687,15 +797,29 @@ impl Sha256 { } } -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)); +impl Fields for Signature { + fn filled_in(&self) -> FilledIn { + FilledIn::default() + } + + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { + 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)) + } +} + +/// The trailer object, which ends a manifest. +struct Trailer; + +impl Fields for Trailer { + fn filled_in(&self) -> FilledIn { + FilledIn::default() + } + + fn write_fields(&self, fields: &mut FieldWriter) -> Result<(), M::Error> { + fields.string(Field::MediaType, Some(TRAILER_MEDIA_TYPE)) } } @@ -705,8 +829,8 @@ mod tests { use crate::error::ErrorKind; use crate::object::{DosFlags, FatSerial, InodeFlags, Location, Mode, Uuid}; use crate::testing::{ - directory, everything, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, EMPTY, - HELLO, ROOT, SIGNATURE, TRAILER, + directory, everything, json, name, read_whole, record, recording_all, sequence, write_whole, written, Whole, + EMPTY, HELLO, ROOT, SIGNATURE, TRAILER, }; use crate::{Sha256, Writer}; use std::collections::BTreeMap; @@ -871,10 +995,10 @@ mod tests { /// Checks that the keys of every object in `value` are in the order of /// their bytes. - fn sorted(value: &json::Value) { + fn sorted(value: &serde_json::Value) { match value { - json::Value::Object(object) => { - let keys: Vec<&str> = object.keys().collect(); + serde_json::Value::Object(object) => { + let keys: Vec<&str> = object.keys().map(String::as_str).collect(); assert!( keys.windows(2).all(|pair| pair[0].as_bytes() < pair[1].as_bytes()), "{:?}", @@ -882,7 +1006,7 @@ mod tests { ); object.iter().for_each(|(_, value)| sorted(value)); } - json::Value::Array(items) => items.iter().for_each(sorted), + serde_json::Value::Array(items) => items.iter().for_each(sorted), _ => {} } } @@ -925,10 +1049,10 @@ mod tests { "{}", record ); - sorted(&json::parse(record).unwrap()); + sorted(&json(record).unwrap()); } - let whole = json::parse(&records[2]).unwrap(); - let keys: Vec<&str> = whole.as_object().unwrap().keys().collect(); + let whole = json(&records[2]).unwrap(); + let keys: Vec<&str> = whole.as_object().unwrap().keys().map(String::as_str).collect(); assert_eq!( keys, [ @@ -962,9 +1086,9 @@ mod tests { ); // 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))); + assert_eq!(whole.get("flagHidden"), Some(&serde_json::Value::Bool(true))); let contents = whole.get("contents").unwrap().as_array().unwrap(); - let keys: Vec<&str> = contents[0].as_object().unwrap().keys().collect(); + let keys: Vec<&str> = contents[0].as_object().unwrap().keys().map(String::as_str).collect(); assert_eq!( keys, [ diff --git a/src/varlink/Cargo.toml b/src/varlink/Cargo.toml index f3fb7fb..993d1c3 100644 --- a/src/varlink/Cargo.toml +++ b/src/varlink/Cargo.toml @@ -12,8 +12,11 @@ publish.workspace = true path = "lib.rs" [dependencies] -json.workspace = true libc.workspace = true +serde_core.workspace = true +# A service reads the floats of its parameters as they were written, and +# a reply keeps its members in the order they were given. +serde_json = { workspace = true, features = ["float_roundtrip", "preserve_order"] } [lints] workspace = true diff --git a/src/varlink/idl.rs b/src/varlink/idl.rs index ba1bc66..ffbc29b 100644 --- a/src/varlink/idl.rs +++ b/src/varlink/idl.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; use std::fmt; -use json::{Object, Value}; +use crate::{Object, Value}; /// A declared type. #[derive(Clone, Debug, PartialEq, Eq)] @@ -484,7 +484,7 @@ impl Interface { } } for key in params.keys() { - if !fields.iter().any(|f| f.name == key) { + if !fields.iter().any(|f| f.name == *key) { return Err(key); } } @@ -499,11 +499,11 @@ impl Interface { Type::Bool => matches!(value, Value::Bool(_)), // Integers beyond the JSON number range may arrive as strings. Type::Int => match value { - Value::Int(_) => true, + Value::Number(n) => n.is_i64() || n.is_u64(), Value::String(s) => s.parse::().is_ok(), _ => false, }, - Type::Float => matches!(value, Value::Int(_) | Value::Float(_)), + Type::Float => matches!(value, Value::Number(_)), Type::String => matches!(value, Value::String(_)), Type::Object => matches!(value, Value::Object(_)), Type::Any => true, @@ -528,6 +528,7 @@ impl Interface { #[cfg(test)] mod tests { use super::*; + use crate::UniqueKeys; const EXAMPLE: &str = "\ # A test interface @@ -587,14 +588,22 @@ error Failed(reason: string) } } + /// The object `text` holds. + fn object(text: &str) -> Object { + match UniqueKeys::parse(text).unwrap() { + Value::Object(o) => o, + other => panic!("{} is not an object", other), + } + } + #[test] fn validation() { let i = parse(EXAMPLE).unwrap(); let run = &i.methods["Run"]; - let ok = json::parse(r#"{"mode":"fast","entries":[{"name":"a","tags":[],"attrs":{"x":1}}]}"#).unwrap(); - assert_eq!(i.validate(&run.input, ok.as_object().unwrap()), Ok(())); - let ok = json::parse(r#"{"mode":"slow","entries":null}"#).unwrap(); - assert_eq!(i.validate(&run.input, ok.as_object().unwrap()), Ok(())); + let ok = object(r#"{"mode":"fast","entries":[{"name":"a","tags":[],"attrs":{"x":1}}]}"#); + assert_eq!(i.validate(&run.input, &ok), Ok(())); + let ok = object(r#"{"mode":"slow","entries":null}"#); + assert_eq!(i.validate(&run.input, &ok), Ok(())); for (text, field) in [ (r#"{}"#, "mode"), (r#"{"mode":"medium"}"#, "mode"), @@ -606,12 +615,15 @@ error Failed(reason: string) ), (r#"{"mode":"fast","options":5}"#, "options"), ] { - let v = json::parse(text).unwrap(); - assert_eq!(i.validate(&run.input, v.as_object().unwrap()), Err(field), "{}", text); + assert_eq!(i.validate(&run.input, &object(text)), Err(field), "{}", text); } assert!(i.matches(&Type::Int, &Value::from("18446744073709551616"))); assert!(!i.matches(&Type::Int, &Value::from("x"))); assert!(i.matches(&Type::Float, &Value::from(1u32))); + // -0 is a float, and no integer. + let zero = UniqueKeys::parse("-0").unwrap(); + assert!(!i.matches(&Type::Int, &zero)); + assert!(i.matches(&Type::Float, &zero)); assert!(!i.matches(&Type::Any, &Value::Null)); } diff --git a/src/varlink/lib.rs b/src/varlink/lib.rs index a3e8287..1ba42a5 100644 --- a/src/varlink/lib.rs +++ b/src/varlink/lib.rs @@ -31,6 +31,7 @@ pub mod idl; mod sys; +mod value; use std::collections::BTreeMap; use std::fmt; @@ -42,7 +43,26 @@ use std::os::unix::net::{SocketAddr, UnixListener, UnixStream}; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; -pub use json::{Object, Value}; +pub use serde_json::Value; +pub use value::UniqueKeys; + +/// A JSON object: the parameters of a call, of a reply or of an error. +pub type Object = serde_json::Map; + +/// Builds an [`Object`] from keys and values. +/// +/// ``` +/// let o = varlink::object! { "name" => "a", "size" => 3u64 }; +/// assert_eq!(serde_json::to_string(&o).unwrap(), r#"{"name":"a","size":3}"#); +/// ``` +#[macro_export] +macro_rules! object { + ($($key:expr => $value:expr),* $(,)?) => {{ + let mut o = $crate::Object::new(); + $( o.insert(::std::string::String::from($key), $crate::Value::from($value)); )* + o + }}; +} /// Largest message accepted, the same limit sd-varlink uses. pub const MAX_MESSAGE_SIZE: usize = 16 * 1024 * 1024; @@ -124,23 +144,20 @@ impl Error { pub fn interface_not_found(interface: &str) -> Error { Error::new( "org.varlink.service.InterfaceNotFound", - json::object! { "interface" => interface }, + object! { "interface" => interface }, ) } /// `org.varlink.service.MethodNotFound` pub fn method_not_found(method: &str) -> Error { - Error::new( - "org.varlink.service.MethodNotFound", - json::object! { "method" => method }, - ) + Error::new("org.varlink.service.MethodNotFound", object! { "method" => method }) } /// `org.varlink.service.MethodNotImplemented` pub fn method_not_implemented(method: &str) -> Error { Error::new( "org.varlink.service.MethodNotImplemented", - json::object! { "method" => method }, + object! { "method" => method }, ) } @@ -148,7 +165,7 @@ impl Error { pub fn invalid_parameter(parameter: &str) -> Error { Error::new( "org.varlink.service.InvalidParameter", - json::object! { "parameter" => parameter }, + object! { "parameter" => parameter }, ) } @@ -170,9 +187,9 @@ impl Error { /// `io.systemd.System`, the generic errno error systemd tools use. pub fn system(errno: i32) -> Error { let errno = i32::try_from(errno.unsigned_abs()).unwrap_or(i32::MAX); - let mut p = json::object! { "origin" => "linux", "errno" => errno }; + let mut p = object! { "origin" => "linux", "errno" => errno }; if let Some(name) = errno_name(errno) { - p.insert("errnoName", name); + p.insert("errnoName".into(), name.into()); } Error::new("io.systemd.System", p) } @@ -451,7 +468,7 @@ impl Connection { .stream .as_mut() .ok_or_else(|| io::Error::new(io::ErrorKind::NotConnected, "connection was upgraded"))?; - let mut text = message.to_string().into_bytes(); + let mut text = serde_json::to_vec(message).expect("an object of JSON values is JSON"); text.push(0); stream.write_all(&text)?; stream.flush() @@ -468,9 +485,9 @@ impl Connection { } let mut m = Object::new(); if !parameters.is_empty() { - m.insert("parameters", parameters); + m.insert("parameters".into(), Value::Object(parameters)); } - m.insert("continues", true); + m.insert("continues".into(), Value::Bool(true)); self.send(&m) } @@ -486,7 +503,7 @@ impl Connection { } let mut m = Object::new(); if !parameters.is_empty() { - m.insert("parameters", parameters); + m.insert("parameters".into(), Value::Object(parameters)); } self.send(&m)?; let stream = self @@ -598,13 +615,14 @@ impl Server { /// Parses and checks a request. Err means the connection must be closed. fn parse_call(&self, message: &[u8]) -> Result { let text = std::str::from_utf8(message).map_err(|_| "message is not UTF-8")?; - let value = json::parse(text).map_err(|_| "message is not valid JSON")?; + let value = UniqueKeys::parse(text).map_err(|_| "message is not valid JSON")?; let Value::Object(mut object) = value else { return Err("message is not a JSON object"); }; // The parameters are taken out of the message, not copied: they can - // be most of a message of MAX_MESSAGE_SIZE bytes. - let parameters = match object.remove("parameters") { + // be most of a message of MAX_MESSAGE_SIZE bytes. The other members + // keep their order. + let parameters = match object.shift_remove("parameters") { None | Some(Value::Null) => Object::new(), Some(Value::Object(o)) => o, Some(_) => return Err("parameters is not an object"), @@ -618,18 +636,18 @@ impl Server { }; let mut has_method = false; let mut flags = 0; - for (key, value) in object.iter() { - match key { + for (key, value) in &object { + match key.as_str() { "method" => { call.method = value.as_str().ok_or("method is not a string")?.to_string(); has_method = true; } - "oneway" | "more" | "upgrade" => { + flag @ ("oneway" | "more" | "upgrade") => { let b = value.as_bool().ok_or("flag is not a boolean")?; if b { flags += 1; } - match key { + match flag { "oneway" => call.oneway = b, "more" => call.more = b, _ => call.upgrade = b, @@ -652,7 +670,7 @@ impl Server { } fn get_info(&self) -> Object { - json::object! { + object! { "vendor" => self.info.vendor.as_str(), "product" => self.info.product.as_str(), "version" => self.info.version.as_str(), @@ -682,7 +700,7 @@ impl Server { } let name = call.parameters.get("interface").and_then(Value::as_str).unwrap_or(""); match self.interfaces.get(name) { - Some(i) => Reply::Final(json::object! { "description" => i.text.as_str() }), + Some(i) => Reply::Final(object! { "description" => i.text.as_str() }), None => Reply::Error(Error::interface_not_found(name)), } } @@ -749,14 +767,14 @@ impl Server { Reply::Final(parameters) => { let mut m = Object::new(); if !parameters.is_empty() { - m.insert("parameters", parameters); + m.insert("parameters".into(), Value::Object(parameters)); } m } Reply::Error(e) => { - let mut m = json::object! { "error" => e.name.as_str() }; + let mut m = object! { "error" => e.name.as_str() }; if !e.parameters.is_empty() { - m.insert("parameters", e.parameters); + m.insert("parameters".into(), Value::Object(e.parameters)); } m } @@ -1097,9 +1115,9 @@ impl Client { /// Sends a call, to be answered the way `mode` asks. pub fn send(&mut self, method: &str, parameters: Object, mode: CallMode) -> io::Result<()> { - let mut m = json::object! { "method" => method }; + let mut m = object! { "method" => method }; if !parameters.is_empty() { - m.insert("parameters", parameters); + m.insert("parameters".into(), Value::Object(parameters)); } let flag = match mode { CallMode::Plain => None, @@ -1108,7 +1126,7 @@ impl Client { CallMode::Upgrade => Some("upgrade"), }; if let Some(flag) = flag { - m.insert(flag, true); + m.insert(flag.into(), Value::Bool(true)); } self.connection.more = mode == CallMode::More; self.connection.send(&m) @@ -1131,12 +1149,12 @@ impl Client { } fn send_fds(&mut self, method: &str, parameters: Object, fds: &[BorrowedFd<'_>], more: bool) -> io::Result<()> { - let mut m = json::object! { "method" => method }; + let mut m = object! { "method" => method }; if !parameters.is_empty() { - m.insert("parameters", parameters); + m.insert("parameters".into(), Value::Object(parameters)); } if more { - m.insert("more", true); + m.insert("more".into(), Value::Bool(true)); } self.connection.more = more; let stream = self @@ -1147,7 +1165,7 @@ impl Client { let socket = stream .socket() .ok_or_else(|| io::Error::from_raw_os_error(libc::ENOTSOCK))?; - let mut text = m.to_string().into_bytes(); + let mut text = serde_json::to_vec(&m).expect("an object of JSON values is JSON"); text.push(0); let sent = sys::send_with_fds(socket, &text, fds)?; stream.write_all(&text[sent..])?; @@ -1171,19 +1189,19 @@ impl Client { Message::End(_) => return Ok(None), }; let text = std::str::from_utf8(&message).map_err(|_| protocol_error("reply is not UTF-8"))?; - let value = json::parse(text).map_err(|_| protocol_error("reply is not JSON"))?; + let value = UniqueKeys::parse(text).map_err(|_| protocol_error("reply is not JSON"))?; let Value::Object(mut object) = value else { return Err(protocol_error("reply is not an object")); }; - let parameters = match object.remove("parameters") { + let parameters = match object.shift_remove("parameters") { None | Some(Value::Null) => Object::new(), Some(Value::Object(o)) => o, Some(_) => return Err(protocol_error("unexpected field in reply")), }; let mut error = None; let mut continues = false; - for (key, value) in object.iter() { - match (key, value) { + for (key, value) in &object { + match (key.as_str(), value) { ("error", Value::String(name)) => error = Some(name.clone()), ("continues", Value::Bool(b)) => continues = *b, (k, _) if k.contains('.') => {} @@ -1250,19 +1268,16 @@ error Boom(reason: string) let text = call.parameters.get("text").and_then(Value::as_str).unwrap(); let times = call.parameters.get("times").and_then(Value::as_u64).unwrap_or(1); if text == "boom" { - return Reply::Error(Error::new( - "io.test.Echo.Boom", - json::object! { "reason" => "asked for it" }, - )); + return Reply::Error(Error::new("io.test.Echo.Boom", object! { "reason" => "asked for it" })); } - Reply::Final(json::object! { "text" => text.repeat(times as usize) }) + Reply::Final(object! { "text" => text.repeat(times as usize) }) } "io.test.Echo.Count" => { let upto = call.parameters.get("upto").and_then(Value::as_u64).unwrap(); for n in 0..upto { - connection.notify(json::object! { "n" => n }).unwrap(); + connection.notify(object! { "n" => n }).unwrap(); } - Reply::Final(json::object! { "n" => upto }) + Reply::Final(object! { "n" => upto }) } "io.test.Echo.Read" => { let index = call.parameters.get("fileDescriptor").and_then(Value::as_u64).unwrap() as usize; @@ -1270,13 +1285,13 @@ error Boom(reason: string) Ok(fd) => { let mut text = String::new(); std::fs::File::from(fd).read_to_string(&mut text).unwrap(); - Reply::Final(json::object! { "text" => text }) + Reply::Final(object! { "text" => text }) } Err(_) => Reply::Error(Error::invalid_parameter("fileDescriptor")), } } "io.test.Echo.Take" => { - let mut up = connection.upgrade(json::object! { "bytes" => 5u32 }).unwrap(); + let mut up = connection.upgrade(object! { "bytes" => 5u32 }).unwrap(); let mut data = up.buffered; let mut rest = vec![0u8; 5 - data.len()]; up.stream.read_exact(&mut rest).unwrap(); @@ -1396,7 +1411,10 @@ error Boom(reason: string) } fn params(text: &str) -> Object { - json::parse(text).unwrap().as_object().unwrap().clone() + match UniqueKeys::parse(text).unwrap() { + Value::Object(o) => o, + other => panic!("{} is not an object", other), + } } #[test] @@ -1574,6 +1592,8 @@ error Boom(reason: string) "{\"method\":\"a.b.C\",\"more\":1}", "{\"method\":\"a.b.C\",\"parameters\":[]}", "{\"method\":5}", + "{\"method\":\"a.b.C\",\"method\":\"a.b.C\"}", + "{\"method\":\"io.test.Echo.Echo\",\"parameters\":{\"text\":\"a\",\"text\":\"b\"}}", ] { let (mut a, b) = UnixStream::pair().unwrap(); let h = std::thread::spawn(move || server().serve(Box::new(b), &Echo)); diff --git a/src/varlink/value.rs b/src/varlink/value.rs new file mode 100644 index 0000000..7ad56a2 --- /dev/null +++ b/src/varlink/value.rs @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +//! Reading the JSON text of a message into a [`Value`]. + +use std::fmt; + +use serde_core::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor}; + +use crate::{Object, Value}; + +/// Reads a JSON value into a [`Value`], and refuses an object that has a +/// key twice, at any depth. RFC 8259 leaves open what such an object +/// means, and serde_json's own reader keeps the last of the two values. +/// The server and the client read every message this way. +pub struct UniqueKeys; + +impl UniqueKeys { + /// Reads `text`, which has to be one JSON value and nothing more. + pub fn parse(text: &str) -> Result { + let mut json = serde_json::Deserializer::from_str(text); + let value = UniqueKeys.deserialize(&mut json)?; + json.end()?; + Ok(value) + } +} + +impl<'de> DeserializeSeed<'de> for UniqueKeys { + type Value = Value; + + fn deserialize>(self, deserializer: D) -> Result { + deserializer.deserialize_any(self) + } +} + +impl<'de> Visitor<'de> for UniqueKeys { + type Value = Value; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a JSON value") + } + + fn visit_unit(self) -> Result { + Ok(Value::Null) + } + + fn visit_bool(self, value: bool) -> Result { + Ok(Value::Bool(value)) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(Value::from(value)) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(Value::from(value)) + } + + fn visit_f64(self, value: f64) -> Result { + Ok(Value::from(value)) + } + + fn visit_str(self, value: &str) -> Result { + Ok(Value::from(value)) + } + + fn visit_string(self, value: String) -> Result { + Ok(Value::String(value)) + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut elements = Vec::new(); + while let Some(element) = seq.next_element_seed(UniqueKeys)? { + elements.push(element); + } + Ok(Value::Array(elements)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut object = Object::new(); + while let Some(key) = map.next_key::()? { + if object.contains_key(&key) { + return Err(de::Error::custom("duplicate key")); + } + let value = map.next_value_seed(UniqueKeys)?; + object.insert(key, value); + } + Ok(Value::Object(object)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_a_key_twice() { + for text in [ + r#"{"a":1,"a":2}"#, + r#"{"a":1,"\u0061":1}"#, + r#"{"x":{"b":[],"b":null}}"#, + r#"[{"a":1},{"b":1,"b":1}]"#, + // What follows the second key is not read. + r#"{"a":1,"a":[}"#, + r#"{"a":1,"a" 2}"#, + ] { + let e = UniqueKeys::parse(text).unwrap_err(); + assert!(e.to_string().starts_with("duplicate key at line 1"), "{}: {}", text, e); + } + // Each object has keys of its own, and keeps them in their order. + let value = UniqueKeys::parse(r#"{"b":{"a":1},"a":[{"a":1},{"a":1.5}],"c":"\u0063"}"#).unwrap(); + let keys: Vec<&str> = value.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys, ["b", "a", "c"]); + assert_eq!(value["a"][1]["a"], Value::from(1.5)); + assert_eq!(value["c"], Value::from("c")); + } + + #[test] + fn reads_what_serde_json_reads() { + for text in [ + "null", + "true", + "-1", + "18446744073709551615", + "-0", + "1e300", + "0.1", + r#""a\u00e9\ud83d\ude00""#, + r#"[1,[2,[3]],{}]"#, + r#" {"k" : [ true , false ] } "#, + ] { + assert_eq!( + UniqueKeys::parse(text).unwrap(), + serde_json::from_str::(text).unwrap(), + "{}", + text + ); + } + for text in ["", "{", "1 2", "[1,]", "1E400", "\"\\ud800\""] { + assert!(UniqueKeys::parse(text).is_err(), "{}", text); + } + // Nesting is limited, and refused without overflowing the stack. + let deep = format!("{}{}", "[".repeat(100_000), "]".repeat(100_000)); + assert!(UniqueKeys::parse(&deep).is_err()); + } +} diff --git a/tests/crash/Cargo.toml b/tests/crash/Cargo.toml index a5a807c..0499b79 100644 --- a/tests/crash/Cargo.toml +++ b/tests/crash/Cargo.toml @@ -22,10 +22,14 @@ path = "crash.rs" [dependencies] blkid.workspace = true -json.workspace = true libc.workspace = true sha2.workspace = true uapi16.workspace = true +# What the unit tests of the library use, which clippy builds with +# --all-targets. +[dev-dependencies] +serde_json = { workspace = true, features = ["preserve_order"] } + [lints] workspace = true diff --git a/tests/varlink.rs b/tests/varlink.rs index 5ff3d76..75f3491 100644 --- a/tests/varlink.rs +++ b/tests/varlink.rs @@ -21,7 +21,7 @@ use std::time::{Duration, UNIX_EPOCH}; use common::{build_tree, find_program, first_difference, ufat, Temp}; use fat::device::{Access, Device}; use fat::volume::Volume; -use varlink::{Client, Object, Response, Stream, Value}; +use varlink::{Client, Object, Response, Stream, UniqueKeys, Value}; const INTERFACE: &str = include_str!("../docs/org.uapi-group.FileSystem.varlink"); const IFACE: &str = "org.uapi-group.FileSystem"; @@ -179,7 +179,10 @@ fn connect_listening(ufat: &Path) -> (Child, Temp, Client) { } fn params(text: &str) -> Object { - json::parse(text).unwrap().as_object().unwrap().clone() + match UniqueKeys::parse(text).unwrap() { + Value::Object(o) => o, + other => panic!("{} is not an object", other), + } } fn reply(r: Response) -> Object { @@ -2761,14 +2764,15 @@ fn describe_with_and_without_a_manifest() { &[img_ro.as_fd()], ); assert_eq!(e.name, format!("{}.NotFileSystem", IFACE)); - let e = error_of( - &mut c, - "Describe", + // -1 is no offset, and neither is -0, which is a float. + for image in [ r#"{"image":{"fileDescriptor":0,"offset":-1}}"#, - &[img_ro.as_fd()], - ); - assert_eq!(e.name, "org.varlink.service.InvalidParameter"); - assert_eq!(str_of(&e.parameters, "parameter"), "image"); + r#"{"image":{"fileDescriptor":0,"offset":-0}}"#, + ] { + let e = error_of(&mut c, "Describe", image, &[img_ro.as_fd()]); + assert_eq!(e.name, "org.varlink.service.InvalidParameter"); + assert_eq!(str_of(&e.parameters, "parameter"), "image"); + } } /// Describe of a volume with a directory whose chain loops answers @@ -3256,7 +3260,7 @@ fn check_finds_damage() { let batches: Vec = replies .iter() .filter_map(|r| r.get("problems").and_then(Value::as_array)) - .map(<[Value]>::len) + .map(Vec::len) .collect(); assert!(batches.len() >= 2, "{} batches", batches.len()); assert!(batches.iter().all(|&b| b <= 100)); @@ -3826,7 +3830,7 @@ fn varlinkctl_can_drive_us() { .output() .unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); - let v = json::parse(String::from_utf8_lossy(&out.stdout).trim()).unwrap(); + let v = UniqueKeys::parse(String::from_utf8_lossy(&out.stdout).trim()).unwrap(); assert_eq!( v.get("description").unwrap().get("label").unwrap().as_str(), Some("CTL") diff --git a/verify/lib.rs b/verify/lib.rs index f6eac85..f5ef3e0 100644 --- a/verify/lib.rs +++ b/verify/lib.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: LGPL-2.1-or-later //! The crate root for verify/run.sh: the pure modules of the library, so -//! that Kani needs neither the json crate nor any I/O. The Kani harnesses +//! that Kani needs neither serde_json nor any I/O. The Kani harnesses //! live in `#[cfg(kani)] mod proofs` blocks inside the modules themselves. #![allow(dead_code, unused_imports, unreachable_pub)] #![cfg_attr(kani, feature(rustc_private))]