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