1
//! New netdoc parsing arrangements, with `derive`
2
//!
3
//! # Parsing principles
4
//!
5
//! A parseable network document is a type implementing [`NetdocParseable`].
6
//! usually via the
7
//! [`NetdocParseable` derive=deftly macro`](crate::derive_deftly_template_NetdocParseable).
8
//!
9
//! A document type is responsible for recognising its own heading item.
10
//! Its parser will also be told other of structural items that it should not consume.
11
//! The structural lines can then be used to pass control to the appropriate parser.
12
//!
13
//! A "structural item" is a netdoc item that is defines the structure of the document.
14
//! This includes the intro items for whole documents,
15
//! the items that introduce document sections
16
//! (which we model by treating the section as a sub-document)
17
//! and signature items (which introduce the signatures at the end of the document,
18
//! and after which no non-signature items may appear).
19
//!
20
//! # Ordering
21
//!
22
//! We don't always parse things into a sorted order.
23
//! Sorting will be done when assembling documents, before outputting.
24
//!
25
//! # Types, and signature handling
26
//!
27
//! Most top-level network documents are signed somehow.
28
//! In this case there are three types:
29
//!
30
//!   * **`FooUnverified`**: a signed `Foo`, with its signatures, not yet verified.
31
//!     Implements [`NetdocParseableUnverified`],
32
//!     typically by invoking the
33
//!     [`NetdocUParseablenverified` derive macro](crate::derive_deftly_template_NetdocParseableUnverified)
34
//!     on `Foo`.
35
//!
36
//!     Type-specific methods are provided for verification,
37
//!     to obtain a `Foo`.
38
//!
39
//!   * **`Foo`**: the body data for the document.
40
//!     This doesn't contain any signatures.
41
//!     Having one of these to play with means signatures have already been validated.
42
//!     Can be parsed as part of the signed document,
43
//!     via the `NetdocParseable` implementation on `FooUnverified`,
44
//!     and then obtained via `.verify_...` method(s) on `FooUnverified`,
45
//!
46
//!   * **`FooSignatures`**: the signatures for a `Foo`.
47
//!     Implements `NetdocParseableSignatures`, via
48
//!     [derive](crate::derive_deftly_template_NetdocParseableSignatures),
49
//!     with `#[deftly(netdoc(signatures))]`.
50
//!
51
//! # Relationship to tor_netdoc::parse
52
//!
53
//! This is a completely new parsing approach, based on different principles.
54
//! The key principle is the recognition of "structural keywords",
55
//! recursively within a parsing stack, via the p`NetdocParseable`] trait.
56
//!
57
//! This allows the parser to be derived.  We have type-driven parsing
58
//! of whole Documents, Items, and their Arguments and Objects,
59
//! including of their multiplicity.
60
//!
61
//! The different keyword handling means we can't use most of the existing lexer,
62
//! and need new item parsing API:
63
//!
64
//!  * [`NetdocParseable`] trait.
65
//!  * [`KeywordRef`] type.
66
//!  * [`ItemStream`], [`UnparsedItem`], [`ArgumentStream`], [`UnparsedObject`].
67
//!
68
//! The different error handling means we have our own error types.
69
//! (The crate's existing parse errors have information that we don't track,
70
//! and is also a portmanteau error for parsing, writing, and other functions.)
71
//!
72
//! Document signing is handled in a more abstract way.
73
//!
74
//! Some old netdoc constructs are not supported.
75
//! For example, the obsolete `opt` prefix on safe-to-ignore Items.
76
//! The parser may make different decisions about netdocs with anomalous item ordering.
77

            
78
#[doc(hidden)]
79
#[macro_use]
80
pub mod internal_prelude;
81

            
82
#[macro_use]
83
mod structural;
84

            
85
#[macro_use]
86
mod derive;
87

            
88
mod error;
89
mod impls;
90
pub mod keyword;
91
mod lex;
92
mod lines;
93
pub mod multiplicity;
94
mod signatures;
95
mod traits;
96

            
97
use internal_prelude::*;
98

            
99
pub use error::{ArgumentError, ErrorProblem, ParseError, UnexpectedArgument, VerifyFailed};
100
pub use impls::times::NdaSystemTimeDeprecatedSyntax;
101
pub use keyword::KeywordRef;
102
pub use lex::{ArgumentStream, ItemStream, NoFurtherArguments, UnparsedItem, UnparsedObject};
103
pub use lines::{Lines, Peeked, StrExt};
104
pub use signatures::{
105
    HasUnverifiedParsedBody, NetdocParseableSignatures, NetdocParseableUnverified,
106
    SignatureHashInputs, SignatureHashesAccumulator, SignatureItemParseable, SignaturesData,
107
    sig_hashes,
108
};
109
#[allow(deprecated)]
110
#[deprecated]
111
pub use signatures::{check_validity_time, check_validity_time_tolerance};
112
pub use structural::{StopAt, StopPredicate};
113
pub use traits::{
114
    IsStructural, ItemArgumentParseable, ItemObjectParseable, ItemValueParseable, NetdocParseable,
115
    NetdocParseableFields,
116
};
117

            
118
#[doc(hidden)]
119
pub use derive::netdoc_parseable_derive_debug;
120

            
121
pub(crate) use internal_prelude::EP;
122

            
123
//---------- input ----------
124

            
125
/// Options for parsing
126
///
127
/// Specific document and type parsing methods may use these parameters
128
/// to control their parsing behaviour at run-time.
129
#[derive(educe::Educe, Debug, Clone)]
130
#[allow(clippy::manual_non_exhaustive)]
131
#[educe(Default)]
132
pub struct ParseOptions {
133
    /// Retain unknown values?
134
    ///
135
    /// Some field types, especially for flags fields, have the capability to retain
136
    /// unknown flags.  But, whereas known flags can be represented as single bits,
137
    /// representing unknown flags involves allocating and copying strings.
138
    /// Unless the document is to be reproduced, this is a waste of effort.
139
    ///
140
    /// Each document field type affected by this option should store the unknowns
141
    /// as `Unknown<HashSet<String>>` or similar.
142
    ///
143
    /// This feature should only be used where performance is important.
144
    /// For example, it is useful for types that appear in md consensus routerdescs,
145
    /// but less useful for types that appear only in a netstatus preamble.
146
    ///
147
    /// This is currently used for router flags.
148
    #[educe(Default(expression = Unknown::new_discard()))]
149
    pub retain_unknown_values: Unknown<()>,
150

            
151
    // Like `#[non_exhaustive]`, but doesn't prevent use of struct display syntax with `..`
152
    #[doc(hidden)]
153
    _private_non_exhaustive: (),
154
}
155

            
156
/// Input to a network document top-level parsing operation
157
#[derive(Debug, Clone, amplify::Getters, Deftly)]
158
#[derive_deftly(ParseInput)]
159
pub struct ParseInput<'s> {
160
    /// The actual document text
