1
//! Break a string into a set of directory-object Items.
2
//!
3
//! This module defines Item, which represents a basic entry in a
4
//! directory document, and NetDocReader, which is used to break a
5
//! string into Items.
6

            
7
use crate::parse::keyword::Keyword;
8
use crate::types::misc::FromBytes;
9
use crate::util::PeekableIterator;
10
use crate::{Error, NetdocErrorKind as EK, Pos, Result};
11
use base64ct::{Base64, Encoding};
12
use itertools::Itertools;
13
use std::cell::{Ref, RefCell};
14
use std::iter::Peekable;
15
use std::str::FromStr;
16
use tor_error::internal;
17

            
18
/// Useful constants for netdoc object syntax
19
pub(crate) mod object {
20
    /// indicates the start of an object
21
    pub(crate) const BEGIN_STR: &str = "-----BEGIN ";
22
    /// indicates the end of an object
23
    pub(crate) const END_STR: &str = "-----END ";
24
    /// indicates the end of a begin or end tag.
25
    pub(crate) const TAG_END: &str = "-----";
26
    /// Maximum PEM base64 line length (not enforced during parsing)
27
    pub(crate) const BASE64_PEM_MAX_LINE: usize = 64;
28
}
29

            
30
/// Return true iff a given character is "space" according to the rules
31
/// of dir-spec.txt
32
37243303
pub(crate) fn is_sp(c: char) -> bool {
33
37243303
    c == ' ' || c == '\t'
34
37243303
}
35
/// Check that all the characters in `s` are valid base64.
36
///
37
/// This is not a perfect check for base64ness -- it is mainly meant
38
/// to help us recover after unterminated base64.
39
163606
fn b64check(s: &str) -> Result<()> {
40
10131538
    for b in s.bytes() {
41
10131538
        match b {
42
20696
            b'=' => (),
43
4106593
            b'a'..=b'z' => (),
44
4176179
            b'A'..=b'Z' => (),
45
1535290
            b'0'..=b'9' => (),
46
292774
            b'/' | b'+' => (),
47
            _ => {
48
6
                return Err(EK::BadObjectBase64.at_pos(Pos::at(s)));
49
            }
50
        };
51
    }
52
163600
    Ok(())
53
163606
}
54

            
55
/// A tagged object that is part of a directory Item.
56
///
57
/// This represents a single blob within a pair of "-----BEGIN
58
/// FOO-----" and "-----END FOO-----".  The data is not guaranteed to
59
/// be actual base64 when this object is created: doing so would
60
/// require either that we parse the base64 twice, or that we allocate
61
/// a buffer to hold the data before it's needed.
62
#[derive(Clone, Copy, Debug)]
63
pub(crate) struct Object<'a> {
64
    /// Reference to the "tag" string (the 'foo') in the BEGIN line.
65
    tag: &'a str,
66
    /// Reference to the allegedly base64-encoded data.  This may or
67
    /// may not actually be base64 at this point.
68
    data: &'a str,
69
    /// Reference to the END line for this object.  This doesn't
70
    /// need to be parsed, but it's used to find where this object
71
    /// ends.
72
    endline: &'a str,
73
}
74

            
75
/// A single part of a directory object.
76
///
77
/// Each Item -- called an "entry" in dir-spec.txt -- has a keyword, a
78
/// (possibly empty) set of arguments, and an optional object.
79
///
80
/// This is a zero-copy implementation that points to slices within a
81
/// containing string.
82
#[derive(Clone, Debug)]
83
pub(crate) struct Item<'a, K: Keyword> {
84
    /// The keyword that determines the type of this item.
85
    kwd: K,
86
    /// A reference to the actual string that defines the keyword for
87
    /// this item.
88
    kwd_str: &'a str,
89
    /// Reference to the arguments that appear in the same line after the
90
    /// keyword.  Does not include the terminating newline or the
91
    /// space that separates the keyword for its arguments.
92
    args: &'a str,
93
    /// The arguments, split by whitespace.  This vector is constructed
94
    /// as needed, using interior mutability.
95
    split_args: RefCell<Option<Vec<&'a str>>>,
96
    /// If present, a base-64-encoded object that appeared at the end
97
    /// of this item.
98
    object: Option<Object<'a>>,
99
}
100

            
101
/// A cursor into a string that returns Items one by one.
102
///
103
/// (This type isn't used directly, but is returned wrapped in a Peekable.)
104
#[derive(Debug)]
105
struct NetDocReaderBase<'a, K: Keyword> {
106
    /// The string we're parsing.
107
    s: &'a str,
108
    /// Our position within the string.
109
    off: usize,
110
    /// Tells Rust it's okay that we are parameterizing on K.
111
    _k: std::marker::PhantomData<K>,
112
}
113

            
114
impl<'a, K: Keyword> NetDocReaderBase<'a, K> {
115
    /// Create a new NetDocReader to split a string into tokens.
116
4395
    fn new(s: &'a str) -> Result<Self> {
117
        Ok(NetDocReaderBase {
118
4395
            s: validate_utf_8_rules(s)?,
119
            off: 0,
120
4395
            _k: std::marker::PhantomData,
121
        })
122
4395
    }
123
    /// Return the current Pos within the string.
124
207
    fn pos(&self, pos: usize) -> Pos {
125
207
        Pos::from_offset(self.s, pos)
126
207
    }
127
    /// Skip forward by n bytes.
128
    ///
129
    /// (Note that standard caveats with byte-oriented processing of
130
    /// UTF-8 strings apply.)
131
292697
    fn advance(&mut self, n: usize) -> Result<()> {
132
292697
        if n > self.remaining() {
133
            return Err(
134
                Error::from(internal!("tried to advance past end of document"))
135
                    .at_pos(Pos::from_offset(self.s, self.off)),
136
            );
137
292697
        }
138
292697
        self.off += n;
139
292697
        Ok(())
140
292697
    }
141
    /// Return the remaining number of bytes in this reader.
142
386939
    fn remaining(&self) -> usize {
143
386939
        self.s.len() - self.off
144
386939
    }
145

            
146
    /// Return true if the next characters in this reader are `s`
147
89790
    fn starts_with(&self, s: &str) -> bool {
148
89790
        self.s[self.off..].starts_with(s)
149
89790
    }
150
    /// Try to extract a NL-terminated line from this reader.  Always
151
    /// remove data if the reader is nonempty.
152
292697
    fn line(&mut self) -> Result<&'a str> {
153
292697
        let remainder = &self.s[self.off..];
154
292697
        if let Some(nl_pos) = remainder.find('\n') {
155
292536
            self.advance(nl_pos + 1)?;
156
292536
            let line = &remainder[..nl_pos];
157

            
158
            // TODO: we should probably detect \r and do something about it.
159
            // Just ignoring it isn't the right answer, though.
160
292536
            Ok(line)
161
        } else {
162
161
            self.advance(remainder.len())?; // drain everything.
163
161
            Err(EK::TruncatedLine.at_pos(self.pos(self.s.len())))
164
        }
165
292697
    }
