team-ljyzipelo

공개
629줄24 KB
1use crate::{
2 archive::{self, Member},
3 filesystem::{self, Dir},
4 protocol::*,
5 wire::{Reader, Writer},
6};
7use std::{
8 collections::BTreeSet,
9 io::{Read, Seek, SeekFrom, Write},
10 sync::{Arc, Condvar, Mutex},
11 time::{Duration, Instant},
12};
13
14type Result<T> = std::result::Result<T, ErrorCode>;
15struct State<W> {
16 writer: Writer<W>,
17 cancelled: bool,
18 phase: u8,
19 fault: Option<ErrorCode>,
20 challenge: Option<u64>,
21 password: Option<Secret>,
22 input_closed: bool,
23}
24struct Job<W> {
25 state: Arc<Mutex<State<W>>>,
26 wake: Arc<Condvar>,
27 next_challenge: u64,
28 started: Instant,
29 terminal: Terminal,
30 parent: crate::parent::Parent,
31}
32impl<W: Write> Job<W> {
33 fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> {
34 self.check()?;
35 self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?;
36 let id = self.next_challenge;
37 let state_ref = Arc::clone(&self.state);
38 let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?;
39 state.challenge = Some(id);
40 state
41 .writer
42 .send(&Message::PasswordRequired {
43 challenge_id: id,
44 attempt,
45 purpose,
46 })
47 .map_err(|_| ErrorCode::Io)?;
48 loop {
49 self.parent.check()?;
50 if let Some(error) = state.fault {
51 return Err(error);
52 }
53 if state.cancelled {
54 return Err(ErrorCode::None);
55 }
56 if let Some(secret) = state.password.take() {
57 return Ok(secret);
58 }
59 if state.input_closed {
60 return Err(ErrorCode::Protocol);
61 }
62 if self.started.elapsed() > Duration::from_secs(300) {
63 return Err(ErrorCode::Limit);
64 }
65 state = self
66 .wake
67 .wait_timeout(state, Duration::from_millis(50))
68 .map_err(|_| ErrorCode::Internal)?
69 .0;
70 }
71 }
72
73 fn event(&mut self, event: Message) -> Result<()> {
74 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
75 state.writer.send(&event).map_err(|_| {
76 state.fault = Some(ErrorCode::Io);
77 ErrorCode::Io
78 })
79 }
80 fn check(&mut self) -> Result<()> {
81 self.parent.check()?;
82 if self.started.elapsed() > Duration::from_secs(300) {
83 return Err(ErrorCode::Limit);
84 }
85 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
86 if let Some(error) = state.fault {
87 return Err(error);
88 }
89 if state.cancelled && state.phase == 0 {
90 return Err(ErrorCode::None);
91 }
92 Ok(())
93 }
94 fn cutoff(&mut self) -> Result<()> {
95 self.check()?;
96 let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
97 if state.phase == 0 && state.cancelled {
98 return Err(ErrorCode::None);
99 }
100 state.phase = 1;
101 Ok(())
102 }
103 fn progress(
104 &mut self,
105 stage: Stage,
106 bytes: u64,
107 total: Option<u64>,
108 entries: u32,
109 ) -> Result<()> {
110 self.event(Message::Progress {
111 stage,
112 processed_bytes: bytes,
113 total_bytes: total,
114 completed_entries: entries,
115 })
116 }
117 fn output(
118 &mut self,
119 root: &Dir,
120 name: &str,
121 data: &[u8],
122 id: Option<u32>,
123 last: bool,
124 ) -> Result<()> {
125 self.output_reader(
126 root,
127 name,
128 &mut std::io::Cursor::new(data),
129 data.len() as u64,
130 id,
131 last,
132 )
133 }
134 fn output_reader(
135 &mut self,
136 root: &Dir,
137 name: &str,
138 data: &mut impl Read,
139 length: u64,
140 id: Option<u32>,
141 last: bool,
142 ) -> Result<()> {
143 self.check()?;
144 self.progress(
145 Stage::Write,
146 0,
147 Some(length),
148 self.terminal.created_count as u32,
149 )?;
150 let p = filesystem::publish_reader(root, name, data, length, &mut |commit| {
151 if commit && last {
152 self.cutoff()
153 } else {
154 self.check()
155 }
156 });
157 self.terminal.retained_partial_count += p.retained;
158 if p.cleanup != Cleanup::Complete {
159 self.terminal.cleanup = p.cleanup;
160 }
161 if p.created {
162 self.terminal.created_count += 1;
163 self.terminal.publication = Publication::Partial;
164 self.terminal.durability = match (self.terminal.durability, p.durability) {
165 (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed,
166 (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => {
167 Durability::Unconfirmed
168 }
169 _ => p.durability,
170 };
171 self.event(Message::Output {
172 entry_id: id,
173 relative_name: name.to_owned(),
174 disposition: Disposition::Created,
175 })?;
176 }
177 if p.uncertain {
178 self.terminal.publication = Publication::Uncertain;
179 self.terminal.durability = Durability::Unconfirmed;
180 self.event(Message::Output {
181 entry_id: id,
182 relative_name: name.to_owned(),
183 disposition: Disposition::CommitUncertain,
184 })?;
185 }
186 if p.retained != 0 {
187 self.event(Message::Output {
188 entry_id: id,
189 relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?,
190 disposition: Disposition::PartialRetained,
191 })?;
192 }
193 if let Some(error) = p.error {
194 return Err(error);
195 }
196 Ok(())
197 }
198 fn run(&mut self, start: Start) -> Result<()> {
199 if !start.limits.valid() {
200 return Err(ErrorCode::InvalidRequest);
201 }
202 self.event(Message::Accepted {
203 action: start.action.kind(),
204 encryption: true,
205 })?;
206 self.check()?;
207 match start.action {
208 Action::List {
209 archive: ref source,
210 }
211 | Action::Extract {
212 archive: ref source,
213 ..
214 } => {
215 let extract = matches!(start.action, Action::Extract { .. });
216 let path = source.to_path()?;
217 self.progress(Stage::Read, 0, None, 0)?;
218 let mut snapshot =
219 crate::spool::Snapshot::open(&path, start.limits.input, &mut || self.check())?;
220 if let Action::Extract {
221 list_id: Some(expected),
222 ..
223 } = &start.action
224 {
225 if expected.catalog_version != 1
226 || expected.source_object != snapshot.object
227 || expected.archive_bytes != snapshot.len
228 || expected.archive_sha256 != snapshot.hash
229 {
230 return Err(ErrorCode::SourceChanged);
231 }
232 }
233 self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?;
234 let mut catalog = crate::streaming::Catalog::open(
235 &mut snapshot.file,
236 snapshot.len,
237 start.limits,
238 false,
239 None,
240 &mut || self.check(),
241 )?;
242 let list_id = ListId {
243 catalog_version: 1,
244 format: catalog.format,
245 source_object: snapshot.object,
246 archive_bytes: snapshot.len,
247 archive_sha256: snapshot.hash,
248 };
249 if !extract {
250 for member in &catalog.members {
251 self.check()?;
252 self.event(Message::Entry(member.entry.clone()))?;
253 }
254 self.event(Message::ListEnd {
255 entry_count: catalog.members.len() as u32,
256 list_id,
257 })?;
258 } else if let Action::Extract {
259 destination,
260 selection,
261 list_id: expected,
262 gzip_output_name,
263 ..
264 } = start.action
265 {
266 if expected
267 .as_ref()
268 .is_some_and(|expected| *expected != list_id)
269 {
270 return Err(ErrorCode::SourceChanged);
271 }
272 let selected = match selection {
273 Selection::All => None,
274 Selection::EntryIds(ids) => {
275 let n = ids.len();
276 let set = ids.into_iter().collect::<BTreeSet<_>>();
277 if expected.is_none()
278 || set.is_empty()
279 || n != set.len()
280 || set.iter().any(|id| *id as usize >= catalog.members.len())
281 {
282 return Err(ErrorCode::InvalidRequest);
283 }
284 Some(set)
285 }
286 };
287 if catalog
288 .members
289 .iter()
290 .any(|m| !matches!(m.entry.kind, EntryKind::File | EntryKind::Directory))
291 {
292 return Err(ErrorCode::UnsafePath);
293 }
294 if catalog.format == Format::Gzip {
295 let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?;
296 let checked = archive::valid_name(&name, false)
297 .map_err(|_| ErrorCode::InvalidRequest)?;
298 if checked.contains('/') {
299 return Err(ErrorCode::InvalidRequest);
300 }
301 catalog.members[0].entry.name = checked;
302 } else if gzip_output_name.is_some() {
303 return Err(ErrorCode::InvalidRequest);
304 }
305 let root = Dir::root(&destination.to_path()?)?;
306 let output_sizes = catalog
307 .members
308 .iter()
309 .filter(|m| {
310 m.entry.kind == EntryKind::File
311 && selected
312 .as_ref()
313 .is_none_or(|s| s.contains(&m.entry.entry_id))
314 })
315 .map(|m| (m.entry.name.clone(), m.entry.size))
316 .collect::<Vec<_>>();
317 let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) {
318 Some((
319 &catalog.data,
320 catalog.members.iter().try_fold(0u64, |sum, m| {
321 sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit)
322 })?,
323 ))
324 } else {
325 None
326 };
327 filesystem::preflight_space(&root, &output_sizes, staged)?;
328 let encrypted = catalog.members.iter().any(|m| m.entry.encrypted);
329 if matches!(catalog.format, Format::Zip | Format::SevenZip) {
330 for attempt in 1..=3 {
331 let secret = if encrypted {
332 Some(self.password(PasswordPurpose::Decrypt, attempt)?)
333 } else {
334 None
335 };
336 match crate::streaming::Catalog::open(
337 &mut snapshot.file,
338 snapshot.len,
339 start.limits,
340 true,
341 secret.as_ref().map(|s| s.0.as_slice()),
342 &mut || self.check(),
343 ) {
344 Ok(decoded) => {
345 catalog = decoded;
346 break;
347 }
348 Err(ErrorCode::WrongPassword) if attempt < 3 => continue,
349 Err(error) => return Err(error),
350 }
351 }
352 }
353 let offsets = catalog.offsets;
354 let mut data = catalog.data;
355 let members = catalog
356 .members
357 .into_iter()
358 .filter(|m| {
359 selected
360 .as_ref()
361 .is_none_or(|s| s.contains(&m.entry.entry_id))
362 })
363 .collect::<Vec<_>>();
364 let dirs = archive::output_directories(&members)?;
365 let files = members
366 .iter()
367 .filter(|m| m.entry.kind == EntryKind::File)
368 .collect::<Vec<_>>();
369 let mut names = dirs
370 .iter()
371 .map(|n| (n.clone(), EntryKind::Directory))
372 .collect::<Vec<_>>();
373 names.extend(
374 files
375 .iter()
376 .map(|m| (m.entry.name.clone(), EntryKind::File)),
377 );
378 filesystem::preflight(&root, &names)?;
379 filesystem::preflight_space(&root, &output_sizes, None)?;
380 for name in dirs {
381 self.check()?;
382 let (created, durability, sync_error) =
383 filesystem::directory(&root, &name)?;
384 if created {
385 self.terminal.created_count += 1;
386 self.terminal.publication = Publication::Partial;
387 self.terminal.durability = durability;
388 self.event(Message::Output {
389 entry_id: None,
390 relative_name: name,
391 disposition: Disposition::Created,
392 })?;
393 if let Some(error) = sync_error {
394 return Err(error);
395 }
396 }
397 }
398 for (index, m) in files.iter().enumerate() {
399 data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize]))
400 .map_err(|_| ErrorCode::Io)?;
401 self.output_reader(
402 &root,
403 &m.entry.name,
404 &mut (&mut data).take(m.entry.size),
405 m.entry.size,
406 Some(m.entry.entry_id),
407 index + 1 == files.len(),
408 )?;
409 }
410 self.terminal.publication = Publication::Complete;
411 }
412 }
413 Action::CreateZip {
414 sources,
415 output_file,
416 method,
417 encryption,
418 } => {
419 let limits = start.limits.legacy();
420 if sources.len() > limits.entries as usize {
421 return Err(ErrorCode::Limit);
422 }
423 let mut members = Vec::new();
424 let mut consumed = 0;
425 for source in sources {
426 self.check()?;
427 let name = archive::valid_name(&source.archive_name, false)?;
428 let snapshot = filesystem::snapshot(
429 &source.path.to_path()?,
430 limits.input - consumed,
431 &mut || self.check(),
432 )?;
433 consumed += snapshot.bytes.len() as u64;
434 members.push(Member {
435 entry: Entry {
436 entry_id: members.len() as u32,
437 name,
438 kind: EntryKind::File,
439 size: snapshot.bytes.len() as u64,
440 compressed_size: 0,
441 encrypted: false,
442 },
443 data: snapshot.bytes,
444 });
445 }
446 let secret = if encryption == Encryption::Aes256 {
447 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
448 if secret.0.is_empty() {
449 return Err(ErrorCode::InvalidRequest);
450 }
451 Some(secret)
452 } else {
453 None
454 };
455 let bytes = archive::create_zip_with_password(
456 &members,
457 method,
458 limits,
459 secret.as_ref().map(|s| s.0.as_slice()),
460 &mut || self.check(),
461 )?;
462 let output = output_file.to_path()?;
463 let leaf = output
464 .file_name()
465 .and_then(|n| n.to_str())
466 .ok_or(ErrorCode::InvalidRequest)?;
467 let name = archive::valid_name(leaf, false)?;
468 let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
469 filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
470 self.output(&root, &name, &bytes, None, true)?;
471 self.terminal.publication = Publication::Complete;
472 }
473 }
474 self.cutoff()?;
475 Ok(())
476 }
477}
478pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
479 input: R,
480 output: W,
481) -> std::io::Result<()> {
482 let parent = crate::parent::Parent::capture()
483 .map_err(|_| std::io::Error::other("worker parent unavailable"))?;
484 let mut reader = Reader::new(input);
485 let (job, _, message) = reader
486 .read()?
487 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?;
488 let Message::Start(start) = message else {
489 return Err(std::io::Error::new(
490 std::io::ErrorKind::InvalidData,
491 "Start required",
492 ));
493 };
494 let state = Arc::new(Mutex::new(State {
495 writer: Writer::new(output, job),
496 cancelled: false,
497 phase: 0,
498 fault: None,
499 challenge: None,
500 password: None,
501 input_closed: false,
502 }));
503 let wake = Arc::new(Condvar::new());
504 let control_wake = Arc::clone(&wake);
505 let control = Arc::clone(&state);
506 std::thread::spawn(move || {
507 loop {
508 let command = reader.read();
509 let Ok(Some((_, sequence, message))) = command else {
510 if let Ok(mut state) = control.lock() {
511 state.input_closed = true;
512 if command.is_err() && state.phase < 2 {
513 state.fault = Some(ErrorCode::Protocol);
514 }
515 control_wake.notify_all();
516 }
517 break;
518 };
519 let Ok(mut state) = control.lock() else {
520 break;
521 };
522 if state.phase == 3 {
523 break;
524 }
525 match message {
526 Message::Password {
527 challenge_id,
528 secret,
529 } => {
530 if state.phase != 0
531 || state.challenge != Some(challenge_id)
532 || state.password.is_some()
533 {
534 state.fault = Some(ErrorCode::Protocol);
535 } else {
536 state.challenge = None;
537 if !state.cancelled {
538 state.password = Some(secret);
539 }
540 }
541 control_wake.notify_all();
542 }
543 Message::Cancel => {
544 let status = match state.phase {
545 2 => CancelStatus::Finished,
546 1 => CancelStatus::TooLate,
547 _ if state.cancelled => CancelStatus::AlreadyRequested,
548 _ => {
549 state.cancelled = true;
550 CancelStatus::Requested
551 }
552 };
553 control_wake.notify_all();
554 if state
555 .writer
556 .send(&Message::CancelAck {
557 request_sequence: sequence,
558 status,
559 })
560 .is_err()
561 {
562 state.fault = Some(ErrorCode::Io);
563 break;
564 }
565 }
566 _ => {
567 state.fault = Some(ErrorCode::Protocol);
568 break;
569 }
570 }
571 }
572 });
573 let mut context = Job {
574 state: Arc::clone(&state),
575 wake,
576 next_challenge: 0,
577 parent,
578 started: Instant::now(),
579 terminal: Terminal {
580 outcome: Outcome::Completed,
581 error: ErrorCode::None,
582 publication: Publication::None,
583 created_count: 0,
584 retained_partial_count: 0,
585 durability: Durability::NotApplicable,
586 cleanup: Cleanup::Complete,
587 detail: String::new(),
588 },
589 };
590 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| context.run(start)));
591 let error = match result {
592 Ok(r) => r.err(),
593 Err(_) => {
594 context.terminal.publication = Publication::Uncertain;
595 context.terminal.cleanup = Cleanup::Unconfirmed;
596 Some(ErrorCode::Internal)
597 }
598 };
599 let mut state = state
600 .lock()
601 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
602 state.phase = 2;
603 state.challenge = None;
604 state.password = None;
605 if let Some(error) = state.fault.or(error) {
606 context.terminal.error = error;
607 context.terminal.outcome = if error == ErrorCode::None {
608 Outcome::Cancelled
609 } else {
610 Outcome::Failed
611 };
612 context.terminal.detail = match error {
613 ErrorCode::None => "취소됨",
614 ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원",
615 ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함",
616 ErrorCode::DiskFull => {
617 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
618 }
619 ErrorCode::Io => {
620 "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요"
621 }
622 _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함",
623 }
624 .to_owned();
625 }
626 state.writer.send(&Message::Terminal(context.terminal))?;
627 state.phase = 3;
628 Ok(())
629}