1use std::fmt;
22
23pub const MAX_ROUTES: usize = 64;
26const MAX_SEGMENTS: usize = 64;
27
28pub const METHOD_OVERRIDE_HEADERS: &[&str] = &[
32 "x-http-method-override",
33 "x-http-method",
34 "x-method-override",
35];
36
37const ECHOING: &[&str] = &["TRACE", "TRACK", "CONNECT"];
39
40const METHOD_OVERRIDE_PARAMETER: &str = "_method";
42
43#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Route {
46 method: String,
47 segments: Vec<Segment>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51enum Segment {
52 Literal(String),
53 One,
55 Any,
57}
58
59impl Route {
60 pub fn parse(text: &str) -> Result<Self, String> {
62 let (method, path) = text
63 .split_once(' ')
64 .ok_or_else(|| format!("rule `{text}` must be `METHOD /path`"))?;
65 if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) {
66 return Err(format!(
67 "rule `{text}`: the method must be capital letters (`GET`, `POST`)"
68 ));
69 }
70 if ECHOING.contains(&method) {
73 return Err(format!(
74 "rule `{text}`: {method} is never given a secret: the server would send it back \
75 or the proxy could not read what follows"
76 ));
77 }
78 let Some(rest) = path.strip_prefix('/') else {
79 return Err(format!("rule `{text}`: the path must start with `/`"));
80 };
81 let mut segments = Vec::new();
82 let parts: Vec<&str> = if rest.is_empty() {
83 Vec::new()
84 } else {
85 rest.split('/').collect()
86 };
87 for (n, part) in parts.iter().enumerate() {
88 let last = n + 1 == parts.len();
89 segments.push(match *part {
90 "*" => Segment::One,
91 "**" => Segment::Any,
92 "" if last => Segment::Literal(String::new()),
94 "" => return Err(format!("rule `{text}`: the path has an empty segment")),
95 "." | ".." => return Err(format!("rule `{text}`: `.` and `..` are not segments")),
96 literal if literal.bytes().all(is_literal_byte) => {
97 Segment::Literal(literal.to_owned())
98 }
99 _ => {
100 return Err(format!(
101 "rule `{text}`: a segment is a literal of letters, digits and \
102 `-._~!$&'()+,=:@`, `*` or `**`"
103 ));
104 }
105 });
106 }
107 if segments.len() > MAX_SEGMENTS {
108 return Err(format!(
109 "rule `{text}` has more than {MAX_SEGMENTS} segments"
110 ));
111 }
112 Ok(Self {
113 method: method.to_owned(),
114 segments,
115 })
116 }
117
118 #[must_use]
120 pub fn matches(&self, method: &str, path: &RequestPath) -> bool {
121 self.method == method && matches(&self.segments, &path.segments)
122 }
123
124 #[must_use]
129 pub fn could_match(&self, method: Option<&str>, path: Option<&[Partial]>) -> bool {
130 method.is_none_or(|m| m == self.method) && path.is_none_or(|p| could(&self.segments, p))
131 }
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Partial {
138 Known(String),
140 One,
142 Rest,
144}
145
146fn could(rule: &[Segment], path: &[Partial]) -> bool {
149 let (r, p) = (rule.len(), path.len());
150 let mut memo = vec![vec![false; p + 1]; r + 1];
151 for i in (0..=r).rev() {
152 for j in (0..=p).rev() {
153 memo[i][j] = if i == r && j == p {
154 true
155 } else if j < p && path[j] == Partial::Rest {
156 memo[i][j + 1] || (i < r && memo[i + 1][j])
157 } else if i < r && rule[i] == Segment::Any {
158 memo[i + 1][j] || (j < p && memo[i][j + 1])
159 } else if i < r && j < p {
160 let one = match (&rule[i], &path[j]) {
161 (Segment::Literal(l), Partial::Known(k)) => l == k,
162 (Segment::One, Partial::Known(k)) => !k.is_empty(),
163 _ => true,
164 };
165 one && memo[i + 1][j + 1]
166 } else {
167 false
168 };
169 }
170 }
171 memo[0][0]
172}
173
174fn matches(rule: &[Segment], path: &[String]) -> bool {
177 let mut matched = vec![false; path.len() + 1];
178 matched[0] = true;
179 for segment in rule {
180 let mut next = vec![false; path.len() + 1];
181 for j in 0..=path.len() {
182 next[j] = match segment {
183 Segment::Any => matched[j] || (j > 0 && next[j - 1]),
184 Segment::One => j > 0 && matched[j - 1] && !path[j - 1].is_empty(),
185 Segment::Literal(literal) => j > 0 && matched[j - 1] && path[j - 1] == *literal,
186 };
187 }
188 matched = next;
189 }
190 matched[path.len()]
191}
192
193fn is_literal_byte(b: u8) -> bool {
195 b.is_ascii_alphanumeric() || b"-._~!$&'()+,=:@".contains(&b)
196}
197
198#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct RequestPath {
202 segments: Vec<String>,
203 overrides_method: bool,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
208#[non_exhaustive]
209pub enum PathRefusal {
210 NotOriginForm,
212 Malformed,
214 DotSegment,
216 AmbiguousSegment,
219 EmptySegment,
221}
222
223impl fmt::Display for PathRefusal {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str(match self {
226 Self::NotOriginForm => "the request target is not a path starting with `/`",
227 Self::Malformed => {
228 "the path holds a byte outside visible ASCII, a `\\`, a `#` or a malformed `%` \
229 escape"
230 }
231 Self::DotSegment => "the path holds a `.` or `..` segment, in some spelling",
232 Self::AmbiguousSegment => {
233 "a path segment holds `;` or decodes to `/`, `\\`, `%`, `;` or a control byte"
234 }
235 Self::EmptySegment => "the path holds an empty segment (`//`)",
236 })
237 }
238}
239
240impl RequestPath {
241 pub fn parse(target: &str) -> Result<Self, PathRefusal> {
244 let Some(rest) = target.strip_prefix('/') else {
245 return Err(PathRefusal::NotOriginForm);
246 };
247 if !target.bytes().all(|b| b.is_ascii_graphic()) || target.contains(['\\', '#']) {
248 return Err(PathRefusal::Malformed);
249 }
250 let (path, query) = rest.split_once('?').unwrap_or((rest, ""));
251 let parts: Vec<&str> = if path.is_empty() {
252 Vec::new()
253 } else {
254 path.split('/').collect()
255 };
256 let mut segments = Vec::with_capacity(parts.len());
257 for (n, part) in parts.iter().enumerate() {
258 if part.is_empty() && n + 1 < parts.len() {
259 return Err(PathRefusal::EmptySegment);
260 }
261 if part.contains(';') {
262 return Err(PathRefusal::AmbiguousSegment);
263 }
264 let decoded = decode(part).ok_or(PathRefusal::Malformed)?;
265 let decoded = String::from_utf8(decoded).map_err(|_| PathRefusal::AmbiguousSegment)?;
266 if decoded == "." || decoded == ".." {
267 return Err(PathRefusal::DotSegment);
268 }
269 if decoded
270 .chars()
271 .any(|c| c.is_control() || matches!(c, '/' | '\\' | '%' | ';'))
272 {
273 return Err(PathRefusal::AmbiguousSegment);
274 }
275 segments.push(decoded);
276 }
277 let overrides_method = query.split('&').any(|pair| {
278 let name = pair.split_once('=').map_or(pair, |(name, _)| name);
279 decode(name)
280 .is_none_or(|n| n.eq_ignore_ascii_case(METHOD_OVERRIDE_PARAMETER.as_bytes()))
281 });
282 Ok(Self {
283 segments,
284 overrides_method,
285 })
286 }
287
288 #[must_use]
291 pub fn overrides_method(&self) -> bool {
292 self.overrides_method
293 }
294
295 pub(crate) fn segments(&self) -> &[String] {
297 &self.segments
298 }
299
300 #[must_use]
303 pub(crate) fn folded(&self) -> Self {
304 Self {
305 segments: self
306 .segments
307 .iter()
308 .map(|s| s.to_ascii_lowercase())
309 .collect(),
310 overrides_method: self.overrides_method,
311 }
312 }
313}
314
315fn decode(text: &str) -> Option<Vec<u8>> {
317 let bytes = text.as_bytes();
318 let mut out = Vec::with_capacity(bytes.len());
319 let mut i = 0;
320 while i < bytes.len() {
321 if bytes[i] == b'%' {
322 let hex = bytes
324 .get(i + 1..i + 3)
325 .filter(|h| h.iter().all(u8::is_ascii_hexdigit))?;
326 out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
327 i += 3;
328 } else {
329 out.push(bytes[i]);
330 i += 1;
331 }
332 }
333 Some(out)
334}
335
336#[cfg(test)]
337mod tests;