1
//! Lexing of netdoc elements
2

            
3
use super::*;
4

            
5
/// Linear whitespace as defined by torspec
6
// Only pub via internal_prelude, for benefit of macros
7
pub const WS: &[char] = &[' ', '\t'];
8

            
9
define_derive_deftly! {
10
    /// Define `parse_options` accessor
11
    ///
12
    /// The driver must have a lifetime named `'s`, which is suitable for the returned
13
    /// `&'s ParseOptions`.
14
    ///
15
    /// # Top-level attributes:
16
    ///
17
    ///  * **`#[deftly(parse_options(field = ".field.field"))]`**, default `.options`
18
    ParseOptions beta_deftly, expect items:
19

            
20
    impl<$tgens> $ttype {
21
        /// Examine the parsing options
22
6324
        pub fn parse_options(&self) -> &'s ParseOptions {
23
            &self
24
                ${tmeta(parse_options(field))
25
                  as token_stream,
26
                  default { .options }}
27
        }
28
    }
29
}
30

            
31
/// Top-level reader: Netdoc text interpreted as a stream of items
32
#[derive(Debug, Clone, Deftly)]
33
#[derive_deftly(ParseOptions)]
34
pub struct ItemStream<'s> {
35
    /// The whole input document.
36
    whole_input: &'s str,
37
    /// Remaining document, as a stream of lines
38
    lines: Lines<'s>,
39
    /// If we have peeked ahead, what we discovered
40
    peeked: PeekState<'s>,
41
    /// Parsing options.
42
    options: &'s ParseOptions,
43
}
44

            
45
/// Whether an `ItemStream` has peeked ahead, and if so what it discovered
46
#[derive(Debug, Clone)]
47
enum PeekState<'s> {
48
    /// We've peeked a line
49
    Some(ItemStreamPeeked<'s>),
50
    /// We've not peeked, or peeking gave `None`
51
    None {
52
        /// Line number of the last item we yielded.
53
        ///
54
        /// `0` at the start.
55
        yielded_item_lno: usize,
56
    },
57
}
58

            
59
/// If an `ItemStream` has peeked ahead, what it discovered
60
#[derive(Debug, Clone)]
61
struct ItemStreamPeeked<'s> {
62
    /// The next keyword
63
    keyword: KeywordRef<'s>,
64
    /// Token proving that we
65
    line: lines::Peeked,
66
    /// Length of the suffix of the line that is the arguments rather than the keyword
67
    ///
68
    /// Does not include the first whitespace, that terminated the keyword.
69
    args_len: usize,
70
}
71

            
72
/// An Item that has been lexed but not parsed
73
#[derive(Debug, Clone, amplify::Getters, Deftly)]
74
#[derive_deftly(ParseOptions)]
75
#[deftly(parse_options(field = ".args.options"))]
76
pub struct UnparsedItem<'s> {
77
    /// The item's Keyword
78
    #[getter(as_copy)]
79
    keyword: KeywordRef<'s>,
80
    /// The Item's Arguments
81
    #[getter(skip)]
82
    args: ArgumentStream<'s>,
83
    /// The Item's Object, if there was one
84
    #[getter(as_clone)]
85
    object: Option<UnparsedObject<'s>>,
86
}
87

            
88
/// Reader for arguments on an Item
89
///
90
/// Represents the (remaining) arguments.
91
#[derive(Debug, Clone, Deftly)]
92
#[derive_deftly(ParseOptions)]
93
pub struct ArgumentStream<'s> {
94
    /// The remaining unparsed arguments
95
    ///
96
    /// Can start with WS, which is usually trimmed
97
    rest: &'s str,
98

            
99
    /// Original line length
100
    ///
101
    /// Used for reporting column of argument errors.
102
    whole_line_len: usize,
103

            
104
    /// Remaining length *before* we last yielded.
105
    previous_rest_len: usize,
106

            
107
    /// Parsing options.
108
    options: &'s ParseOptions,
