| 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 | struct State<W> { |
| 16 | writer: Writer<W>, |
| 17 | cancelled: bool, |
| 18 | phase: u8, |
| 19 | fault: Option<ErrorCode>, |
| 20 | challenge: Option<u64>, |
| 21 | password: Option<Secret>, |
| 22 | input_closed: bool, |
| 23 | } |
| 24 | struct Job<W> { |
| 25 | state: Arc<Mutex<State<W>>>, |
| 26 | wake: Arc<Condvar>, |
| 27 | next_challenge: u64, |
| 28 | started: Instant, |
| 29 | terminal: Terminal, |
| 30 | parent: crate::parent::Parent, |
| 31 | } |
| 32 | impl<W: Write> Job<W> { |
| 33 | fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> { |
| 34 | self.check()?; |
| 35 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 36 | let id = self.next_challenge; |
| 37 | let state_ref = Arc::clone(&self.state); |
| 38 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 39 | state.challenge = Some(id); |
| 40 | state |
| 41 | .writer |
| 42 | .send(&Message::PasswordRequired { |
| 43 | challenge_id: id, |
| 44 | attempt, |
| 45 | purpose, |
| 46 | }) |
| 47 | .map_err(|_| ErrorCode::Io)?; |
| 48 | loop { |
| 49 | self.parent.check()?; |
| 50 | if let Some(error) = state.fault { |
| 51 | return Err(error); |
| 52 | } |
| 53 | if state.cancelled { |
| 54 | return Err(ErrorCode::None); |
| 55 | } |
| 56 | if let Some(secret) = state.password.take() { |
| 57 | return Ok(secret); |
| 58 | } |
| 59 | if state.input_closed { |
| 60 | return Err(ErrorCode::Protocol); |
| 61 | } |
| 62 | if self.started.elapsed() > Duration::from_secs(300) { |
| 63 | return Err(ErrorCode::Limit); |
| 64 | } |
| 65 | state = self |
| 66 | .wake |
| 67 | .wait_timeout(state, Duration::from_millis(50)) |
| 68 | .map_err(|_| ErrorCode::Internal)? |
| 69 | .0; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn event(&mut self, event: Message) -> Result<()> { |
| 74 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 75 | state.writer.send(&event).map_err(|_| { |
| 76 | state.fault = Some(ErrorCode::Io); |
| 77 | ErrorCode::Io |
| 78 | }) |
| 79 | } |
| 80 | fn check(&mut self) -> Result<()> { |
| 81 | self.parent.check()?; |
| 82 | if self.started.elapsed() > Duration::from_secs(300) { |
| 83 | return Err(ErrorCode::Limit); |
| 84 | } |
| 85 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 86 | if let Some(error) = state.fault { |
| 87 | return Err(error); |
| 88 | } |
| 89 | if state.cancelled && state.phase == 0 { |
| 90 | return Err(ErrorCode::None); |
| 91 | } |
| 92 | Ok(()) |
| 93 | } |
| 94 | fn cutoff(&mut self) -> Result<()> { |
| 95 | self.check()?; |
| 96 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 97 | if state.phase == 0 && state.cancelled { |
| 98 | return Err(ErrorCode::None); |
| 99 | } |
| 100 | state.phase = 1; |
| 101 | Ok(()) |
| 102 | } |
| 103 | fn progress( |
| 104 | &mut self, |
| 105 | stage: Stage, |
| 106 | bytes: u64, |
| 107 | total: Option<u64>, |
| 108 | entries: u32, |
| 109 | ) -> Result<()> { |
| 110 | self.event(Message::Progress { |
| 111 | stage, |
| 112 | processed_bytes: bytes, |
| 113 | total_bytes: total, |
| 114 | completed_entries: entries, |
| 115 | }) |
| 116 | } |
| 117 | fn output_reader( |
| 118 | &mut self, |
| 119 | root: &Dir, |
| 120 | name: &str, |
| 121 | data: &mut impl Read, |
| 122 | length: u64, |
| 123 | id: Option<u32>, |
| 124 | last: bool, |
| 125 | ) -> Result<()> { |
| 126 | self.check()?; |
| 127 | self.progress( |
| 128 | Stage::Write, |
| 129 | 0, |
| 130 | Some(length), |
| 131 | self.terminal.created_count as u32, |
| 132 | )?; |
| 133 | let p = filesystem::publish_reader(root, name, data, length, &mut |commit| { |
| 134 | if commit && last { |
| 135 | self.cutoff() |
| 136 | } else { |
| 137 | self.check() |
| 138 | } |
| 139 | }); |
| 140 | self.terminal.retained_partial_count += p.retained; |
| 141 | if p.cleanup != Cleanup::Complete { |
| 142 | self.terminal.cleanup = p.cleanup; |
| 143 | } |
| 144 | if p.created { |
| 145 | self.terminal.created_count += 1; |
| 146 | self.terminal.publication = Publication::Partial; |
| 147 | self.terminal.durability = match (self.terminal.durability, p.durability) { |
| 148 | (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, |
| 149 | (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { |
| 150 | Durability::Unconfirmed |
| 151 | } |
| 152 | _ => p.durability, |
| 153 | }; |
| 154 | self.event(Message::Output { |
| 155 | entry_id: id, |
| 156 | relative_name: name.to_owned(), |
| 157 | disposition: Disposition::Created, |
| 158 | })?; |
| 159 | } |
| 160 | if p.uncertain { |
| 161 | self.terminal.publication = Publication::Uncertain; |
| 162 | self.terminal.durability = Durability::Unconfirmed; |
| 163 | self.event(Message::Output { |
| 164 | entry_id: id, |
| 165 | relative_name: name.to_owned(), |
| 166 | disposition: Disposition::CommitUncertain, |
| 167 | })?; |
| 168 | } |
| 169 | if p.retained != 0 { |
| 170 | self.event(Message::Output { |
| 171 | entry_id: id, |
| 172 | relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?, |
| 173 | disposition: Disposition::PartialRetained, |
| 174 | })?; |
| 175 | } |
| 176 | if let Some(error) = p.error { |
| 177 | return Err(error); |
| 178 | } |
| 179 | Ok(()) |
| 180 | } |
| 181 | fn run(&mut self, start: Start) -> Result<()> { |
| 182 | if !start.limits.valid() { |
| 183 | return Err(ErrorCode::InvalidRequest); |
| 184 | } |
| 185 | self.event(Message::Accepted { |
| 186 | action: start.action.kind(), |
| 187 | encryption: true, |
| 188 | })?; |
| 189 | self.check()?; |
| 190 | match start.action { |
| 191 | Action::List { |
| 192 | archive: ref source, |
| 193 | } |
| 194 | | Action::Extract { |
| 195 | archive: ref source, |
| 196 | .. |
| 197 | } => { |
| 198 | let extract = matches!(start.action, Action::Extract { .. }); |
| 199 | let path = source.to_path()?; |
| 200 | self.progress(Stage::Read, 0, None, 0)?; |
| 201 | let mut snapshot = |
| 202 | crate::spool::Snapshot::open(&path, start.limits.input, &mut || self.check())?; |
| 203 | if let Action::Extract { |
| 204 | list_id: Some(expected), |
| 205 | .. |
| 206 | } = &start.action |
| 207 | { |
| 208 | if expected.catalog_version != 1 |
| 209 | || expected.source_object != snapshot.object |
| 210 | || expected.archive_bytes != snapshot.len |
| 211 | || expected.archive_sha256 != snapshot.hash |
| 212 | { |
| 213 | return Err(ErrorCode::SourceChanged); |
| 214 | } |
| 215 | } |
| 216 | self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?; |
| 217 | let mut catalog = crate::streaming::Catalog::open( |
| 218 | &mut snapshot.file, |
| 219 | snapshot.len, |
| 220 | start.limits, |
| 221 | false, |
| 222 | None, |
| 223 | &mut || self.check(), |
| 224 | )?; |
| 225 | let list_id = ListId { |
| 226 | catalog_version: 1, |
| 227 | format: catalog.format, |
| 228 | source_object: snapshot.object, |
| 229 | archive_bytes: snapshot.len, |
| 230 | archive_sha256: snapshot.hash, |
| 231 | }; |
| 232 | if !extract { |
| 233 | for member in &catalog.members { |
| 234 | self.check()?; |
| 235 | self.event(Message::Entry(member.entry.clone()))?; |
| 236 | } |
| 237 | self.event(Message::ListEnd { |
| 238 | entry_count: catalog.members.len() as u32, |
| 239 | list_id, |
| 240 | })?; |
| 241 | } else if let Action::Extract { |
| 242 | destination, |
| 243 | selection, |
| 244 | list_id: expected, |
| 245 | gzip_output_name, |
| 246 | .. |
| 247 | } = start.action |
| 248 | { |
| 249 | if expected |
| 250 | .as_ref() |
| 251 | .is_some_and(|expected| *expected != list_id) |
| 252 | { |
| 253 | return Err(ErrorCode::SourceChanged); |
| 254 | } |
| 255 | let selected = match selection { |
| 256 | Selection::All => None, |
| 257 | Selection::EntryIds(ids) => { |
| 258 | let n = ids.len(); |
| 259 | let set = ids.into_iter().collect::<BTreeSet<_>>(); |
| 260 | if expected.is_none() |
| 261 | || set.is_empty() |
| 262 | || n != set.len() |
| 263 | || set.iter().any(|id| *id as usize >= catalog.members.len()) |
| 264 | { |
| 265 | return Err(ErrorCode::InvalidRequest); |
| 266 | } |
| 267 | Some(set) |
| 268 | } |
| 269 | }; |
| 270 | if catalog |
| 271 | .members |
| 272 | .iter() |
| 273 | .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory)) |
| 274 | { |
| 275 | return Err(ErrorCode::UnsafePath); |
| 276 | } |
| 277 | if catalog.format == Format::Gzip { |
| 278 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| 279 | let checked = archive::valid_name(&name, false) |
| 280 | .map_err(|_| ErrorCode::InvalidRequest)?; |
| 281 | if checked.contains('/') { |
| 282 | return Err(ErrorCode::InvalidRequest); |
| 283 | } |
| 284 | catalog.members[0].entry.name = checked; |
| 285 | } else if gzip_output_name.is_some() { |
| 286 | return Err(ErrorCode::InvalidRequest); |
| 287 | } |
| 288 | let root = Dir::root(&destination.to_path()?)?; |
| 289 | let output_sizes = catalog |
| 290 | .members |
| 291 | .iter() |
| 292 | .filter(|m| { |
| 293 | m.entry.kind == EntryKind::File |
| 294 | && selected |
| 295 | .as_ref() |
| 296 | .is_none_or(|s| s.contains(&m.entry.entry_id)) |
| 297 | }) |
| 298 | .map(|m| (m.entry.name.clone(), m.entry.size)) |
| 299 | .collect::<Vec<_>>(); |
| 300 | let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 301 | Some(( |
| 302 | &catalog.data, |
| 303 | catalog.members.iter().try_fold(0u64, |sum, m| { |
| 304 | sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit) |
| 305 | })?, |
| 306 | )) |
| 307 | } else { |
| 308 | None |
| 309 | }; |
| 310 | filesystem::preflight_space(&root, &output_sizes, staged)?; |
| 311 | let encrypted = catalog.members.iter().any(|m| m.entry.encrypted); |
| 312 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 313 | for attempt in 1..=3 { |
| 314 | let secret = if encrypted { |
| 315 | Some(self.password(PasswordPurpose::Decrypt, attempt)?) |
| 316 | } else { |
| 317 | None |
| 318 | }; |
| 319 | match crate::streaming::Catalog::open( |
| 320 | &mut snapshot.file, |
| 321 | snapshot.len, |
| 322 | start.limits, |
| 323 | true, |
| 324 | secret.as_ref().map(|s| s.0.as_slice()), |
| 325 | &mut || self.check(), |
| 326 | ) { |
| 327 | Ok(decoded) => { |
| 328 | catalog = decoded; |
| 329 | break; |
| 330 | } |
| 331 | Err(ErrorCode::WrongPassword) if attempt < 3 => continue, |
| 332 | Err(error) => return Err(error), |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | let offsets = catalog.offsets; |
| 337 | let mut data = catalog.data; |
| 338 | let members = catalog |
| 339 | .members |
| 340 | .into_iter() |
| 341 | .filter(|m| { |
| 342 | selected |
| 343 | .as_ref() |
| 344 | .is_none_or(|s| s.contains(&m.entry.entry_id)) |
| 345 | }) |
| 346 | .collect::<Vec<_>>(); |
| 347 | let dirs = archive::output_directories(&members)?; |
| 348 | let files = members |
| 349 | .iter() |
| 350 | .filter(|m| m.entry.kind == EntryKind::File) |
| 351 | .collect::<Vec<_>>(); |
| 352 | let mut names = dirs |
| 353 | .iter() |
| 354 | .map(|n| (n.clone(), EntryKind::Directory)) |
| 355 | .collect::<Vec<_>>(); |
| 356 | names.extend( |
| 357 | files |
| 358 | .iter() |
| 359 | .map(|m| (m.entry.name.clone(), EntryKind::File)), |
| 360 | ); |
| 361 | filesystem::preflight(&root, &names)?; |
| 362 | filesystem::preflight_space(&root, &output_sizes, None)?; |
| 363 | for name in dirs { |
| 364 | self.check()?; |
| 365 | let (created, durability, sync_error) = |
| 366 | filesystem::directory(&root, &name)?; |
| 367 | if created { |
| 368 | self.terminal.created_count += 1; |
| 369 | self.terminal.publication = Publication::Partial; |
| 370 | self.terminal.durability = durability; |
| 371 | self.event(Message::Output { |
| 372 | entry_id: None, |
| 373 | relative_name: name, |
| 374 | disposition: Disposition::Created, |
| 375 | })?; |
| 376 | if let Some(error) = sync_error { |
| 377 | return Err(error); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | for (index, m) in files.iter().enumerate() { |
| 382 | data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) |
| 383 | .map_err(|_| ErrorCode::Io)?; |
| 384 | self.output_reader( |
| 385 | &root, |
| 386 | &m.entry.name, |
| 387 | &mut (&mut data).take(m.entry.size), |
| 388 | m.entry.size, |
| 389 | Some(m.entry.entry_id), |
| 390 | index + 1 == files.len(), |
| 391 | )?; |
| 392 | } |
| 393 | self.terminal.publication = Publication::Complete; |
| 394 | } |
| 395 | } |
| 396 | Action::CreateZip { |
| 397 | sources, |
| 398 | output_file, |
| 399 | method, |
| 400 | encryption, |
| 401 | } => { |
| 402 | let output = output_file.to_path()?; |
| 403 | let leaf = output |
| 404 | .file_name() |
| 405 | .and_then(|n| n.to_str()) |
| 406 | .ok_or(ErrorCode::InvalidRequest)?; |
| 407 | let name = archive::valid_name(leaf, false)?; |
| 408 | let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?; |
| 409 | filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?; |
| 410 | let members = crate::create::plan(&sources, start.limits, &mut || self.check())?; |
| 411 | let secret = if encryption == Encryption::Aes256 { |
| 412 | let secret = self.password(PasswordPurpose::Encrypt, 1)?; |
| 413 | if secret.0.is_empty() { |
| 414 | return Err(ErrorCode::InvalidRequest); |
| 415 | } |
| 416 | Some(secret) |
| 417 | } else { |
| 418 | None |
| 419 | }; |
| 420 | let (mut data, length) = crate::create::zip( |
| 421 | &members, |
| 422 | method, |
| 423 | start.limits, |
| 424 | secret.as_ref().map(|s| s.0.as_slice()), |
| 425 | &mut || self.check(), |
| 426 | )?; |
| 427 | filesystem::preflight_space(&root, &[(name.clone(), length)], None)?; |
| 428 | self.output_reader(&root, &name, &mut data, length, None, true)?; |
| 429 | self.terminal.publication = Publication::Complete; |
| 430 | } |
| 431 | } |
| 432 | self.cutoff()?; |
| 433 | Ok(()) |
| 434 | } |
| 435 | } |
| 436 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 437 | input: R, |
| 438 | output: W, |
| 439 | ) -> std::io::Result<()> { |
| 440 | let parent = crate::parent::Parent::capture() |
| 441 | .map_err(|_| std::io::Error::other("worker parent unavailable"))?; |
| 442 | let mut reader = Reader::new(input); |
| 443 | let (job, _, message) = reader |
| 444 | .read()? |
| 445 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 446 | let Message::Start(start) = message else { |
| 447 | return Err(std::io::Error::new( |
| 448 | std::io::ErrorKind::InvalidData, |
| 449 | "Start required", |
| 450 | )); |
| 451 | }; |
| 452 | let state = Arc::new(Mutex::new(State { |
| 453 | writer: Writer::new(output, job), |
| 454 | cancelled: false, |
| 455 | phase: 0, |
| 456 | fault: None, |
| 457 | challenge: None, |
| 458 | password: None, |
| 459 | input_closed: false, |
| 460 | })); |
| 461 | let wake = Arc::new(Condvar::new()); |
| 462 | let control_wake = Arc::clone(&wake); |
| 463 | let control = Arc::clone(&state); |
| 464 | std::thread::spawn(move || { |
| 465 | loop { |
| 466 | let command = reader.read(); |
| 467 | let Ok(Some((_, sequence, message))) = command else { |
| 468 | if let Ok(mut state) = control.lock() { |
| 469 | state.input_closed = true; |
| 470 | if command.is_err() && state.phase < 2 { |
| 471 | state.fault = Some(ErrorCode::Protocol); |
| 472 | } |
| 473 | control_wake.notify_all(); |
| 474 | } |
| 475 | break; |
| 476 | }; |
| 477 | let Ok(mut state) = control.lock() else { |
| 478 | break; |
| 479 | }; |
| 480 | if state.phase == 3 { |
| 481 | break; |
| 482 | } |
| 483 | match message { |
| 484 | Message::Password { |
| 485 | challenge_id, |
| 486 | secret, |
| 487 | } => { |
| 488 | if state.phase != 0 |
| 489 | || state.challenge != Some(challenge_id) |
| 490 | || state.password.is_some() |
| 491 | { |
| 492 | state.fault = Some(ErrorCode::Protocol); |
| 493 | } else { |
| 494 | state.challenge = None; |
| 495 | if !state.cancelled { |
| 496 | state.password = Some(secret); |
| 497 | } |
| 498 | } |
| 499 | control_wake.notify_all(); |
| 500 | } |
| 501 | Message::Cancel => { |
| 502 | let status = match state.phase { |
| 503 | 2 => CancelStatus::Finished, |
| 504 | 1 => CancelStatus::TooLate, |
| 505 | _ if state.cancelled => CancelStatus::AlreadyRequested, |
| 506 | _ => { |
| 507 | state.cancelled = true; |
| 508 | CancelStatus::Requested |
| 509 | } |
| 510 | }; |
| 511 | control_wake.notify_all(); |
| 512 | if state |
| 513 | .writer |
| 514 | .send(&Message::CancelAck { |
| 515 | request_sequence: sequence, |
| 516 | status, |
| 517 | }) |
| 518 | .is_err() |
| 519 | { |
| 520 | state.fault = Some(ErrorCode::Io); |
| 521 | break; |
| 522 | } |
| 523 | } |
| 524 | _ => { |
| 525 | state.fault = Some(ErrorCode::Protocol); |
| 526 | break; |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | }); |
| 531 | let mut context = Job { |
| 532 | state: Arc::clone(&state), |
| 533 | wake, |
| 534 | next_challenge: 0, |
| 535 | parent, |
| 536 | started: Instant::now(), |
| 537 | terminal: Terminal { |
| 538 | outcome: Outcome::Completed, |
| 539 | error: ErrorCode::None, |
| 540 | publication: Publication::None, |
| 541 | created_count: 0, |
| 542 | retained_partial_count: 0, |
| 543 | durability: Durability::NotApplicable, |
| 544 | cleanup: Cleanup::Complete, |
| 545 | detail: String::new(), |
| 546 | }, |
| 547 | }; |
| 548 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start))); |
| 549 | let error = match result { |
| 550 | Ok(r) => r.err(), |
| 551 | Err(_) => { |
| 552 | context.terminal.publication = Publication::Uncertain; |
| 553 | context.terminal.cleanup = Cleanup::Unconfirmed; |
| 554 | Some(ErrorCode::Internal) |
| 555 | } |
| 556 | }; |
| 557 | let mut state = state |
| 558 | .lock() |
| 559 | .map_err(|_| std::io::Error::other("worker state poisoned"))?; |
| 560 | state.phase = 2; |
| 561 | state.challenge = None; |
| 562 | state.password = None; |
| 563 | if let Some(error) = state.fault.or(error) { |
| 564 | context.terminal.error = error; |
| 565 | context.terminal.outcome = if error == ErrorCode::None { |
| 566 | Outcome::Cancelled |
| 567 | } else { |
| 568 | Outcome::Failed |
| 569 | }; |
| 570 | context.terminal.detail = match error { |
| 571 | ErrorCode::None => "취소됨", |
| 572 | ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", |
| 573 | ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", |
| 574 | ErrorCode::DiskFull => { |
| 575 | "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요" |
| 576 | } |
| 577 | ErrorCode::Io => { |
| 578 | "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요" |
| 579 | } |
| 580 | _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", |
| 581 | } |
| 582 | .to_owned(); |
| 583 | } |
| 584 | state.writer.send(&Message::Terminal(context.terminal))?; |
| 585 | state.phase = 3; |
| 586 | Ok(()) |
| 587 | } |