1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
use std::{fmt, hash::Hash, ops::Deref, str::FromStr};

use camino::Utf8Path;

const TSPECIALS: &str = "()<>@,;:\\\"/[]?={} \t";
const PSAFE: &str = "$-_.+~";
const PEXTRA: &str = "!*'(),";

fn is_rfc1945_token(c: char) -> bool {
    c.is_ascii() && !c.is_ascii_control() || TSPECIALS.contains(c)
}
fn is_rfc1945_path(c: char) -> bool {
    c == '/' || c == '%' || c.is_ascii_alphanumeric() || PSAFE.contains(c) || PEXTRA.contains(c)
}
#[derive(Debug)]
pub enum UserAgentParseError {
    EmptyUserAgent,

    InvalidUserAgentEncoding,

    InvalidCharacters,
}

impl fmt::Display for UserAgentParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UserAgentParseError::EmptyUserAgent => write!(f, "User agent must be non-empty"),
            UserAgentParseError::InvalidUserAgentEncoding => {
                write!(f, "User agent must be a valid ascii")
            }
            UserAgentParseError::InvalidCharacters => {
                write!(f, "User agent contains invalid characters")
            }
        }
    }
}

impl std::error::Error for UserAgentParseError {}

#[derive(Debug, Clone)]
pub struct UserAgent(Option<Box<str>>);

impl UserAgent {
    pub const ANY: UserAgent = UserAgent(None);

    fn is_wildcard(&self) -> bool {
        self.0.is_none()
    }
}

impl PartialEq for UserAgent {
    fn eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (Some(a), Some(b)) => a == b,
            (None, _) => true,
            (_, None) => true,
        }
    }
}

impl Eq for UserAgent {}

impl Hash for UserAgent {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match &self.0 {
            Some(agent) => agent.hash(state),
            None => "*".hash(state),
        }
    }
}

impl FromStr for UserAgent {
    type Err = UserAgentParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "*" {
            return Ok(UserAgent(None));
        }

        if s.is_empty() {
            return Err(UserAgentParseError::EmptyUserAgent);
        }

        if !s.is_ascii() {
            return Err(UserAgentParseError::InvalidUserAgentEncoding);
        }

        if !s.chars().all(is_rfc1945_token) {
            return Err(UserAgentParseError::InvalidCharacters);
        }

        Ok(UserAgent(Some(s.into())))
    }
}

impl fmt::Display for UserAgent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Some(agent) => write!(f, "{}", agent),
            None => write!(f, "*"),
        }
    }
}

#[derive(Debug)]
pub enum DirectivePathParseError {
    InvalidPathEncoding,

    InvalidCharacters,
}

impl fmt::Display for DirectivePathParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DirectivePathParseError::InvalidPathEncoding => {
                write!(f, "Path must be a valid ascii")
            }
            DirectivePathParseError::InvalidCharacters => {
                write!(f, "Path contains invalid characters")
            }
        }
    }
}

impl std::error::Error for DirectivePathParseError {}

#[derive(Debug, Clone, Hash)]
enum PathInner {
    None,
    Any,
    Path(Box<Utf8Path>),
    Robots,
}

#[derive(Debug, Clone)]
pub struct DirectivePath(PathInner);

impl DirectivePath {
    /// A directive path which matches all possible paths.
    pub const ANY: DirectivePath = DirectivePath(PathInner::Any);

    /// A directive path which matches no paths
    pub const NONE: DirectivePath = DirectivePath(PathInner::None);

    /// Matches just `/robots.txt`
    pub const ROBOTS: DirectivePath = DirectivePath(PathInner::Robots);

    /// Check if a path matches this directive path.
    pub fn matches(&self, path: &str) -> bool {
        match &self.0 {
            PathInner::None => false,
            PathInner::Any => true,
            PathInner::Path(pattern) => {
                let path = Utf8Path::new(path);
                path.starts_with(pattern.deref())
            }
            PathInner::Robots => {
                let path = Utf8Path::new(path);
                path == Utf8Path::new("/robots.txt")
            }
        }
    }

    pub fn is_none(&self) -> bool {
        matches!(self.0, PathInner::None)
    }

    pub fn is_any(&self) -> bool {
        matches!(self.0, PathInner::Any)
    }

    pub fn is_robots(&self) -> bool {
        matches!(self.0, PathInner::Robots)
    }
}

impl fmt::Display for DirectivePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            PathInner::None => write!(f, ""),
            PathInner::Any => write!(f, "/"),
            PathInner::Path(path) => write!(f, "{}", path.as_str().trim_end_matches('/')),
            PathInner::Robots => write!(f, "/robots.txt"),
        }
    }
}

