| 1 | use crate::{ |
| 2 | archive, |
| 3 | filesystem::{self, Dir}, |
| 4 | protocol::*, |
| 5 | resources::{Budget, Monitor, Watchdog, completed}, |
| 6 | wire::{Reader, Writer}, |
| 7 | }; |
| 8 | use std::{ |
| 9 | collections::BTreeSet, |
| 10 | io::{Read, Seek, SeekFrom, Write}, |
| 11 | sync::{Arc, Condvar, Mutex}, |
| 12 | time::{Duration, Instant}, |
| 13 | }; |
| 14 | |
| 15 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 16 | #[derive(PartialEq, Eq)] |
| 17 | enum Challenge { |
| 18 | Password(u64), |
| 19 | Conflict(u64), |
| 20 | Resource(u64, ResourceScope), |
| 21 | } |
| 22 | struct State<W> { |
| 23 | writer: Writer<W>, |
| 24 | cancelled: bool, |
| 25 | phase: u8, |
| 26 | fault: Option<ErrorCode>, |
| 27 | challenge: Option<Challenge>, |
| 28 | conflict_reply: Option<(ConflictChoice, bool)>, |
| 29 | password: Option<Secret>, |
| 30 | resource_reply: Option<bool>, |
| 31 | input_closed: bool, |
| 32 | } |
| 33 | struct Job<W> { |
| 34 | state: Arc<Mutex<State<W>>>, |
| 35 | wake: Arc<Condvar>, |
| 36 | next_challenge: u64, |
| 37 | interactive: bool, |
| 38 | action: ActionKind, |
| 39 | budget: Option<Budget>, |
| 40 | watchdog: Watchdog, |
| 41 | remaining_choice: Option<ConflictChoice>, |
| 42 | source_group: Option<crate::split_seven_zip::Group>, |
| 43 | started: Instant, |
| 44 | terminal: Terminal, |
| 45 | parent: crate::parent::Parent, |
| 46 | } |
| 47 | impl<W: Write> Job<W> { |
| 48 | fn request_resource( |
| 49 | &mut self, |
| 50 | scope: ResourceScope, |
| 51 | mut usage: ResourceUsage, |
| 52 | storage: Option<&std::fs::File>, |
| 53 | ) -> Result<()> { |
| 54 | let budget = self.budget.as_ref().ok_or(ErrorCode::Internal)?; |
| 55 | let (soft_limits, ceiling) = (budget.soft, budget.ceiling); |
| 56 | if let Some(file) = storage { |
| 57 | usage.available_bytes = |
| 58 | Some(crate::space::available(file)?.min(u64::MAX as u128) as u64); |
| 59 | } |
| 60 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 61 | let id = self.next_challenge; |
| 62 | let state_ref = Arc::clone(&self.state); |
| 63 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 64 | if state.challenge.is_some() { |
| 65 | return Err(ErrorCode::Internal); |
| 66 | } |
| 67 | state.challenge = Some(Challenge::Resource(id, scope)); |
| 68 | state |
| 69 | .writer |
| 70 | .send(&Message::ResourceRequired { |
| 71 | challenge_id: id, |
| 72 | action: self.action, |
| 73 | scope, |
| 74 | usage, |
| 75 | soft_limits, |
| 76 | ceiling, |
| 77 | }) |
| 78 | .map_err(|_| ErrorCode::Io)?; |
| 79 | let waiting = Instant::now(); |
| 80 | loop { |
| 81 | self.parent.check()?; |
| 82 | if let Some(error) = state.fault { |
| 83 | return Err(error); |
| 84 | } |
| 85 | if state.cancelled { |
| 86 | return Err(ErrorCode::None); |
| 87 | } |
| 88 | if let Some(allow) = state.resource_reply.take() { |
| 89 | if !allow { |
| 90 | return Err(ErrorCode::None); |
| 91 | } |
| 92 | self.budget |
| 93 | .as_mut() |
| 94 | .ok_or(ErrorCode::Internal)? |
| 95 | .grant(scope); |
| 96 | self.watchdog.resume(self.started.elapsed(), true); |
| 97 | return Ok(()); |
| 98 | } |
| 99 | if state.input_closed { |
| 100 | return Err(ErrorCode::Protocol); |
| 101 | } |
| 102 | if waiting.elapsed() >= Duration::from_secs(300) { |
| 103 | return Err(ErrorCode::Limit); |
| 104 | } |
| 105 | state = self |
| 106 | .wake |
| 107 | .wait_timeout(state, Duration::from_millis(50)) |
| 108 | .map_err(|_| ErrorCode::Internal)? |
| 109 | .0; |
| 110 | } |
| 111 | } |
| 112 | fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> { |
| 113 | self.check()?; |
| 114 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 115 | let id = self.next_challenge; |
| 116 | let state_ref = Arc::clone(&self.state); |
| 117 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 118 | state.challenge = Some(Challenge::Password(id)); |
| 119 | state |
| 120 | .writer |
| 121 | .send(&Message::PasswordRequired { |
| 122 | challenge_id: id, |
| 123 | attempt, |
| 124 | purpose, |
| 125 | }) |
| 126 | .map_err(|_| ErrorCode::Io)?; |
| 127 | let waiting = Instant::now(); |
| 128 | loop { |
| 129 | self.parent.check()?; |
| 130 | if let Some(error) = state.fault { |
| 131 | return Err(error); |
| 132 | } |
| 133 | if state.cancelled { |
| 134 | return Err(ErrorCode::None); |
| 135 | } |
| 136 | if let Some(secret) = state.password.take() { |
| 137 | self.watchdog.resume(self.started.elapsed(), false); |
| 138 | return Ok(secret); |
| 139 | } |
| 140 | if state.input_closed { |
| 141 | return Err(ErrorCode::Protocol); |
| 142 | } |
| 143 | if if self.budget.is_some() { |
| 144 | waiting.elapsed() >= Duration::from_secs(300) |
| 145 | } else { |
| 146 | self.started.elapsed() > Duration::from_secs(300) |
| 147 | } { |
| 148 | return Err(ErrorCode::Limit); |
| 149 | } |
| 150 | state = self |
| 151 | .wake |
| 152 | .wait_timeout(state, Duration::from_millis(50)) |
| 153 | .map_err(|_| ErrorCode::Internal)? |
| 154 | .0; |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | fn conflict(&mut self, entry: &Entry, existing_size: u64) -> Result<ConflictChoice> { |
| 159 | self.check()?; |
| 160 | if let Some(choice) = self.remaining_choice { |
| 161 | return Ok(choice); |
| 162 | } |
| 163 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 164 | let id = self.next_challenge; |
| 165 | let state_ref = Arc::clone(&self.state); |
| 166 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 167 | state.challenge = Some(Challenge::Conflict(id)); |
| 168 | state |
| 169 | .writer |
| 170 | .send(&Message::ConflictRequired { |
| 171 | challenge_id: id, |
| 172 | entry_id: entry.entry_id, |
| 173 | relative_name: entry.name.clone(), |
| 174 | incoming_size: entry.size, |
| 175 | existing_size, |
| 176 | }) |
| 177 | .map_err(|_| ErrorCode::Io)?; |
| 178 | let waiting = Instant::now(); |
| 179 | loop { |
| 180 | self.parent.check()?; |
| 181 | if let Some(error) = state.fault { |
| 182 | return Err(error); |
| 183 | } |
| 184 | if state.cancelled { |
| 185 | return Err(ErrorCode::None); |
| 186 | } |
| 187 | if let Some((choice, apply)) = state.conflict_reply.take() { |
| 188 | if apply { |
| 189 | self.remaining_choice = Some(choice); |
| 190 | } |
| 191 | self.watchdog.resume(self.started.elapsed(), false); |
| 192 | return Ok(choice); |
| 193 | } |
| 194 | if state.input_closed { |
| 195 | return Err(ErrorCode::Protocol); |
| 196 | } |
| 197 | if if self.budget.is_some() { |
| 198 | waiting.elapsed() >= Duration::from_secs(300) |
| 199 | } else { |
| 200 | self.started.elapsed() > Duration::from_secs(300) |
| 201 | } { |
| 202 | return Err(ErrorCode::Limit); |
| 203 | } |
| 204 | state = self |
| 205 | .wake |
| 206 | .wait_timeout(state, Duration::from_millis(50)) |
| 207 | .map_err(|_| ErrorCode::Internal)? |
| 208 | .0; |
| 209 | } |
| 210 | } |
| 211 | fn rename(&mut self, root: &Dir, name: &str, reserved: &BTreeSet<String>) -> Result<String> { |
| 212 | let (prefix, leaf) = name.rsplit_once('/').unwrap_or(("", name)); |
| 213 | let (stem, extension) = match leaf.rsplit_once('.') { |
| 214 | Some((stem, ext)) if !stem.is_empty() => (stem, format!(".{ext}")), |
| 215 | _ => (leaf, String::new()), |
| 216 | }; |
| 217 | for index in 1..=10000 { |
| 218 | self.check()?; |
| 219 | fn clip(text: &str, bytes: usize) -> &str { |
| 220 | let mut end = text.len().min(bytes); |
| 221 | while !text.is_char_boundary(end) { |
| 222 | end -= 1; |
| 223 | } |
| 224 | &text[..end] |
| 225 | } |
| 226 | let suffix = format!(" ({index})"); |
| 227 | let extension = clip(&extension, 255 - suffix.len() - 4).trim_end_matches(['.', ' ']); |
| 228 | let stem = clip(stem, 255 - suffix.len() - extension.len()); |
| 229 | let stem = if stem.is_empty() { "file" } else { stem }; |
| 230 | let leaf = format!("{stem}{suffix}{extension}"); |
| 231 | let candidate = if prefix.is_empty() { |
| 232 | leaf |
| 233 | } else { |
| 234 | format!("{prefix}/{leaf}") |
| 235 | }; |
| 236 | archive::valid_name(&candidate, false)?; |
| 237 | let unused = !reserved.contains(&candidate.to_lowercase()) |
| 238 | && filesystem::unused_with(root, &candidate, self)?; |
| 239 | completed(Ok(()), self)?; |
| 240 | if unused { |
| 241 | return Ok(candidate); |
| 242 | } |
| 243 | } |
| 244 | Err(ErrorCode::Conflict) |
| 245 | } |
| 246 | fn event(&mut self, event: Message) -> Result<()> { |
| 247 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 248 | state.writer.send(&event).map_err(|_| { |
| 249 | state.fault = Some(ErrorCode::Io); |
| 250 | ErrorCode::Io |
| 251 | }) |
| 252 | } |
| 253 | fn split_result<T>( |
| 254 | &mut self, |
| 255 | result: std::result::Result<T, crate::split_seven_zip::Failure>, |
| 256 | ) -> Result<T> { |
| 257 | match result { |
| 258 | Ok(value) => Ok(value), |
| 259 | Err(failure) => { |
| 260 | self.check()?; |
| 261 | if let Some((reason, volume)) = failure.problem { |
| 262 | self.event(Message::VolumeProblem { reason, volume })?; |
| 263 | } |
| 264 | Err(failure.error) |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | fn verify_split(&mut self) -> Result<()> { |
| 269 | let Some(group) = self.source_group.take() else { |
| 270 | return Ok(()); |
| 271 | }; |
| 272 | let result = (|| { |
| 273 | self.progress(Stage::Verify, 0, None, 0)?; |
| 274 | group.verify(&mut |step| match step { |
| 275 | crate::spool::Step::Check => self.check(), |
| 276 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 277 | crate::spool::Step::Read { bytes, total } => { |
| 278 | self.progress(Stage::Verify, bytes, Some(total), 0) |
| 279 | } |
| 280 | }) |
| 281 | })(); |
| 282 | self.source_group = Some(group); |
| 283 | self.split_result(result) |
| 284 | } |
| 285 | fn check(&mut self) -> Result<()> { |
| 286 | self.parent.check()?; |
| 287 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 288 | if let Some(error) = state.fault { |
| 289 | return Err(error); |
| 290 | } |
| 291 | if state.cancelled && state.phase == 0 { |
| 292 | return Err(ErrorCode::None); |
| 293 | } |
| 294 | self.watchdog.check(self.started.elapsed()) |
| 295 | } |
| 296 | fn cutoff(&mut self) -> Result<()> { |
| 297 | self.check()?; |
| 298 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 299 | if state.phase == 0 && state.cancelled { |
| 300 | return Err(ErrorCode::None); |
| 301 | } |
| 302 | state.phase = 1; |
| 303 | Ok(()) |
| 304 | } |
| 305 | fn progress( |
| 306 | &mut self, |
| 307 | stage: Stage, |
| 308 | bytes: u64, |
| 309 | total: Option<u64>, |
| 310 | entries: u32, |
| 311 | ) -> Result<()> { |
| 312 | self.event(Message::Progress { |
| 313 | stage, |
| 314 | processed_bytes: bytes, |
| 315 | total_bytes: total, |
| 316 | completed_entries: entries, |
| 317 | }) |
| 318 | } |
| 319 | fn output_reader( |
| 320 | &mut self, |
| 321 | root: &Dir, |
| 322 | name: &str, |
| 323 | data: &mut impl Read, |
| 324 | length: u64, |
| 325 | id: Option<u32>, |
| 326 | last: bool, |
| 327 | replace: Option<&filesystem::Existing>, |
| 328 | ) -> Result<()> { |
| 329 | self.check()?; |
| 330 | self.progress( |
| 331 | Stage::Write, |
| 332 | 0, |
| 333 | Some(length), |
| 334 | self.terminal.created_count as u32, |
| 335 | )?; |
| 336 | let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| { |
| 337 | match step { |
| 338 | filesystem::PublishStep::Check => self.check(), |
| 339 | filesystem::PublishStep::Activity => completed(Ok(()), self), |
| 340 | filesystem::PublishStep::Commit => { |
| 341 | if self.terminal.created_count == 0 { |
| 342 | self.verify_split()?; |
| 343 | } |
| 344 | if last { self.cutoff() } else { self.check() } |
| 345 | } |
| 346 | } |
| 347 | }); |
| 348 | self.terminal.retained_partial_count += p.retained; |
| 349 | if p.cleanup != Cleanup::Complete { |
| 350 | self.terminal.cleanup = p.cleanup; |
| 351 | } |
| 352 | if p.created { |
| 353 | self.terminal.created_count += 1; |
| 354 | self.terminal.publication = Publication::Partial; |
| 355 | self.terminal.durability = match (self.terminal.durability, p.durability) { |
| 356 | (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, |
| 357 | (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { |
| 358 | Durability::Unconfirmed |
| 359 | } |
| 360 | _ => p.durability, |
| 361 | }; |
| 362 | self.event(Message::Output { |
| 363 | entry_id: id, |
| 364 | relative_name: name.to_owned(), |
| 365 | disposition: Disposition::Created, |
| 366 | })?; |
| 367 | } |
| 368 | if p.uncertain { |
| 369 | self.terminal.publication = Publication::Uncertain; |
| 370 | self.terminal.durability = Durability::Unconfirmed; |
| 371 | self.event(Message::Output { |
| 372 | entry_id: id, |
| 373 | relative_name: name.to_owned(), |
| 374 | disposition: Disposition::CommitUncertain, |
| 375 | })?; |
| 376 | } |
| 377 | if p.retained != 0 { |
| 378 | self.event(Message::Output { |
| 379 | entry_id: id, |
| 380 | relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?, |
| 381 | disposition: Disposition::PartialRetained, |
| 382 | })?; |
| 383 | } |
| 384 | if let Some(error) = p.error { |
| 385 | return Err(error); |
| 386 | } |
| 387 | if p.created { |
| 388 | completed(Ok(()), self)?; |
| 389 | } |
| 390 | Ok(()) |
| 391 | } |
| 392 | fn preview( |
| 393 | &mut self, |
| 394 | archive: NativePath, |
| 395 | entry_id: u32, |
| 396 | expected: ListId, |
| 397 | limits: Limits, |
| 398 | ) -> Result<()> { |
| 399 | use sha2::{Digest, Sha256}; |
| 400 | use std::io::{Read, Seek, SeekFrom}; |
| 401 | let path = archive.to_path()?; |
| 402 | if crate::split_seven_zip::is_split(&path) |
| 403 | || crate::split_seven_zip::unsupported_split(&path) |
| 404 | || matches!(expected.source_object, SourceObject::SplitSevenZip { .. }) |
| 405 | { |
| 406 | return Err(ErrorCode::UnsupportedFeature); |
| 407 | } |
| 408 | self.progress(Stage::Read, 0, None, 0)?; |
| 409 | let mut snapshot = |
| 410 | crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step { |
| 411 | crate::spool::Step::Check => self.check(), |
| 412 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 413 | crate::spool::Step::Read { bytes, total } => { |
| 414 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 415 | } |
| 416 | })?; |
| 417 | if expected.catalog_version != 1 |
| 418 | || expected.source_object != snapshot.object |
| 419 | || expected.archive_bytes != snapshot.len |
| 420 | || expected.archive_sha256 != snapshot.hash |
| 421 | { |
| 422 | return Err(ErrorCode::SourceChanged); |
| 423 | } |
| 424 | let mut catalog = crate::streaming::Catalog::open( |
| 425 | &mut snapshot.file, |
| 426 | snapshot.len, |
| 427 | limits, |
| 428 | false, |
| 429 | None, |
| 430 | self, |
| 431 | )?; |
| 432 | if expected.format != catalog.format { |
| 433 | return Err(ErrorCode::SourceChanged); |
| 434 | } |
| 435 | let entry = catalog |
| 436 | .members |
| 437 | .get(entry_id as usize) |
| 438 | .ok_or(ErrorCode::InvalidRequest)? |
| 439 | .entry |
| 440 | .clone(); |
| 441 | if entry.entry_id != entry_id || entry.kind != EntryKind::File { |
| 442 | return Err(ErrorCode::InvalidRequest); |
| 443 | } |
| 444 | let name = if catalog.format == Format::Gzip { |
| 445 | let name = path |
| 446 | .file_name() |
| 447 | .and_then(|s| s.to_str()) |
| 448 | .ok_or(ErrorCode::UnsupportedFeature)?; |
| 449 | if !name.to_ascii_lowercase().ends_with(".gz") { |
| 450 | return Err(ErrorCode::UnsupportedFeature); |
| 451 | } |
| 452 | &name[..name.len() - 3] |
| 453 | } else { |
| 454 | &entry.name |
| 455 | }; |
| 456 | let kind = crate::preview::Kind::from_name(name)?; |
| 457 | if entry.size > kind.limit() { |
| 458 | return Err(ErrorCode::Limit); |
| 459 | } |
| 460 | self.progress(Stage::Decode, 0, Some(entry.size), 0)?; |
| 461 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 462 | for attempt in 1..=3 { |
| 463 | let secret = if entry.encrypted { |
| 464 | Some(self.password(PasswordPurpose::Decrypt, attempt)?) |
| 465 | } else { |
| 466 | None |
| 467 | }; |
| 468 | match crate::streaming::Catalog::preview( |
| 469 | &mut snapshot.file, |
| 470 | snapshot.len, |
| 471 | limits, |
| 472 | secret.as_ref().map(|s| s.0.as_slice()), |
| 473 | entry_id, |
| 474 | self, |
| 475 | ) { |
| 476 | Ok(decoded) => { |
| 477 | catalog = decoded; |
| 478 | break; |
| 479 | } |
| 480 | Err(ErrorCode::WrongPassword) if entry.encrypted && attempt < 3 => continue, |
| 481 | Err(error) => return Err(error), |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | let mut bytes = Vec::new(); |
| 486 | bytes |
| 487 | .try_reserve_exact(entry.size as usize) |
| 488 | .map_err(|_| ErrorCode::Limit)?; |
| 489 | catalog |
| 490 | .data |
| 491 | .seek(SeekFrom::Start(catalog.offsets[entry_id as usize])) |
| 492 | .map_err(crate::space::io_error)?; |
| 493 | let mut remaining = entry.size; |
| 494 | let mut chunk = [0; 32768]; |
| 495 | while remaining != 0 { |
| 496 | self.check()?; |
| 497 | let length = remaining.min(chunk.len() as u64) as usize; |
| 498 | catalog |
| 499 | .data |
| 500 | .read_exact(&mut chunk[..length]) |
| 501 | .map_err(|_| ErrorCode::Integrity)?; |
| 502 | bytes.extend_from_slice(&chunk[..length]); |
| 503 | remaining -= length as u64; |
| 504 | completed(Ok(()), self)?; |
| 505 | } |
| 506 | let (info, bytes) = crate::preview::decode(kind, entry_id, bytes, self)?; |
| 507 | self.check()?; |
| 508 | let hash: [u8; 32] = Sha256::digest(&bytes).into(); |
| 509 | completed(self.event(Message::PreviewBegin(info)), self)?; |
| 510 | for (index, chunk) in bytes.chunks(MAX_PREVIEW_CHUNK_BYTES).enumerate() { |
| 511 | self.check()?; |
| 512 | completed( |
| 513 | self.event(Message::PreviewChunk { |
| 514 | entry_id, |
| 515 | offset: (index * MAX_PREVIEW_CHUNK_BYTES) as u64, |
| 516 | data: chunk.to_vec(), |
| 517 | }), |
| 518 | self, |
| 519 | )?; |
| 520 | } |
| 521 | self.check()?; |
| 522 | completed( |
| 523 | self.event(Message::PreviewEnd { |
| 524 | entry_id, |
| 525 | total_bytes: info.total_bytes, |
| 526 | sha256: hash, |
| 527 | }), |
| 528 | self, |
| 529 | )?; |
| 530 | Ok(()) |
| 531 | } |
| 532 | fn run(&mut self, start: Start) -> Result<()> { |
| 533 | if !start.limits.valid() { |
| 534 | return Err(ErrorCode::InvalidRequest); |
| 535 | } |
| 536 | let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); |
| 537 | self.event(Message::Accepted { |
| 538 | action: start.action.kind(), |
| 539 | encryption: true, |
| 540 | })?; |
| 541 | self.check()?; |
| 542 | if let Some(budget) = &self.budget { |
| 543 | let scope = ResourceScope { |
| 544 | output: budget.ceiling.output > budget.soft.output, |
| 545 | entries: budget.ceiling.entries > budget.soft.entries, |
| 546 | ratio: false, |
| 547 | }; |
| 548 | if scope.any() { |
| 549 | let temporary = crate::spool::temporary()?; |
| 550 | self.request_resource(scope, ResourceUsage::default(), Some(&temporary))?; |
| 551 | } |
| 552 | } |
| 553 | match start.action { |
| 554 | Action::List { |
| 555 | archive: ref source, |
| 556 | } |
| 557 | | Action::Extract { |
| 558 | archive: ref source, |
| 559 | .. |
| 560 | } => { |
| 561 | let extract = matches!(start.action, Action::Extract { .. }); |
| 562 | let path = source.to_path()?; |
| 563 | self.progress( |
| 564 | if crate::split_seven_zip::is_split(&path) { |
| 565 | Stage::Scan |
| 566 | } else { |
| 567 | Stage::Read |
| 568 | }, |
| 569 | 0, |
| 570 | None, |
| 571 | 0, |
| 572 | )?; |
| 573 | let expected = match &start.action { |
| 574 | Action::Extract { list_id, .. } => list_id.as_ref(), |
| 575 | _ => None, |
| 576 | }; |
| 577 | let metadata_limits = self.metadata_limits(); |
| 578 | let captured = crate::split_seven_zip::open( |
| 579 | &path, |
| 580 | expected, |
| 581 | limits.input, |
| 582 | metadata_limits, |
| 583 | &mut |step| match step { |
| 584 | crate::spool::Step::Check => self.check(), |
| 585 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 586 | crate::spool::Step::Read { bytes, total } => { |
| 587 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 588 | } |
| 589 | }, |
| 590 | ); |
| 591 | let mut snapshot = if let Some(captured) = self.split_result(captured)? { |
| 592 | self.source_group = Some(captured.group); |
| 593 | captured.snapshot |
| 594 | } else { |
| 595 | crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| { |
| 596 | match step { |
| 597 | crate::spool::Step::Check => self.check(), |
| 598 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 599 | crate::spool::Step::Read { bytes, total } => { |
| 600 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 601 | } |
| 602 | } |
| 603 | })? |
| 604 | }; |
| 605 | if let Action::Extract { |
| 606 | list_id: Some(expected), |
| 607 | .. |
| 608 | } = &start.action |
| 609 | { |
| 610 | if expected.catalog_version != if self.source_group.is_some() { 2 } else { 1 } |
| 611 | || expected.source_object != snapshot.object |
| 612 | || expected.archive_bytes != snapshot.len |
| 613 | || expected.archive_sha256 != snapshot.hash |
| 614 | { |
| 615 | return Err(ErrorCode::SourceChanged); |
| 616 | } |
| 617 | } |
| 618 | self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?; |
| 619 | let mut catalog = crate::streaming::Catalog::open( |
| 620 | &mut snapshot.file, |
| 621 | snapshot.len, |
| 622 | limits, |
| 623 | false, |
| 624 | None, |
| 625 | self, |
| 626 | )?; |
| 627 | let list_id = ListId { |
| 628 | catalog_version: if self.source_group.is_some() { 2 } else { 1 }, |
| 629 | format: catalog.format, |
| 630 | source_object: snapshot.object, |
| 631 | archive_bytes: snapshot.len, |
| 632 | archive_sha256: snapshot.hash, |
| 633 | }; |
| 634 | if !extract { |
| 635 | for member in &catalog.members { |
| 636 | self.check()?; |
| 637 | completed(self.event(Message::Entry(member.entry.clone())), self)?; |
| 638 | } |
| 639 | self.verify_split()?; |
| 640 | completed( |
| 641 | self.event(Message::ListEnd { |
| 642 | entry_count: catalog.members.len() as u32, |
| 643 | list_id, |
| 644 | }), |
| 645 | self, |
| 646 | )?; |
| 647 | } else if let Action::Extract { |
| 648 | destination, |
| 649 | selection, |
| 650 | list_id: expected, |
| 651 | gzip_output_name, |
| 652 | .. |
| 653 | } = start.action |
| 654 | { |
| 655 | if expected |
| 656 | .as_ref() |
| 657 | .is_some_and(|expected| *expected != list_id) |
| 658 | { |
| 659 | return Err(ErrorCode::SourceChanged); |
| 660 | } |
| 661 | let selected = match selection { |
| 662 | Selection::All => None, |
| 663 | Selection::EntryIds(ids) => { |
| 664 | if expected.is_none() || ids.is_empty() { |
| 665 | return Err(ErrorCode::InvalidRequest); |
| 666 | } |
| 667 | let mut set = BTreeSet::new(); |
| 668 | for id in ids { |
| 669 | if id as usize >= catalog.members.len() || !set.insert(id) { |
| 670 | return Err(ErrorCode::InvalidRequest); |
| 671 | } |
| 672 | completed(Ok(()), self)?; |
| 673 | } |
| 674 | Some(set) |
| 675 | } |
| 676 | }; |
| 677 | for member in &catalog.members { |
| 678 | if !matches!(member.entry.kind, EntryKind::File | EntryKind::Directory) { |
| 679 | return Err(ErrorCode::UnsafePath); |
| 680 | } |
| 681 | completed(Ok(()), self)?; |
| 682 | } |
| 683 | if catalog.format == Format::Gzip { |
| 684 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| 685 | let checked = archive::valid_name(&name, false) |
| 686 | .map_err(|_| ErrorCode::InvalidRequest)?; |
| 687 | if checked.contains('/') { |
| 688 | return Err(ErrorCode::InvalidRequest); |
| 689 | } |
| 690 | catalog.members[0].entry.name = checked; |
| 691 | } else if gzip_output_name.is_some() { |
| 692 | return Err(ErrorCode::InvalidRequest); |
| 693 | } |
| 694 | let root = completed(Dir::root(&destination.to_path()?), self)?; |
| 695 | let mut output_sizes = Vec::new(); |
| 696 | let mut staged_total = 0u64; |
| 697 | let mut encrypted = false; |
| 698 | for member in &catalog.members { |
| 699 | if member.entry.kind == EntryKind::File |
| 700 | && selected |
| 701 | .as_ref() |
| 702 | .is_none_or(|s| s.contains(&member.entry.entry_id)) |
| 703 | { |
| 704 | output_sizes.push((member.entry.name.clone(), member.entry.size)); |
| 705 | } |
| 706 | staged_total = staged_total |
| 707 | .checked_add(member.entry.size) |
| 708 | .ok_or(ErrorCode::Limit)?; |
| 709 | encrypted |= member.entry.encrypted; |
| 710 | completed(Ok(()), self)?; |
| 711 | } |
| 712 | let staged = matches!(catalog.format, Format::Zip | Format::SevenZip) |
| 713 | .then_some((&catalog.data, staged_total)); |
| 714 | // 선택 전에는 검증에 필요한 스테이징 공간만 계산함. |
| 715 | let initial_outputs = if self.interactive { |
| 716 | &[][..] |
| 717 | } else { |
| 718 | &output_sizes[..] |
| 719 | }; |
| 720 | filesystem::preflight_space_with(&root, initial_outputs, staged, self)?; |
| 721 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 722 | for attempt in 1..=3 { |
| 723 | let secret = if encrypted { |
| 724 | Some(self.password(PasswordPurpose::Decrypt, attempt)?) |
| 725 | } else { |
| 726 | None |
| 727 | }; |
| 728 | match crate::streaming::Catalog::open( |
| 729 | &mut snapshot.file, |
| 730 | snapshot.len, |
| 731 | limits, |
| 732 | true, |
| 733 | secret.as_ref().map(|s| s.0.as_slice()), |
| 734 | self, |
| 735 | ) { |
| 736 | Ok(decoded) => { |
| 737 | catalog = decoded; |
| 738 | break; |
| 739 | } |
| 740 | Err(ErrorCode::WrongPassword) if attempt < 3 => continue, |
| 741 | Err(error) => return Err(error), |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | let offsets = catalog.offsets; |
| 746 | let mut data = catalog.data; |
| 747 | let mut members = Vec::new(); |
| 748 | for member in catalog.members { |
| 749 | if selected |
| 750 | .as_ref() |
| 751 | .is_none_or(|s| s.contains(&member.entry.entry_id)) |
| 752 | { |
| 753 | members.push(member); |
| 754 | } |
| 755 | completed(Ok(()), self)?; |
| 756 | } |
| 757 | let dirs = archive::output_directories(&members, self)?; |
| 758 | let files = members |
| 759 | .iter() |
| 760 | .filter(|m| m.entry.kind == EntryKind::File) |
| 761 | .map(|member| completed(Ok(member), self)) |
| 762 | .collect::<Result<Vec<_>>>()?; |
| 763 | let mut names = dirs |
| 764 | .iter() |
| 765 | .map(|name| completed(Ok((name.clone(), EntryKind::Directory)), self)) |
| 766 | .collect::<Result<Vec<_>>>()?; |
| 767 | names.extend( |
| 768 | files |
| 769 | .iter() |
| 770 | .map(|member| { |
| 771 | completed(Ok((member.entry.name.clone(), EntryKind::File)), self) |
| 772 | }) |
| 773 | .collect::<Result<Vec<_>>>()?, |
| 774 | ); |
| 775 | filesystem::preflight_mode_with(&root, &names, self.interactive, self)?; |
| 776 | if !self.interactive { |
| 777 | filesystem::preflight_space_with(&root, &output_sizes, None, self)?; |
| 778 | } |
| 779 | let mut reserved = names |
| 780 | .iter() |
| 781 | .map(|(name, _)| completed(Ok(name.to_lowercase()), self)) |
| 782 | .collect::<Result<BTreeSet<_>>>()?; |
| 783 | for name in dirs { |
| 784 | self.check()?; |
| 785 | if self.terminal.created_count == 0 { |
| 786 | self.verify_split()?; |
| 787 | } |
| 788 | let (created, durability, sync_error) = |
| 789 | filesystem::directory_with(&root, &name, self)?; |
| 790 | if created { |
| 791 | self.terminal.created_count += 1; |
| 792 | self.terminal.publication = Publication::Partial; |
| 793 | self.terminal.durability = durability; |
| 794 | self.event(Message::Output { |
| 795 | entry_id: None, |
| 796 | relative_name: name, |
| 797 | disposition: Disposition::Created, |
| 798 | })?; |
| 799 | if let Some(error) = sync_error { |
| 800 | return Err(error); |
| 801 | } |
| 802 | completed(Ok(()), self)?; |
| 803 | } |
| 804 | } |
| 805 | for (index, m) in files.iter().enumerate() { |
| 806 | completed( |
| 807 | data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) |
| 808 | .map_err(|_| ErrorCode::Io), |
| 809 | self, |
| 810 | )?; |
| 811 | self.check()?; |
| 812 | let existing = if self.interactive { |
| 813 | filesystem::existing_with(&root, &m.entry.name, self)? |
| 814 | } else { |
| 815 | None |
| 816 | }; |
| 817 | let mut name = m.entry.name.clone(); |
| 818 | let mut replace = None; |
| 819 | if let Some(ref existing) = existing { |
| 820 | let choice = self.conflict(&m.entry, existing.size)?; |
| 821 | self.check()?; |
| 822 | if choice == ConflictChoice::Rename { |
| 823 | name = self.rename(&root, &name, &reserved)?; |
| 824 | reserved.insert(name.to_lowercase()); |
| 825 | } else if choice == ConflictChoice::Overwrite { |
| 826 | replace = Some(existing); |
| 827 | } |
| 828 | completed( |
| 829 | self.event(Message::ConflictResolved { |
| 830 | entry_id: m.entry.entry_id, |
| 831 | relative_name: name.clone(), |
| 832 | choice, |
| 833 | }), |
| 834 | self, |
| 835 | )?; |
| 836 | if choice == ConflictChoice::Skip { |
| 837 | continue; |
| 838 | } |
| 839 | } |
| 840 | if self.interactive { |
| 841 | // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함. |
| 842 | filesystem::preflight_space_with( |
| 843 | &root, |
| 844 | &[(name.clone(), m.entry.size)], |
| 845 | None, |
| 846 | self, |
| 847 | )?; |
| 848 | } |
| 849 | self.output_reader( |
| 850 | &root, |
| 851 | &name, |
| 852 | &mut (&mut data).take(m.entry.size), |
| 853 | m.entry.size, |
| 854 | Some(m.entry.entry_id), |
| 855 | index + 1 == files.len(), |
| 856 | replace, |
| 857 | )?; |
| 858 | } |
| 859 | if self.terminal.created_count == 0 { |
| 860 | self.verify_split()?; |
| 861 | } |
| 862 | if !self.interactive || self.terminal.created_count != 0 { |
| 863 | self.terminal.publication = Publication::Complete; |
| 864 | } |
| 865 | } |
| 866 | } |
| 867 | Action::Preview { |
| 868 | archive, |
| 869 | entry_id, |
| 870 | list_id, |
| 871 | } => { |
| 872 | self.preview(archive, entry_id, list_id, limits)?; |
| 873 | } |
| 874 | Action::CreateZip { |
| 875 | sources, |
| 876 | output_file, |
| 877 | method, |
| 878 | encryption, |
| 879 | } => { |
| 880 | let output = output_file.to_path()?; |
| 881 | let leaf = output |
| 882 | .file_name() |
| 883 | .and_then(|n| n.to_str()) |
| 884 | .ok_or(ErrorCode::InvalidRequest)?; |
| 885 | let name = archive::valid_name(leaf, false)?; |
| 886 | let root = completed( |
| 887 | Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), |
| 888 | self, |
| 889 | )?; |
| 890 | filesystem::preflight_mode_with( |
| 891 | &root, |
| 892 | &[(name.clone(), EntryKind::File)], |
| 893 | false, |
| 894 | self, |
| 895 | )?; |
| 896 | let members = crate::create::plan(&sources, limits, self)?; |
| 897 | let secret = if encryption == Encryption::Aes256 { |
| 898 | let secret = self.password(PasswordPurpose::Encrypt, 1)?; |
| 899 | if secret.0.is_empty() { |
| 900 | return Err(ErrorCode::InvalidRequest); |
| 901 | } |
| 902 | Some(secret) |
| 903 | } else { |
| 904 | None |
| 905 | }; |
| 906 | let (mut data, length) = crate::create::zip( |
| 907 | &members, |
| 908 | method, |
| 909 | limits, |
| 910 | secret.as_ref().map(|s| s.0.as_slice()), |
| 911 | self, |
| 912 | )?; |
| 913 | filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; |
| 914 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 915 | self.terminal.publication = Publication::Complete; |
| 916 | } |
| 917 | } |
| 918 | self.cutoff()?; |
| 919 | Ok(()) |
| 920 | } |
| 921 | } |
| 922 | impl<W: Write> Monitor for Job<W> { |
| 923 | fn metadata_limits(&self) -> archive::MetadataLimits { |
| 924 | self.budget |
| 925 | .as_ref() |
| 926 | .map_or_else(archive::MetadataLimits::default, |b| b.metadata_limits()) |
| 927 | } |
| 928 | fn check(&mut self) -> Result<()> { |
| 929 | Job::check(self) |
| 930 | } |
| 931 | fn activity(&mut self) -> Result<()> { |
| 932 | self.check()?; |
| 933 | self.watchdog.activity(self.started.elapsed()) |
| 934 | } |
| 935 | fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> { |
| 936 | self.check()?; |
| 937 | let Some(budget) = &self.budget else { |
| 938 | return Ok(()); |
| 939 | }; |
| 940 | let scope = budget.required(usage)?; |
| 941 | if !scope.any() { |
| 942 | return Ok(()); |
| 943 | } |
| 944 | self.request_resource(scope, usage, storage) |
| 945 | } |
| 946 | } |
| 947 | |
| 948 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 949 | input: R, |
| 950 | output: W, |
| 951 | ) -> std::io::Result<()> { |
| 952 | let parent = crate::parent::Parent::capture() |
| 953 | .map_err(|_| std::io::Error::other("worker parent unavailable"))?; |
| 954 | let mut reader = Reader::new(input); |
| 955 | let (job, _, message) = reader |
| 956 | .read()? |
| 957 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 958 | let (start, interactive, budget) = match message { |
| 959 | Message::Start(start) => (start, false, None), |
| 960 | Message::StartInteractive(start) => (start, true, None), |
| 961 | Message::StartGuarded(guarded) if guarded.valid() => { |
| 962 | let budget = Budget { |
| 963 | soft: guarded.start.limits, |
| 964 | ceiling: guarded.ceiling, |
| 965 | granted: ResourceScope::default(), |
| 966 | }; |
| 967 | (guarded.start, guarded.interactive, Some(budget)) |
| 968 | } |
| 969 | _ => { |
| 970 | return Err(std::io::Error::new( |
| 971 | std::io::ErrorKind::InvalidData, |
| 972 | "Start required", |
| 973 | )); |
| 974 | } |
| 975 | }; |
| 976 | let state = Arc::new(Mutex::new(State { |
| 977 | writer: Writer::new(output, job), |
| 978 | cancelled: false, |
| 979 | phase: 0, |
| 980 | fault: None, |
| 981 | challenge: None, |
| 982 | conflict_reply: None, |
| 983 | password: None, |
| 984 | resource_reply: None, |
| 985 | input_closed: false, |
| 986 | })); |
| 987 | let wake = Arc::new(Condvar::new()); |
| 988 | let control_wake = Arc::clone(&wake); |
| 989 | let control = Arc::clone(&state); |
| 990 | std::thread::spawn(move || { |
| 991 | loop { |
| 992 | let command = reader.read(); |
| 993 | let Ok(Some((_, sequence, message))) = command else { |
| 994 | if let Ok(mut state) = control.lock() { |
| 995 | state.input_closed = true; |
| 996 | if command.is_err() && state.phase < 2 { |
| 997 | state.fault = Some(ErrorCode::Protocol); |
| 998 | } |
| 999 | control_wake.notify_all(); |
| 1000 | } |
| 1001 | break; |
| 1002 | }; |
| 1003 | let Ok(mut state) = control.lock() else { |
| 1004 | break; |
| 1005 | }; |
| 1006 | if state.phase == 3 { |
| 1007 | break; |
| 1008 | } |
| 1009 | match message { |
| 1010 | Message::Password { |
| 1011 | challenge_id, |
| 1012 | secret, |
| 1013 | } => { |
| 1014 | if state.phase != 0 |
| 1015 | || state.challenge != Some(Challenge::Password(challenge_id)) |
| 1016 | || state.password.is_some() |
| 1017 | { |
| 1018 | state.fault = Some(ErrorCode::Protocol); |
| 1019 | } else { |
| 1020 | state.challenge = None; |
| 1021 | if !state.cancelled { |
| 1022 | state.password = Some(secret); |
| 1023 | } |
| 1024 | } |
| 1025 | control_wake.notify_all(); |
| 1026 | } |
| 1027 | Message::ConflictReply { |
| 1028 | challenge_id, |
| 1029 | choice, |
| 1030 | apply_to_remaining, |
| 1031 | } => { |
| 1032 | if state.phase != 0 |
| 1033 | || state.challenge != Some(Challenge::Conflict(challenge_id)) |
| 1034 | || state.conflict_reply.is_some() |
| 1035 | { |
| 1036 | state.fault = Some(ErrorCode::Protocol); |
| 1037 | } else { |
| 1038 | state.challenge = None; |
| 1039 | if !state.cancelled { |
| 1040 | state.conflict_reply = Some((choice, apply_to_remaining)); |
| 1041 | } |
| 1042 | } |
| 1043 | control_wake.notify_all(); |
| 1044 | } |
| 1045 | Message::ResourceReply { |
| 1046 | challenge_id, |
| 1047 | scope, |
| 1048 | allow, |
| 1049 | } => { |
| 1050 | if state.phase != 0 |
| 1051 | || state.challenge != Some(Challenge::Resource(challenge_id, scope)) |
| 1052 | || state.resource_reply.is_some() |
| 1053 | { |
| 1054 | state.fault = Some(ErrorCode::Protocol); |
| 1055 | } else { |
| 1056 | state.challenge = None; |
| 1057 | if !state.cancelled { |
| 1058 | state.resource_reply = Some(allow); |
| 1059 | } |
| 1060 | } |
| 1061 | control_wake.notify_all(); |
| 1062 | } |
| 1063 | Message::Cancel => { |
| 1064 | let status = match state.phase { |
| 1065 | 2 => CancelStatus::Finished, |
| 1066 | 1 => CancelStatus::TooLate, |
| 1067 | _ if state.cancelled => CancelStatus::AlreadyRequested, |
| 1068 | _ => { |
| 1069 | state.cancelled = true; |
| 1070 | CancelStatus::Requested |
| 1071 | } |
| 1072 | }; |
| 1073 | control_wake.notify_all(); |
| 1074 | if state |
| 1075 | .writer |
| 1076 | .send(&Message::CancelAck { |
| 1077 | request_sequence: sequence, |
| 1078 | status, |
| 1079 | }) |
| 1080 | .is_err() |
| 1081 | { |
| 1082 | state.fault = Some(ErrorCode::Io); |
| 1083 | break; |
| 1084 | } |
| 1085 | } |
| 1086 | _ => { |
| 1087 | state.fault = Some(ErrorCode::Protocol); |
| 1088 | break; |
| 1089 | } |
| 1090 | } |
| 1091 | } |
| 1092 | }); |
| 1093 | let mut context = Job { |
| 1094 | state: Arc::clone(&state), |
| 1095 | wake, |
| 1096 | next_challenge: 0, |
| 1097 | interactive, |
| 1098 | action: start.action.kind(), |
| 1099 | budget, |
| 1100 | watchdog: Watchdog::new(), |
| 1101 | remaining_choice: None, |
| 1102 | source_group: None, |
| 1103 | parent, |
| 1104 | started: Instant::now(), |
| 1105 | terminal: Terminal { |
| 1106 | outcome: Outcome::Completed, |
| 1107 | error: ErrorCode::None, |
| 1108 | publication: Publication::None, |
| 1109 | created_count: 0, |
| 1110 | retained_partial_count: 0, |
| 1111 | durability: Durability::NotApplicable, |
| 1112 | cleanup: Cleanup::Complete, |
| 1113 | detail: String::new(), |
| 1114 | }, |
| 1115 | }; |
| 1116 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start))); |
| 1117 | let error = match result { |
| 1118 | Ok(r) => r.err(), |
| 1119 | Err(_) => { |
| 1120 | context.terminal.publication = Publication::Uncertain; |
| 1121 | context.terminal.cleanup = Cleanup::Unconfirmed; |
| 1122 | Some(ErrorCode::Internal) |
| 1123 | } |
| 1124 | }; |
| 1125 | let mut state = state |
| 1126 | .lock() |
| 1127 | .map_err(|_| std::io::Error::other("worker state poisoned"))?; |
| 1128 | state.phase = 2; |
| 1129 | state.challenge = None; |
| 1130 | state.password = None; |
| 1131 | state.conflict_reply = None; |
| 1132 | state.resource_reply = None; |
| 1133 | if let Some(error) = state.fault.or(error) { |
| 1134 | context.terminal.error = error; |
| 1135 | context.terminal.outcome = if error == ErrorCode::None { |
| 1136 | Outcome::Cancelled |
| 1137 | } else { |
| 1138 | Outcome::Failed |
| 1139 | }; |
| 1140 | context.terminal.detail = match error { |
| 1141 | ErrorCode::None => "취소됨", |
| 1142 | ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", |
| 1143 | ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", |
| 1144 | ErrorCode::DiskFull => { |
| 1145 | "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요" |
| 1146 | } |
| 1147 | ErrorCode::Io => { |
| 1148 | "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요" |
| 1149 | } |
| 1150 | _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", |
| 1151 | } |
| 1152 | .to_owned(); |
| 1153 | } |
| 1154 | state.writer.send(&Message::Terminal(context.terminal))?; |
| 1155 | state.phase = 3; |
| 1156 | Ok(()) |
| 1157 | } |