| 1 | use crate::{ |
| 2 | archive::{self, Member, MetadataBudget}, |
| 3 | filesystem, |
| 4 | protocol::*, |
| 5 | }; |
| 6 | use std::{ |
| 7 | fs::{self, File, Metadata}, |
| 8 | path::{Component, Path, PathBuf}, |
| 9 | time::SystemTime, |
| 10 | }; |
| 11 | |
| 12 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 13 | |
| 14 | pub(super) struct Input { |
| 15 | pub file: File, |
| 16 | #[cfg(windows)] |
| 17 | _parents: Vec<File>, |
| 18 | } |
| 19 | impl 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 | Ok(pinned) |
| 49 | } |
| 50 | #[cfg(target_os = "linux")] |
| 51 | fn read(pinned: File) -> Result<File> { |
| 52 | use std::os::fd::AsRawFd; |
| 53 | // 읽기 권한은 최종 입력에만 요청함. |
| 54 | File::open(format!("/proc/self/fd/{}", pinned.as_raw_fd())).map_err(crate::space::io_error) |
| 55 | } |
| 56 | pub fn open(path: &Path) -> Result<Self> { |
| 57 | if !path.is_absolute() { |
| 58 | return Err(ErrorCode::InvalidRequest); |
| 59 | } |
| 60 | #[cfg(target_os = "linux")] |
| 61 | { |
| 62 | use std::os::unix::fs::OpenOptionsExt; |
| 63 | let mut file = fs::OpenOptions::new() |
| 64 | .read(true) |
| 65 | .custom_flags(0x200000 | 0x20000 | 0x10000 | 0x80000) |
| 66 | .open("/") |
| 67 | .map_err(crate::space::io_error)?; |
| 68 | for part in path.components() { |
| 69 | match part { |
| 70 | Component::RootDir => {} |
| 71 | Component::Normal(name) => file = Self::child(&file, name)?, |
| 72 | _ => return Err(ErrorCode::UnsafePath), |
| 73 | } |
| 74 | } |
| 75 | let file = Self::read(file)?; |
| 76 | Self::validate(&file)?; |
| 77 | Ok(Self { file }) |
| 78 | } |
| 79 | #[cfg(windows)] |
| 80 | { |
| 81 | use std::os::windows::fs::OpenOptionsExt; |
| 82 | let mut current = PathBuf::new(); |
| 83 | let mut parents = Vec::new(); |
| 84 | for part in path.components() { |
| 85 | match part { |
| 86 | Component::Prefix(_) | Component::RootDir => current.push(part.as_os_str()), |
| 87 | Component::Normal(name) => { |
| 88 | if parents.is_empty() { |
| 89 | parents.push(Self::lock(¤t)?); |
| 90 | } |
| 91 | current.push(name); |
| 92 | parents.push(Self::lock(¤t)?); |
| 93 | } |
| 94 | _ => return Err(ErrorCode::UnsafePath), |
| 95 | } |
| 96 | } |
| 97 | let file = fs::OpenOptions::new() |
| 98 | .read(true) |
| 99 | .share_mode(1) |
| 100 | .custom_flags(0x02000000 | 0x00200000) |
| 101 | .open(¤t) |
| 102 | .map_err(crate::space::io_error)?; |
| 103 | Self::validate(&file)?; |
| 104 | Ok(Self { |
| 105 | file, |
| 106 | _parents: parents, |
| 107 | }) |
| 108 | } |
| 109 | } |
| 110 | #[cfg(windows)] |
| 111 | fn lock(path: &Path) -> Result<File> { |
| 112 | use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; |
| 113 | let file = fs::OpenOptions::new() |
| 114 | .access_mode(0) |
| 115 | .share_mode(3) |
| 116 | .custom_flags(0x02000000 | 0x00200000) |
| 117 | .open(path) |
| 118 | .map_err(crate::space::io_error)?; |
| 119 | if file |
| 120 | .metadata() |
| 121 | .map_err(crate::space::io_error)? |
| 122 | .file_attributes() |
| 123 | & 0x400 |
| 124 | != 0 |
| 125 | { |
| 126 | return Err(ErrorCode::UnsafePath); |
| 127 | } |
| 128 | Ok(file) |
| 129 | } |
| 130 | fn validate(file: &File) -> Result<()> { |
| 131 | let metadata = file.metadata().map_err(crate::space::io_error)?; |
| 132 | #[cfg(windows)] |
| 133 | { |
| 134 | use std::os::windows::fs::MetadataExt; |
| 135 | if metadata.file_attributes() & 0x400 != 0 { |
| 136 | return Err(ErrorCode::UnsafePath); |
| 137 | } |
| 138 | } |
| 139 | if !metadata.is_dir() && !metadata.is_file() { |
| 140 | return Err(ErrorCode::UnsafePath); |
| 141 | } |
| 142 | Ok(()) |
| 143 | } |
| 144 | fn open_child(&self, path: &Path, name: &str) -> Result<Self> { |
| 145 | self.open_named(path, std::ffi::OsStr::new(name)) |
| 146 | } |
| 147 | pub(crate) fn open_named(&self, path: &Path, name: &std::ffi::OsStr) -> Result<Self> { |
| 148 | if !NativePath::from_path(Path::new(name)).is_basename() { |
| 149 | return Err(ErrorCode::UnsafePath); |
| 150 | } |
| 151 | #[cfg(target_os = "linux")] |
| 152 | { |
| 153 | let _ = path; |
| 154 | let file = Self::read(Self::child(&self.file, name)?)?; |
| 155 | Self::validate(&file)?; |
| 156 | Ok(Self { file }) |
| 157 | } |
| 158 | #[cfg(windows)] |
| 159 | { |
| 160 | Self::open(&path.join(name)) |
| 161 | } |
| 162 | } |
| 163 | pub(crate) fn children(&self, path: &Path) -> Result<fs::ReadDir> { |
| 164 | #[cfg(target_os = "linux")] |
| 165 | { |
| 166 | use std::os::fd::AsRawFd; |
| 167 | let _ = path; |
| 168 | fs::read_dir(format!("/proc/self/fd/{}", self.file.as_raw_fd())) |
| 169 | .map_err(crate::space::io_error) |
| 170 | } |
| 171 | #[cfg(windows)] |
| 172 | { |
| 173 | fs::read_dir(path).map_err(crate::space::io_error) |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | pub(super) struct Planned { |
| 179 | pub member: Member, |
| 180 | path: PathBuf, |
| 181 | object: SourceObject, |
| 182 | modified: Option<SystemTime>, |
| 183 | children: Vec<String>, |
| 184 | } |
| 185 | impl Planned { |
| 186 | pub fn open(&self) -> Result<Input> { |
| 187 | let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; |
| 188 | if !self.matches(&input.file)? { |
| 189 | return Err(ErrorCode::SourceChanged); |
| 190 | } |
| 191 | Ok(input) |
| 192 | } |
| 193 | fn matches(&self, file: &File) -> Result<bool> { |
| 194 | let metadata = file.metadata().map_err(crate::space::io_error)?; |
| 195 | Ok(filesystem::object(file)? == self.object |
| 196 | && metadata.modified().ok() == self.modified |
| 197 | && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory) |
| 198 | && (metadata.is_dir() || metadata.len() == self.member.entry.size)) |
| 199 | } |
| 200 | fn verify_with_temporary( |
| 201 | &self, |
| 202 | temporary: &filesystem::PublicationTemp, |
| 203 | check: &mut impl crate::resources::Monitor, |
| 204 | ) -> Result<()> { |
| 205 | let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; |
| 206 | let before = input.file.metadata().map_err(crate::space::io_error)?; |
| 207 | if !before.is_dir() || filesystem::object(&input.file)? != self.object { |
| 208 | return Err(ErrorCode::SourceChanged); |
| 209 | } |
| 210 | // 게시 임시 파일의 부모만 시각 대신 원래 항목과 소유 객체를 대조함. |
| 211 | let mut count = 0; |
| 212 | let mut found = false; |
| 213 | for entry in input.children(&self.path)? { |
| 214 | check.check()?; |
| 215 | let name = entry.map_err(crate::space::io_error)?.file_name(); |
| 216 | let name = name.to_str().ok_or(ErrorCode::SourceChanged)?; |
| 217 | if name == temporary.name { |
| 218 | let child = input |
| 219 | .open_child(&self.path, name) |
| 220 | .map_err(|_| ErrorCode::SourceChanged)?; |
| 221 | if found |
| 222 | || !child |
| 223 | .file |
| 224 | .metadata() |
| 225 | .map_err(crate::space::io_error)? |
| 226 | .is_file() |
| 227 | || filesystem::object(&child.file)? != temporary.object |
| 228 | { |
| 229 | return Err(ErrorCode::SourceChanged); |
| 230 | } |
| 231 | found = true; |
| 232 | } else if self |
| 233 | .children |
| 234 | .binary_search_by(|leaf| leaf.as_str().cmp(name)) |
| 235 | .is_ok() |
| 236 | { |
| 237 | count += 1; |
| 238 | } else { |
| 239 | return Err(ErrorCode::SourceChanged); |
| 240 | } |
| 241 | crate::resources::completed(Ok(()), check)?; |
| 242 | } |
| 243 | let after = input.file.metadata().map_err(crate::space::io_error)?; |
| 244 | if !found || count != self.children.len() || before.modified().ok() != after.modified().ok() |
| 245 | { |
| 246 | return Err(ErrorCode::SourceChanged); |
| 247 | } |
| 248 | Ok(()) |
| 249 | } |
| 250 | } |
| 251 | pub(super) struct Plan { |
| 252 | pub items: Vec<Planned>, |
| 253 | limits: Limits, |
| 254 | budget: MetadataBudget, |
| 255 | total: u64, |
| 256 | } |
| 257 | impl Plan { |
| 258 | pub fn new( |
| 259 | sources: &[Source], |
| 260 | limits: Limits, |
| 261 | check: &mut impl crate::resources::Monitor, |
| 262 | ) -> Result<Self> { |
| 263 | if sources.len() > limits.entries as usize { |
| 264 | return Err(ErrorCode::Limit); |
| 265 | } |
| 266 | let mut plan = Self { |
| 267 | items: Vec::new(), |
| 268 | limits, |
| 269 | budget: MetadataBudget::default(), |
| 270 | total: 0, |
| 271 | }; |
| 272 | let mut roots = std::collections::BTreeSet::new(); |
| 273 | for source in sources { |
| 274 | check.check()?; |
| 275 | let name = archive::valid_name(&source.archive_name, false)?; |
| 276 | if !roots.insert(name.to_lowercase()) { |
| 277 | return Err(ErrorCode::Conflict); |
| 278 | } |
| 279 | crate::resources::completed(Ok(()), check)?; |
| 280 | } |
| 281 | for source in sources { |
| 282 | let path = source.path.to_path()?; |
| 283 | let input = crate::resources::completed(Input::open(&path), check)?; |
| 284 | plan.visit(path, source.archive_name.clone(), input, check)?; |
| 285 | } |
| 286 | let members = plan |
| 287 | .items |
| 288 | .iter() |
| 289 | .map(|p| { |
| 290 | crate::resources::completed( |
| 291 | Ok(Member { |
| 292 | entry: p.member.entry.clone(), |
| 293 | data: Vec::new(), |
| 294 | }), |
| 295 | check, |
| 296 | ) |
| 297 | }) |
| 298 | .collect::<Result<Vec<_>>>()?; |
| 299 | archive::validate_members_with(&members, check)?; |
| 300 | Ok(plan) |
| 301 | } |
| 302 | fn visit( |
| 303 | &mut self, |
| 304 | path: PathBuf, |
| 305 | name: String, |
| 306 | input: Input, |
| 307 | check: &mut impl crate::resources::Monitor, |
| 308 | ) -> Result<()> { |
| 309 | check.check()?; |
| 310 | if self.items.len() >= self.limits.entries as usize { |
| 311 | return Err(ErrorCode::Limit); |
| 312 | } |
| 313 | let metadata: Metadata = crate::resources::completed( |
| 314 | input.file.metadata().map_err(crate::space::io_error), |
| 315 | check, |
| 316 | )?; |
| 317 | let directory = metadata.is_dir(); |
| 318 | let name = archive::valid_name(&name, directory)?; |
| 319 | self.budget.charge_with(&name, check.metadata_limits())?; |
| 320 | self.budget |
| 321 | .charge_copy(&path.to_string_lossy(), check.metadata_limits())?; |
| 322 | let size = if directory { 0 } else { metadata.len() }; |
| 323 | self.total = self |
| 324 | .total |
| 325 | .checked_add(size) |
| 326 | .filter(|n| *n <= self.limits.input.min(self.limits.output)) |
| 327 | .ok_or(ErrorCode::Limit)?; |
| 328 | check.observe( |
| 329 | ResourceUsage { |
| 330 | estimated_bytes: Some(self.total), |
| 331 | actual_entries: Some(self.items.len() as u32 + 1), |
| 332 | ..ResourceUsage::default() |
| 333 | }, |
| 334 | None, |
| 335 | )?; |
| 336 | crate::resources::completed(Ok(()), check)?; |
| 337 | let index = self.items.len(); |
| 338 | self.items.push(Planned { |
| 339 | member: Member { |
| 340 | entry: Entry { |
| 341 | entry_id: self.items.len() as u32, |
| 342 | name: name.clone(), |
| 343 | kind: if directory { |
| 344 | EntryKind::Directory |
| 345 | } else { |
| 346 | EntryKind::File |
| 347 | }, |
| 348 | size, |
| 349 | compressed_size: 0, |
| 350 | encrypted: false, |
| 351 | }, |
| 352 | data: Vec::new(), |
| 353 | }, |
| 354 | path: path.clone(), |
| 355 | object: crate::resources::completed(filesystem::object(&input.file), check)?, |
| 356 | modified: metadata.modified().ok(), |
| 357 | children: Vec::new(), |
| 358 | }); |
| 359 | if directory { |
| 360 | let mut children = Vec::new(); |
| 361 | for entry in input.children(&path)? { |
| 362 | check.check()?; |
| 363 | if self.items.len() + children.len() >= self.limits.entries as usize { |
| 364 | return Err(ErrorCode::Limit); |
| 365 | } |
| 366 | let leaf = entry |
| 367 | .map_err(crate::space::io_error)? |
| 368 | .file_name() |
| 369 | .into_string() |
| 370 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 371 | self.budget.charge_copy(&leaf, check.metadata_limits())?; |
| 372 | children.push(leaf); |
| 373 | check.observe( |
| 374 | ResourceUsage { |
| 375 | estimated_bytes: Some(self.total), |
| 376 | estimated_entries: Some((self.items.len() + children.len()) as u32), |
| 377 | ..ResourceUsage::default() |
| 378 | }, |
| 379 | None, |
| 380 | )?; |
| 381 | crate::resources::completed(Ok(()), check)?; |
| 382 | } |
| 383 | children.sort(); |
| 384 | for leaf in &children { |
| 385 | let child = crate::resources::completed(input.open_child(&path, leaf), check)?; |
| 386 | self.visit(path.join(leaf), format!("{name}/{leaf}"), child, check)?; |
| 387 | } |
| 388 | self.items[index].children = children; |
| 389 | } |
| 390 | Ok(()) |
| 391 | } |
| 392 | pub fn reserve_metadata( |
| 393 | &mut self, |
| 394 | bytes: usize, |
| 395 | check: &impl crate::resources::Monitor, |
| 396 | ) -> Result<()> { |
| 397 | self.budget.charge_bytes(bytes, check.metadata_limits()) |
| 398 | } |
| 399 | pub fn verify(&self, check: &mut impl crate::resources::Monitor) -> Result<()> { |
| 400 | for item in &self.items { |
| 401 | check.check()?; |
| 402 | item.open()?; |
| 403 | crate::resources::completed(Ok(()), check)?; |
| 404 | } |
| 405 | Ok(()) |
| 406 | } |
| 407 | pub fn verify_for_publication( |
| 408 | &self, |
| 409 | temporary: &filesystem::PublicationTemp, |
| 410 | check: &mut impl crate::resources::Monitor, |
| 411 | ) -> Result<()> { |
| 412 | for item in &self.items { |
| 413 | check.check()?; |
| 414 | if item.member.entry.kind == EntryKind::Directory && item.object == temporary.parent { |
| 415 | item.verify_with_temporary(temporary, check)?; |
| 416 | } else { |
| 417 | item.open()?; |
| 418 | } |
| 419 | crate::resources::completed(Ok(()), check)?; |
| 420 | } |
| 421 | Ok(()) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | #[cfg(test)] |
| 426 | #[path = "../../../tests/rust-archive-worker/create_sources.rs"] |
| 427 | mod tests; |