team-ljyzipelo

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