static_files_module/
path.rs

1// Copyright 2024 Wladimir Palant
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Path resolution logic
16
17use percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS};
18use std::io::{Error, ErrorKind};
19use std::path::{Path, PathBuf};
20
21// This matches pingora logic, see https://github.com/cloudflare/pingora/blob/2501d4adb038d93613c0edbd7c1e3b3de9b415b1/pingora-core/src/protocols/http/v1/server.rs#L934
22const URI_ESC_CHARSET: &AsciiSet = &CONTROLS.add(b' ').add(b'<').add(b'>').add(b'"');
23
24#[cfg(unix)]
25fn path_from_bytes(bytes: &[u8]) -> &std::ffi::OsStr {
26    use std::ffi::OsStr;
27    use std::os::unix::ffi::OsStrExt;
28
29    OsStr::from_bytes(bytes)
30}
31
32#[cfg(not(unix))]
33fn path_from_bytes(bytes: &[u8]) -> String {
34    // This should really be OsStr::from_encoded_bytes_unchecked() but it’s
35    // unsafe. With this fallback non-Unicode file names will result in 404.
36    String::from_utf8_lossy(bytes).into_owned()
37}
38
39/// Resolves the path from a URI against the path to a root directory.
40///
41/// This will return an error under the following conditions:
42///
43/// * Invalid path, not starting with a slash (/): results in [`ErrorKind::InvalidInput`]
44/// * Resolved path outside the root directory: results in [`ErrorKind::InvalidData`]
45/// * [`std::fs::canonicalize()`] failed: results in [`ErrorKind::NotFound`],
46///   [`ErrorKind::PermissionDenied`] and other errors
47pub fn resolve_uri(uri_path: &str, root: &Path) -> Result<PathBuf, Error> {
48    let uri_path = uri_path.strip_prefix('/').ok_or(ErrorKind::InvalidInput)?;
49
50    let uri_path = uri_path.strip_suffix('/').unwrap_or(uri_path);
51
52    let mut path = root.to_path_buf();
53    for component in uri_path.split('/') {
54        let decoded = percent_decode_str(component).collect::<Vec<_>>();
55        path.push(path_from_bytes(&decoded))
56    }
57
58    let path = path.canonicalize()?;
59
60    if path.starts_with(root) {
61        Ok(path)
62    } else {
63        Err(ErrorKind::InvalidData.into())
64    }
65}
66
67/// Calculates the canonical URI path describing the path relative to a root directory.
68///
69/// This will return `None` for paths outside the root directory.
70pub fn path_to_uri(path: &Path, root: &Path) -> Option<String> {
71    let rel_path = path.strip_prefix(root).ok()?;
72
73    let mut uri = String::from('/');
74    for component in rel_path.components() {
75        uri.push_str(
76            &percent_encode(component.as_os_str().as_encoded_bytes(), URI_ESC_CHARSET).to_string(),
77        );
78        uri.push('/');
79    }
80    if !path.is_dir() && uri.len() > 1 {
81        uri.pop();
82    }
83    Some(uri)
84}