onenote_parser 2.0.0

A parser for Microsoft OneNoteĀ® files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use crate::Reader;
use crate::errors::ErrorKind;
use crate::errors::Result;
use crate::onestore::desktop::ExGuid;
use crate::onestore::desktop::common::FileChunkReference;
use crate::onestore::desktop::file_node::FileNodeDataRef;
use crate::onestore::desktop::file_structure::FileNodeList;
use crate::onestore::desktop::parse::{Parse, ParseWithCount};
use crate::onestore::shared::compact_id::CompactId;
use crate::onestore::shared::file_blob::FileBlob;
use crate::onestore::shared::jcid::JcId;
use crate::onestore::shared::object_prop_set::ObjectPropSet;
use crate::shared::guid::Guid;
use crate::utils::Utf16ToString;
use onenote_parser_macros::Parse;
use std::fmt::Debug;

pub(crate) trait ParseWithRef<'a>
where
    Self: Sized,
{
    fn parse(reader: Reader, data_ref: &FileNodeDataRef) -> Result<Self>;
}

pub(crate) fn read_property_set(
    reader: Reader,
    property_set_ref: &FileNodeDataRef,
) -> Result<ObjectPropSet> {
    match property_set_ref {
        FileNodeDataRef::SingleElement(data_ref) => {
            let mut prop_set_reader = data_ref.resolve_to_reader(reader)?;
            let prop_set = ObjectPropSet::parse(&mut prop_set_reader)?;
            Ok(prop_set)
        }
        FileNodeDataRef::ElementList(_) => Err(ErrorKind::MalformedOneStoreData(
            "Expected a single element (reading PropertySet)".into(),
        )
        .into()),
        _ => Err(
            ErrorKind::MalformedOneStoreData("Expected a reference to a property set".into())
                .into(),
        ),
    }
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct PointerToListFND {
    pub(crate) list: FileNodeList,
}

impl<'a> ParseWithRef<'a> for PointerToListFND {
    fn parse(_reader: Reader, data_ref: &FileNodeDataRef) -> Result<Self> {
        match data_ref {
            FileNodeDataRef::ElementList(list) => Ok(Self { list: list.clone() }),
            other => Err(onestore_parse_error!("Expected a list, got {:?}", other).into()),
        }
    }
}

#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
pub(crate) struct RevisionRoleDeclarationFND {
    pub(crate) rid: ExGuid,
    /// "should be 0x01" per MS-ONESTORE 2.1.12.
    pub(crate) revision_role: u32,
}

#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
pub(crate) struct RevisionRoleAndContextDeclarationFND {
    /// Revision role & pointer to the revision
    pub(crate) base: RevisionRoleDeclarationFND,
    /// The revision context
    pub(crate) gctxid: ExGuid,
}

/// See [\[MS-ONESTORE\] 2.2.3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/af15f3eb-f2a8-4333-8d04-e05e55c2af07)
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct StringInStorageBuffer {
    cch: usize,
    pub(crate) data: String,
}

impl Parse for StringInStorageBuffer {
    fn parse(reader: Reader) -> Result<Self> {
        let characer_count = reader.get_u32()? as usize;
        let string_size = characer_count * 2; // 2 bytes per character
        let data = reader.read(string_size)?;
        let data = data.as_ref().utf16_to_string()?;
        Ok(Self {
            cch: characer_count,
            data,
        })
    }
}

#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
pub(crate) struct ObjectRefAndId<Id: Parse> {
    id: Id,
}

/// Points to encrypted data. See [\[MS-ONESTORE\] 2.5.19](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/542f09eb-9db8-4b6a-86e5-2d9a930b41c0).
#[derive(Debug, Clone, Parse)]
pub(crate) struct ObjectDataEncryptionKeyV2FNDX {}

#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
struct ObjectInfoDependencyOverride<RefSize: Parse> {
    oid: CompactId,
    c_ref: RefSize,
}

/// See [\[MS-ONESTORE\] 2.6.10](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/af821117-689f-42cf-8136-c72c1e238f1e)
#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
struct ObjectInfoDependencyOverrideData {
    c8_override_count: u32,
    c32_override_count: u32,
    crc: u32,
    #[parse_additional_args(c8_override_count as usize)]
    overrides1: Vec<ObjectInfoDependencyOverride<u8>>,
    #[parse_additional_args(c32_override_count as usize)]
    overrides2: Vec<ObjectInfoDependencyOverride<u32>>,
}

/// See [\[MS-ONESTORE\] 2.5.20](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/80125c83-199e-43b9-9a13-4085752eddac)
/// Specifies reference counts for objects.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ObjectInfoDependencyOverridesFND {
    data: ObjectInfoDependencyOverrideData,
}