166

            
167
    /// Try to extract a line that begins with a keyword from this reader.
168
    ///
169
    /// Returns a (kwd, args) tuple on success.
170
89989
    fn kwdline(&mut self) -> Result<(&'a str, &'a str)> {
171
89989
        let pos = self.off;
172
89989
        let line = self.line()?;
173
89828
        if line.is_empty() {
174
14
            return Err(EK::EmptyLine.at_pos(self.pos(pos)));
175
89814
        }
176
89814
        let (line, anno_ok) = if let Some(rem) = line.strip_prefix("opt ") {
177
4
            (rem, false)
178
        } else {
179
89810
            (line, true)
180
        };
181
89814
        let mut parts_iter = line.splitn(2, [' ', '\t']);
182
89814
        let kwd = match parts_iter.next() {
183
89814
            Some(k) => k,
184
            // This case seems like it can't happen: split always returns
185
            // something, apparently.
186
            None => return Err(EK::MissingKeyword.at_pos(self.pos(pos))),
187
        };
188
89814
        if !keyword_ok(kwd, anno_ok) {
189
24
            return Err(EK::BadKeyword.at_pos(self.pos(pos)));
190
89790
        }
191
        // TODO(nickm): dir-spec does not yet allow unicode in the arguments, but we're
192
        // assuming that proposal 285 is accepted.
193
89790
        let args = match parts_iter.next() {
194
70954
            Some(a) => a,
195
            // take a zero-length slice, so it will be within the string.
196
18836
            None => &kwd[kwd.len()..],
197
        };
198
89790
        Ok((kwd, args))
199
89989
    }
200

            
201
    /// Try to extract an Object beginning wrapped within BEGIN/END tags.
202
    ///
203
    /// Returns Ok(Some(Object(...))) on success if an object is
204
    /// found, Ok(None) if no object is found, and Err only if a
205
    /// corrupt object is found.
206
89790
    fn object(&mut self) -> Result<Option<Object<'a>>> {
207
        use object::*;
208

            
209
89790
        let pos = self.off;
210
89790
        if !self.starts_with(BEGIN_STR) {
211
70234
            return Ok(None);
212
19556
        }
213
19556
        let line = self.line()?;
214
19556
        if !line.ends_with(TAG_END) {
215
2
            return Err(EK::BadObjectBeginTag.at_pos(self.pos(pos)));
216
19554
        }
217
19554
        let tag = &line[BEGIN_STR.len()..(line.len() - TAG_END.len())];
218
19554
        if !tag_keywords_ok(tag) {
219
2
            return Err(EK::BadObjectBeginTag.at_pos(self.pos(pos)));
220
19552
        }
221
19552
        let datapos = self.off;
222
19546
        let (endlinepos, endline) = loop {
223
183152
            let p = self.off;
224
183152
            let line = self.line()?;
225
183152
            if line.starts_with(END_STR) {
226
19546
                break (p, line);
227
163606
            }
228
            // Exit if this line isn't plausible base64.  Otherwise,
229
            // an unterminated base64 block could potentially
230
            // "consume" all the rest of the string, which would stop
231
            // us from recovering.
232
163606
            b64check(line).map_err(|e| e.within(self.s))?;
233
        };
234
19546
        let data = &self.s[datapos..endlinepos];
235
19546
        if !endline.ends_with(TAG_END) {
236
2
            return Err(EK::BadObjectEndTag.at_pos(self.pos(endlinepos)));
237
19544
        }
238
19544
        let endtag = &endline[END_STR.len()..(endline.len() - TAG_END.len())];
239
19544
        if endtag != tag {
240
2
            return Err(EK::BadObjectMismatchedTag.at_pos(self.pos(endlinepos)));
241
19542
        }
242
19542
        Ok(Some(Object { tag, data, endline }))
243
89790
    }
244

            
245
    /// Read the next Item from this NetDocReaderBase.
246
    ///
247
    /// If successful, returns Ok(Some(Item)), or Ok(None) if exhausted.
248
    /// Returns Err on failure.
249
    ///
250
    /// Always consumes at least one line if possible; always ends on a
251
    /// line boundary if one exists.
252
94242
    fn item(&mut self) -> Result<Option<Item<'a, K>>> {
253
94242
        if self.remaining() == 0 {
254
4253
            return Ok(None);
255
89989
        }
256
89989
        let (kwd_str, args) = self.kwdline()?;
257
89790
        let object = self.object()?;
258
89776
        let split_args = RefCell::new(None);
259
89776
        let kwd = K::from_str(kwd_str);
260
89776
        Ok(Some(Item {
261
89776
            kwd,
262
89776
            kwd_str,
263
89776
            args,
264
89776
            split_args,
265
89776
            object,
266
89776
        }))
267
94242
    }
