team-ljyzipelo

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