109
}
110

            
111
/// An Object that has been lexed but not parsed
112
#[derive(Debug, Clone, amplify::Getters, Deftly)]
113
#[derive_deftly(ParseOptions)]
114
pub struct UnparsedObject<'s> {
115
    /// The Label
116
    #[getter(as_copy)]
117
    label: &'s str,
118

            
119
    /// The portion of the input document which is base64 data (and newlines)
120
    #[getter(skip)]
121
    data_b64: &'s str,
122

            
123
    /// Parsing options.
124
    options: &'s ParseOptions,
125
}
126

            
127
impl<'s> ItemStream<'s> {
128
    /// Start reading a network document as a series of Items
129
3715
    pub fn new(input: &'s ParseInput<'s>) -> Self {
130
3715
        ItemStream {
131
3715
            whole_input: input.input,
132
3715
            lines: Lines::new(input.input),
133
3715
            peeked: PeekState::None {
134
3715
                yielded_item_lno: 0,
135
3715
            },
136
3715
            options: &input.options,
137
3715
        }
138
3715
    }
139

            
140
    /// Line number for reporting an error we have just discovered
141
    ///
142
    /// If we have recent peeked, we report the line number of the peeked keyword line.
143
    ///
144
    /// Otherwise, we report the line number of the most-recently yielded item.
145
116
    pub fn lno_for_error(&self) -> usize {
146
116
        match self.peeked {
147
            PeekState::Some { .. } => {
148
                // The error was presumably caused by whatever was seen in the peek.
149
                // That's the current line number.
150
18
                self.lines.peek_lno()
151
            }
152
98
            PeekState::None { yielded_item_lno } => {
153
                // The error was presumably caused by the results of next_item().
154
98
                yielded_item_lno
155
            }
156
        }
157
116
    }
158

            
159
    /// Core of peeking.  Tries to make `.peeked` be `Some`.
160
346380
    fn peek_internal<'i>(&'i mut self) -> Result<(), EP> {
161
346380
        if matches!(self.peeked, PeekState::None { .. }) {
162
171024
            let Some(peeked) = self.lines.peek() else {
163
6888
                return Ok(());
164
            };
165

            
166
164136
            let peeked_line = self.lines.peeked_line(&peeked);
167

            
168
164136
            let (keyword, args) = peeked_line.split_once(WS).unwrap_or((peeked_line, ""));
169
164136
            let keyword = KeywordRef::new(keyword)?;
170

            
171
164136
            self.peeked = PeekState::Some(ItemStreamPeeked {
172
164136
                keyword,
173
164136
                line: peeked,
174
164136
                args_len: args.len(),
175
164136
            });
176
175356
        }
177

            
178
339492
        Ok(())
179
346380
    }
180

            
181
    /// Peek the next keyword
182
175770
    pub fn peek_keyword(&mut self) -> Result<Option<KeywordRef<'s>>, EP> {
183
175770
        self.peek_internal()?;
184
175770
        let PeekState::Some(peeked) = &self.peeked else {
185
6878
            return Ok(None);
186
        };
187
168892
        Ok(Some(peeked.keyword))
188
175770
    }
189

            
190
    /// Obtain the body so far, suitable for hashing for an Orderly signature
191
    #[allow(clippy::string_slice)] // TODO
192
9697
    pub fn body_sofar_for_signature(&self) -> SignedDocumentBody<'s> {
193
9697
        let body = &self.whole_input[0..self.byte_position()];
194
9697
        SignedDocumentBody { body }
195
9697
    }
196

            
197
    /// Byte position, pointing to the start of the next item to yield
198
    ///
199
    /// Offset in bytes from the start of the original input string
200
    /// to the "current" position,
201
    /// ie to just after the item we yielded and just before the next item (or EOF).
202
13852
    pub fn byte_position(&self) -> usize {
203
13852
        self.whole_input.len() - self.lines.remaining().len()
204
13852
    }
205

            
206
    /// Access for the entire input string
