返回 CodeWhale
path_io.rs
根目录 / crates / config / src / path_io.rs
1 use anyhow::Context as _;
2 use anyhow::{Result, bail};
3 use std::ffi::OsString;
4 use std::fs;
5 use std::io::Read;
6 #[cfg(unix)]
7 use std::os::unix::fs::OpenOptionsExt;
8 use std::path::{Component, Path, PathBuf};
9
10 pub(crate) fn normalize_config_file_path(path: PathBuf) -> Result<PathBuf> {
11 if path.as_os_str().is_empty() {
12 bail!("config path cannot be empty");
13 }
14 if path
15 .components()
16 .any(|component| matches!(component, Component::ParentDir))
17 {
18 bail!("config path cannot contain '..' components");
19 }
20 if path.file_name().is_none() {
21 bail!("config path must include a file name");
22 }
23 let absolute = if path.is_absolute() {
24 path
25 } else {
26 std::env::current_dir()
27 .context("failed to resolve current directory for config path")?
28 .join(path)
29 };
30 let file_name = absolute
31 .file_name()
32 .map(OsString::from)
33 .context("config path must include a file name")?;
34 let parent = absolute
35 .parent()
36 .context("config path must include a parent directory")?;
37 let parent = match parent.canonicalize() {
38 Ok(parent) => parent,
39 Err(err) if err.kind() == std::io::ErrorKind::NotFound => parent.to_path_buf(),
40 Err(err) => {
41 return Err(err).with_context(|| {
42 format!("failed to resolve config directory {}", parent.display())
43 });
44 }
45 };
46 let normalized = parent.join(file_name);
47 reject_path_symlink(&normalized)?;
48 Ok(normalized)
49 }
50
51 pub fn normalize_project_workspace(workspace: &Path) -> Result<PathBuf> {
52 if workspace.as_os_str().is_empty() {
53 bail!("project workspace path cannot be empty");
54 }
55 if workspace
56 .components()
57 .any(|component| matches!(component, Component::ParentDir))
58 {
59 bail!("project workspace path cannot contain '..' components");
60 }
61 let absolute = if workspace.is_absolute() {
62 workspace.to_path_buf()
63 } else {
64 std::env::current_dir()
65 .context("failed to resolve current directory for project workspace")?
66 .join(workspace)
67 };
68 match absolute.canonicalize() {
69 Ok(path) => Ok(path),
70 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
71 Ok(normalize_path_components(&absolute))
72 }
73 Err(err) => Err(err).with_context(|| {
74 format!(
75 "failed to resolve project workspace {}",
76 workspace.display()
77 )
78 }),
79 }
80 }
81
82 pub(crate) fn normalize_path_components(path: &Path) -> PathBuf {
83 let mut normalized = PathBuf::new();
84 for component in path.components() {
85 match component {
86 Component::Prefix(_) | Component::RootDir => normalized.push(component.as_os_str()),
87 Component::CurDir => {}
88 Component::ParentDir => {
89 normalized.pop();
90 }
91 Component::Normal(part) => normalized.push(part),
92 }
93 }
94 if normalized.as_os_str().is_empty() {
95 PathBuf::from(".")
96 } else {
97 normalized
98 }
99 }
100
101 pub(crate) fn checked_path_exists(path: &Path) -> Result<bool> {
102 let path = normalize_config_file_path(path.to_path_buf())?;
103 path.try_exists()
104 .with_context(|| format!("failed to inspect config path {}", path.display()))
105 }
106
107 pub fn read_checked_config_file(path: &Path) -> Result<String> {
108 read_checked_toml_file(path, "config")
109 }
110
111 pub(crate) fn read_checked_permissions_file(path: &Path) -> Result<String> {
112 read_checked_toml_file(path, "permissions")
113 }
114
115 pub(crate) fn read_checked_toml_file(path: &Path, label: &str) -> Result<String> {
116 let path = normalize_config_file_path(path.to_path_buf())?;
117 read_string_no_follow(&path)
118 .with_context(|| format!("failed to read {label} at {}", path.display()))
119 }
120
121 /// Maximum bytes read from a config file. Configs are kilobytes; anything
122 /// larger is not a config file.
123 pub(crate) const MAX_CONFIG_FILE_BYTES: u64 = 1024 * 1024;
124
125 pub(crate) fn reject_path_symlink(path: &Path) -> Result<()> {
126 let Ok(metadata) = fs::symlink_metadata(path) else {
127 return Ok(());
128 };
129 if metadata.file_type().is_symlink() {
130 bail!("config path must not be a symlink: {}", path.display());
131 }
132 Ok(())
133 }
134
135 pub(crate) fn read_bounded_file_to_string(
136 file: &fs::File,
137 path: &Path,
138 max_bytes: u64,
139 label: &str,
140 ) -> std::io::Result<String> {
141 let too_large = || {
142 let limit = if max_bytes == MAX_CONFIG_FILE_BYTES {
143 "1 MiB".to_string()
144 } else {
145 format!("{max_bytes}-byte")
146 };
147 std::io::Error::new(
148 std::io::ErrorKind::InvalidData,
149 format!("{label} {} exceeds the {limit} limit", path.display()),
150 )
151 };
152 if file.metadata()?.len() > max_bytes {
153 return Err(too_large());
154 }
155 let mut raw = Vec::new();
156 file.take(max_bytes.saturating_add(1))
157 .read_to_end(&mut raw)?;
158 if raw.len() as u64 > max_bytes {
159 return Err(too_large());
160 }
161 String::from_utf8(raw).map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
162 }
163
164 pub(crate) fn read_string_no_follow(path: &Path) -> std::io::Result<String> {
165 #[cfg(unix)]
166 let file = fs::OpenOptions::new()
167 .read(true)
168 .custom_flags(libc::O_NOFOLLOW)
169 .open(path)?;
170 #[cfg(not(unix))]
171 let file = fs::File::open(path)?;
172 read_bounded_file_to_string(&file, path, MAX_CONFIG_FILE_BYTES, "config file")
173 }
174
174 lines RUST