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
//! Defines the types used to indicate a non-matching route, and associated metadata.

use std::collections::HashSet;

use hyper::{Method, StatusCode};

/// The error type used for a non-matching route, as returned by `RouteMatcher::is_match`. Multiple
/// values of this type can be combined by matchers that are wrapping other matchers, using the
/// `intersection` / `union` methods.  The data within is used by the `Router` to create a
/// `Response` when no routes were successfully matched.
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Method, StatusCode};
/// # use gotham::router::non_match::RouteNonMatch;
/// # use gotham::router::route::matcher::RouteMatcher;
/// # use gotham::state::State;
/// #
/// #[derive(Clone)]
/// struct MyRouteMatcher;
///
/// impl RouteMatcher for MyRouteMatcher {
///     fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> {
///         match state.borrow::<Method>() {
///             &Method::GET => Ok(()),
///             _ => Err(
///                 RouteNonMatch::new(StatusCode::METHOD_NOT_ALLOWED)
///                     .with_allow_list(&[Method::GET]),
///             ),
///         }
///     }
/// }
/// #
/// # fn main() {
/// #     State::with_new(|state| {
/// #         state.put(Method::POST);
/// #         assert!(MyRouteMatcher.is_match(&state).is_err());
/// #     });
/// # }
/// ```
#[derive(Clone)]
pub struct RouteNonMatch {
    status: StatusCode,
    allow: MethodSet,
}

impl RouteNonMatch {
    /// Creates a new `RouteNonMatch` value with the given HTTP status.
    pub fn new(status: StatusCode) -> RouteNonMatch {
        RouteNonMatch {
            status,
            allow: MethodSet::default(),
        }
    }

    /// Adds an allow list to a `RouteNonMatch`. Typically this is used with a `405 Method Not
    /// Allowed` status code, so the `Router` can accurately populate the `Allow` header in the
    /// response. It must be populated by any `RouteMatcher` which restricts the HTTP method.
    pub fn with_allow_list(self, allow: &[Method]) -> RouteNonMatch {
        RouteNonMatch {
            allow: allow.into(),
            ..self
        }
    }

    /// Takes the intersection of two `RouteNonMatch` values, producing a single result.  This is
    /// intended for use in cases where two `RouteMatcher` instances with a logical **AND**
    /// connection have both indicated a non-match, and their results need to be aggregated.
    ///
    /// This is typically for Gotham internal use, but may be useful for implementors of matchers
    /// which wrap other `RouteMatcher` instances. See the `AndRouteMatcher` implementation (in
    /// `gotham::router::route::matcher::and`) for an example.
    pub fn intersection(self, other: RouteNonMatch) -> RouteNonMatch {
        let status = higher_precedence_status(self.status, other.status);
        let allow = self.allow.intersection(other.allow);
        RouteNonMatch { status, allow }
    }

    /// Takes the union of two `RouteNonMatch` values, producing a single result. This is intended
    /// for use in cases where two `RouteMatcher` instances with a logical **OR** connection have
    /// both indicated a non-match, and their results need to be aggregated.
    ///
    /// This is typically for Gotham internal use, but may be useful for implementors of matchers
    /// which wrap other `RouteMatcher` instances. See the `Node::select_route` implementation (in
    /// `gotham::router::tree`) for an example.
    pub fn union(self, other: RouteNonMatch) -> RouteNonMatch {
        let status = higher_precedence_status(self.status, other.status);
        let allow = self.allow.union(other.allow);
        RouteNonMatch { status, allow }
    }

    pub(super) fn deconstruct(self) -> (StatusCode, Vec<Method>) {
        (self.status, self.allow.into())
    }
}

impl From<RouteNonMatch> for StatusCode {
    fn from(val: RouteNonMatch) -> StatusCode {
        val.status
    }
}