161
    #[getter(skip)]
162
    input: Cow<'s, str>,
163

            
164
    /// Filename (for error reporting); if not from a file, `<...>`
165
    #[getter(skip)]
166
    file: Cow<'s, str>,
167

            
168
    /// Parsing options
169
    #[deftly(parse_input(default))]
170
    #[getter(as_ref, as_mut)]
171
    options: ParseOptions,
172
}
173

            
174
define_derive_deftly! {
175
    /// Derives for [`ParseInput`]
176
    ///
177
    /// Expands to the whole impl block, for convenience
178
    ParseInput:
179

            
180
    ${defcond F_DEF fmeta(parse_input(default))}
181
    ${defcond F_STR not(fmeta(parse_input(default)))}
182

            
183
    impl<'s> ParseInput<'s> {
184
    /// Prepare to parse an input string
185
        ///
186
        /// `file` is used only for error reporting, and is often used within
187
        /// `{file}:{line}` or `{file}{line}.{column}` in error messages.
188
        /// If the input didn't come from a file, use a terse human-readable description,
189
        /// conventionally formatted as `<...>`.
190
51016
        pub fn new( $(
191
51016
            ${when not(F_DEF)}
192
51016
            $fname: impl Into<$ftype>,
193
51016
        ) ) -> Self {
194
            ParseInput { $(
195
                $fname: ${select1
196
                          F_STR { $fname.into() }
197
                          F_DEF { Default::default() }
198
                },
199
            ) }
200
        }
201

            
202
      $(
203
        ${when not(F_DEF)}
204

            
205
        ${fattrs doc}
206
2
        pub fn $fname(&self) -> &str {
207
            &self.$fname
208
        }
209
      )
210

            
211
        /// Enable retention of unknown values during parsing
212
        ///
213
        /// Convenience method to set
214
        /// [`.options_mut().retain_unknown_values`](ParseOptions::retain_unknown_values)
215
        /// to [`Unknown::Retained`].
216
        #[cfg(feature = "retain-unknown")]
217
        #[must_use = "retain_unknown_values returns a new ParseInput, which should then be used"]
218
568
        pub fn retain_unknown_values(mut self) -> Self {
219
            self.options_mut().retain_unknown_values = Unknown::Retained(());
220
            self
221
        }
222
    }
223
}
224
use derive_deftly_template_ParseInput;
225

            
226
//---------- parser ----------
227

            
228
/// Common code for `parse_netdoc` and `parse_netdoc_multiple`
229
///
230
/// Creates the `ItemStream`, calls `parse_completely`, and handles errors.
231
52350
fn parse_internal<T, D: NetdocParseable>(
232
52350
    input: &ParseInput<'_>,
233
52350
    parse_completely: impl FnOnce(&mut ItemStream) -> Result<T, ErrorProblem>,
234
52350
) -> Result<T, ParseError> {
235
52350
    let mut items = ItemStream::new(input);
236
52350
    parse_completely(&mut items).map_err(error_handler::<D>(input, &items))
237
52350
}
238

            
239
/// Return a function for converting `ErrorProblem` to `ParseError`
240
///
241
/// For use in `.map_err()`.
242
//
243
// Returning a closure means the usual kind of call site doesn't need to name `problem`.
244
58521
fn error_handler<D: NetdocParseable>(
245
58521
    input: &ParseInput<'_>,
246
58521
    items: &ItemStream<'_>,
247
58521
) -> impl Fn(ErrorProblem) -> ParseError {
248
    |problem| ParseError {
249
217
        problem,
250
217
        doctype: D::doctype_for_error(),
251
217
        file: input.file.clone().into_owned(),
252
217
        lno: items.lno_for_error(),
253
217
        column: problem.column(),
254
217
    }
255
58521
}
256

            
257
/// Parse a network document - **toplevel entrypoint**
258
52272
pub fn parse_netdoc<D: NetdocParseable>(input: &ParseInput<'_>) -> Result<D, ParseError> {
259
52272
    parse_internal::<_, D>(input, |items| {
260
52272
        let doc = D::from_items(items, StopAt(false))?;
261
52059
        if let Some(_kw) = items.peek_keyword()? {
262
            return Err(EP::MultipleDocuments);
263
52059
        }
264
52059
        Ok(doc)
265
52272
    })
266
52272
}
267

            
268
/// Parse multiple concatenated network documents - **toplevel entrypoint**
269
25
pub fn parse_netdoc_multiple<D: NetdocParseable>(
270
25
    input: &ParseInput<'_>,
271
25
) -> Result<Vec<D>, ParseError> {
272
25
    parse_internal::<_, D>(input, |items| {
273
25
        let mut docs = vec![];
274
234
        while items.peek_keyword()?.is_some() {
275
209
            let doc = D::from_items(items, StopAt(false))?;
276
209
            docs.push(doc);
277
        }
278
25
        Ok(docs)
279
25
    })
280
25
}
281

            
282
/// Error from `multi_push_doc`
283
#[derive(Debug, Error)]
284
#[error("out of bounds bug")]
285
struct OutOfBoundsBug;
286

            
287
/// Add `(doc, start_pos, end_pos)` to `docs`, checking bounds
288
///
289
/// Helper function for use by `parse_netdoc_ multiple_*` functions that return offsets.
290
1041
fn multi_push_doc<T>(
291
1041
    docs: &mut Vec<(T, usize, usize)>,
292
1041
    input: &ParseInput<'_>,
293
1041
    doc: T,
294
1041
    start_pos: usize,
295
1041
    end_pos: usize,
296
1041
) -> Result<(), OutOfBoundsBug> {
297
    // Check start_pos and end_pos are in range.
298
1041
    if input.input.get(start_pos..end_pos).is_none() {
299
        return Err(OutOfBoundsBug);
300
1041
    }
301

            
302
1041
    docs.push((doc, start_pos, end_pos));
303
1041
    Ok(())
304
1041
}
305

            
306
/// Parse multiple network documents, also returning their offsets  - **toplevel entrypoint**
307
///
308
/// Each returned document is accompanied by the byte offsets of its start and end.
309
///
310
/// (The netdoc metaformat does not allow anything in between subsequent documents in a file,
311
/// so the end of one document is the start of the next.)
312
///
313
/// This returns byte offsets rather than string slices,
314
/// because the caller can always convert the offsets into string slices,
315
/// but it is not straightforward to convert string slices borrowed from some input string
316
/// into offsets, in a way that is obviously correct without nightly `str::substr_range`.
317
///
318
/// Interfacing code can assume that slicing the input string with the returned
319
/// [`usize`] values will not cause an out-of-bounds error, meaning runtime
320
/// checks are not necessary there.
321
53
pub fn parse_netdoc_multiple_with_offsets<D: NetdocParseable>(
322
53
    input: &ParseInput<'_>,
323
53
) -> Result<Vec<(D, usize, usize)>, ParseError> {
324
53
    parse_internal::<_, D>(input, |items| {
325
53
        let mut docs = vec![];
326
1007
        while items.peek_keyword()?.is_some() {
327
954
            let start_pos = items.byte_position();
328
954
            let doc = D::from_items(items, StopAt(false))?;
329
954
            let end_pos = items.byte_position();
330

            
331
954
            multi_push_doc(&mut docs, input, doc, start_pos, end_pos)
332
                .map_err(|OutOfBoundsBug| ErrorProblem::Internal("out-of-bounds bug?"))?;
333
        }
334
53
        Ok(docs)
335
53
    })
336
53
}
337

            
338
/// Parse multiple network documents, with error recovery  - **toplevel entrypoint**
339
///
340
/// Parses multiple documents.  If an error is encountered, it is returned,
341
/// and parsing continues with the next document (if possible).
342
///
343
/// Each document or error is accompanied by the applicable byte offsets in the input document,
344
/// as with [`parse_netdoc_multiple_with_offsets`].
345
#[allow(clippy::type_complexity)] // Yes, the return type is complicated
346
13
pub fn parse_netdoc_multiple_sophisticated<D: NetdocParseable>(
347
13
    input: &ParseInput<'_>,
348
13
) -> Result<Vec<(Result<D, ParseError>, usize, usize)>, Bug> {
349
    // Largely separate from parse_netdoc_multiple_with_offsets because the differences
350
    // are control flow; attempts at unifying these led to very confusing code.
351

            
352
13
    let mut items = ItemStream::new(input);
353
13
    let mut docs = vec![];
354
87
    let mut push_doc = |doc, start, end| {
355
87
        multi_push_doc(&mut docs, input, doc, start, end)
356
87
            .map_err(into_internal!("while parsing netdoc sequence"))
357
87
    };
358

            
359
    'docs: loop {
360
99
        let start_pos = items.byte_position();
361

            
362
        // Insisting on a KeywordRef prevents mistaken omission of code in match arms.
363
99
        let _intro_kw: KeywordRef = match items.peek_keyword() {
364
87
            Ok(Some(kw)) => kw,
365
12
            Ok(None) => break 'docs,
366
            Err(e) => {
367
                push_doc(
368
                    Err(error_handler::<D>(input, &items)(e)),
369
                    start_pos,
370
                    items.whole_input().len(),
371
                )?;
372
                // can't continue
373
                break 'docs;
374
            }
375
        };
376

            
377
87
        let doc = D::from_items(&mut items, StopAt(false)) //
378
87
            .map_err(error_handler::<D>(input, &items));
379

            
380
        /// How did we find the end of this document?
381
        enum EndedBy {
382
            /// `D::from_items` succeeded, or error recovery found intro item for the next doc
383
            ///
384
            /// The `ItemStream` can tell us where this document ends,
385
            /// and we can continue looking for another document.
386
            Normal,
387

            
388
            /// Eof during error recovery
389
            ///
390
            /// We must exit the document loop.
391
            Eof,
392
        }
393

            
394
87
        let ended_by = (|| {
395
87
            if doc.is_ok() {
396
83
                return EndedBy::Normal;
397
4
            }
398

            
399
            // Skip the rest of the erroneous document until we find the next intro item.
400
            //
401
            // If we get lexical errors during error recovery, we don't *also* report them
402
            // and instead, just stop processing the input; hence the `.unwrap_or(None)`.
403
            // (And this is why we insist on `return EndedBy::Eof`, rather than just `break`.)
404
            //
405
            // Insisting on KeywordRef and UnparsedItem helps prevent mistakes.
406
            let _next_intro_kw: KeywordRef = 'skip: loop {
407
5
                let _discard_item: UnparsedItem = match items.peek_keyword().unwrap_or(None) {
408
1
                    None => return EndedBy::Eof,
409
4
                    Some(kw) if D::is_intro_item_keyword(kw) => break 'skip kw,
410
1
                    Some(_other_kw) => match items.next().transpose().unwrap_or(None) {
411
1
                        Some(item) => item,
412
                        None => return EndedBy::Eof,
413
                    },
414
                };
415
            };
416

            
417
3
            EndedBy::Normal
418
        })(); // <- infallible; IEFE prevents failure to push output doc (or error)
419

            
420
87
        let end_pos = match ended_by {
421
86
            EndedBy::Normal => items.byte_position(),
422
1
            EndedBy::Eof => input.input().len(),
423
        };
424

            
425
87
        push_doc(doc, start_pos, end_pos)?;
426

            
427
87
        match ended_by {
428
86
            EndedBy::Normal => {}
429
1
            EndedBy::Eof => break 'docs,
430
        }
431
    }
432
13
    Ok(docs)
433
13
}