207
    ///
208
    /// The original `input: &str` argument to [`ParseInput::new`].
209
    ///
210
    /// Includes both yielded and unyielded items.
211
1988
    pub fn whole_input(&self) -> &'s str {
212
1988
        self.whole_input
213
1988
    }
214

            
215
    /// Parse a (sub-)document with its own signatures
216
    ///
217
    /// Used (mostly) by the
218
    /// [`NetdocParseableUnverified`](derive_deftly_template_NetdocParseableUnverified)
219
    /// derive macro.
220
    ///
221
    /// Generic parameters:
222
    ///
223
    ///  * **`B`**: the body type: the type to which `NetdocParseableUnverified` is applied.
224
    ///  * **`S`**: the signatures section type.
225
    ///  * **`O`**: the `FooUnverified` type, which embodies the parsed body and signatures.
226
    #[allow(clippy::string_slice)] // TODO
227
1275
    pub fn parse_signed<
228
1275
        B: HasUnverifiedParsedBody,
229
1275
        S: NetdocParseableSignatures,
230
1275
        O: NetdocParseableUnverified<Body = B, Signatures = S>,
231
1275
    >(
232
1275
        &mut self,
233
1275
        outer_stop: stop_at!(),
234
1275
    ) -> Result<O, EP> {
235
1275
        let mut input = ItemStream {
236
1275
            whole_input: &self.whole_input[self.whole_input.len() - self.lines.remaining().len()..],
237
1275
            ..self.clone()
238
1275
        };
239
1275
        let r = (|| {
240
1275
            let inner_always_stop = outer_stop | StopAt::doc_intro::<B::UnverifiedParsedBody>();
241
1275
            let body = B::UnverifiedParsedBody::from_items(
242
1275
                &mut input,
243
1275
                inner_always_stop | StopAt(S::is_item_keyword),
244
2
            )?;
245
1273
            let signed_doc_body = input.body_sofar_for_signature();
246
1273
            let unsigned_body_len = signed_doc_body.body().len();
247
1273
            let mut hashes = S::HashesAccu::default();
248
1273
            let sigs = S::from_items(&mut input, signed_doc_body, &mut hashes, inner_always_stop)?;
249
1273
            let sigs = SignaturesData {
250
1273
                sigs,
251
1273
                unsigned_body_len,
252
1273
                hashes,
253
1273
            };
254
            // SECURITY
255
            // We unwrap the UnverifiedParsedBody and immediately wrap it up again
256
            // in FooUnverified, passing on the obligation to verify the signatures,
257
            // and still enforcing that with a newtype.
258
1273
            let signed = O::from_parts(B::unverified_into_inner_unchecked(body), sigs);
259
1273
            Ok(signed)
260
        })(); // don't exit here
261

            
262
1275
        *self = ItemStream {
263
1275
            whole_input: self.whole_input,
264
1275
            ..input
265
1275
        };
266

            
267
1275
        r
268
1275
    }
269

            
270
    /// Obtain the inputs that would be needed to hash any (even Disorderly) signature
271
    ///
272
    /// These are the hash inputs which would be needed for the next item,
273
    /// assuming it's a signature keyword.
274
6639
    pub fn peek_signature_hash_inputs(
275
6639
        &mut self,
276
6639
        body: SignedDocumentBody<'s>,
277
6639
    ) -> Result<Option<SignatureHashInputs<'s>>, EP> {
278
6639
        self.peek_internal()?;
279
6639
        let PeekState::Some(peeked) = &self.peeked else {
280
            return Ok(None);
281
        };
282
6639
        let document_sofar = self.body_sofar_for_signature().body();
283
6639
        let signature_item_line = self.lines.peeked_line(&peeked.line);
284
6639
        let signature_item_kw_spc = signature_item_line.strip_end_counted(peeked.args_len);
