team-ljyzipelo

공개
303줄9.8 KB
1use crate::{
2 archive::{self, Member, MetadataBudget},
3 filesystem,
4 protocol::*,
5};
6use std::{
7 fs::{self, File, Metadata},
8 path::{Component, Path, PathBuf},
9 time::SystemTime,
10};
11
12type Result<T> = std::result::Result<T, ErrorCode>;
13
14pub(super) struct Input {
15 pub file: File,
16 #[cfg(windows)]
17 _parents: Vec<File>,
18}
19impl Input {
20 #[cfg(target_os = "linux")]
21 fn child(file: &File, name: &std::ffi::OsStr) -> Result<File> {
22 use std::os::{
23 fd::{AsRawFd, FromRawFd},
24 unix::ffi::OsStrExt,
25 };
26 unsafe extern "C" {
27 fn openat(fd: i32, name: *const i8, flags: i32, ...) -> i32;
28 }
29 let name = std::ffi::CString::new(name.as_bytes()).map_err(|_| ErrorCode::UnsafePath)?;
30 // 객체 종류를 확인한 뒤 고정 핸들로만 읽기 열기를 수행함.
31 let fd = unsafe {
32 openat(
33 file.as_raw_fd(),
34 name.as_ptr(),
35 0x80000 | 0x20000 | 0x200000,
36 )
37 };
38 if fd < 0 {
39 let error = std::io::Error::last_os_error();
40 return Err(if matches!(error.raw_os_error(), Some(20 | 40)) {
41 ErrorCode::UnsafePath
42 } else {
43 crate::space::io_error(error)
44 });
45 }
46 let pinned = unsafe { File::from_raw_fd(fd) };
47 Self::validate(&pinned)?;
48 File::open(format!("/proc/self/fd/{}", pinned.as_raw_fd())).map_err(crate::space::io_error)
49 }
50 pub fn open(path: &Path) -> Result<Self> {
51 if !path.is_absolute() {
52 return Err(ErrorCode::InvalidRequest);
53 }
54 #[cfg(target_os = "linux")]
55 {
56 let mut file = File::open("/").map_err(crate::space::io_error)?;
57 for part in path.components() {
58 match part {
59 Component::RootDir => {}
60 Component::Normal(name) => file = Self::child(&file, name)?,
61 _ => return Err(ErrorCode::UnsafePath),
62 }
63 }
64 Self::validate(&file)?;
65 Ok(Self { file })
66 }
67 #[cfg(windows)]
68 {
69 use std::os::windows::fs::OpenOptionsExt;
70 let mut current = PathBuf::new();
71 let mut parents = Vec::new();
72 for part in path.components() {
73 match part {
74 Component::Prefix(_) | Component::RootDir => current.push(part.as_os_str()),
75 Component::Normal(name) => {
76 if parents.is_empty() {
77 parents.push(Self::lock(&current)?);
78 }
79 current.push(name);
80 parents.push(Self::lock(&current)?);
81 }
82 _ => return Err(ErrorCode::UnsafePath),
83 }
84 }
85 let file = fs::OpenOptions::new()
86 .read(true)
87 .share_mode(1)
88 .custom_flags(0x02000000 | 0x00200000)
89 .open(&current)
90 .map_err(crate::space::io_error)?;
91 Self::validate(&file)?;
92 Ok(Self {
93 file,
94 _parents: parents,
95 })
96 }
97 }
98 #[cfg(windows)]
99 fn lock(path: &Path) -> Result<File> {
100 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
101 let file = fs::OpenOptions::new()
102 .access_mode(0x80)
103 .share_mode(3)
104 .custom_flags(0x02000000 | 0x00200000)
105 .open(path)
106 .map_err(crate::space::io_error)?;
107 if file
108 .metadata()
109 .map_err(crate::space::io_error)?
110 .file_attributes()
111 & 0x400
112 != 0
113 {
114 return Err(ErrorCode::UnsafePath);
115 }
116 Ok(file)
117 }
118 fn validate(file: &File) -> Result<()> {
119 let metadata = file.metadata().map_err(crate::space::io_error)?;
120 #[cfg(windows)]
121 {
122 use std::os::windows::fs::MetadataExt;
123 if metadata.file_attributes() & 0x400 != 0 {
124 return Err(ErrorCode::UnsafePath);
125 }
126 }
127 if !metadata.is_dir() && !metadata.is_file() {
128 return Err(ErrorCode::UnsafePath);
129 }
130 Ok(())
131 }
132 fn open_child(&self, path: &Path, name: &str) -> Result<Self> {
133 #[cfg(target_os = "linux")]
134 {
135 let _ = path;
136 let file = Self::child(&self.file, std::ffi::OsStr::new(name))?;
137 Self::validate(&file)?;
138 Ok(Self { file })
139 }
140 #[cfg(windows)]
141 {
142 Self::open(&path.join(name))
143 }
144 }
145 fn children(&self, path: &Path) -> Result<fs::ReadDir> {
146 #[cfg(target_os = "linux")]
147 {
148 use std::os::fd::AsRawFd;
149 let _ = path;
150 fs::read_dir(format!("/proc/self/fd/{}", self.file.as_raw_fd()))
151 .map_err(crate::space::io_error)
152 }
153 #[cfg(windows)]
154 {
155 fs::read_dir(path).map_err(crate::space::io_error)
156 }
157 }
158}
159
160pub(super) struct Planned {
161 pub member: Member,
162 path: PathBuf,
163 object: SourceObject,
164 modified: Option<SystemTime>,
165}
166impl Planned {
167 pub fn open(&self) -> Result<Input> {
168 let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
169 if !self.matches(&input.file)? {
170 return Err(ErrorCode::SourceChanged);
171 }
172 Ok(input)
173 }
174 fn matches(&self, file: &File) -> Result<bool> {
175 let metadata = file.metadata().map_err(crate::space::io_error)?;
176 Ok(filesystem::object(file)? == self.object
177 && metadata.modified().ok() == self.modified
178 && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory)
179 && (metadata.is_dir() || metadata.len() == self.member.entry.size))
180 }
181}
182pub(super) struct Plan {
183 pub items: Vec<Planned>,
184 limits: Limits,
185 budget: MetadataBudget,
186 total: u64,
187}
188impl Plan {
189 pub fn new(
190 sources: &[Source],
191 limits: Limits,
192 check: &mut impl FnMut() -> Result<()>,
193 ) -> Result<Self> {
194 if sources.len() > limits.entries as usize {
195 return Err(ErrorCode::Limit);
196 }
197 let mut plan = Self {
198 items: Vec::new(),
199 limits,
200 budget: MetadataBudget::default(),
201 total: 0,
202 };
203 let mut roots = std::collections::BTreeSet::new();
204 for source in sources {
205 check()?;
206 let name = archive::valid_name(&source.archive_name, false)?;
207 if !roots.insert(name.to_lowercase()) {
208 return Err(ErrorCode::Conflict);
209 }
210 }
211 for source in sources {
212 let path = source.path.to_path()?;
213 let input = Input::open(&path)?;
214 plan.visit(path, source.archive_name.clone(), input, check)?;
215 }
216 let members = plan
217 .items
218 .iter()
219 .map(|p| Member {
220 entry: p.member.entry.clone(),
221 data: Vec::new(),
222 })
223 .collect::<Vec<_>>();
224 archive::validate_members(&members)?;
225 Ok(plan)
226 }
227 fn visit(
228 &mut self,
229 path: PathBuf,
230 name: String,
231 input: Input,
232 check: &mut impl FnMut() -> Result<()>,
233 ) -> Result<()> {
234 check()?;
235 if self.items.len() >= self.limits.entries as usize {
236 return Err(ErrorCode::Limit);
237 }
238 let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?;
239 let directory = metadata.is_dir();
240 let name = archive::valid_name(&name, directory)?;
241 self.budget.charge(&name)?;
242 self.budget.charge(&path.to_string_lossy())?;
243 let size = if directory { 0 } else { metadata.len() };
244 self.total = self
245 .total
246 .checked_add(size)
247 .filter(|n| *n <= self.limits.input.min(self.limits.output))
248 .ok_or(ErrorCode::Limit)?;
249 self.items.push(Planned {
250 member: Member {
251 entry: Entry {
252 entry_id: self.items.len() as u32,
253 name: name.clone(),
254 kind: if directory {
255 EntryKind::Directory
256 } else {
257 EntryKind::File
258 },
259 size,
260 compressed_size: 0,
261 encrypted: false,
262 },
263 data: Vec::new(),
264 },
265 path: path.clone(),
266 object: filesystem::object(&input.file)?,
267 modified: metadata.modified().ok(),
268 });
269 if directory {
270 let mut children = Vec::new();
271 for entry in input.children(&path)? {
272 check()?;
273 if self.items.len() + children.len() >= self.limits.entries as usize {
274 return Err(ErrorCode::Limit);
275 }
276 let leaf = entry
277 .map_err(crate::space::io_error)?
278 .file_name()
279 .into_string()
280 .map_err(|_| ErrorCode::UnsafePath)?;
281 self.budget.charge(&leaf)?;
282 children.push(leaf);
283 }
284 children.sort();
285 for leaf in children {
286 let child = input.open_child(&path, &leaf)?;
287 self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?;
288 }
289 }
290 Ok(())
291 }
292 pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> {
293 for item in &self.items {
294 check()?;
295 item.open()?;
296 }
297 Ok(())
298 }
299}
300
301#[cfg(test)]
302#[path = "../../../tests/rust-archive-worker/create_sources.rs"]
303mod tests;