impl PartialEq for DirectivePath {
    fn eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (PathInner::None, _) | (_, PathInner::None) => false,
            (PathInner::Any, _) | (_, PathInner::Any) => true,
            (PathInner::Path(a), PathInner::Path(b)) => a == b,
            (PathInner::Robots, PathInner::Robots) => true,
            _ => false,
        }
    }
}

impl FromStr for DirectivePath {
    type Err = DirectivePathParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let path = s.trim();

        if path == "/" {
            return Ok(DirectivePath::ANY);
        }

        if path == "/robots.txt" || path == "robots.txt" {
            return Ok(DirectivePath::ROBOTS);
        }

        if path.is_empty() {
            return Ok(DirectivePath::NONE);
        }

        if !path.is_ascii() {
            return Err(DirectivePathParseError::InvalidCharacters);
        }

        if !path.starts_with('/') {
            return Err(DirectivePathParseError::InvalidCharacters);
        }

        if !path.chars().all(is_rfc1945_path) {
            return Err(DirectivePathParseError::InvalidPathEncoding);
        }

        Ok(DirectivePath(PathInner::Path(
            (path.to_string() + "/").as_str().into(),
        )))
    }
}

#[derive(Debug)]
pub enum DirectiveParseError {
    InvalidRule,
    InvalidPath(DirectivePathParseError),
}

impl fmt::Display for DirectiveParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DirectiveParseError::InvalidRule => write!(f, "Directive rule is invalid"),
            DirectiveParseError::InvalidPath(err) => write!(f, "{}", err),
        }
    }
}

impl From<DirectivePathParseError> for DirectiveParseError {
    fn from(err: DirectivePathParseError) -> Self {
        DirectiveParseError::InvalidPath(err)
    }
}

impl std::error::Error for DirectiveParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            DirectiveParseError::InvalidRule => None,
            DirectiveParseError::InvalidPath(err) => Some(err),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DirectiveType {
    Allow,
    Disallow,
    Extension(Box<str>),
}

impl fmt::Display for DirectiveType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DirectiveType::Allow => write!(f, "Allow"),
            DirectiveType::Disallow => write!(f, "Disallow"),
            DirectiveType::Extension(extension) => write!(f, "{}", extension),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Directive {
    path: DirectivePath,
    rule: DirectiveType,
}

impl FromStr for Directive {
    type Err = DirectiveParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let d = s.split('#').next().unwrap_or("").trim();

        let mut parts = d.splitn(2, ':');
        let rule = match parts.next() {
            Some("Allow") => DirectiveType::Allow,
            Some("Disallow") => DirectiveType::Disallow,
            Some(extension) if extension.chars().all(is_rfc1945_token) => {
                DirectiveType::Extension(extension.into())
            }
            _ => return Err(DirectiveParseError::InvalidRule),
        };

        let path: DirectivePath = match parts.next() {
            Some(path) => path.parse()?,
            None => DirectivePath::NONE,
        };

        Ok(Directive { path, rule })
    }
}

impl fmt::Display for Directive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_none() {
            // Doesn't print trailing whitespace.
            write!(f, "{}:", self.rule)
        } else {
            write!(f, "{}: {}", self.rule, self.path)
        }
    }
}

#[derive(Debug)]
pub enum RobotParseError {
    InvalidUserAgent(UserAgentParseError, String),
    InvalidDirective(DirectiveParseError, String),
}

impl fmt::Display for RobotParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RobotParseError::InvalidUserAgent(err, agent) => {
                write!(f, "{}: {}", err, agent)
            }
            RobotParseError::InvalidDirective(err, directive) => {
                write!(f, "{}: {}", err, directive)
            }
        }
    }
}

impl std::error::Error for RobotParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            RobotParseError::InvalidUserAgent(err, _) => Some(err),
            RobotParseError::InvalidDirective(err, _) => Some(err),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct RobotAgent {
    agents: Vec<UserAgent>,
    directives: Vec<Directive>,
}