285
6639
        Ok(Some(SignatureHashInputs {
286
6639
            body,
287
6639
            document_sofar,
288
6639
            signature_item_kw_spc,
289
6639
            signature_item_line,
290
6639
        }))
291
6639
    }
292

            
293
    /// Yield the next item.
294
    #[allow(clippy::string_slice)] // TODO
295
163971
    pub fn next_item(&mut self) -> Result<Option<UnparsedItem<'s>>, EP> {
296
163971
        self.peek_internal()?;
297
163971
        let peeked = match self.peeked {
298
10
            PeekState::None { .. } => return Ok(None),
299
163961
            PeekState::Some { .. } => match mem::replace(
300
163961
                &mut self.peeked,
301
163961
                PeekState::None {
302
163961
                    yielded_item_lno: self.lines.peek_lno(),
303
163961
                },
304
163961
            ) {
305
163961
                PeekState::Some(peeked) => peeked,
306
                PeekState::None { .. } => panic!("it was Some just now"),
307
            },
308
        };
309

            
310
163961
        let keyword = peeked.keyword;
311
163961
        let line = self.lines.consume_peeked(peeked.line);
312
163961
        let args = &line[keyword.len()..];
313
163961
        let options = self.options;
314
163961
        let args = ArgumentStream::new(args, line.len(), options);
315

            
316
163961
        let object = if self.lines.remaining().starts_with('-') {
317
            // Swap out self.lines, so that if we do not find matching delimiters, we don't
318
            // ever yield any more items.  Otherwise, if we continue reading after an error, we
319
            // might get a framing mismatch where we treat base64 contents as if it were item
320
            // keyword lines.
321
18013
            let leave_if_error = self.lines.clone_entirely_consumed();
322
18013
            let mut lines = mem::replace(&mut self.lines, leave_if_error);
323
18013
            let self_lines_prevent = &mut self.lines;
324

            
325
36024
            fn pem_delimiter<'s>(lines: &mut Lines<'s>, start: &str) -> Result<&'s str, EP> {
326
36024
                let line = lines.next().ok_or(
327
                    // If this is the *header*, we already know there's a line,
328
                    // so this error path is only for footers.
329
36024
                    EP::ObjectMissingFooter,
330
                )?;
331
36024
                let label = line
332
36024
                    .strip_prefix(start)
333
36024
                    .ok_or(EP::InvalidObjectDelimiters)?
334
36022
                    .strip_suffix(PEM_AFTER_LABEL)
335
36022
                    .ok_or(EP::InvalidObjectDelimiters)?;
336
36020
                Ok(label)
337
36024
            }
338

            
339
18013
            let label1 = pem_delimiter(&mut lines, PEM_HEADER_START)?;
340
18011
            let base64_start_remaining = lines.remaining();
341
94997
            while !lines.remaining().starts_with('-') {
342
76986
                let _: &str = lines.next().ok_or(EP::ObjectMissingFooter)?;
343
            }
344
18011
            let data_b64 = base64_start_remaining.strip_end_counted(lines.remaining().len());
345
18011
            let label2 = pem_delimiter(&mut lines, PEM_FOOTER_START)?;
346
18009
            let label = [label1, label2]
347
18009
                .into_iter()
348
18009
                .all_equal_value()
349
18009
                .map_err(|_| EP::ObjectMismatchedLabels)?;
350

            
351
            // Proves that self.lines isn't used between setup and here: we have it borrowed.
352
18007
            let _: &mut Lines = self_lines_prevent;
353
18007
            self.lines = lines;
354

            
355
18007
            Some(UnparsedObject {
356
18007
                label,
357
18007
                data_b64,
358
18007
                options,
359
18007
            })
360
        } else {
361
145948
            None
362
        };
363

            
364
163955
        Ok(Some(UnparsedItem {
365
163955
            keyword,
366
163955
            args,
367
163955
            object,
368
163955
        }))
369
163971
    }
