imessage_database/util/plist.rs
1/*!
2 Contains logic and data structures used to parse and deserialize [`NSKeyedArchiver`](https://developer.apple.com/documentation/foundation/nskeyedarchiver) property list files into native Rust data structures.
3
4 The main entry point is [`parse_ns_keyed_archiver()`]. For normal property lists, use [`plist_as_dictionary()`].
5
6 ## Overview
7
8 The `NSKeyedArchiver` format is a property list-based serialization protocol used by Apple's Foundation framework.
9 It stores object graphs in a keyed format, allowing for more flexible deserialization and better handling of
10 object references compared to the older typedstream format.
11
12 ## Origin
13
14 Introduced in Mac OS X 10.2 as part of the Foundation framework, `NSKeyedArchiver` replaced `NSArchiver`
15 ([`typedstream`](crate::util::typedstream)) system as Apple's primary object serialization mechanism.
16
17 ## Features
18
19 - Pure Rust implementation for efficient and safe deserialization
20 - Support for both XML and binary property list formats
21 - No dependencies on Apple frameworks
22 - Robust error handling for malformed or invalid archives
23*/
24
25use plist::{Dictionary, Value};
26
27use crate::error::plist::PlistParseError;
28
29/// Serialize a message's `payload_data` BLOB in the [`NSKeyedArchiver`](https://developer.apple.com/documentation/foundation/nskeyedarchiver) format to a [`Dictionary`]
30/// that follows the references in the XML document's UID pointers. First, we find the root of the
31/// document, then walk the structure, promoting values to the places where their pointers are stored.
32///
33/// For example, a document with a root pointing to some `XML` like
34///
35/// ```xml
36/// <array>
37/// <dict>
38/// <key>link</key>
39/// <dict>
40/// <key>CF$UID</key>
41/// <integer>2</integer>
42/// </dict>
43/// </dict>
44/// <string>https://chrissardegna.com</string>
45/// </array>
46/// ```
47///
48/// Will serialize to a dictionary that looks like:
49///
50/// ```json
51/// {
52/// link: https://chrissardegna.com
53/// }
54/// ```
55///
56/// Some detail on this format is described [here](https://en.wikipedia.org/wiki/Property_list#Serializing_to_plist):
57///
58/// > Internally, `NSKeyedArchiver` somewhat recapitulates the binary plist format by
59/// > storing an object table array called `$objects` in the dictionary. Everything else,
60/// > including class information, is referenced by a UID pointer. A `$top` entry under
61/// > the dict points to the top-level object the programmer was meaning to encode.
62///
63/// # Data Source
64///
65/// The source plist data generally comes from [`Message::payload_data()`](crate::tables::messages::message::Message::payload_data).
66pub fn parse_ns_keyed_archiver(plist: &Value) -> Result<Value, PlistParseError> {
67 let body = plist_as_dictionary(plist)?;
68 let objects = extract_array_key(body, "$objects")?;
69
70 // Index of root object
71 let root = extract_uid_key(extract_dictionary(body, "$top")?, "root")?;
72
73 follow_uid(objects, root, None, None)
74}
75
76/// Recursively follows pointers in an `NSKeyedArchiver` format, promoting the values
77/// to the positions where the pointers live
78fn follow_uid<'a>(
79 objects: &'a [Value],
80 root: usize,
81 parent: Option<&str>,
82 item: Option<&'a Value>,
83) -> Result<Value, PlistParseError> {
84 let item = match item {
85 Some(item) => item,
86 None => objects
87 .get(root)
88 .ok_or(PlistParseError::NoValueAtIndex(root))?,
89 };
90
91 match item {
92 Value::Array(arr) => {
93 let mut array = vec![];
94 for item in arr {
95 if let Some(idx) = item.as_uid() {
96 array.push(follow_uid(objects, idx.get() as usize, parent, None)?);
97 }
98 }
99 Ok(plist::Value::Array(array))
100 }
101 Value::Dictionary(dict) => {
102 let mut dictionary = Dictionary::new();
103 // Handle where type is a Dictionary that points to another single value
104 if let Some(relative) = dict.get("NS.relative") {
105 if let Some(idx) = relative.as_uid() {
106 if let Some(p) = &parent {
107 dictionary.insert(
108 p.to_string(),
109 follow_uid(objects, idx.get() as usize, Some(p), None)?,
110 );
111 }
112 }
113 }
114 // Handle the NSDictionary and NSMutableDictionary types
115 else if dict.contains_key("NS.keys") && dict.contains_key("NS.objects") {
116 let keys = extract_array_key(dict, "NS.keys")?;
117 // These are the values in the objects list
118 let values = extract_array_key(dict, "NS.objects")?;
119 // Die here if the data is invalid
120 if keys.len() != values.len() {
121 return Err(PlistParseError::InvalidDictionarySize(
122 keys.len(),
123 values.len(),
124 ));
125 }
126
127 for idx in 0..keys.len() {
128 let key_index = extract_uid_idx(keys, idx)?;
129 let value_index = extract_uid_idx(values, idx)?;
130 let key = extract_string_idx(objects, key_index)?;
131
132 dictionary.insert(
133 String::from(key),
134 follow_uid(objects, value_index, Some(key), None)?,
135 );
136 }
137 }
138 // Handle a normal `{key: value}` style dictionary
139 else {
140 for (key, val) in dict {
141 // Skip class names; we don't need them
142 if key == "$class" {
143 continue;
144 }
145 // If the value is a pointer, follow it
146 if let Some(idx) = val.as_uid() {
147 dictionary.insert(
148 String::from(key),
149 follow_uid(objects, idx.get() as usize, Some(key), None)?,
150 );
151 }
152 // If the value is not a pointer, try and follow the data itself
153 else if let Some(p) = parent {
154 dictionary.insert(
155 String::from(p),
156 follow_uid(objects, root, Some(p), Some(val))?,
157 );
158 }
159 }
160 }
161 Ok(plist::Value::Dictionary(dictionary))
162 }
163 Value::Uid(uid) => follow_uid(objects, uid.get() as usize, None, None),
164 _ => Ok(item.to_owned()),
165 }
166}
167
168/// Extract a dictionary from table `plist` data.
169pub fn plist_as_dictionary(plist: &Value) -> Result<&Dictionary, PlistParseError> {
170 plist
171 .as_dictionary()
172 .ok_or_else(|| PlistParseError::InvalidType("body".to_string(), "dictionary".to_string()))
173}
174
175/// Extract a dictionary from a specific key in a collection
176pub fn extract_dictionary<'a>(
177 body: &'a Dictionary,
178 key: &str,
179) -> Result<&'a Dictionary, PlistParseError> {
180 body.get(key)
181 .ok_or_else(|| PlistParseError::MissingKey(key.to_string()))?
182 .as_dictionary()
183 .ok_or_else(|| PlistParseError::InvalidType(key.to_string(), "dictionary".to_string()))
184}
185
186/// Extract an array from a specific key in a collection
187pub fn extract_array_key<'a>(
188 body: &'a Dictionary,
189 key: &str,
190) -> Result<&'a Vec<Value>, PlistParseError> {
191 body.get(key)
192 .ok_or_else(|| PlistParseError::MissingKey(key.to_string()))?
193 .as_array()
194 .ok_or_else(|| PlistParseError::InvalidType(key.to_string(), "array".to_string()))
195}
196
197/// Extract a Uid from a specific key in a collection
198fn extract_uid_key(body: &Dictionary, key: &str) -> Result<usize, PlistParseError> {
199 Ok(body
200 .get(key)
201 .ok_or_else(|| PlistParseError::MissingKey(key.to_string()))?
202 .as_uid()
203 .ok_or_else(|| PlistParseError::InvalidType(key.to_string(), "uid".to_string()))?
204 .get() as usize)
205}
206
207/// Extract bytes from a specific key in a collection
208pub fn extract_bytes_key<'a>(body: &'a Dictionary, key: &str) -> Result<&'a [u8], PlistParseError> {
209 body.get(key)
210 .ok_or_else(|| PlistParseError::MissingKey(key.to_string()))?
211 .as_data()
212 .ok_or_else(|| PlistParseError::InvalidType(key.to_string(), "data".to_string()))
213}
214
215/// Extract an int from a specific key in a collection
216pub fn extract_int_key(body: &Dictionary, key: &str) -> Result<i64, PlistParseError> {
217 Ok(body
218 .get(key)
219 .ok_or_else(|| PlistParseError::MissingKey(key.to_string()))?
220 .as_real()
221 .ok_or_else(|| PlistParseError::InvalidType(key.to_string(), "int".to_string()))?
222 as i64)
223}
224
225/// Extract a Uid from a specific index in a collection
226fn extract_uid_idx(body: &[Value], idx: usize) -> Result<usize, PlistParseError> {
227 Ok(body
228 .get(idx)
229 .ok_or(PlistParseError::NoValueAtIndex(idx))?
230 .as_uid()
231 .ok_or_else(|| PlistParseError::InvalidTypeIndex(idx, "uid".to_string()))?
232 .get() as usize)
233}
234
235/// Extract a string from a specific index in a collection
236fn extract_string_idx(body: &[Value], idx: usize) -> Result<&str, PlistParseError> {
237 body.get(idx)
238 .ok_or(PlistParseError::NoValueAtIndex(idx))?
239 .as_string()
240 .ok_or_else(|| PlistParseError::InvalidTypeIndex(idx, "string".to_string()))
241}
242
243/// Extract a string from a key-value pair that looks like `{key: String("value")}`
244pub fn get_string_from_dict<'a>(payload: &'a Value, key: &'a str) -> Option<&'a str> {
245 payload
246 .as_dictionary()?
247 .get(key)?
248 .as_string()
249 .filter(|s| !s.is_empty())
250}
251
252/// Extract an inner dict from a key-value pair that looks like `{key: {key2: val}}`
253pub fn get_value_from_dict<'a>(payload: &'a Value, key: &'a str) -> Option<&'a Value> {
254 payload.as_dictionary()?.get(key)
255}
256
257/// Extract a bool from a key-value pair that looks like `{key: true}`
258pub fn get_bool_from_dict<'a>(payload: &'a Value, key: &'a str) -> Option<bool> {
259 payload.as_dictionary()?.get(key)?.as_boolean()
260}
261
262/// Extract a string from a key-value pair that looks like `{key: {key: String("value")}}`
263pub fn get_string_from_nested_dict<'a>(payload: &'a Value, key: &'a str) -> Option<&'a str> {
264 payload
265 .as_dictionary()?
266 .get(key)?
267 .as_dictionary()?
268 .get(key)?
269 .as_string()
270 .filter(|s| !s.is_empty())
271}
272
273/// Extract a float from a key-value pair that looks like `{key: {key: 1.2}}`
274pub fn get_float_from_nested_dict<'a>(payload: &'a Value, key: &'a str) -> Option<f64> {
275 payload
276 .as_dictionary()?
277 .get(key)?
278 .as_dictionary()?
279 .get(key)?
280 .as_real()
281}