impl fmt::Display for RobotAgent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for agent in &self.agents {
            writeln!(f, "User-agent: {}", agent)?;
        }
        for directive in &self.directives {
            writeln!(f, "{}", directive)?;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct Robots {
    /// Wildcard directives
    ///
    /// Stored separately because they should only be applied when
    /// no other agent matches.
    pub wildcard: Vec<Directive>,

    /// Agents
    pub agents: Vec<RobotAgent>,
}

impl Robots {
    fn push(&mut self, mut agent: RobotAgent) {
        if agent.agents.iter().any(|a| a.is_wildcard()) {
            if self.wildcard.is_empty() {
                self.wildcard.extend(agent.directives.iter().cloned());
            }
            agent.agents.retain(|a| !a.is_wildcard());

            if !agent.agents.is_empty() {
                self.agents.push(agent);
            }
        } else {
            self.agents.push(agent);
        }
    }
}

impl FromStr for Robots {
    type Err = RobotParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut robots = Robots::default();

        let mut agents = Vec::new();
        let mut directives = Vec::new();

        for line in s.lines() {
            let line = line.split('#').next().unwrap_or("").trim();

            if line.is_empty() {
                continue;
            }

            // Case-insensitive parse of the user-agent line
            if line.to_ascii_lowercase().starts_with("user-agent") {
                if !directives.is_empty() {
                    robots.push(RobotAgent {
                        agents: agents.clone(),
                        directives: directives.clone(),
                    });
                    agents.clear();
                    directives.clear();
                }

                let agent = line.split_once(':').map(|x| x.1).unwrap_or("").trim();
                agents.push(
                    agent
                        .parse()
                        .map_err(|err| RobotParseError::InvalidUserAgent(err, agent.to_string()))?,
                );
            } else {
                directives.push(
                    line.parse()
                        .map_err(|err| RobotParseError::InvalidDirective(err, line.to_string()))?,
                );
            }
        }

        if !(agents.is_empty() && directives.is_empty()) {
            robots.push(RobotAgent {
                agents: agents.clone(),
                directives: directives.clone(),
            });
        }

        Ok(robots)
    }
}

impl fmt::Display for Robots {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some((last, remainder)) = self.agents.split_last() {
            for agent in remainder {
                writeln!(f, "{}", agent)?;
            }

            write!(f, "{}", last)?;
        };

        if !self.wildcard.is_empty() {
            if !self.agents.is_empty() {
                writeln!(f)?;
            }
            writeln!(f, "User-agent: *")?;
            for directive in &self.wildcard {
                writeln!(f, "{}", directive)?;
            }
        }
        Ok(())
    }
}

impl Robots {
    /// Create a new robots.txt with a wildcard directive that disallows everything.
    pub fn deny() -> Self {
        Self {
            wildcard: vec![Directive {
                path: DirectivePath::ANY,
                rule: DirectiveType::Disallow,
            }],
            agents: Vec::new(),
        }
    }

    /// Create a new robots.txt with a wildcard directive that allows everything.
    pub fn allow() -> Self {
        Self {
            wildcard: vec![Directive {
                path: DirectivePath::ANY,
                rule: DirectiveType::Allow,
            }],
            agents: Vec::new(),
        }
    }

