team-ljyzipelo

공개
1,283줄50 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 if let Some(budget) = &self.budget {
590 let scope = ResourceScope {
591 output: budget.ceiling.output > budget.soft.output,
592 entries: budget.ceiling.entries > budget.soft.entries,
593 ratio: false,
594 };
595 if scope.any() {
596 let temporary = crate::spool::temporary()?;
597 self.request_resource(scope, ResourceUsage::default(), Some(&temporary))?;
598 }
599 }
600 match start.action {
601 Action::RecoverZip {
602 archive: source,
603 output_file,
604 } => {
605 let source = source.to_path()?;
606 let output = output_file.to_path()?;
607 let leaf = output
608 .file_name()
609 .and_then(|n| n.to_str())
610 .ok_or(ErrorCode::InvalidRequest)?;
611 let name = archive::valid_name(leaf, false)?;
612 let root = completed(
613 Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
614 self,
615 )?;
616 filesystem::preflight_mode_with(
617 &root,
618 &[(name.clone(), EntryKind::File)],
619 false,
620 self,
621 )?;
622 self.progress(Stage::Scan, 0, None, 0)?;
623 let mut recovery = crate::zip_recovery::Recovery::open(&source, limits, self)?;
624 for finding in &recovery.findings {
625 self.event(Message::RecoveryEntry(finding.clone()))?;
626 }
627 self.event(Message::RecoveryEnd(recovery.summary.clone()))?;
628 if recovery.summary.verified_entries == 0 {
629 return Err(ErrorCode::RecoveryImpossible);
630 }
631 let incomplete = !recovery.summary.complete();
632 let (mut data, length) = recovery.build(limits, self)?;
633 filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
634 self.recovery = Some(recovery);
635 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
636 self.terminal.publication = Publication::Complete;
637 if incomplete {
638 return Err(ErrorCode::RecoveryIncomplete);
639 }
640 }
641 Action::List {
642 archive: ref source,
643 }
644 | Action::Extract {
645 archive: ref source,
646 ..
647 } => {
648 let extract = matches!(start.action, Action::Extract { .. });
649 let path = source.to_path()?;
650 self.progress(
651 if crate::split_seven_zip::is_split(&path) {
652 Stage::Scan
653 } else {
654 Stage::Read
655 },
656 0,
657 None,
658 0,
659 )?;
660 let expected = match &start.action {
661 Action::Extract { list_id, .. } => list_id.as_ref(),
662 _ => None,
663 };
664 let metadata_limits = self.metadata_limits();
665 let captured = crate::split_seven_zip::open(
666 &path,
667 expected,
668 limits.input,
669 metadata_limits,
670 &mut |step| match step {
671 crate::spool::Step::Check => self.check(),
672 crate::spool::Step::Activity => completed(Ok(()), self),
673 crate::spool::Step::Read { bytes, total } => {
674 self.progress(Stage::Read, bytes, Some(total), 0)
675 }
676 },
677 );
678 let mut snapshot = if let Some(captured) = self.split_result(captured)? {
679 self.source_group = Some(captured.group);
680 captured.snapshot
681 } else {
682 crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| {
683 match step {
684 crate::spool::Step::Check => self.check(),
685 crate::spool::Step::Activity => completed(Ok(()), self),
686 crate::spool::Step::Read { bytes, total } => {
687 self.progress(Stage::Read, bytes, Some(total), 0)
688 }
689 }
690 })?
691 };
692 if let Action::Extract {
693 list_id: Some(expected),
694 ..
695 } = &start.action
696 {
697 if expected.catalog_version != if self.source_group.is_some() { 2 } else { 1 }
698 || expected.source_object != snapshot.object
699 || expected.archive_bytes != snapshot.len
700 || expected.archive_sha256 != snapshot.hash
701 {
702 return Err(ErrorCode::SourceChanged);
703 }
704 }
705 self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?;
706 let mut catalog = crate::streaming::Catalog::open(
707 &mut snapshot.file,
708 snapshot.len,
709 limits,
710 false,
711 None,
712 self,
713 )?;
714 let list_id = ListId {
715 catalog_version: if self.source_group.is_some() { 2 } else { 1 },
716 format: catalog.format,
717 source_object: snapshot.object,
718 archive_bytes: snapshot.len,
719 archive_sha256: snapshot.hash,
720 };
721 if !extract {
722 for member in &catalog.members {
723 self.check()?;
724 completed(self.event(Message::Entry(member.entry.clone())), self)?;
725 }
726 self.verify_split()?;
727 completed(
728 self.event(Message::ListEnd {
729 entry_count: catalog.members.len() as u32,
730 list_id,
731 }),
732 self,
733 )?;
734 } else if let Action::Extract {
735 destination,
736 selection,
737 list_id: expected,
738 gzip_output_name,
739 ..
740 } = start.action
741 {
742 if expected
743 .as_ref()
744 .is_some_and(|expected| *expected != list_id)
745 {
746 return Err(ErrorCode::SourceChanged);
747 }
748 let selected = match selection {
749 Selection::All => None,
750 Selection::EntryIds(ids) => {
751 if expected.is_none() || ids.is_empty() {
752 return Err(ErrorCode::InvalidRequest);
753 }
754 let mut set = BTreeSet::new();
755 for id in ids {
756 if id as usize >= catalog.members.len() || !set.insert(id) {
757 return Err(ErrorCode::InvalidRequest);
758 }
759 completed(Ok(()), self)?;
760 }
761 Some(set)
762 }
763 };
764 for member in &catalog.members {
765 if !matches!(member.entry.kind, EntryKind::File | EntryKind::Directory) {
766 return Err(ErrorCode::UnsafePath);
767 }
768 completed(Ok(()), self)?;
769 }
770 if catalog.format == Format::Gzip {
771 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
772 let checked = archive::valid_name(&name, false)
773 .map_err(|_| ErrorCode::InvalidRequest)?;
774 if checked.contains('/') {
775 return Err(ErrorCode::InvalidRequest);
776 }
777 catalog.members[0].entry.name = checked;
778 } else if gzip_output_name.is_some() {
779 return Err(ErrorCode::InvalidRequest);
780 }
781 let root = completed(Dir::root(&destination.to_path()?), self)?;
782 let mut output_sizes = Vec::new();
783 let mut staged_total = 0u64;
784 let mut encrypted = false;
785 for member in &catalog.members {
786 if member.entry.kind == EntryKind::File
787 && selected
788 .as_ref()
789 .is_none_or(|s| s.contains(&member.entry.entry_id))
790 {
791 output_sizes.push((member.entry.name.clone(), member.entry.size));
792 }
793 staged_total = staged_total
794 .checked_add(member.entry.size)
795 .ok_or(ErrorCode::Limit)?;
796 encrypted |= member.entry.encrypted;
797 completed(Ok(()), self)?;
798 }
799 let staged = matches!(catalog.format, Format::Zip | Format::SevenZip)
800 .then_some((&catalog.data, staged_total));
801 // 선택 전에는 검증에 필요한 스테이징 공간만 계산함.
802 let initial_outputs = if self.interactive {
803 &[][..]
804 } else {
805 &output_sizes[..]
806 };
807 filesystem::preflight_space_with(&root, initial_outputs, staged, self)?;
808 if matches!(catalog.format, Format::Zip | Format::SevenZip) {
809 for attempt in 1..=3 {
810 let secret = if encrypted {
811 Some(self.password(PasswordPurpose::Decrypt, attempt)?)
812 } else {
813 None
814 };
815 match crate::streaming::Catalog::open(
816 &mut snapshot.file,
817 snapshot.len,
818 limits,
819 true,
820 secret.as_ref().map(|s| s.0.as_slice()),
821 self,
822 ) {
823 Ok(decoded) => {
824 catalog = decoded;
825 break;
826 }
827 Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
828 Err(error) => return Err(error),
829 }
830 }
831 }
832 let offsets = catalog.offsets;
833 let mut data = catalog.data;
834 let mut members = Vec::new();
835 for member in catalog.members {
836 if selected
837 .as_ref()
838 .is_none_or(|s| s.contains(&member.entry.entry_id))
839 {
840 members.push(member);
841 }
842 completed(Ok(()), self)?;
843 }
844 let dirs = archive::output_directories(&members, self)?;
845 let files = members
846 .iter()
847 .filter(|m| m.entry.kind == EntryKind::File)
848 .map(|member| completed(Ok(member), self))
849 .collect::<Result<Vec<_>>>()?;
850 let mut names = dirs
851 .iter()
852 .map(|name| completed(Ok((name.clone(), EntryKind::Directory)), self))
853 .collect::<Result<Vec<_>>>()?;
854 names.extend(
855 files
856 .iter()
857 .map(|member| {
858 completed(Ok((member.entry.name.clone(), EntryKind::File)), self)
859 })
860 .collect::<Result<Vec<_>>>()?,
861 );
862 filesystem::preflight_mode_with(&root, &names, self.interactive, self)?;
863 if !self.interactive {
864 filesystem::preflight_space_with(&root, &output_sizes, None, self)?;
865 }
866 let mut reserved = names
867 .iter()
868 .map(|(name, _)| completed(Ok(name.to_lowercase()), self))
869 .collect::<Result<BTreeSet<_>>>()?;
870 for name in dirs {
871 self.check()?;
872 let (created, durability, sync_error) =
873 filesystem::directory_steps(&root, &name, &mut |step| {
874 self.publication_step(step, false)
875 })?;
876 if created {
877 self.terminal.created_count += 1;
878 self.terminal.publication = Publication::Partial;
879 self.terminal.durability = durability;
880 self.event(Message::Output {
881 entry_id: None,
882 relative_name: name,
883 disposition: Disposition::Created,
884 })?;
885 if let Some(error) = sync_error {
886 return Err(error);
887 }
888 completed(Ok(()), self)?;
889 }
890 }
891 for (index, m) in files.iter().enumerate() {
892 completed(
893 data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
894 .map_err(|_| ErrorCode::Io),
895 self,
896 )?;
897 self.check()?;
898 let existing = if self.interactive {
899 filesystem::existing_with(&root, &m.entry.name, self)?
900 } else {
901 None
902 };
903 let mut name = m.entry.name.clone();
904 let mut replace = None;
905 if let Some(ref existing) = existing {
906 let choice = self.conflict(&m.entry, existing.size)?;
907 self.check()?;
908 if choice == ConflictChoice::Rename {
909 name = self.rename(&root, &name, &reserved)?;
910 reserved.insert(name.to_lowercase());
911 } else if choice == ConflictChoice::Overwrite {
912 replace = Some(existing);
913 }
914 completed(
915 self.event(Message::ConflictResolved {
916 entry_id: m.entry.entry_id,
917 relative_name: name.clone(),
918 choice,
919 }),
920 self,
921 )?;
922 if choice == ConflictChoice::Skip {
923 continue;
924 }
925 }
926 if self.interactive {
927 // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함.
928 filesystem::preflight_space_with(
929 &root,
930 &[(name.clone(), m.entry.size)],
931 None,
932 self,
933 )?;
934 }
935 self.output_reader(
936 &root,
937 &name,
938 &mut (&mut data).take(m.entry.size),
939 m.entry.size,
940 Some(m.entry.entry_id),
941 index + 1 == files.len(),
942 replace,
943 )?;
944 }
945 // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함.
946 self.verify_before_publication(None)?;
947 if !self.interactive || self.terminal.created_count != 0 {
948 self.terminal.publication = Publication::Complete;
949 }
950 }
951 }
952 Action::Preview {
953 archive,
954 entry_id,
955 list_id,
956 } => {
957 self.preview(archive, entry_id, list_id, limits)?;
958 }
959 Action::CreateZip {
960 sources,
961 output_file,
962 method,
963 encryption,
964 } => {
965 let output = output_file.to_path()?;
966 let leaf = output
967 .file_name()
968 .and_then(|n| n.to_str())
969 .ok_or(ErrorCode::InvalidRequest)?;
970 let name = archive::valid_name(leaf, false)?;
971 let root = completed(
972 Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
973 self,
974 )?;
975 filesystem::preflight_mode_with(
976 &root,
977 &[(name.clone(), EntryKind::File)],
978 false,
979 self,
980 )?;
981 let members = crate::create::plan(&sources, limits, self)?;
982 let secret = if encryption == Encryption::Aes256 {
983 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
984 if secret.0.is_empty() {
985 return Err(ErrorCode::InvalidRequest);
986 }
987 Some(secret)
988 } else {
989 None
990 };
991 let (mut data, length) = crate::create::zip(
992 &members,
993 method,
994 limits,
995 secret.as_ref().map(|s| s.0.as_slice()),
996 self,
997 )?;
998 filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
999 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
1000 self.terminal.publication = Publication::Complete;
1001 }
1002 Action::CreateSevenZip {
1003 sources,
1004 output_file,
1005 ..
1006 } => {
1007 let output = output_file.to_path()?;
1008 let leaf = output
1009 .file_name()
1010 .and_then(|n| n.to_str())
1011 .ok_or(ErrorCode::InvalidRequest)?;
1012 let name = archive::valid_name(leaf, false)?;
1013 let root = completed(
1014 Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?),
1015 self,
1016 )?;
1017 filesystem::preflight_mode_with(
1018 &root,
1019 &[(name.clone(), EntryKind::File)],
1020 false,
1021 self,
1022 )?;
1023 self.progress(Stage::Scan, 0, None, 0)?;
1024 let mut plan = crate::create::plan(&sources, limits, self)?;
1025 let (mut data, length) = crate::seven_zip_create::archive(&mut plan, limits, self)?;
1026 filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?;
1027 self.creation_plan = Some(plan);
1028 self.output_reader(&root, &name, &mut data, length, None, true, None)?;
1029 self.terminal.publication = Publication::Complete;
1030 }
1031 }
1032 self.cutoff()?;
1033 Ok(())
1034 }
1035}
1036impl<W: Write> Monitor for Job<W> {
1037 fn progress(
1038 &mut self,
1039 stage: Stage,
1040 bytes: u64,
1041 total: Option<u64>,
1042 entries: u32,
1043 ) -> Result<()> {
1044 Job::progress(self, stage, bytes, total, entries)
1045 }
1046 fn metadata_limits(&self) -> archive::MetadataLimits {
1047 self.budget
1048 .as_ref()
1049 .map_or_else(archive::MetadataLimits::default, |b| b.metadata_limits())
1050 }
1051 fn check(&mut self) -> Result<()> {
1052 Job::check(self)
1053 }
1054 fn activity(&mut self) -> Result<()> {
1055 self.check()?;
1056 self.watchdog.activity(self.started.elapsed())
1057 }
1058 fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> {
1059 self.check()?;
1060 let Some(budget) = &self.budget else {
1061 return Ok(());
1062 };
1063 let scope = budget.required(usage)?;
1064 if !scope.any() {
1065 return Ok(());
1066 }
1067 self.request_resource(scope, usage, storage)
1068 }
1069}
1070
1071pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
1072 input: R,
1073 output: W,
1074) -> std::io::Result<()> {
1075 let parent = crate::parent::Parent::capture()
1076 .map_err(|_| std::io::Error::other("worker parent unavailable"))?;
1077 let mut reader = Reader::new(input);
1078 let (job, _, message) = reader
1079 .read()?
1080 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?;
1081 let (start, interactive, budget) = match message {
1082 Message::Start(start) => (start, false, None),
1083 Message::StartInteractive(start) => (start, true, None),
1084 Message::StartGuarded(guarded) if guarded.valid() => {
1085 let budget = Budget {
1086 soft: guarded.start.limits,
1087 ceiling: guarded.ceiling,
1088 granted: ResourceScope::default(),
1089 };
1090 (guarded.start, guarded.interactive, Some(budget))
1091 }
1092 _ => {
1093 return Err(std::io::Error::new(
1094 std::io::ErrorKind::InvalidData,
1095 "Start required",
1096 ));
1097 }
1098 };
1099 let state = Arc::new(Mutex::new(State {
1100 writer: Writer::new(output, job),
1101 cancelled: false,
1102 phase: 0,
1103 fault: None,
1104 challenge: None,
1105 conflict_reply: None,
1106 password: None,
1107 resource_reply: None,
1108 input_closed: false,
1109 }));
1110 let wake = Arc::new(Condvar::new());
1111 let control_wake = Arc::clone(&wake);
1112 let control = Arc::clone(&state);
1113 std::thread::spawn(move || {
1114 loop {
1115 let command = reader.read();
1116 let Ok(Some((_, sequence, message))) = command else {
1117 if let Ok(mut state) = control.lock() {
1118 state.input_closed = true;
1119 if command.is_err() && state.phase < 2 {
1120 state.fault = Some(ErrorCode::Protocol);
1121 }
1122 control_wake.notify_all();
1123 }
1124 break;
1125 };
1126 let Ok(mut state) = control.lock() else {
1127 break;
1128 };
1129 if state.phase == 3 {
1130 break;
1131 }
1132 match message {
1133 Message::Password {
1134 challenge_id,
1135 secret,
1136 } => {
1137 if state.phase != 0
1138 || state.challenge != Some(Challenge::Password(challenge_id))
1139 || state.password.is_some()
1140 {
1141 state.fault = Some(ErrorCode::Protocol);
1142 } else {
1143 state.challenge = None;
1144 if !state.cancelled {
1145 state.password = Some(secret);
1146 }
1147 }
1148 control_wake.notify_all();
1149 }
1150 Message::ConflictReply {
1151 challenge_id,
1152 choice,
1153 apply_to_remaining,
1154 } => {
1155 if state.phase != 0
1156 || state.challenge != Some(Challenge::Conflict(challenge_id))
1157 || state.conflict_reply.is_some()
1158 {
1159 state.fault = Some(ErrorCode::Protocol);
1160 } else {
1161 state.challenge = None;
1162 if !state.cancelled {
1163 state.conflict_reply = Some((choice, apply_to_remaining));
1164 }
1165 }
1166 control_wake.notify_all();
1167 }
1168 Message::ResourceReply {
1169 challenge_id,
1170 scope,
1171 allow,
1172 } => {
1173 if state.phase != 0
1174 || state.challenge != Some(Challenge::Resource(challenge_id, scope))
1175 || state.resource_reply.is_some()
1176 {
1177 state.fault = Some(ErrorCode::Protocol);
1178 } else {
1179 state.challenge = None;
1180 if !state.cancelled {
1181 state.resource_reply = Some(allow);
1182 }
1183 }
1184 control_wake.notify_all();
1185 }
1186 Message::Cancel => {
1187 let status = match state.phase {
1188 2 => CancelStatus::Finished,
1189 1 => CancelStatus::TooLate,
1190 _ if state.cancelled => CancelStatus::AlreadyRequested,
1191 _ => {
1192 state.cancelled = true;
1193 CancelStatus::Requested
1194 }
1195 };
1196 control_wake.notify_all();
1197 if state
1198 .writer
1199 .send(&Message::CancelAck {
1200 request_sequence: sequence,
1201 status,
1202 })
1203 .is_err()
1204 {
1205 state.fault = Some(ErrorCode::Io);
1206 break;
1207 }
1208 }
1209 _ => {
1210 state.fault = Some(ErrorCode::Protocol);
1211 break;
1212 }
1213 }
1214 }
1215 });
1216 let mut context = Job {
1217 state: Arc::clone(&state),
1218 wake,
1219 next_challenge: 0,
1220 interactive,
1221 action: start.action.kind(),
1222 budget,
1223 watchdog: Watchdog::new(),
1224 remaining_choice: None,
1225 source_group: None,
1226 source_verified_for_publication: false,
1227 creation_plan: None,
1228 recovery: None,
1229 parent,
1230 started: Instant::now(),
1231 terminal: Terminal {
1232 outcome: Outcome::Completed,
1233 error: ErrorCode::None,
1234 publication: Publication::None,
1235 created_count: 0,
1236 retained_partial_count: 0,
1237 durability: Durability::NotApplicable,
1238 cleanup: Cleanup::Complete,
1239 detail: String::new(),
1240 },
1241 };
1242 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start)));
1243 let error = match result {
1244 Ok(r) => r.err(),
1245 Err(_) => {
1246 context.terminal.publication = Publication::Uncertain;
1247 context.terminal.cleanup = Cleanup::Unconfirmed;
1248 Some(ErrorCode::Internal)
1249 }
1250 };
1251 let mut state = state
1252 .lock()
1253 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
1254 state.phase = 2;
1255 state.challenge = None;
1256 state.password = None;
1257 state.conflict_reply = None;
1258 state.resource_reply = None;
1259 if let Some(error) = state.fault.or(error) {
1260 context.terminal.error = error;
1261 context.terminal.outcome = if error == ErrorCode::None {
1262 Outcome::Cancelled
1263 } else {
1264 Outcome::Failed
1265 };
1266 context.terminal.detail = match error {
1267 ErrorCode::None => "취소됨",
1268 ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원",
1269 ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함",
1270 ErrorCode::DiskFull => {
1271 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
1272 }
1273 ErrorCode::Io => {
1274 "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요"
1275 }
1276 _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함",
1277 }
1278 .to_owned();
1279 }
1280 state.writer.send(&Message::Terminal(context.terminal))?;
1281 state.phase = 3;
1282 Ok(())
1283}