268
}
269

            
270
/// Return true iff 's' is a valid keyword or annotation.
271
///
272
/// (Only allow annotations if `anno_ok` is true.`
273
188862
fn keyword_ok(mut s: &str, anno_ok: bool) -> bool {
274
    /// Helper: return true if this character can appear in keywords.
275
1526274
    fn kwd_char_ok(c: char) -> bool {
276
1526274
        matches!(c,'A'..='Z' | 'a'..='z' |'0'..='9' | '-')
277
1526274
    }
278

            
279
188862
    if s.is_empty() {
280
6
        return false;
281
188856
    }
282
188856
    if anno_ok && s.starts_with('@') {
283
30
        s = &s[1..];
284
188826
    }
285
188856
    if s.starts_with('-') {
286
8
        return false;
287
188848
    }
288
188848
    s.chars().all(kwd_char_ok)
289
188862
}
290

            
291
/// Return true iff 's' is a valid keywords string for a BEGIN/END tag.
292
53992
pub(crate) fn tag_keywords_ok(s: &str) -> bool {
293
100442
    s.split(' ').all(|w| keyword_ok(w, false))
294
53992
}
295

            
296
/// When used as an Iterator, returns a sequence of `Result<Item>`.
297
impl<'a, K: Keyword> Iterator for NetDocReaderBase<'a, K> {
298
    type Item = Result<Item<'a, K>>;
299
94242
    fn next(&mut self) -> Option<Self::Item> {
300
94242
        self.item().transpose()
301
94242
    }
302
}
303

            
304
/// Helper: as base64::decode(), but allows newlines in the middle of the
305
/// encoded object.
306
25126
pub(crate) fn base64_decode_multiline(s: &str) -> std::result::Result<Vec<u8>, base64ct::Error> {
307
    // base64 module hates whitespace.
308
25126
    let mut s = s.to_string();
309
12604298
    s.retain(|ch| ch != '\n');
310
25126
    let v = Base64::decode_vec(&s)?;
311
25124
    Ok(v)
312
25126
}
313

            
314
impl<'a, K: Keyword> Item<'a, K> {
315
    /// Return the parsed keyword part of this item.
316
154422
    pub(crate) fn kwd(&self) -> K {
317
154422
        self.kwd
318
154422
    }
319
    /// Return the keyword part of this item, as a string.
320
2704
    pub(crate) fn kwd_str(&self) -> &'a str {
321
2704
        self.kwd_str
322
2704
    }
323
    /// Return true if the keyword for this item is in 'ks'.
324
69257
    pub(crate) fn has_kwd_in(&self, ks: &[K]) -> bool {
325
69257
        ks.contains(&self.kwd)
326
69257
    }
327
    /// Return the arguments of this item, as a single string.
328
23319
    pub(crate) fn args_as_str(&self) -> &'a str {
329
23319
        self.args
330
23319
    }
331
    /// Return the arguments of this item as a vector.
332
80692
    fn args_as_vec(&self) -> Ref<'_, Vec<&'a str>> {
333
        // We're using an interior mutability pattern here to lazily
334
        // construct the vector.
335
80692
        if self.split_args.borrow().is_none() {
336
37505
            self.split_args.replace(Some(self.args().collect()));
337
43187
        }
338
80692
        Ref::map(self.split_args.borrow(), |opt| match opt {
339
80692
            Some(v) => v,
340
            None => panic!(),
341
80692
        })
342
80692
    }
343
    /// Return an iterator over the arguments of this item.
344
129674
    pub(crate) fn args(&self) -> impl Iterator<Item = &'a str> + use<'a, K> {
345
361210
        self.args.split(is_sp).filter(|s| !s.is_empty())
346
129674
    }
347
    /// Return the nth argument of this item, if there is one.
348
80684
    pub(crate) fn arg(&self, idx: usize) -> Option<&'a str> {
349
80684
        self.args_as_vec().get(idx).copied()
350
80684
    }
351
    /// Return the nth argument of this item, or an error if it isn't there.
352
27011
    pub(crate) fn required_arg(&self, idx: usize) -> Result<&'a str> {
353
27011
        self.arg(idx)
354
27011
            .ok_or_else(|| EK::MissingArgument.at_pos(Pos::at(self.args)))
355
27011
    }
356
    /// Try to parse the nth argument (if it exists) into some type
357
    /// that supports FromStr.
358
    ///
359
    /// Returns Ok(None) if the argument doesn't exist.
360
49971
    pub(crate) fn parse_optional_arg<V: FromStr>(&self, idx: usize) -> Result<Option<V>>
361
49971
    where
362
49971
        Error: From<V::Err>,
363
    {
364
49971
        match self.arg(idx) {
365
6
            None => Ok(None),
366
49965
            Some(s) => match s.parse() {
367
49961
                Ok(r) => Ok(Some(r)),
368
4
                Err(e) => {
369
4
                    let e: Error = e.into();
370
4
                    Err(e.or_at_pos(Pos::at(s)))
371
                }
372
            },
373
        }
374
49971
    }
375
    /// Try to parse the nth argument (if it exists) into some type
376
    /// that supports FromStr.
377
    ///
378
    /// Return an error if the argument doesn't exist.
379
49963
    pub(crate) fn parse_arg<V: FromStr>(&self, idx: usize) -> Result<V>
380
49963
    where
381
49963
        Error: From<V::Err>,
382
    {
383
49963
        match self.parse_optional_arg(idx) {
384
49957
            Ok(Some(v)) => Ok(v),
385
2
            Ok(None) => Err(EK::MissingArgument.at_pos(self.arg_pos(idx))),
386
4
            Err(e) => Err(e),
387
        }
388
49963
    }
389
    /// Return the number of arguments for this Item
390
89688
    pub(crate) fn n_args(&self) -> usize {
391
89688
        self.args().count()
392
89688
    }
393
    /// Return true iff this Item has an associated object.
394
89013
    pub(crate) fn has_obj(&self) -> bool {
395
89013
        self.object.is_some()
396
89013
    }
397
    /// Return the tag of this item's associated object, if it has one.
