team-ljyzipelo

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