1use std::io::Cursor;
9
10use anyhow::{Result, anyhow, bail};
11use plist::Value;
12
13#[derive(Debug, Clone, PartialEq)]
14pub enum Ka {
15 Null,
16 Bool(bool),
17 Int(i64),
18 UInt(u64),
19 Real(f64),
20 Str(String),
21 Data(Vec<u8>),
22 Array(Vec<Ka>),
23 Dict(Vec<(Ka, Ka)>),
24 Obj {
25 class: String,
26 fields: Vec<(String, Ka)>,
27 },
28}
29
30impl Ka {
31 pub fn as_str(&self) -> Option<&str> {
32 match self {
33 Ka::Str(s) => Some(s),
34 _ => None,
35 }
36 }
37
38 pub fn as_bool(&self) -> Option<bool> {
39 match self {
40 Ka::Bool(b) => Some(*b),
41 Ka::Int(i) => Some(*i != 0),
42 Ka::UInt(u) => Some(*u != 0),
43 _ => None,
44 }
45 }
46
47 pub fn as_u64(&self) -> Option<u64> {
48 match self {
49 Ka::UInt(u) => Some(*u),
50 Ka::Int(i) => Some(*i as u64),
51 Ka::Bool(b) => Some(*b as u64),
52 _ => None,
53 }
54 }
55
56 pub fn as_i64(&self) -> Option<i64> {
57 match self {
58 Ka::Int(i) => Some(*i),
59 Ka::UInt(u) => i64::try_from(*u).ok(),
60 Ka::Bool(b) => Some(*b as i64),
61 _ => None,
62 }
63 }
64
65 pub fn as_f64(&self) -> Option<f64> {
66 match self {
67 Ka::Real(r) => Some(*r),
68 Ka::Int(i) => Some(*i as f64),
69 Ka::UInt(u) => Some(*u as f64),
70 _ => None,
71 }
72 }
73
74 pub fn as_array(&self) -> Option<&[Ka]> {
75 match self {
76 Ka::Array(a) => Some(a),
77 _ => None,
78 }
79 }
80
81 pub fn class(&self) -> Option<&str> {
82 match self {
83 Ka::Obj { class, .. } => Some(class),
84 _ => None,
85 }
86 }
87
88 pub fn get(&self, name: &str) -> Option<&Ka> {
91 match self {
92 Ka::Obj { fields, .. } => fields.iter().find(|(k, _)| k == name).map(|(_, v)| v),
93 Ka::Dict(entries) => entries
94 .iter()
95 .find(|(k, _)| k.as_str() == Some(name))
96 .map(|(_, v)| v),
97 _ => None,
98 }
99 }
100
101 pub fn text(&self) -> Option<String> {
103 match self {
104 Ka::Str(s) => Some(s.clone()),
105 Ka::Obj { class, .. } if class.contains("AttributedString") => {
106 self.get("NSString").and_then(|s| s.text())
107 }
108 _ => None,
109 }
110 }
111
112 pub fn to_json(&self) -> serde_json::Value {
114 use serde_json::{Value as J, json};
115 match self {
116 Ka::Null => J::Null,
117 Ka::Bool(b) => json!(b),
118 Ka::Int(i) => json!(i),
119 Ka::UInt(u) => json!(u),
120 Ka::Real(r) => serde_json::Number::from_f64(*r).map(J::Number).unwrap_or(J::Null),
121 Ka::Str(s) => json!(s),
122 Ka::Data(d) => json!({ "$data": d.len() }),
123 Ka::Array(a) => J::Array(a.iter().map(|x| x.to_json()).collect()),
124 Ka::Dict(entries) => {
125 let mut m = serde_json::Map::new();
126 for (k, v) in entries {
127 let key = match k {
128 Ka::Str(s) => s.clone(),
129 Ka::Int(i) => i.to_string(),
130 Ka::UInt(u) => u.to_string(),
131 other => other.to_json().to_string(),
132 };
133 m.insert(key, v.to_json());
134 }
135 J::Object(m)
136 }
137 Ka::Obj { class, fields } => {
138 let mut m = serde_json::Map::new();
139 m.insert("$class".into(), json!(class));
140 for (k, v) in fields {
141 m.insert(k.clone(), v.to_json());
142 }
143 J::Object(m)
144 }
145 }
146 }
147}
148
149pub const DEFAULT_BUDGET: usize = 400_000;
153
154pub fn decode(bytes: &[u8]) -> Result<Ka> {
156 decode_with_budget(bytes, DEFAULT_BUDGET).map(|(root, _)| root)
157}
158
159pub fn decode_with_budget(bytes: &[u8], budget: usize) -> Result<(Ka, usize)> {
162 let top = Value::from_reader(Cursor::new(bytes)).map_err(|e| anyhow!("not a plist: {e}"))?;
163 let dict = top
164 .as_dictionary()
165 .ok_or_else(|| anyhow!("archive is not a dictionary"))?;
166 let objects = dict
167 .get("$objects")
168 .and_then(|o| o.as_array())
169 .ok_or_else(|| anyhow!("archive has no $objects"))?;
170 let root = dict
171 .get("$top")
172 .and_then(|t| t.as_dictionary())
173 .and_then(|t| t.get("root").or_else(|| t.values().next()))
174 .ok_or_else(|| anyhow!("archive has no $top root"))?;
175 let mut r = Resolver {
176 objects,
177 active: vec![false; objects.len()],
178 depth: 0,
179 left: budget,
180 };
181 let root = r.value(root)?;
182 Ok((root, budget - r.left))
183}
184
185pub fn looks_like_archive(bytes: &[u8]) -> bool {
187 bytes.starts_with(b"bplist00")
188}
189
190struct Resolver<'a> {
191 objects: &'a [Value],
192 active: Vec<bool>,
194 depth: usize,
195 left: usize,
197}
198
199const MAX_DEPTH: usize = 200;
200
201impl Resolver<'_> {
202 fn value(&mut self, v: &Value) -> Result<Ka> {
203 Ok(match v {
204 Value::Uid(u) => return self.object(u.get() as usize),
205 Value::Boolean(b) => Ka::Bool(*b),
206 Value::Integer(i) => match i.as_signed() {
207 Some(s) => Ka::Int(s),
208 None => Ka::UInt(i.as_unsigned().unwrap_or(0)),
209 },
210 Value::Real(r) => Ka::Real(*r),
211 Value::String(s) => Ka::Str(s.clone()),
212 Value::Data(d) => Ka::Data(d.clone()),
213 Value::Array(a) => Ka::Array(a.iter().map(|x| self.value(x)).collect::<Result<_>>()?),
214 Value::Dictionary(d) => Ka::Dict(
215 d.iter()
216 .map(|(k, x)| Ok((Ka::Str(k.clone()), self.value(x)?)))
217 .collect::<Result<_>>()?,
218 ),
219 Value::Date(d) => Ka::Str(d.to_xml_format()),
220 _ => Ka::Null,
221 })
222 }
223
224 fn object(&mut self, index: usize) -> Result<Ka> {
225 if index == 0 {
226 return Ok(Ka::Null);
227 }
228 let Some(obj) = self.objects.get(index) else {
229 bail!("archive points at missing object {index}");
230 };
231 let Some(dict) = obj.as_dictionary().filter(|d| d.contains_key("$class")) else {
232 return self.value(obj);
233 };
234 if self.active[index] || self.depth >= MAX_DEPTH {
235 return Ok(Ka::Null);
236 }
237 if self.left == 0 {
238 bail!("archive unfolds into too many objects");
239 }
240 self.left -= 1;
241 self.active[index] = true;
242 self.depth += 1;
243 let out = self.instance(dict);
244 self.depth -= 1;
245 self.active[index] = false;
246 out
247 }
248
249 fn class_name(&self, dict: &plist::Dictionary) -> String {
250 dict.get("$class")
251 .and_then(|c| match c {
252 Value::Uid(u) => self.objects.get(u.get() as usize),
253 _ => None,
254 })
255 .and_then(|c| c.as_dictionary())
256 .and_then(|c| c.get("$classname"))
257 .and_then(|n| n.as_string())
258 .unwrap_or("")
259 .to_string()
260 }
261
262 fn list(&mut self, dict: &plist::Dictionary, key: &str) -> Result<Vec<Ka>> {
263 match dict.get(key).and_then(|v| v.as_array()) {
264 Some(items) => items.iter().map(|x| self.value(x)).collect(),
265 None => Ok(Vec::new()),
266 }
267 }
268
269 fn instance(&mut self, dict: &plist::Dictionary) -> Result<Ka> {
270 let class = self.class_name(dict);
271 match class.as_str() {
272 "NSArray" | "NSMutableArray" | "NSSet" | "NSMutableSet" | "NSOrderedSet"
273 | "NSMutableOrderedSet" => Ok(Ka::Array(self.list(dict, "NS.objects")?)),
274 "NSDictionary" | "NSMutableDictionary" => {
275 let keys = self.list(dict, "NS.keys")?;
276 let values = self.list(dict, "NS.objects")?;
277 Ok(Ka::Dict(keys.into_iter().zip(values).collect()))
278 }
279 "NSString" | "NSMutableString" => {
280 if let Some(s) = dict.get("NS.string").and_then(|s| s.as_string()) {
281 Ok(Ka::Str(s.to_string()))
282 } else if let Some(b) = dict.get("NS.bytes").and_then(|b| b.as_data()) {
283 Ok(Ka::Str(String::from_utf8_lossy(b).into_owned()))
284 } else {
285 Ok(Ka::Str(String::new()))
286 }
287 }
288 "NSData" | "NSMutableData" => Ok(Ka::Data(
289 dict.get("NS.data")
290 .and_then(|d| d.as_data())
291 .map(|d| d.to_vec())
292 .unwrap_or_default(),
293 )),
294 _ => {
295 let mut fields = Vec::with_capacity(dict.len());
296 for (k, v) in dict.iter() {
297 if k == "$class" {
298 continue;
299 }
300 fields.push((k.clone(), self.value(v)?));
301 }
302 Ok(Ka::Obj { class, fields })
303 }
304 }
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311 use plist::{Dictionary, Uid};
312
313 fn archive(objects: Vec<Value>) -> Vec<u8> {
314 let mut top = Dictionary::new();
315 top.insert("root".into(), Value::Uid(Uid::new(1)));
316 let mut d = Dictionary::new();
317 d.insert("$archiver".into(), "NSKeyedArchiver".into());
318 d.insert("$version".into(), Value::Integer(100000.into()));
319 d.insert("$top".into(), Value::Dictionary(top));
320 d.insert("$objects".into(), Value::Array(objects));
321 let mut out = Vec::new();
322 Value::Dictionary(d).to_writer_binary(&mut out).unwrap();
323 out
324 }
325
326 fn class(name: &str) -> Value {
327 let mut d = Dictionary::new();
328 d.insert("$classname".into(), name.into());
329 Value::Dictionary(d)
330 }
331
332 #[test]
333 fn decodes_dictionary_with_numeric_keys_and_custom_objects() {
334 let mut dict = Dictionary::new();
336 dict.insert("$class".into(), Value::Uid(Uid::new(6)));
337 dict.insert(
338 "NS.keys".into(),
339 Value::Array(vec![Value::Uid(Uid::new(2)), Value::Uid(Uid::new(3))]),
340 );
341 dict.insert(
342 "NS.objects".into(),
343 Value::Array(vec![Value::Uid(Uid::new(4)), Value::Uid(Uid::new(5))]),
344 );
345 let mut rect = Dictionary::new();
346 rect.insert("$class".into(), Value::Uid(Uid::new(7)));
347 rect.insert("NS.rectval".into(), "{{0, 0}, {430, 932}}".into());
348 let bytes = archive(vec![
349 "$null".into(),
350 Value::Dictionary(dict),
351 Value::Integer(3.into()),
352 Value::Integer(21.into()),
353 "설정".into(),
354 Value::Dictionary(rect),
355 class("NSDictionary"),
356 class("NSValue"),
357 ]);
358 let root = decode(&bytes).unwrap();
359 let Ka::Dict(entries) = &root else {
360 panic!("not a dict: {root:?}")
361 };
362 assert_eq!(entries[0].0, Ka::Int(3));
363 assert_eq!(entries[0].1.as_str(), Some("설정"));
364 assert_eq!(entries[1].1.class(), Some("NSValue"));
365 assert_eq!(
366 entries[1].1.get("NS.rectval").and_then(|v| v.as_str()),
367 Some("{{0, 0}, {430, 932}}")
368 );
369 }
370
371 #[test]
372 fn null_reference_and_cycles_do_not_loop() {
373 let mut thing = Dictionary::new();
375 thing.insert("$class".into(), Value::Uid(Uid::new(2)));
376 thing.insert("next".into(), Value::Uid(Uid::new(1)));
377 thing.insert("nothing".into(), Value::Uid(Uid::new(0)));
378 let bytes = archive(vec!["$null".into(), Value::Dictionary(thing), class("Thing")]);
379 let root = decode(&bytes).unwrap();
380 assert_eq!(root.class(), Some("Thing"));
381 assert_eq!(root.get("next"), Some(&Ka::Null));
382 assert_eq!(root.get("nothing"), Some(&Ka::Null));
383 }
384
385 #[test]
386 fn densely_linked_objects_hit_the_budget_instead_of_running_forever() {
387 let n = 12;
390 let mut objects: Vec<Value> = vec!["$null".into()];
391 for _ in 0..n {
392 let mut d = Dictionary::new();
393 d.insert("$class".into(), Value::Uid(Uid::new(n as u64 + 1)));
394 d.insert(
395 "others".into(),
396 Value::Array((1..=n as u64).map(|i| Value::Uid(Uid::new(i))).collect()),
397 );
398 objects.push(Value::Dictionary(d));
399 }
400 objects.push(class("Thing"));
401 let bytes = archive(objects);
402 let started = std::time::Instant::now();
403 let err = decode_with_budget(&bytes, 50_000).unwrap_err();
404 assert!(err.to_string().contains("too many objects"));
405 assert!(started.elapsed() < std::time::Duration::from_secs(5));
406 }
407
408 #[test]
409 fn rejects_non_archives() {
410 assert!(decode(b"hello").is_err());
411 }
412}