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