impl<'a> ParseWithRef<'a> for ObjectInfoDependencyOverridesFND {
    fn parse(reader: Reader, obj_ref: &FileNodeDataRef) -> Result<Self> {
        if let FileNodeDataRef::SingleElement(obj_ref) = obj_ref {
            if !obj_ref.is_fcr_nil() {
                let data = ObjectInfoDependencyOverrideData::parse(
                    &mut obj_ref.resolve_to_reader(reader)?,
                )?;
                Ok(Self { data })
            } else {
                Ok(Self {
                    data: ObjectInfoDependencyOverrideData::parse(reader)?,
                })
            }
        } else {
            Err(ErrorKind::MalformedOneStoreData(
                "Missing ref to data (parsing ObjectInfoDependencyOverridesFND)".into(),
            )
            .into())
        }
    }
}

/// Terminates ObjectGroupEndFND, DataSignatureGroupDefinitionFND, and RevisionManifestEndFND.
/// See [\[MS-ONESTORE\] 2.5.33](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/0fa4c886-011a-4c19-9651-9a69e43a19c6)
#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
pub(crate) struct DataSignatureGroupDefinitionFND {
    data_signature_group: ExGuid,
}

/// See [\[MS-ONESTORE\] 2.5.21](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/2701cc42-3601-49f9-a3ba-7c40cd8a2be9)
pub(crate) type FileDataStoreListReferenceFND = PointerToListFND;

/// See [\[MS-ONESTORE\] 2.6.13](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/8806fd18-6735-4874-b111-227b83eaac26)
#[derive(Debug, Parse, Clone)]
#[validate(guid_header == Guid::from_str("{BDE316E7-2665-4511-A4C4-8D4D0B7A9EAC}").unwrap())]
#[validate(guid_footer == Guid::from_str("{71FBA722-0F79-4A0B-BB13-899256426B24}").unwrap())]
#[allow(unused)]
pub(crate) struct FileDataStoreObject {
    guid_header: Guid,
    /// Length of the file data (without padding)
    cb_length: u64,
    _unused: u32,
    _reserved: u64,
    #[parse_additional_args(cb_length as usize)]
    #[pad_to_alignment(8)]
    pub(crate) file_data: FileData,
    guid_footer: Guid,
}

#[derive(Clone)]
pub(crate) struct FileData(pub(crate) FileBlob);

impl Debug for FileData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "FileData(size={:} KiB)", self.0.size() / 1024)
    }
}

impl ParseWithCount for FileData {
    fn parse(reader: Reader, size: usize) -> Result<Self> {
        // Capture a refcount-shared reference into the underlying source
        // instead of copying the bytes out. For a memory-mapped notebook
        // this means attachments don't duplicate the file's contents in
        // process memory.
        let source = reader.source();
        let offset = reader.position();
        reader.advance(size)?;
        Ok(FileData(FileBlob::from_source(source, offset, size as u64)))
    }
}

/// See [\[MS-ONESTORE\] 2.5.22](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/6f6d5729-ad03-420f-b8fa-7683751218b3)
#[derive(Debug, Clone)]
pub(crate) struct FileDataStoreObjectReferenceFND {
    pub(crate) target: FileDataStoreObject,
    pub(crate) guid: Guid,
}