370
}
371

            
372
impl<'s> UnparsedItem<'s> {
373
    /// Access the arguments, mutably (for consuming and parsing them)
374
88261
    pub fn args_mut(&mut self) -> &mut ArgumentStream<'s> {
375
88261
        &mut self.args
376
88261
    }
377
    /// Access a copy of the arguments
378
    ///
379
    /// When using this, be careful not to process any arguments twice.
380
6894
    pub fn args_copy(&self) -> ArgumentStream<'s> {
381
6894
        self.args.clone()
382
6894
    }
383

            
384
    /// Access the arguments (readonly)
385
    ///
386
    /// When using this, be careful not to process any arguments twice.
387
31402
    pub fn args(&self) -> &ArgumentStream<'s> {
388
31402
        &self.args
389
31402
    }
390

            
391
    /// Check that this item has no Object.
392
37299
    pub fn check_no_object(&self) -> Result<(), EP> {
393
37299
        if self.object.is_some() {
394
2
            return Err(EP::ObjectUnexpected);
395
37297
        }
396
37297
        Ok(())
397
37299
    }
398
    /// Convenience method for handling an error parsing an argument
399
    ///
400
    /// Returns a closure that converts every error into [`ArgumentError::Invalid`]
401
    /// and then to an [`ErrorProblem`] using
402
    /// [`.args().handle_error()`](ArgumentStream::handle_error).
403
    ///
404
    /// Useful in manual `ItemValueParseable` impls, when parsing arguments ad-hoc.
405
11841
    pub fn invalid_argument_handler<E>(
406
11841
        &self,
407
11841
        field: &'static str,
408
11841
    ) -> impl FnOnce(E) -> ErrorProblem {
409
11841
        let error = self.args().handle_error(field, AE::Invalid);
410
        move |_any_error| error
411
11841
    }
412
}
413

            
414
#[deprecated = "use types::NoFurtherArguments"]
415
pub use crate::types::NoMoreArguments as NoFurtherArguments;
416

            
417
impl<'s> Iterator for ItemStream<'s> {
418
    type Item = Result<UnparsedItem<'s>, EP>;
419
56977
    fn next(&mut self) -> Option<Result<UnparsedItem<'s>, EP>> {
420
56977
        self.next_item().transpose()
421
56977
    }
422
}
423

            
424
impl<'s> ArgumentStream<'s> {
425
    /// Make a new `ArgumentStream` from a string
426
    ///
427
    /// The string may start with whitespace (which will be ignored).
428
168949
    pub fn new(rest: &'s str, whole_line_len: usize, options: &'s ParseOptions) -> Self {
429
168949
        let previous_rest_len = whole_line_len;
430
168949
        ArgumentStream {
431
168949
            rest,
432
168949
            whole_line_len,
433
168949
            previous_rest_len,
434
168949
            options,
435
168949
        }
436
168949
    }
437

            
438
    /// Consume this whole `ArgumentStream`, giving the remaining arguments as a string
439
    ///
440
    /// The returned string won't start with whitespace.
441
    //
442
    /// `self` will be empty on return.
443
    // (We don't take `self` by value because that makes use with `UnparsedItem` annoying.)
444
15449
    pub fn into_remaining(&mut self) -> &'s str {
445
15449
        self.prep_yield();
446
15449
        mem::take(&mut self.rest)
447
15449
    }
448

            
449
    /// Return the component parts of this `ArgumentStream`
450
    ///
451
    /// The returned string might start with whitespace.
452
4988
    pub fn whole_line_len(&self) -> usize {
453
4988
        self.whole_line_len
454
4988
    }
455

            
456
    /// Prepares to yield an argument (or the rest)
457
    ///
458
    ///  * Trims leading WS from `rest`.
459
    ///  * Records the `previous_rest_len`
460
164416
    fn prep_yield(&mut self) {
461
164416
        self.rest = self.rest.trim_start_matches(WS);
462
164416
        self.previous_rest_len = self.rest.len();
463
164416
    }
464

            
465
    /// Prepares to yield, and then determines if there *is* anything to yield.