fn higher_precedence_status(lhs: StatusCode, rhs: StatusCode) -> StatusCode {
    match (lhs, rhs) {
        // For 404, prefer routes that indicated *some* kind of match.
        (StatusCode::NOT_FOUND, _) => rhs,
        (_, StatusCode::NOT_FOUND) => lhs,
        // For 405, prefer routes that matched the HTTP method.
        (StatusCode::METHOD_NOT_ALLOWED, _) => rhs,
        (_, StatusCode::METHOD_NOT_ALLOWED) => lhs,
        // For 406, allow "harder" errors to overrule.
        (StatusCode::NOT_ACCEPTABLE, _) => rhs,
        (_, StatusCode::NOT_ACCEPTABLE) => lhs,
        // This is a silly safeguard that prefers errors over non-errors. This should never be
        // needed, but guards against strange custom `RouteMatcher` impls in applications.
        (_, _) if lhs.is_client_error() => lhs,
        (_, _) if rhs.is_client_error() => rhs,
        (_, _) => lhs,
    }
}

// This customised set prevents memory allocations while computing `Allow` lists, except in the
// case where extension methods are provided using the `hyper::Method::Extension` variant.
#[derive(Clone)]
struct MethodSet {
    connect: bool,
    delete: bool,
    get: bool,
    head: bool,
    options: bool,
    patch: bool,
    post: bool,
    put: bool,
    trace: bool,
    other: HashSet<Method>,
}

impl MethodSet {
    fn intersection(self, other: MethodSet) -> MethodSet {
        MethodSet {
            connect: self.connect && other.connect,
            delete: self.delete && other.delete,
            get: self.get && other.get,
            head: self.head && other.head,
            options: self.options && other.options,
            patch: self.patch && other.patch,
            post: self.post && other.post,
            put: self.put && other.put,
            trace: self.trace && other.trace,
            other: self.other.intersection(&other.other).cloned().collect(),
        }
    }

    fn union(self, other: MethodSet) -> MethodSet {
        MethodSet {
            connect: self.connect || other.connect,
            delete: self.delete || other.delete,
            get: self.get || other.get,
            head: self.head || other.head,
            options: self.options || other.options,
            patch: self.patch || other.patch,
            post: self.post || other.post,
            put: self.put || other.put,
            trace: self.trace || other.trace,
            other: self.other.union(&other.other).cloned().collect(),
        }
    }
}

impl Default for MethodSet {
    fn default() -> MethodSet {
        MethodSet {
            connect: false,
            delete: true,
            get: true,
            head: true,
            options: true,
            patch: true,
            post: true,
            put: true,
            trace: false,
            other: HashSet::default(),
        }
    }
}

impl<'a> From<&'a [Method]> for MethodSet {
    fn from(methods: &[Method]) -> MethodSet {
        let (
            mut connect,
            mut delete,
            mut get,
            mut head,
            mut options,
            mut patch,
            mut post,
            mut put,
            mut trace,
        ) = (
            false, false, false, false, false, false, false, false, false,
        );

        let mut other = HashSet::new();

        for method in methods {
            match *method {
                Method::CONNECT => {
                    connect = true;
                }
                Method::DELETE => {
                    delete = true;
                }
                Method::GET => {
                    get = true;
                }
                Method::HEAD => {
                    head = true;
                }
                Method::OPTIONS => {
                    options = true;
                }
                Method::PATCH => {
                    patch = true;
                }
                Method::POST => {
                    post = true;
                }
                Method::PUT => {
                    put = true;
                }
                Method::TRACE => {
                    trace = true;
                }
                _ => {
                    other.insert(method.clone());
                }
            }
        }

        MethodSet {
            connect,
            delete,
            get,
            head,
            options,
            patch,
            post,
            put,
            trace,
            other,
        }
    }
}