398
187
    pub(crate) fn obj_tag(&self) -> Option<&'a str> {
399
187
        self.object.map(|o| o.tag)
400
187
    }
401
    /// Try to decode the base64 contents of this Item's associated object.
402
    ///
403
    /// On success, return the object's tag and decoded contents.
404
21824
    pub(crate) fn obj_raw(&self) -> Result<Option<(&'a str, Vec<u8>)>> {
405
21824
        match self.object {
406
2406
            None => Ok(None),
407
19418
            Some(obj) => {
408
19418
                let decoded = base64_decode_multiline(obj.data)
409
19418
                    .map_err(|_| EK::BadObjectBase64.at_pos(Pos::at(obj.data)))?;
410
19418
                Ok(Some((obj.tag, decoded)))
411
            }
412
        }
413
21824
    }
414
    /// Try to decode the base64 contents of this Item's associated object,
415
    /// and make sure that its tag matches 'want_tag'.
416
19420
    pub(crate) fn obj(&self, want_tag: &str) -> Result<Vec<u8>> {
417
19420
        match self.obj_raw()? {
418
2
            None => Err(EK::MissingObject
419
2
                .with_msg(self.kwd.to_str())
420
2
                .at_pos(self.end_pos())),
421
19418
            Some((tag, decoded)) => {
422
19418
                if tag != want_tag {
423
4
                    Err(EK::WrongObject.at_pos(Pos::at(tag)))
424
                } else {
425
19414
                    Ok(decoded)
426
                }
427
            }
428
        }
429
19420
    }
430
    /// Try to decode the base64 contents of this item's associated object
431
    /// as a given type that implements FromBytes.
432
12663
    pub(crate) fn parse_obj<V: FromBytes>(&self, want_tag: &str) -> Result<V> {
433
12663
        let bytes = self.obj(want_tag)?;
434
        // Unwrap may be safe because above `.obj()` should return an Error if
435
        // wanted tag was not present
436
        #[allow(clippy::unwrap_used)]
437
12663
        let p = Pos::at(self.object.unwrap().data);
438
12663
        V::from_vec(bytes, p).map_err(|e| e.at_pos(p))
439
12663
    }
440
    /// Return the position of this item.
441
    ///
442
    /// This position won't be useful unless it is later contextualized
443
    /// with the containing string.
444
3917
    pub(crate) fn pos(&self) -> Pos {
445
3917
        Pos::at(self.kwd_str)
446
3917
    }
447
    /// Return the position of this Item in a string.
448
    ///
449
    /// Returns None if this item doesn't actually belong to the string.
450
10130
    pub(crate) fn offset_in(&self, s: &str) -> Option<usize> {
451
10130
        crate::util::str::str_offset(s, self.kwd_str)
452
10130
    }
453
    /// Return the position of the n'th argument of this item.
454
    ///
455
    /// If this item does not have a n'th argument, return the
456
    /// position of the end of the final argument.
457
8
    pub(crate) fn arg_pos(&self, n: usize) -> Pos {
458
8
        let args = self.args_as_vec();
459
8
        if n < args.len() {
460
6
            Pos::at(args[n])
461
        } else {
462
2
            self.last_arg_end_pos()
463
        }
464
8
    }
465
    /// Return the position at the end of the last argument.  (This will
466
    /// point to a newline.)
467
847
    fn last_arg_end_pos(&self) -> Pos {
468
847
        Pos::at_end_of(self.args)
469
847
    }
470
    /// Return the position of the end of this object. (This will point to a
471
    /// newline.)
472
1036
    pub(crate) fn end_pos(&self) -> Pos {
473
1036
        match self.object {
474
193
            Some(o) => Pos::at_end_of(o.endline),
475
843
            None => self.last_arg_end_pos(),
476
        }
477
1036
    }
478
    /// If this item occurs within s, return the byte offset
479
    /// immediately after the end of this item.
480
442
    pub(crate) fn offset_after(&self, s: &str) -> Option<usize> {
481
442
        self.end_pos().offset_within(s).map(|nl_pos| nl_pos + 1)
482
442
    }
483

            
484
    /// Return the text of this item, if it originated within `str`,
485
    /// from the start of its keyword up to and including its final newline.
486
    #[allow(dead_code)] // unused when hsdesc not enabled.
487
395
    pub(crate) fn text_within<'b>(&self, s: &'b str) -> Option<&'b str> {
488
395
        let start = self.pos().offset_within(s)?;
489
395
        let end = self.end_pos().offset_within(s)?;
490
395
        s.get(start..=end)
491
395
    }
