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
use serde_derive::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Rule<'a> {
    Allow(&'a str),
    Disallow(&'a str),
}

impl<'a> Rule<'a> {
    fn inner(&self) -> &str {
        match self {
            Rule::Allow(inner) => inner,
            Rule::Disallow(inner) => inner,
        }
    }
}

#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
enum Edge {
    MatchChar(char),
    MatchAny,
    MatchEow,
}

#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
struct Transition(Edge, usize);

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
enum State {
    Allow,
    Disallow,
    Intermediate,
}

/// A Cylon is a DFA that recognizes rules from a compiled robots.txt
/// file. By providing it a URL path, it can decide whether or not
/// the robots file that compiled it allows or disallows that path in
/// roughly O(n) time, where n is the length of the path.
#[derive(Debug, Serialize, Deserialize)]
pub struct Cylon {
    states: Vec<State>,
    transitions: Vec<Vec<Transition>>,
}

impl Cylon {
    /// Match whether the rules allow or disallow the target path.
    pub fn allow(&self, path: &str) -> bool {
        let mut state = path.chars().fold(2, |state, path_char| {
            let t = &self.transitions[state];
            t.iter()
                .rev()
                // Pick the last transition to always prioritize MatchChar
                // over MatchAny (which will always be the first transition.)
                .find(|transition| match transition {
                    Transition(Edge::MatchAny, ..) => true,
                    Transition(Edge::MatchEow, ..) => false,
                    Transition(Edge::MatchChar(edge_char), ..) => *edge_char == path_char,
                })
                .map(|Transition(.., next_state)| *next_state)
                // We are guaranteed at least one matching state because of
                // the way the DFA is constructed.
                .unwrap()
        });

        // Follow the EoW transition, if necessary
        let t = &self.transitions[state];
        state = t
            .iter()
            .rev()
            .find(|transition| match transition {
                Transition(Edge::MatchEow, ..) => true,
                Transition(Edge::MatchAny, ..) => true,
                _ => false,
            })
            .map(|Transition(.., next_state)| *next_state)
            .unwrap_or(state);

        match self.states[state] {
            State::Allow => true,
            State::Disallow => false,
            // Intermediate states are not preserved in the DFA
            State::Intermediate => unreachable!(),
        }
    }

    /// Compile a machine from a list of rules.
    pub fn compile(mut rules: Vec<Rule>) -> Self {
        // This algorithm constructs a DFA by doing BFS over the prefix tree of
        // paths in the provided list of rules. However, for performance reasons
        // it does not actually build a tree structure. (Vecs have better
        // cache-locality by avoiding random memory access.)

        let mut transitions: Vec<Vec<Transition>> = vec![
            vec![Transition(Edge::MatchAny, 0)],
            vec![Transition(Edge::MatchAny, 1)],
        ];
        let mut states: Vec<State> = vec![State::Allow, State::Disallow];

        rules.sort_by(|a, b| Ord::cmp(a.inner(), b.inner()));

        let mut queue = vec![("", 0, 0, State::Intermediate)];
        while !queue.is_empty() {
            // parent_prefix is the "parent node" in the prefix tree. We are
            // going to visit its children by filtering from the list of
            // paths only the paths that start with the parent_prefix.
            // wildcard_state is a node to jump to when an unmatched character
            // is encountered. This is usually a node higher up in the tree
            // that can match any character legally, but is also a prefix
            // (read: ancestor) of the current node.
            let (parent_prefix, mut wildcard_state, parent_state, state) = queue.remove(0);
            let last_char = parent_prefix.chars().last();

            wildcard_state = match state {
                State::Allow => 0,
                State::Disallow if last_char == Some('$') => wildcard_state,
                State::Disallow => 1,
                State::Intermediate => wildcard_state,
            };

            let mut t = match last_char {
                Some('$') => {
                    // The EOW character cannot match anything else
                    vec![Transition(Edge::MatchAny, wildcard_state)]
                }
                Some('*') => {
                    // The wildcard character overrides the wildcard state
                    vec![Transition(Edge::MatchAny, transitions.len())]
                }
                _ => {
                    // Every other state has a self-loop that matches anything
                    vec![Transition(Edge::MatchAny, wildcard_state)]
                }
            };

            let mut curr_prefix = "";
            rules
                .iter()
                .map(Rule::inner)
                .zip(&rules)
                .filter(|(path, _)| (*path).starts_with(parent_prefix))
                .filter(|(path, _)| (*path) != parent_prefix)
                .for_each(|(path, rule)| {
                    let child_prefix = &path[0..parent_prefix.len() + 1];
                    if curr_prefix == child_prefix {
                        // We only want to visit a child node once, but
                        // many rules might have the same child_prefix, so
                        // we skip the duplicates after the first time
                        // we see a prefix. (This could be a filter(), but
                        // it's a bit hard to encode earlier in the chain.)
                        return;
                    }
                    curr_prefix = child_prefix;

                    let eow = child_prefix == path;
                    let state = match (rule, eow) {
                        (Rule::Allow(..), true) => State::Allow,
                        (Rule::Disallow(..), true) => State::Disallow,
                        _ => State::Intermediate,
                    };

                    queue.push((child_prefix, wildcard_state, transitions.len(), state));

                    // NB: we can predict what state index the child
                    // will have before it's even pushed onto the state vec.
                    let child_index = transitions.len() + queue.len();
                    let edge_char = child_prefix.chars().last().unwrap();
                    let transition = Transition(
                        match edge_char {
                            '*' => Edge::MatchAny,
                            '$' => Edge::MatchEow,
                            c => Edge::MatchChar(c),
                        },
                        child_index,
                    );

                    // Add transitions from the parent state to the child state
                    // so that the wildcard character matches are optional.
                    if last_char == Some('*') {
                        let parent_t = &mut transitions[parent_state];
                        parent_t.push(transition);
                    }

                    t.push(transition);
                });

            states.push(match state {
                State::Allow | State::Disallow => state,
                State::Intermediate => states[wildcard_state],
            });
            transitions.push(t);
        }

        Self {
            states,
            transitions,
        }
    }
}

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

    macro_rules! t {
        ('*' => $x:expr) => {
            Transition(Edge::MatchAny, $x)
        };
        ('$' => $x:expr) => {
            Transition(Edge::MatchEow, $x)
        };
        ($x:expr => $y:expr) => {
            Transition(Edge::MatchChar($x), $y)
        };
    }

    #[test]
    fn test_compile() {
        let rules = vec![
            Rule::Disallow("/"),
            Rule::Allow("/a"),
            Rule::Allow("/abc"),
            Rule::Allow("/b"),
        ];

        let expect_transitions = vec![
            vec![t!('*' => 0)],
            vec![t!('*' => 1)],
            vec![t!('*' => 0), t!('/' => 3)],               // ""
            vec![t!('*' => 1), t!('a' => 4), t!('b' => 5)], // "/"
            vec![t!('*' => 0), t!('b' => 6)],               // "/a"
            vec![t!('*' => 0)],                             // "/b"
            vec![t!('*' => 0), t!('c' => 7)],               // "/ab"
            vec![t!('*' => 0)],                             // "/abc"
        ];

        let expect_states = vec![
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Allow,
            State::Allow,
            State::Allow,
        ];

        let actual = Cylon::compile(rules);
        assert_eq!(actual.transitions, expect_transitions);
        assert_eq!(actual.states, expect_states);
    }

    #[test]
    fn test_compile_with_wildcard() {
        let rules = vec![Rule::Disallow("/"), Rule::Allow("/a"), Rule::Allow("/*.b")];

        let expect_transitions = vec![
            vec![t!('*' => 0)],
            vec![t!('*' => 1)],
            vec![t!('*' => 0), t!('/' => 3)], // ""
            vec![t!('*' => 1), t!('*' => 4), t!('a' => 5), t!('.' => 6)], // "/"
            vec![t!('*' => 4), t!('.' => 6)], // "/*"
            vec![t!('*' => 0)],               // "/a"
            vec![t!('*' => 1), t!('b' => 7)], // "/*."
            vec![t!('*' => 0)],               // "/*.b"
        ];

        let expect_states = vec![
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Disallow,
            State::Disallow,
            State::Allow,
            State::Disallow,
            State::Allow,
        ];

        let actual = Cylon::compile(rules);
        assert_eq!(actual.transitions, expect_transitions);
        assert_eq!(actual.states, expect_states);
    }

    #[test]
    fn test_compile_tricky_wildcard() {
        let rules = vec![Rule::Disallow("/"), Rule::Allow("/*.")];

        let expect_transitions = vec![
            vec![t!('*' => 0)],
            vec![t!('*' => 1)],
            vec![t!('*' => 0), t!('/' => 3)],               // ""
            vec![t!('*' => 1), t!('*' => 4), t!('.' => 5)], // "/"
            vec![t!('*' => 4), t!('.' => 5)],               // "/*"
            vec![t!('*' => 0)],                             // "/*."
        ];

        let expect_states = vec![
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Disallow,
            State::Disallow,
            State::Allow,
        ];

        let actual = Cylon::compile(rules);
        assert_eq!(actual.transitions, expect_transitions);
        assert_eq!(actual.states, expect_states);
    }

    #[test]
    fn test_compile_with_eow() {
        let rules = vec![
            Rule::Allow("/"),
            Rule::Disallow("/a$"),
            // Note that this rule is nonsensical. It will compile, but
            // no guarantees are made as to how it's matched. Rules should
            // use url-encoded strings to escape $.
            Rule::Disallow("/x$y"),
        ];

        let expect_transitions = vec![
            vec![t!('*' => 0)],
            vec![t!('*' => 1)],
            vec![t!('*' => 0), t!('/' => 3)],               // ""
            vec![t!('*' => 0), t!('a' => 4), t!('x' => 5)], // "/"
            vec![t!('*' => 0), t!('$' => 6)],               // "/a"
            vec![t!('*' => 0), t!('$' => 7)],               // "/x"
            vec![t!('*' => 0)],                             // "/a$"
            vec![t!('*' => 0), t!('y' => 8)],               // "/x$"
            vec![t!('*' => 1)],                             // "/x$y"
        ];

        let expect_states = vec![
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Allow,
            State::Allow,
            State::Allow,
            State::Disallow,
            State::Allow,
            State::Disallow,
        ];

        let actual = Cylon::compile(rules);
        assert_eq!(actual.transitions, expect_transitions);
        assert_eq!(actual.states, expect_states);
    }

    #[test]
    fn test_allow() {
        let rules = vec![
            Rule::Disallow("/"),
            Rule::Allow("/a"),
            Rule::Allow("/abc"),
            Rule::Allow("/b"),
        ];

        let machine = Cylon::compile(rules);
        assert_eq!(false, machine.allow("/"));
        assert_eq!(true, machine.allow("/a"));
        assert_eq!(true, machine.allow("/a/b"));
        assert_eq!(true, machine.allow("/a"));
        assert_eq!(true, machine.allow("/abc"));
        assert_eq!(true, machine.allow("/abc/def"));
        assert_eq!(true, machine.allow("/b"));
        assert_eq!(true, machine.allow("/b/c"));
    }

    #[test]
    fn test_allow_match_any() {
        let rules = vec![
            Rule::Allow("/"),
            Rule::Disallow("/secret/*.txt"),
            Rule::Disallow("/private/*"),
        ];

        let machine = Cylon::compile(rules);
        assert_eq!(true, machine.allow("/"));
        assert_eq!(true, machine.allow("/abc"));
        assert_eq!(false, machine.allow("/secret/abc.txt"));
        assert_eq!(false, machine.allow("/secret/123.txt"));
        assert_eq!(true, machine.allow("/secret/abc.csv"));
        assert_eq!(true, machine.allow("/secret/123.csv"));
        assert_eq!(false, machine.allow("/private/abc.txt"));
        assert_eq!(false, machine.allow("/private/123.txt"));
        assert_eq!(false, machine.allow("/private/abc.csv"));
        assert_eq!(false, machine.allow("/private/123.csv"));
    }

    #[test]
    fn test_allow_match_eow() {
        let rules = vec![
            Rule::Allow("/"),
            Rule::Disallow("/ignore$"),
            Rule::Disallow("/foo$bar"),
        ];

        let machine = Cylon::compile(rules);
        assert_eq!(true, machine.allow("/"));
        assert_eq!(true, machine.allow("/abc"));
        assert_eq!(false, machine.allow("/ignore"));
        assert_eq!(true, machine.allow("/ignoreabc"));
        assert_eq!(true, machine.allow("/ignore/abc"));
        // These are technically undefined, and no behavior
        // is guaranteed since the rule is malformed. However
        // it is safer to accept them rather than reject them.
        assert_eq!(true, machine.allow("/foo"));
        assert_eq!(true, machine.allow("/foo$bar"));
    }

    #[test]
    fn test_allow_more_complicated() {
        let rules = vec![
            Rule::Allow("/"),
            Rule::Disallow("/a$"),
            Rule::Disallow("/abc"),
            Rule::Allow("/abc/*"),
            Rule::Disallow("/foo/bar"),
            Rule::Allow("/*/bar"),
            Rule::Disallow("/www/*/images"),
            Rule::Allow("/www/public/images"),
        ];

        let machine = Cylon::compile(rules);
        assert_eq!(true, machine.allow("/"));
        assert_eq!(true, machine.allow("/directory"));
        assert_eq!(false, machine.allow("/a"));
        assert_eq!(true, machine.allow("/ab"));
        assert_eq!(false, machine.allow("/abc"));
        assert_eq!(true, machine.allow("/abc/123"));
        assert_eq!(true, machine.allow("/foo"));
        assert_eq!(true, machine.allow("/foobar"));
        assert_eq!(false, machine.allow("/foo/bar"));
        assert_eq!(false, machine.allow("/foo/bar/baz"));
        assert_eq!(true, machine.allow("/baz/bar"));
        assert_eq!(false, machine.allow("/www/cat/images"));
        assert_eq!(true, machine.allow("/www/public/images"));
    }

    #[test]
    fn test_matches() {
        // Test cases from:
        // https://developers.google.com/search/reference/robots_txt#group-member-rules

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/fish")]);
        assert_eq!(true, machine.allow("/fish"));
        assert_eq!(true, machine.allow("/fish.html"));
        assert_eq!(true, machine.allow("/fish/salmon.html"));
        assert_eq!(true, machine.allow("/fishheads.html"));
        assert_eq!(true, machine.allow("/fishheads/yummy.html"));
        assert_eq!(true, machine.allow("/fish.php?id=anything"));
        assert_eq!(false, machine.allow("/Fish.asp"));
        assert_eq!(false, machine.allow("/catfish"));
        assert_eq!(false, machine.allow("/?id=fish"));

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/fish*")]);
        assert_eq!(true, machine.allow("/fish"));
        assert_eq!(true, machine.allow("/fish.html"));
        assert_eq!(true, machine.allow("/fish/salmon.html"));
        assert_eq!(true, machine.allow("/fishheads.html"));
        assert_eq!(true, machine.allow("/fishheads/yummy.html"));
        assert_eq!(true, machine.allow("/fish.php?id=anything"));
        assert_eq!(false, machine.allow("/Fish.asp"));
        assert_eq!(false, machine.allow("/catfish"));
        assert_eq!(false, machine.allow("/?id=fish"));

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/fish/")]);
        assert_eq!(true, machine.allow("/fish/"));
        assert_eq!(true, machine.allow("/fish/?id=anything"));
        assert_eq!(true, machine.allow("/fish/salmon.htm"));
        assert_eq!(false, machine.allow("/fish"));
        assert_eq!(false, machine.allow("/fish.html"));
        assert_eq!(false, machine.allow("/Fish/Salmon.asp"));

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/*.php")]);
        assert_eq!(true, machine.allow("/filename.php"));
        assert_eq!(true, machine.allow("/folder/filename.php"));
        assert_eq!(true, machine.allow("/folder/filename.php?parameters"));
        assert_eq!(true, machine.allow("/folder/any.php.file.html"));
        assert_eq!(true, machine.allow("/filename.php/"));
        assert_eq!(false, machine.allow("/"));
        assert_eq!(false, machine.allow("/windows.PHP"));

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/*.php$")]);
        assert_eq!(true, machine.allow("/filename.php"));
        assert_eq!(true, machine.allow("/folder/filename.php"));
        assert_eq!(false, machine.allow("/filename.php?parameters"));
        assert_eq!(false, machine.allow("/filename.php/"));
        assert_eq!(false, machine.allow("/filename.php5"));
        assert_eq!(false, machine.allow("/windows.PHP"));

        let machine = Cylon::compile(vec![Rule::Disallow("/"), Rule::Allow("/fish*.php")]);
        assert_eq!(true, machine.allow("/fish.php"));
        assert_eq!(true, machine.allow("/fishheads/catfish.php?parameters"));
        assert_eq!(false, machine.allow("/Fish.PHP"));
    }
}