466
    ///
467
    ///  * Trim leading whitespace
468
    ///  * Records the `previous_rest_len`
469
    ///  * See if we're now empty
470
148967
    pub fn something_to_yield(&mut self) -> bool {
471
148967
        self.prep_yield();
472
148967
        !self.rest.is_empty()
473
148967
    }
474

            
475
    /// Throw and error if there are further arguments
476
    //
477
    // (We don't take `self` by value because that makes use with `UnparsedItem` annoying.)
478
7654
    pub fn reject_extra_args(&mut self) -> Result<NoFurtherArguments, UnexpectedArgument> {
479
7654
        if self.something_to_yield() {
480
4
            let column = self.next_arg_column();
481
4
            Err(UnexpectedArgument { column })
482
        } else {
483
7650
            Ok(NoFurtherArguments)
484
        }
485
7654
    }
486

            
487
    /// Convert a "length of `rest`" into the corresponding column number.
488
116762
    fn arg_column_from_rest_len(&self, rest_len: usize) -> usize {
489
        // Can't underflow since rest is always part of the whole.
490
        // Can't overflow since that would mean the document was as big as the address space.
491
116762
        self.whole_line_len - rest_len + 1
492
116762
    }
493

            
494
    /// Obtain the column number of the previously yielded argument.
495
    ///
496
    /// (After `into_remaining`, gives the column number
497
    /// of the start of the returned remaining argument string.)
498
116758
    pub fn prev_arg_column(&self) -> usize {
499
116758
        self.arg_column_from_rest_len(self.previous_rest_len)
500
116758
    }
501

            
502
    /// Obtains the column number of the *next* argument.
503
    ///
504
    /// Should be called after `something_to_yield`; otherwise the returned value
505
    /// may point to whitespace which is going to be skipped.
506
    // ^ this possible misuse doesn't seem worth defending against with type-fu,
507
    //   for a private function with few call sites.
508
4
    fn next_arg_column(&self) -> usize {
509
4
        self.arg_column_from_rest_len(self.rest.len())
510
4
    }
511

            
512
    /// Convert an `ArgumentError` to an `ErrorProblem`.
513
    ///
514
    /// The caller must supply the field name.
515
11841
    pub fn handle_error(&self, field: &'static str, ae: ArgumentError) -> ErrorProblem {
516
11841
        self.error_handler(field)(ae)
517
11841
    }
518

            
519
    /// Return a converter from `ArgumentError` to `ErrorProblem`.
520
    ///
521
    /// Useful in `.map_err`.
522
116758
    pub fn error_handler(
523
116758
        &self,
524
116758
        field: &'static str,
525
116758
    ) -> impl Fn(ArgumentError) -> ErrorProblem + 'static {
526
116758
        let column = self.prev_arg_column();
527
11875
        move |ae| match ae {
528
4
            AE::Missing => EP::MissingArgument { field },
529
11871
            AE::Invalid => EP::InvalidArgument { field, column },
530
            AE::Unexpected => EP::UnexpectedArgument { column },
531
11875
        }
532
116758
    }
533
}
534

            
535
impl<'s> Iterator for ArgumentStream<'s> {
536
    type Item = &'s str;
537
131987
    fn next(&mut self) -> Option<&'s str> {
538
131987
        if !self.something_to_yield() {
539
2859
            return None;
540
129128
        }
541
        let arg;
542
129128
        (arg, self.rest) = self.rest.split_once(WS).unwrap_or((self.rest, ""));
543
129128
        Some(arg)
544
131987
    }
545
}
546

            
547
impl<'s> UnparsedObject<'s> {
548
    /// Obtain the Object data, as decoded bytes
549
14335
    pub fn decode_data(&self) -> Result<Vec<u8>, EP> {
550
14335
        crate::parse::tokenize::base64_decode_multiline(self.data_b64)
551
14335
            .map_err(|_e| EP::ObjectInvalidBase64)
552
14335
    }
553
}