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
    #[cfg(feature = "hs-service")]
28
    pub(crate) const BASE64_PEM_MAX_LINE: usize = 64;
29
}
30

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

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

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

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

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

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

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

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

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

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

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

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

            
280
167910
    if s.is_empty() {
281
        return false;
282
167910
    }
283
167910
    if anno_ok && s.starts_with('@') {
284
30
        s = &s[1..];
285
167880
    }
286
167910
    if s.starts_with('-') {
287
8
        return false;
288
167902
    }
289
167902
    s.chars().all(kwd_char_ok)
290
167910
}
291

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

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

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

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

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

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

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

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

            
568
impl<'a, K: Keyword> ItemResult<K> for Result<Item<'a, K>> {
569
4026
    fn is_ok_with_annotation(&self) -> bool {
570
4026
        match self {
571
4012
            Ok(item) => item.kwd().is_annotation(),
572
14
            Err(_) => false,
573
        }
574
4026
    }
575
42
    fn is_ok_with_non_annotation(&self) -> bool {
576
42
        match self {
577
38
            Ok(item) => !item.kwd().is_annotation(),
578
4
            Err(_) => false,
579
        }
580
42
    }
581
46690
    fn is_ok_with_kwd_in(&self, ks: &[K]) -> bool {
582
46690
        match self {
583
46674
            Ok(item) => item.has_kwd_in(ks),
584
16
            Err(_) => false,
585
        }
586
46690
    }
587
6116
    fn is_ok_with_kwd_not_in(&self, ks: &[K]) -> bool {
588
6116
        match self {
589
6020
            Ok(item) => !item.has_kwd_in(ks),
590
96
            Err(_) => false,
591
        }
592
6116
    }
593
4020
    fn is_empty_line(&self) -> bool {
594
12
        matches!(
595
12
            self,
596
12
            Err(e) if e.netdoc_error_kind() == crate::err::NetdocErrorKind::EmptyLine
597
        )
598
4020
    }
599
}
600

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

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

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

            
650
    /// Give an error if there are remaining tokens in this NetDocReader.
651
2096
    pub(crate) fn should_be_exhausted(&mut self) -> Result<()> {
652
2096
        match self.peek() {
653
2094
            None => Ok(()),
654
2
            Some(Ok(t)) => Err(EK::UnexpectedToken
655
2
                .with_msg(t.kwd().to_str())
656
2
                .at_pos(t.pos())),
657
            Some(Err(e)) => Err(e.clone()),
658
        }
659
2096
    }
660

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

            
678
    /// Return the position from which the underlying reader is about to take
679
    /// the next token.  Use to make sure that the reader is progressing.
680
507
    pub(crate) fn pos(&mut self) -> Pos {
681
507
        match self.tokens.peek() {
682
501
            Some(Ok(tok)) => tok.pos(),
683
2
            Some(Err(e)) => e.pos(),
684
4
            None => Pos::at_end_of(self.s),
685
        }
686
507
    }
687
}
688

            
689
impl<'a, K: Keyword> Iterator for NetDocReader<'a, K> {
690
    type Item = Result<Item<'a, K>>;
691
60421
    fn next(&mut self) -> Option<Self::Item> {
692
60421
        self.tokens.next()
693
60421
    }
694
}
695

            
696
impl<'a, K: Keyword> PeekableIterator for NetDocReader<'a, K> {
697
65881
    fn peek(&mut self) -> Option<&Self::Item> {
698
65881
        self.tokens.peek()
699
65881
    }
700
}
701

            
702
impl<'a, K: Keyword> itertools::PeekingNext for NetDocReader<'a, K> {
703
50008
    fn peeking_next<F>(&mut self, f: F) -> Option<Self::Item>
704
50008
    where
705
50008
        F: FnOnce(&Self::Item) -> bool,
706
50008
    {
707
50008
        if f(self.peek()?) {
708
43290
            self.next()
709
        } else {
710
4571
            None
711
        }
712
50008
    }
713
}
714

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

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

            
755
    #[test]
756
    fn read_simple() {
757
        use Fruit::*;
758

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

            
771
        assert_eq!(r.str(), s);
772
        assert!(r.should_be_exhausted().is_err()); // it's not exhausted.
773

            
774
        let toks: Result<Vec<_>> = r.by_ref().collect();
775
        assert!(r.should_be_exhausted().is_ok());
776

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

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

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

            
815
    #[test]
816
    fn test_badtoks() {
817
        use Fruit::*;
818

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

            
848
truncated line";
849

            
850
        let r: NetDocReader<'_, Fruit> = NetDocReader::new(s).unwrap();
851
        let toks: Vec<_> = r.collect();
852

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

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

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

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

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

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

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

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

            
908
        assert!(toks[8].is_ok());
909
        let t = toks[8].as_ref().unwrap();
910
        assert_eq!(t.kwd(), GUAVA);
911

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

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

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

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

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

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

            
973
    #[test]
974
    fn test_validate_strings() {
975
        use validate_utf_8_rules as v;
976
        assert_eq!(v(""), Ok(""));
977
        assert_eq!(v("hello world"), Ok("hello world"));
978
        // We don't have to test a lot more valid cases, since this function is called before
979
        // parsing any string.
980

            
981
        for s in ["\u{feff}", "\u{feff}hello world", "\u{fffe}hello world"] {
982
            let e = v(s).unwrap_err();
983
            assert_eq!(e.netdoc_error_kind(), EK::BomMarkerFound);
984
            assert_eq!(e.pos().offset_within(s), Some(0));
985
        }
986

            
987
        for s in [
988
            "\0hello world",
989
            "\0",
990
            "\0\0\0",
991
            "hello\0world",
992
            "hello world\0",
993
        ] {
994
            let e = v(s).unwrap_err();
995
            assert_eq!(e.netdoc_error_kind(), EK::NulFound);
996
            let nul_pos = e.pos().offset_within(s).unwrap();
997
            assert_eq!(s.as_bytes()[nul_pos], 0);
998
        }
999
    }
}