492
}
493

            
494
/// Represents an Item that might not be present, whose arguments we
495
/// want to inspect.  If the Item is there, this acts like a proxy to the
496
/// item; otherwise, it treats the item as having no arguments.
497
pub(crate) struct MaybeItem<'a, 'b, K: Keyword>(Option<&'a Item<'b, K>>);
498

            
499
// All methods here are as for Item.
500
impl<'a, 'b, K: Keyword> MaybeItem<'a, 'b, K> {
501
    /// Return the position of this item, if it has one.
502
4
    fn pos(&self) -> Pos {
503
4
        match self.0 {
504
4
            Some(item) => item.pos(),
505
            None => Pos::None,
506
        }
507
4
    }
508
    /// Construct a MaybeItem from an Option reference to an item.
509
12327
    pub(crate) fn from_option(opt: Option<&'a Item<'b, K>>) -> Self {
510
12327
        MaybeItem(opt)
511
12327
    }
512

            
513
    /// If this item is present, parse its argument at position `idx`.
514
    /// Treat the absence or malformedness of the argument as an error,
515
    /// but treat the absence of this item as acceptable.
516
    #[cfg(any(test, feature = "routerdesc"))]
517
2252
    pub(crate) fn parse_arg<V: FromStr>(&self, idx: usize) -> Result<Option<V>>
518
2252
    where
519
2252
        Error: From<V::Err>,
520
    {
521
2252
        match self.0 {
522
2250
            Some(item) => match item.parse_arg(idx) {
523
2248
                Ok(v) => Ok(Some(v)),
524
2
                Err(e) => Err(e.or_at_pos(self.pos())),
525
            },
526
2
            None => Ok(None),
527
        }
528
2252
    }
529
    /// If this item is present, return its arguments as a single string.
530
4070
    pub(crate) fn args_as_str(&self) -> Option<&str> {
531
4070
        self.0.map(|item| item.args_as_str())
532
4070
    }
533
    /// If this item is present, parse all of its arguments as a
534
    /// single string.
535
6005
    pub(crate) fn parse_args_as_str<V: FromStr>(&self) -> Result<Option<V>>
536
6005
    where
537
6005
        Error: From<V::Err>,
538
    {
539
6005
        match self.0 {
540
2541
            Some(item) => match item.args_as_str().parse::<V>() {
541
2539
                Ok(v) => Ok(Some(v)),
542
2
                Err(e) => {
543
2
                    let e: Error = e.into();
544
2
                    Err(e.or_at_pos(self.pos()))
545
                }
546
            },
547
3464
            None => Ok(None),
548
        }
549
6005
    }
550
}
551

            
552
/// Extension trait for `Result<Item>` -- makes it convenient to implement
553
/// PauseAt predicates
554
pub(crate) trait ItemResult<K: Keyword> {
555
    /// Return true if this is an ok result with an annotation.
556
    fn is_ok_with_annotation(&self) -> bool;
557
    /// Return true if this is an ok result with a non-annotation.
558
    fn is_ok_with_non_annotation(&self) -> bool;
559
    /// Return true if this is an ok result with the keyword 'k'
560
13130
    fn is_ok_with_kwd(&self, k: K) -> bool {
561
13130
        self.is_ok_with_kwd_in(&[k])
562
13130
    }
563
    /// Return true if this is an ok result with a keyword in the slice 'ks'
564
    fn is_ok_with_kwd_in(&self, ks: &[K]) -> bool;
565
    /// Return true if this is an ok result with a keyword not in the slice 'ks'
566
    fn is_ok_with_kwd_not_in(&self, ks: &[K]) -> bool;
567
    /// Return true if this is an empty-line error.
568
    fn is_empty_line(&self) -> bool;
569
}
570

            
571
impl<'a, K: Keyword> ItemResult<K> for Result<Item<'a, K>> {
572
4530
    fn is_ok_with_annotation(&self) -> bool {
573
4530
        match self {
574
4516
            Ok(item) => item.kwd().is_annotation(),
575
14
            Err(_) => false,
576
        }
577
4530
    }
578
42
    fn is_ok_with_non_annotation(&self) -> bool {
579
42
        match self {
580
38
            Ok(item) => !item.kwd().is_annotation(),
581
4
            Err(_) => false,
582
        }
583
42
    }
584
62548
    fn is_ok_with_kwd_in(&self, ks: &[K]) -> bool {
585
62548
        match self {
586
62481
            Ok(item) => item.has_kwd_in(ks),
587
67
            Err(_) => false,
588
        }
589
62548
    }
590
6884
    fn is_ok_with_kwd_not_in(&self, ks: &[K]) -> bool {
591
6884
        match self {
592
6776
            Ok(item) => !item.has_kwd_in(ks),
593
108
            Err(_) => false,
594
        }
595
6884
    }
596
4524
    fn is_empty_line(&self) -> bool {
597
12
        matches!(
598
12
            self,
599
12
            Err(e) if e.netdoc_error_kind() == crate::err::NetdocErrorKind::EmptyLine
600
        )
601
4524
    }
602
}
603

            
604
/// A peekable cursor into a string that returns Items one by one.
605
///
606
/// This is an [`Iterator`], yielding [`Item`]s.
607
#[derive(Debug)]
608
pub(crate) struct NetDocReader<'a, K: Keyword> {
609
    // TODO: I wish there were some way around having this string
610
    // reference, since we already need one inside NetDocReaderBase.
611
    /// The underlying string being parsed.
612
    s: &'a str,
613
    /// A stream of tokens being parsed by this NetDocReader.
614
    tokens: Peekable<NetDocReaderBase<'a, K>>,
615
}
616

            
617
impl<'a, K: Keyword> NetDocReader<'a, K> {
618
    /// Construct a new NetDocReader to read tokens from `s`.
619
4395
    pub(crate) fn new(s: &'a str) -> Result<Self> {
620
        Ok(NetDocReader {
621
4395
            s,
622
4395
            tokens: NetDocReaderBase::new(s)?.peekable(),
623
        })
624
4395
    }
625
    /// Return a reference to the string used for this NetDocReader.
626
4735
    pub(crate) fn str(&self) -> &'a str {
627
4735
        self.s
628
4735
    }
629
    /// Return a wrapper around the peekable iterator in this
630
    /// NetDocReader that reads tokens until it reaches an element where
631
    /// 'f' is true.
632
11406
    pub(crate) fn pause_at<'f, 'r, F>(
633
11406
        &mut self,
634
11406
        mut f: F,
635
11406
    ) -> itertools::PeekingTakeWhile<
636
11406
        '_,
637
11406
        Self,