impl From<MethodSet> for Vec<Method> {
    fn from(method_set: MethodSet) -> Vec<Method> {
        let methods_with_flags: [(Method, bool); 9] = [
            (Method::CONNECT, method_set.connect),
            (Method::DELETE, method_set.delete),
            (Method::GET, method_set.get),
            (Method::HEAD, method_set.head),
            (Method::OPTIONS, method_set.options),
            (Method::PATCH, method_set.patch),
            (Method::POST, method_set.post),
            (Method::PUT, method_set.put),
            (Method::TRACE, method_set.trace),
        ];

        let mut result = methods_with_flags
            .iter()
            .filter_map(|&(ref method, flag)| if flag { Some(method.clone()) } else { None })
            .chain(method_set.other.into_iter())
            .collect::<Vec<Method>>();

        result.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
        result
    }
}

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

    use hyper::{Method, StatusCode};

    #[test]
    fn intersection_tests() {
        let all = [
            Method::DELETE,
            Method::GET,
            Method::HEAD,
            Method::OPTIONS,
            Method::PATCH,
            Method::POST,
            Method::PUT,
        ];

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_FOUND)
            .intersection(RouteNonMatch::new(StatusCode::NOT_FOUND))
            .deconstruct();
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(&allow_list[..], &all);

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_FOUND)
            .intersection(
                RouteNonMatch::new(StatusCode::METHOD_NOT_ALLOWED).with_allow_list(&[Method::GET]),
            )
            .deconstruct();
        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
        assert_eq!(&allow_list[..], &[Method::GET]);

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_ACCEPTABLE)
            .with_allow_list(&[Method::GET, Method::PATCH, Method::POST])
            .intersection(
                RouteNonMatch::new(StatusCode::METHOD_NOT_ALLOWED).with_allow_list(&[
                    Method::GET,
                    Method::POST,
                    Method::OPTIONS,
                ]),
            )
            .deconstruct();
        assert_eq!(status, StatusCode::NOT_ACCEPTABLE);
        assert_eq!(&allow_list[..], &[Method::GET, Method::POST]);
    }

    #[test]
    fn union_tests() {
        let all = [
            Method::DELETE,
            Method::GET,
            Method::HEAD,
            Method::OPTIONS,
            Method::PATCH,
            Method::POST,
            Method::PUT,
        ];

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_FOUND)
            .union(RouteNonMatch::new(StatusCode::NOT_FOUND))
            .deconstruct();
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert_eq!(&allow_list[..], &all);

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_FOUND)
            .union(
                RouteNonMatch::new(StatusCode::METHOD_NOT_ALLOWED).with_allow_list(&[Method::GET]),
            )
            .deconstruct();
        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
        assert_eq!(&allow_list[..], &all);

        let (status, allow_list) = RouteNonMatch::new(StatusCode::NOT_ACCEPTABLE)
            .with_allow_list(&[Method::GET, Method::PATCH, Method::POST])
            .union(
                RouteNonMatch::new(StatusCode::METHOD_NOT_ALLOWED).with_allow_list(&[
                    Method::GET,
                    Method::POST,
                    Method::OPTIONS,
                ]),
            )
            .deconstruct();
        assert_eq!(status, StatusCode::NOT_ACCEPTABLE);
        assert_eq!(
            &allow_list[..],
            &[Method::GET, Method::OPTIONS, Method::PATCH, Method::POST]
        );
    }

    #[test]
    fn deconstruct_tests() {
        let (_, allow_list) = RouteNonMatch::new(StatusCode::NOT_FOUND)
            .with_allow_list(&[
                Method::DELETE,
                Method::GET,
                Method::HEAD,
                Method::OPTIONS,
                Method::PATCH,
                Method::POST,
                Method::PUT,
                Method::CONNECT,
                Method::TRACE,
                Method::from_bytes(b"PROPFIND").unwrap(),
                Method::from_bytes(b"PROPSET").unwrap(),
            ])
            .deconstruct();

        assert_eq!(
            &allow_list[..],
            &[
                Method::CONNECT,
                Method::DELETE,
                Method::GET,
                Method::HEAD,
                Method::OPTIONS,
                Method::PATCH,
                Method::POST,
                Method::from_bytes(b"PROPFIND").unwrap(),
                Method::from_bytes(b"PROPSET").unwrap(),
                Method::PUT,
                Method::TRACE,
            ]
        );
    }
}