    pub fn is_allowed(&self, user_agent: &UserAgent, path: &str) -> bool {
        // robots.txt must be always allowed.
        if DirectivePath::ROBOTS.matches(path) {
            return true;
        }

        for agent in &self.agents {
            // Check if the User-Agent matches.
            if agent.agents.iter().any(|a| a == user_agent) {
                // Check all directives for the matched User-Agent.
                for directive in &agent.directives {
                    if directive.path.matches(path) {
                        match directive.rule {
                            DirectiveType::Allow => return true,
                            DirectiveType::Disallow => return false,
                            DirectiveType::Extension(_) => {}
                        }
                    }
                }

                // Checked all the rules for the matched User-Agent, so we can stop.
                return true;
            }
        }

        for directive in &self.wildcard {
            if directive.path.matches(path) {
                match directive.rule {
                    DirectiveType::Allow => return true,
                    DirectiveType::Disallow => return false,
                    DirectiveType::Extension(_) => {}
                }
            }
        }

        // By default, all pages are allowed.
        true
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use indoc::indoc;

    #[test]
    fn user_agent() {
        let ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
        let ua = ua.parse::<UserAgent>().unwrap();
        assert_eq!(ua, UserAgent::ANY);
        assert_ne!(ua, "Mozilla/5.0".parse().unwrap());

        let ua = "excite".parse::<UserAgent>().unwrap();
        assert_ne!(&"googlebot".parse::<UserAgent>().unwrap(), &ua);
        let ua = "*".parse::<UserAgent>().unwrap();
        assert_eq!(&"googlebot".parse::<UserAgent>().unwrap(), &ua);
    }

    #[test]
    fn directive_path() {
        let path = "/foo/bar".parse::<DirectivePath>().unwrap();
        assert!(path.matches("/foo/bar/baz"));
        assert!(!path.matches("/foo"));

        let path = DirectivePath::ANY;
        assert!(path.matches("/foo/bar/baz"));
        assert!(path.matches("/foo"));

        let path = DirectivePath::NONE;
        assert!(!path.matches("/foo/bar/baz"));
        assert!(!path.matches("/foo"));
        assert!(!path.matches(""));
    }

    #[test]
    fn directive() {
        let directive = "Allow: /foo/bar".parse::<Directive>().unwrap();
        assert_eq!(directive.rule, DirectiveType::Allow);
        assert!(matches!(directive.path, DirectivePath(PathInner::Path(_))));
        assert!(directive.path.matches("/foo/bar/baz"));
        assert!(!directive.path.matches("/foo"));

        let directive = "Disallow: /foo/bar".parse::<Directive>().unwrap();
        assert_eq!(directive.rule, DirectiveType::Disallow);
        assert!(directive.path.matches("/foo/bar/baz"));
        assert!(!directive.path.matches("/foo"));

        let directive = "Allow: /foo/bar".parse::<Directive>().unwrap();
        assert_eq!(directive.rule, DirectiveType::Allow);
        assert!(directive.path.matches("/foo/bar/baz"));
        assert!(!directive.path.matches("/foo"));

        let directive = "Allow:".parse::<Directive>().unwrap();
        assert_eq!(directive.rule, DirectiveType::Allow);
        assert!(!directive.path.matches("/foo/bar/baz"));
        assert!(!directive.path.matches("/foo"));

        let directive = "Allow: /".parse::<Directive>().unwrap();
        assert_eq!(directive.rule, DirectiveType::Allow);
        assert!(directive.path.matches("/foo/bar/baz"));
        assert!(directive.path.matches("/foo"));
    }

    #[test]
    fn robot_txt() {
        let example = indoc! {
            r#"
      # /robots.txt for http://www.fict.org/
      # comments to webmaster@fict.org

      User-agent: unhipbot
      Disallow: /

      User-agent: webcrawler
      User-agent: excite
      Disallow:

      User-agent: *
      Disallow: /org/plans.html
      Allow: /org/
      Allow: /serv
      Allow: /~mak
      Disallow: /
            "#
        }
        .parse::<Robots>()
        .unwrap();

        assert!(!example.is_allowed(&"unhipbot".parse().unwrap(), "/org/plans.html"));
        assert!(example.is_allowed(&"unhipbot".parse().unwrap(), "/robots.txt"));

        assert!(example.is_allowed(&"webcrawler".parse().unwrap(), "/org/plans.html"));
        assert!(DirectivePath::ANY.matches("/org/plans.html"));
        assert!(example.is_allowed(&"excite".parse().unwrap(), "/org/plans.html"));

        assert!(example.is_allowed(&"googlebot".parse().unwrap(), "/org/about.html"));
        assert!(!example.is_allowed(&"googlebot".parse().unwrap(), "/org/plans.html"));
    }

    #[test]
    fn default_deny() {
        let robots = Robots::deny();
        assert!(!robots.is_allowed(&"googlebot".parse().unwrap(), "/"));
        assert!(!robots.is_allowed(&"googlebot".parse().unwrap(), "/foo"));
        assert!(!robots.is_allowed(&"googlebot".parse().unwrap(), "/foo/bar"));
        assert!(robots.is_allowed(&"googlebot".parse().unwrap(), "/robots.txt"));

        let expected = indoc! {
            r#"
            User-agent: *
            Disallow: /
            "#
        };

        assert_eq!(robots.to_string().trim(), expected.trim());
    }

    macro_rules! test_format {
        {$doc:tt} => {
            let expected = indoc! {
                $doc
            };

            let robots: Robots = expected.parse().unwrap();

            assert_eq!(robots.to_string(), expected);
        };
    }

    #[test]
    fn format_path() {
        test_format! {
            r#"User-agent: *
            Disallow: /foo/bar
            Allow: /hello
            "#
        };
    }

    #[test]
    fn format_blank_last() {
        test_format! {
            r#"User-agent: sus
            Allow: /boobytrap
            Disallow: /

            User-agent: cool
            Disallow: /secret
            Disallow:
            "#
        };
    }

    #[test]
    fn format_wildcard() {
        test_format! {
            r#"User-agent: sus
            Disallow: /

            User-agent: cool
            Allow:

            User-agent: *
            Disallow: /foo/bar
            Allow: /hello
            "#
        };
    }
}