team-ljyzipelo

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