638
11406
        impl FnMut(&Result<Item<'a, K>>) -> bool + 'f + use<'a, 'f, F, K>,
639
11406
    >
640
11406
    where
641
11406
        'f: 'r,
642
11406
        F: FnMut(&Result<Item<'a, K>>) -> bool + 'f,
643
11406
        K: 'f,
644
    {
645
79452
        self.peeking_take_while(move |i| !f(i))
646
11406
    }
647

            
648
    /// Return true if there are no more items in this NetDocReader.
649
    // The implementation sadly needs to mutate the inner state, even if it's not *semantically*
650
    // mutated..  We don't want inner mutability just to placate clippy for an internal API.
651
    #[allow(clippy::wrong_self_convention)]
652
    #[allow(dead_code)] // TODO perhaps we should remove this ?
653
    pub(crate) fn is_exhausted(&mut self) -> bool {
654
        self.peek().is_none()
655
    }
656

            
657
    /// Give an error if there are remaining tokens in this NetDocReader.
658
2360
    pub(crate) fn should_be_exhausted(&mut self) -> Result<()> {
659
2360
        match self.peek() {
660
2358
            None => Ok(()),
661
2
            Some(Ok(t)) => Err(EK::UnexpectedToken
662
2
                .with_msg(t.kwd().to_str())
663
2
                .at_pos(t.pos())),
664
            Some(Err(e)) => Err(e.clone()),
665
        }
666
2360
    }
667

            
668
    /// Give an error if there are remaining tokens in this NetDocReader.
669
    ///
670
    /// Like [`should_be_exhausted`](Self::should_be_exhausted),
671
    /// but permit empty lines at the end of the document.
672
    #[cfg(feature = "routerdesc")]
673
2232
    pub(crate) fn should_be_exhausted_but_for_empty_lines(&mut self) -> Result<()> {
674
        use crate::err::NetdocErrorKind as K;
675
2234
        while let Some(Err(e)) = self.peek() {
676
2
            if e.netdoc_error_kind() == K::EmptyLine {
677
2
                let _ignore = self.next();
678
2
            } else {
679
                break;
680
            }
681
        }
682
2232
        self.should_be_exhausted()
683
2232
    }
684

            
685
    /// Return the position from which the underlying reader is about to take
686
    /// the next token.  Use to make sure that the reader is progressing.
687
2485
    pub(crate) fn pos(&mut self) -> Pos {
688
2485
        match self.tokens.peek() {
689
2479
            Some(Ok(tok)) => tok.pos(),
690
2
            Some(Err(e)) => e.pos(),
691
4
            None => Pos::at_end_of(self.s),
692
        }
693
2485
    }
694
}
695

            
696
impl<'a, K: Keyword> Iterator for NetDocReader<'a, K> {
697
    type Item = Result<Item<'a, K>>;
698
91211
    fn next(&mut self) -> Option<Self::Item> {
699
91211
        self.tokens.next()
700
91211
    }
701
}
702

            
703
impl<'a, K: Keyword> PeekableIterator for NetDocReader<'a, K> {
704
103305
    fn peek(&mut self) -> Option<&Self::Item> {
705
103305
        self.tokens.peek()
706
103305
    }
707
}
708

            
709
impl<'a, K: Keyword> itertools::PeekingNext for NetDocReader<'a, K> {
710
81869
    fn peeking_next<F>(&mut self, f: F) -> Option<Self::Item>
711
81869
    where
712
81869
        F: FnOnce(&Self::Item) -> bool,
713
    {
714
81869
        if f(self.peek()?) { self.next() } else { None }
715
81869
    }
716
}
717

            
718
/// Check additional UTF-8 rules that the netdoc metaformat imposes on
719
/// our documents.
720
//
721
// NOTE: We might decide in the future to loosen our rules here
722
// for parsers that handle concatenated documents:
723
// we might want to reject only those documents that contain NULs.
724
// But with luck that will never be necessary.
725
4415
fn validate_utf_8_rules(s: &str) -> Result<&str> {
726
    // No BOM, or mangled BOM, is allowed.
727
4415
    let first_char = s.chars().next();
728
4415
    if [Some('\u{feff}'), Some('\u{fffe}')].contains(&first_char) {
729
6
        return Err(EK::BomMarkerFound.at_pos(Pos::at(s)));
730
4409
    }
731
    // No NUL bytes are allowed.
732
4409
    if let Some(nul_pos) = memchr::memchr(0, s.as_bytes()) {
733
10
        return Err(EK::NulFound.at_pos(Pos::from_byte(nul_pos)));
734
4399
    }
735
4399
    Ok(s)
736
4415
}
737

            
738
#[cfg(test)]
739
mod test {
740
    // @@ begin test lint list maintained by maint/add_warning @@
741
    #![allow(clippy::bool_assert_comparison)]
742
    #![allow(clippy::clone_on_copy)]
743
    #![allow(clippy::dbg_macro)]
744
    #![allow(clippy::mixed_attributes_style)]
745
    #![allow(clippy::print_stderr)]
746
    #![allow(clippy::print_stdout)]
747
    #![allow(clippy::single_char_pattern)]
748
    #![allow(clippy::unwrap_used)]
749
    #![allow(clippy::unchecked_time_subtraction)]
750
    #![allow(clippy::useless_vec)]
751
    #![allow(clippy::needless_pass_by_value)]
752
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
753
    #![allow(clippy::cognitive_complexity)]
754
    use super::*;
755
    use crate::parse::macros::test::Fruit;
756
    use crate::{NetdocErrorKind as EK, Pos, Result};
757

            
758
    #[test]
759
    fn read_simple() {
760
        use Fruit::*;
761

            
762
        let s = "\
763
@tasty very much so
764
opt apple 77
765
banana 60
766
cherry 6
767
-----BEGIN CHERRY SYNOPSIS-----
768
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
769
-----END CHERRY SYNOPSIS-----
770
plum hello there
771
";
772
        let mut r: NetDocReader<'_, Fruit> = NetDocReader::new(s).unwrap();
773

            
774
        assert_eq!(r.str(), s);
775
        assert!(r.should_be_exhausted().is_err()); // it's not exhausted.
776

            
777
        let toks: Result<Vec<_>> = r.by_ref().collect();
778
        assert!(r.should_be_exhausted().is_ok());
779

            
780
        let toks = toks.unwrap();
781
        assert_eq!(toks.len(), 5);
782
        assert_eq!(toks[0].kwd(), ANN_TASTY);
783
        assert_eq!(toks[0].n_args(), 3);
784
        assert_eq!(toks[0].args_as_str(), "very much so");
785
        assert_eq!(toks[0].arg(1), Some("much"));
786
        {
787
            let a: Vec<_> = toks[0].args().collect();
788
            assert_eq!(a, vec!["very", "much", "so"]);
789
        }
790
        assert!(toks[0].parse_arg::<usize>(0).is_err());
791
        assert!(toks[0].parse_arg::<usize>(10).is_err());
792
        assert!(!toks[0].has_obj());
793
        assert_eq!(toks[0].obj_tag(), None);
794

            
795
        assert_eq!(toks[2].pos().within(s), Pos::from_line(3, 1));
796
        assert_eq!(toks[2].arg_pos(0).within(s), Pos::from_line(3, 8));
797
        assert_eq!(toks[2].last_arg_end_pos().within(s), Pos::from_line(3, 10));
798
        assert_eq!(toks[2].end_pos().within(s), Pos::from_line(3, 10));
799

            
800
        assert_eq!(toks[3].kwd(), STONEFRUIT);
801
        assert_eq!(toks[3].kwd_str(), "cherry"); // not cherry/plum!
802
        assert_eq!(toks[3].n_args(), 1);
803
        assert_eq!(toks[3].required_arg(0), Ok("6"));
804
        assert_eq!(toks[3].parse_arg::<usize>(0), Ok(6));
805
        assert_eq!(toks[3].parse_optional_arg::<usize>(0), Ok(Some(6)));
806
        assert_eq!(toks[3].parse_optional_arg::<usize>(3), Ok(None));
807
        assert!(toks[3].has_obj());
808
        assert_eq!(toks[3].obj_tag(), Some("CHERRY SYNOPSIS"));
809
        assert_eq!(
810
            &toks[3].obj("CHERRY SYNOPSIS").unwrap()[..],
811
            "🍒🍒🍒🍒🍒🍒".as_bytes()
812
        );
813
        assert!(toks[3].obj("PLUOT SYNOPSIS").is_err());
814
        // this "end-pos" value is questionable!
815
        assert_eq!(toks[3].end_pos().within(s), Pos::from_line(7, 30));
816
    }
817

            
818
    #[test]
819
    fn test_badtoks() {
820
        use Fruit::*;
821

            
822
        let s = "\
823
-foobar 9090
824
apple 3.14159
825
$hello
826
unrecognized 127.0.0.1 foo
827
plum
828
-----BEGIN WHATEVER-----
829
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
830
-----END SOMETHING ELSE-----
831
orange
832
orange
833
-----BEGIN WHATEVER-----
834
not! base64!
835
-----END WHATEVER-----
836
guava paste
837
opt @annotation
838
orange
839
-----BEGIN LOBSTER
840
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
841
-----END SOMETHING ELSE-----
842
orange
843
-----BEGIN !!!!!!-----
844
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
845
-----END !!!!!!-----
846
cherry
847
-----BEGIN CHERRY SYNOPSIS-----
848
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
849
-----END CHERRY SYNOPSIS
850

            
851
truncated line";
852

            
853
        let r: NetDocReader<'_, Fruit> = NetDocReader::new(s).unwrap();
854
        let toks: Vec<_> = r.collect();
855

            
856
        assert!(toks[0].is_err());
857
        assert_eq!(
858
            toks[0].as_ref().err().unwrap(),
859
            &EK::BadKeyword.at_pos(Pos::from_line(1, 1))
860
        );
861

            
862
        assert!(toks[1].is_ok());
863
        assert!(toks[1].is_ok_with_non_annotation());
864
        assert!(!toks[1].is_ok_with_annotation());
865
        assert!(toks[1].is_ok_with_kwd_in(&[APPLE, ORANGE]));
866
        assert!(toks[1].is_ok_with_kwd_not_in(&[ORANGE, UNRECOGNIZED]));
867
        let t = toks[1].as_ref().unwrap();
868
        assert_eq!(t.kwd(), APPLE);
869
        assert_eq!(t.arg(0), Some("3.14159"));
870

            
871
        assert!(toks[2].is_err());
872
        assert!(!toks[2].is_ok_with_non_annotation());
873
        assert!(!toks[2].is_ok_with_annotation());
874
        assert!(!toks[2].is_ok_with_kwd_in(&[APPLE, ORANGE]));
875
        assert!(!toks[2].is_ok_with_kwd_not_in(&[ORANGE, UNRECOGNIZED]));
876
        assert_eq!(
877
            toks[2].as_ref().err().unwrap(),
878
            &EK::BadKeyword.at_pos(Pos::from_line(3, 1))
879
        );
880

            
881
        assert!(toks[3].is_ok());
882
        let t = toks[3].as_ref().unwrap();
883
        assert_eq!(t.kwd(), UNRECOGNIZED);
884
        assert_eq!(t.arg(1), Some("foo"));
885

            
886
        assert!(toks[4].is_err());
887
        assert_eq!(
888
            toks[4].as_ref().err().unwrap(),
889
            &EK::BadObjectMismatchedTag.at_pos(Pos::from_line(8, 1))
890
        );
891

            
892
        assert!(toks[5].is_ok());
893
        let t = toks[5].as_ref().unwrap();
894
        assert_eq!(t.kwd(), ORANGE);
895
        assert_eq!(t.args_as_str(), "");
896

            
897
        // This blob counts as two errors: a bad base64 blob, and
898
        // then an end line.
899
        assert!(toks[6].is_err());
900
        assert_eq!(
901
            toks[6].as_ref().err().unwrap(),
902
            &EK::BadObjectBase64.at_pos(Pos::from_line(12, 1))
903
        );
904

            
905
        assert!(toks[7].is_err());
906
        assert_eq!(
907
            toks[7].as_ref().err().unwrap(),
908
            &EK::BadKeyword.at_pos(Pos::from_line(13, 1))
909
        );
910

            
911
        assert!(toks[8].is_ok());
912
        let t = toks[8].as_ref().unwrap();
913
        assert_eq!(t.kwd(), GUAVA);
914

            
915
        // this is an error because you can't use opt with annotations.
916
        assert!(toks[9].is_err());
917
        assert_eq!(
918
            toks[9].as_ref().err().unwrap(),
919
            &EK::BadKeyword.at_pos(Pos::from_line(15, 1))
920
        );
921

            
922
        // this looks like a few errors.
923
        assert!(toks[10].is_err());
924
        assert_eq!(
925
            toks[10].as_ref().err().unwrap(),
926
            &EK::BadObjectBeginTag.at_pos(Pos::from_line(17, 1))
927
        );
928
        assert!(toks[11].is_err());
929
        assert_eq!(
930
            toks[11].as_ref().err().unwrap(),
931
            &EK::BadKeyword.at_pos(Pos::from_line(18, 1))
932
        );
933
        assert!(toks[12].is_err());
934
        assert_eq!(
935
            toks[12].as_ref().err().unwrap(),
936
            &EK::BadKeyword.at_pos(Pos::from_line(19, 1))
937
        );
938

            
939
        // so does this.
940
        assert!(toks[13].is_err());
941
        assert_eq!(
942
            toks[13].as_ref().err().unwrap(),
943
            &EK::BadObjectBeginTag.at_pos(Pos::from_line(21, 1))
944
        );
945
        assert!(toks[14].is_err());
946
        assert_eq!(
947
            toks[14].as_ref().err().unwrap(),
948
            &EK::BadKeyword.at_pos(Pos::from_line(22, 1))
949
        );
950
        assert!(toks[15].is_err());
951
        assert_eq!(
952
            toks[15].as_ref().err().unwrap(),
953
            &EK::BadKeyword.at_pos(Pos::from_line(23, 1))
954
        );
955

            
956
        // not this.
957
        assert!(toks[16].is_err());
958
        assert_eq!(
959
            toks[16].as_ref().err().unwrap(),
960
            &EK::BadObjectEndTag.at_pos(Pos::from_line(27, 1))
961
        );
962

            
963
        assert!(toks[17].is_err());
964
        assert_eq!(
965
            toks[17].as_ref().err().unwrap(),
966
            &EK::EmptyLine.at_pos(Pos::from_line(28, 1))
967
        );
968

            
969
        assert!(toks[18].is_err());
970
        assert_eq!(
971
            toks[18].as_ref().err().unwrap(),
972
            &EK::TruncatedLine.at_pos(Pos::from_line(29, 15))
973
        );
974
    }
975

            
976
    #[test]
977
    fn test_leading_space_forbidden() {
978
        // We need to make sure that items with a leading space aren't accepted:
979
        // the spec forbids it, and it can provide a vector for inflating the size
980
        // of downloaded hsdescs (see prop360).
981

            
982
        // Try a simple item with a space at the front.
983
        let s = "    guava space\n";
984
        let r: NetDocReader<'_, Fruit> = NetDocReader::new(s).unwrap();
985
        let toks: Vec<_> = r.collect();
986

            
987
        // No space allowed at the start of a line.
988
        assert_eq!(
989
            toks[0].as_ref().err().unwrap(),
990
            &EK::BadKeyword.at_pos(Pos::from_line(1, 1))
991
        );
992

            
993
        // Try an item with an object, inserting space at the start of each ine in turn.
994
        let s = "cherry
995
-----BEGIN WHATEVER-----
996
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
997
-----END WHATEVER-----
998
";
999

            
        let orig_lines = s
            .split_terminator('\n')
            .map(str::to_string)
            .collect::<Vec<_>>();
        assert_eq!(orig_lines.len(), 4);
        let expected_kinds = [
            EK::BadKeyword,
            EK::BadKeyword,
            EK::BadObjectBase64,
            EK::BadObjectBase64,
        ];
        for pos in 0..orig_lines.len() {
            let mut lines = orig_lines.clone();
            lines[pos] = format!(" {}", lines[pos]);
            let joined = format!("{}\n", lines.join("\n"));
            let r: NetDocReader<'_, Fruit> = NetDocReader::new(&joined).unwrap();
            let toks: Result<Vec<_>> = r.collect();
            assert_eq!(toks.unwrap_err().netdoc_error_kind(), expected_kinds[pos]);
        }
    }
    #[test]
    fn test_validate_strings() {
        use validate_utf_8_rules as v;
        assert_eq!(v(""), Ok(""));
        assert_eq!(v("hello world"), Ok("hello world"));
        // We don't have to test a lot more valid cases, since this function is called before
        // parsing any string.
        for s in ["\u{feff}", "\u{feff}hello world", "\u{fffe}hello world"] {
            let e = v(s).unwrap_err();
            assert_eq!(e.netdoc_error_kind(), EK::BomMarkerFound);
            assert_eq!(e.pos().offset_within(s), Some(0));
        }
        for s in [
            "\0hello world",
            "\0",
            "\0\0\0",
            "hello\0world",
            "hello world\0",
        ] {
            let e = v(s).unwrap_err();
            assert_eq!(e.netdoc_error_kind(), EK::NulFound);
            let nul_pos = e.pos().offset_within(s).unwrap();
            assert_eq!(s.as_bytes()[nul_pos], 0);
        }
    }
    fn single_fruit(s: &str) -> Item<'_, Fruit> {
        NetDocReader::<Fruit>::new(s)
            .unwrap()
            .next()
            .unwrap()
            .unwrap()
    }
    #[test]
    fn end_of_item() {
        let s = "guava friends 123   \n";
        let item = single_fruit(s);
        assert_eq!(
            item.end_pos().within(s),
            Pos::from_byte(s.find('\n').unwrap()).within(s)
        );
        let s = "cherry
-----BEGIN WHATEVER-----
8J+NkvCfjZLwn42S8J+NkvCfjZLwn42S
-----END WHATEVER-----\n";
        let item = single_fruit(s);
        dbg!(&item);
        assert_eq!(
            item.end_pos().within(s),
            Pos::from_byte(s.rfind('\n').unwrap()).within(s)
        );
    }
}