team-ljyzipelo

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