impl<'a> ParseWithRef<'a> for FileDataStoreObjectReferenceFND {
    fn parse(reader: Reader, data_ref: &FileNodeDataRef) -> Result<Self> {
        let guid = Guid::parse(reader)?;
        if let FileNodeDataRef::SingleElement(data_ref) = data_ref {
            let mut reader = data_ref.resolve_to_reader(reader)?;
            Ok(Self {
                target: FileDataStoreObject::parse(&mut reader)?,
                guid,
            })
        } else {
            Err(onestore_parse_error!(
                "FileDataStoreObjectReferenceFND should point to a single file node object"
            )
            .into())
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct AttachmentInfo {
    pub(crate) extension: String,
    pub(crate) data_ref: String,
}

impl AttachmentInfo {
    pub(crate) fn load_data<F>(&self, file_blob_by_id: F) -> Result<FileBlob>
    where
        F: FnOnce(&str) -> Result<FileBlob>,
    {
        // See https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/da2bbc7d-0529-4bf4-a843-6f3f55c87e8f
        if self.data_ref.starts_with("<ifndf>") {
            file_blob_by_id(&self.data_ref["<ifndf>".len()..])
        } else if self.data_ref.starts_with("<file>") {
            // An external file reference
            // TODO: Find a test .one file that uses this and implement it.
            Err(parser_error!(
                ResolutionFailed,
                "Not supported: Loading an attachment from a file: {} (ext: {})",
                self.data_ref,
                self.extension,
            )
            .into())
        } else if self.data_ref.starts_with("<invfdo>") {
            // Preserve the invalid state rather than presenting it as a valid
            // zero-byte payload.
            log::warn!(
                "Attempted to load an invalid {} file. Preserving it as unavailable.",
                self.extension
            );

            Ok(FileBlob::invalid())
        } else {
            Err(parser_error!(
                ResolutionFailed,
                "Failed to resolve file reference: {} (ext: {})",
                self.data_ref,
                self.extension
            )
            .into())
        }
    }
}

/// Common functionality available for most nodes that declare objects
pub(crate) trait ObjectDeclarationNode {
    fn id(&self) -> JcId;
    fn compact_id(&self) -> CompactId;
    fn props(&self) -> Option<&ObjectPropSet>;
    fn get_attachment_info(&self) -> Option<AttachmentInfo> {
        None
    }
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
struct ObjectDeclaration2Body {
    /// The object ID
    oid: CompactId,
    /// Specifies the object type
    jcid: JcId,
    f_has_oid_references: bool,
    f_has_osid_references: bool,
}

impl Parse for ObjectDeclaration2Body {
    fn parse(reader: Reader) -> Result<Self> {
        let oid = CompactId::parse(reader)?;
        let jcid = JcId::parse(reader)?;
        let metadata = reader.get_u8()?;

        Ok(Self {
            oid,
            jcid,
            f_has_oid_references: metadata & 0x1 > 0,
            f_has_osid_references: metadata & 0x2 > 0,
        })
    }
}

/// See [\[MS-ONESTORE\] 2.5.25](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/a6ea1707-b205-4cd8-be40-d4c3462b226b)
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ObjectDeclaration2RefCount<RefSize: Parse> {
    props: ObjectPropSet,
    body: ObjectDeclaration2Body,
    c_ref: RefSize,
}

impl<RefSize: Parse> ObjectDeclarationNode for ObjectDeclaration2RefCount<RefSize> {
    fn id(&self) -> JcId {
        self.body.jcid
    }

    fn compact_id(&self) -> CompactId {
        self.body.oid
    }

    fn props(&self) -> Option<&ObjectPropSet> {
        Some(&self.props)
    }
}

impl<'a, RefSize: Parse> ParseWithRef<'a> for ObjectDeclaration2RefCount<RefSize> {
    fn parse(reader: Reader, property_set_ref: &FileNodeDataRef) -> Result<Self> {
        Ok(Self {
            props: read_property_set(reader, property_set_ref)?,
            body: ObjectDeclaration2Body::parse(reader)?,
            c_ref: RefSize::parse(reader)?,
        })
    }
}

#[allow(unused)]
#[derive(Debug, Clone)]
pub(crate) struct ObjectGroupListReferenceFND {
    pub(crate) list: FileNodeList,
    pub(crate) id: ExGuid,
}

impl<'a> ParseWithRef<'a> for ObjectGroupListReferenceFND {
    fn parse(reader: Reader, data_ref: &FileNodeDataRef) -> Result<Self> {
        match data_ref {
            FileNodeDataRef::ElementList(list) => Ok(Self {
                list: list.clone(),
                id: ExGuid::parse(reader)?,
            }),
            other => Err(parser_error!(
                MalformedOneStoreData,
                "Expected a list (parsing ObjectGroupListReferenceFND), got {:?}",
                other
            )
            .into()),
        }
    }
}

/// See [MS-ONESTORE 2.5.32](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-onestore/2b639cb8-1185-4f63-82cb-0f3e4106611e)
#[derive(Debug, Clone, Parse)]
#[allow(dead_code)]
pub(crate) struct ObjectGroupStartFND {
    /// The ID of the object group
    pub(crate) oid: ExGuid,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct HashedChunkDescriptor<Hash: Parse> {
    prop_set: ObjectPropSet,
    hash: Hash,
}

impl<'a, Hash: Parse> ParseWithRef<'a> for HashedChunkDescriptor<Hash> {
    fn parse(reader: Reader, prop_ref: &FileNodeDataRef) -> Result<Self> {
        let prop_set = read_property_set(reader, prop_ref)?;
        Ok(Self {
            prop_set,
            hash: Hash::parse(reader)?,
        })
    }
}

pub(crate) type HashedChunkDescriptor2FND = HashedChunkDescriptor<u128>;

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ReadOnlyObjectDeclaration2RefCount<Base> {
    pub(crate) base: Base,
    md5_hash: u128,
}

impl<'a, Base: ParseWithRef<'a>> ParseWithRef<'a> for ReadOnlyObjectDeclaration2RefCount<Base> {
    fn parse(reader: Reader, prop_ref: &FileNodeDataRef) -> Result<Self> {
        Ok(Self {
            base: Base::parse(reader, prop_ref)?,
            md5_hash: u128::parse(reader)?,
        })
    }
}

impl<Base: ObjectDeclarationNode> ObjectDeclarationNode
    for ReadOnlyObjectDeclaration2RefCount<Base>
{
    fn id(&self) -> JcId {
        self.base.id()
    }

    fn compact_id(&self) -> CompactId {
        self.base.compact_id()
    }

    fn props(&self) -> Option<&ObjectPropSet> {
        self.base.props()
    }
}

#[derive(Debug, Clone)]
pub(crate) struct UnknownNode {}

impl ParseWithCount for UnknownNode {
    fn parse(reader: Reader, size: usize) -> Result<Self> {
        reader.advance(size)?;
        Ok(UnknownNode {})
    }
}