From 72ee990e036fc2305adf2180110b42d32d49716c Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH] Import binary plist parser changes from Craft Anything f64ae3bf --- crates/plist/LICENSE-APACHE | 177 ++++++++++++++++++++++++++ crates/plist/LICENSE-MIT | 21 ++++ crates/plist/src/binary.rs | 241 ++++++++++++++++++++++++++++++++++++ crates/plist/src/bytes.rs | 82 ++++++++++++ 4 files changed, 521 insertions(+) create mode 100644 crates/plist/LICENSE-APACHE create mode 100644 crates/plist/LICENSE-MIT create mode 100644 crates/plist/src/binary.rs create mode 100644 crates/plist/src/bytes.rs diff --git a/crates/plist/LICENSE-APACHE b/crates/plist/LICENSE-APACHE new file mode 100644 index 000000000..f433b1a53 --- /dev/null +++ b/crates/plist/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/crates/plist/LICENSE-MIT b/crates/plist/LICENSE-MIT new file mode 100644 index 000000000..8e6399401 --- /dev/null +++ b/crates/plist/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs new file mode 100644 index 000000000..21ac84a86 --- /dev/null +++ b/crates/plist/src/binary.rs @@ -0,0 +1,241 @@ +use crate::{FormatError, bytes::Reader}; + +pub const MAX_DEPTH: usize = 256; +pub const MAX_NODES: usize = 2_000_000; +pub const MAX_EXPANDED_BYTES: usize = 64 << 20; + +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + Dict(Vec<(String, Value)>), + Array(Vec), + String(String), + Integer(i128), + Real(f64), + Bool(bool), + /// Seconds since 2001-01-01T00:00:00Z (binary), or the ISO text (XML). + Date(DateValue), + Data(Vec), + /// A keyed-archive object reference. + Uid(u64), + Null, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DateValue { + Seconds(f64), + Text(String), +} + +impl Value { + pub fn get(&self, key: &str) -> Option<&Value> { + match self { + Value::Dict(d) => d.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::String(s) => Some(s), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(a) => Some(a), + _ => None, + } + } + + pub fn as_uid(&self) -> Option { + match self { + Value::Uid(u) => Some(*u), + _ => None, + } + } + + pub fn as_int(&self) -> Option { + match self { + Value::Integer(i) => Some(*i), + _ => None, + } + } + +} +struct Bin<'a> { + r: Reader<'a>, + offsets: Vec, + ref_size: usize, + nodes: usize, +} + +/// Parse a `bplist00` binary property list. +pub fn parse_binary(data: &[u8]) -> Result { + if !data.starts_with(b"bplist") { + return Err(FormatError::Malformed("not a binary plist".into())); + } + let len = data.len(); + if len < 8 + 32 { + return Err(FormatError::Truncated("binary plist trailer".into())); + } + let r = Reader::new(data); + let t = len - 32; + let off_size = usize::from(r.u8(t + 6).unwrap_or(0)); + let ref_size = usize::from(r.u8(t + 7).unwrap_or(0)); + let num = r.u64_be(t + 8).unwrap_or(0); + let top = r.u64_be(t + 16).unwrap_or(0); + let table = r.u64_be(t + 24).unwrap_or(0); + if !(1..=8).contains(&off_size) || !(1..=8).contains(&ref_size) { + return Err(FormatError::Malformed("bad offset or reference size".into())); + } + let num = usize::try_from(num).map_err(|_| FormatError::Malformed("object count".into()))?; + let table = usize::try_from(table).map_err(|_| FormatError::Malformed("offset table".into()))?; + if num == 0 || num > len { + return Err(FormatError::Malformed(format!("{num} objects in a {len}-byte file"))); + } + let need = num.checked_mul(off_size).and_then(|n| n.checked_add(table)).ok_or_else(|| FormatError::Malformed("offset table".into()))?; + if need > t || table < 8 { + return Err(FormatError::Truncated("offset table runs past the trailer".into())); + } + let mut offsets = Vec::with_capacity(num); + for i in 0..num { + let o = read_be(&r, table + i * off_size, off_size).ok_or_else(|| FormatError::Truncated("offset table".into()))?; + let o = usize::try_from(o).map_err(|_| FormatError::Malformed("object offset".into()))?; + if o >= table { + return Err(FormatError::Malformed(format!("object {i} lies outside the object area"))); + } + offsets.push(o); + } + let top = usize::try_from(top).map_err(|_| FormatError::Malformed("top object".into()))?; + let mut b = Bin { r, offsets, ref_size, nodes: 0 }; + let mut stack = Vec::new(); + b.object(top, &mut stack) +} + +fn read_be(r: &Reader<'_>, off: usize, n: usize) -> Option { + let s = r.slice(off, n)?; + Some(s.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) +} + +impl Bin<'_> { + fn count(&self, at: usize, low: u8) -> Result<(usize, usize), FormatError> { + if low != 0xf { + return Ok((usize::from(low), at + 1)); + } + let m = self.r.u8(at + 1).ok_or_else(|| FormatError::Truncated("length".into()))?; + if m & 0xf0 != 0x10 { + return Err(FormatError::Malformed("bad extended length marker".into())); + } + let n = 1usize << (m & 0x0f).min(3); + let v = read_be(&self.r, at + 2, n).ok_or_else(|| FormatError::Truncated("length".into()))?; + let v = usize::try_from(v).map_err(|_| FormatError::Malformed("length".into()))?; + Ok((v, at + 2 + n)) + } + + fn reference(&self, at: usize, i: usize) -> Result { + let off = i.checked_mul(self.ref_size).and_then(|x| x.checked_add(at)).ok_or_else(|| FormatError::Malformed("reference".into()))?; + let v = read_be(&self.r, off, self.ref_size).ok_or_else(|| FormatError::Truncated("object reference".into()))?; + usize::try_from(v).map_err(|_| FormatError::Malformed("reference".into())) + } + + fn object(&mut self, idx: usize, stack: &mut Vec) -> Result { + self.nodes += 1; + if self.nodes > MAX_NODES { + return Err(FormatError::TooLarge(format!("more than {MAX_NODES} plist nodes"))); + } + if stack.len() >= MAX_DEPTH { + return Err(FormatError::Malformed("nesting too deep".into())); + } + if stack.contains(&idx) { + return Err(FormatError::Malformed(format!("object {idx} contains itself"))); + } + let at = *self.offsets.get(idx).ok_or_else(|| FormatError::Malformed(format!("reference to missing object {idx}")))?; + let m = self.r.u8(at).ok_or_else(|| FormatError::Truncated("object marker".into()))?; + let (hi, lo) = (m >> 4, m & 0x0f); + let v = match hi { + 0x0 => match lo { + 0x0 => Value::Null, + 0x8 => Value::Bool(false), + 0x9 => Value::Bool(true), + _ => Value::Null, + }, + 0x1 => { + let n = 1usize << lo.min(4); + let bytes = self.r.slice(at + 1, n).ok_or_else(|| FormatError::Truncated("integer".into()))?; + let v = match n { + 8 => i128::from(i64::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?)), + 16 => i128::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?), + _ => i128::from(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))), + }; + Value::Integer(v) + } + 0x2 => { + let v = match lo { + 2 => self.r.u32_be(at + 1).map(|b| f64::from(f32::from_bits(b))), + 3 => self.r.u64_be(at + 1).map(f64::from_bits), + _ => None, + }; + Value::Real(v.ok_or_else(|| FormatError::Truncated("real".into()))?) + } + 0x3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), + 0x4 => { + let (n, s) = self.count(at, lo)?; + Value::Data(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?.to_vec()) + } + 0x5 => { + let (n, s) = self.count(at, lo)?; + Value::String(String::from_utf8_lossy(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?).into_owned()) + } + 0x6 => { + let (n, s) = self.count(at, lo)?; + let bytes = self + .r + .slice(s, n.checked_mul(2).ok_or_else(|| FormatError::Malformed("string".into()))?) + .ok_or_else(|| FormatError::Truncated("string".into()))?; + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); + Value::String(String::from_utf16_lossy(&units)) + } + 0x8 => { + let n = usize::from(lo) + 1; + Value::Uid(read_be(&self.r, at + 1, n).ok_or_else(|| FormatError::Truncated("uid".into()))?) + } + 0xa | 0xc => { + let (n, s) = self.count(at, lo)?; + if n > self.offsets.len().saturating_mul(4).max(16) || s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { + return Err(FormatError::Malformed("array larger than the file".into())); + } + stack.push(idx); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let child = self.reference(s, i)?; + out.push(self.object(child, stack)?); + } + stack.pop(); + Value::Array(out) + } + 0xd => { + let (n, s) = self.count(at, lo)?; + if s.saturating_add(n.saturating_mul(self.ref_size).saturating_mul(2)) > self.r.len() { + return Err(FormatError::Malformed("dictionary larger than the file".into())); + } + stack.push(idx); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let k = self.reference(s, i)?; + let v = self.reference(s, i + n)?; + let key = match self.object(k, stack)? { + Value::String(s) => s, + other => format!("{:?}", other.to_json()), + }; + out.push((key, self.object(v, stack)?)); + } + stack.pop(); + Value::Dict(out) + } + _ => return Err(FormatError::Malformed(format!("unknown object marker {m:#04x}"))), + }; + Ok(v) + } +} + diff --git a/crates/plist/src/bytes.rs b/crates/plist/src/bytes.rs new file mode 100644 index 000000000..b9de989c3 --- /dev/null +++ b/crates/plist/src/bytes.rs @@ -0,0 +1,82 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + pub fn u64_le(&self, off: usize) -> Option { + self.arr(off).map(u64::from_le_bytes) + } + + pub fn u16_be(&self, off: usize) -> Option { + self.arr(off).map(u16::from_be_bytes) + } + + pub fn u32_be(&self, off: usize) -> Option { + self.arr(off).map(u32::from_be_bytes) + } + + pub fn u64_be(&self, off: usize) -> Option { + self.arr(off).map(u64::from_be_bytes) + } + + /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. + pub fn cstr(&self, off: usize, max: usize) -> Option { + let rest = self.data.get(off..)?; + let rest = rest.get(..max.min(rest.len()))?; + let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); + Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) + } + + /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. + pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { + let mut result = 0u64; + for i in 0..10usize { + let b = self.u8(off.checked_add(i)?)?; + result |= u64::from(b & 0x7f).checked_shl(7 * i as u32)?; + if b & 0x80 == 0 { + return Some((result, i + 1)); + } + } + None + } +}